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 _03.AnimalHierarchy
{
public interface ISound
{
string MakeSound();
}
} | 14.571429 | 30 | 0.617647 | [
"Apache-2.0"
] | iliantrifonov/TelerikAcademy | OOP/4.OOPPrinciples/OOPPrinciples/03.AnimalHierarchy/ISound.cs | 104 | C# |
namespace TrackerClient
{
partial class RfMain
{
/// <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();
Telerik.WinControls.UI.ListViewDetailColumn listViewDetailColumn1 = new Telerik.WinControls.UI.ListViewDetailColumn("Column 0", "Item");
Telerik.WinControls.UI.ListViewDetailColumn listViewDetailColumn2 = new Telerik.WinControls.UI.ListViewDetailColumn("Column 1", "Amount");
this.rtVSDark = new Telerik.WinControls.Themes.VisualStudio2012DarkTheme();
this.rpvMain = new Telerik.WinControls.UI.RadPageView();
this.rpvpPlayers = new Telerik.WinControls.UI.RadPageViewPage();
this.lblBM = new System.Windows.Forms.LinkLabel();
this.lblSteamID = new System.Windows.Forms.LinkLabel();
this.rtebVehicleInfo = new Telerik.WinControls.UI.RadTextBox();
this.rlvVirItems = new Telerik.WinControls.UI.RadListView();
this.rlcVehicles = new Telerik.WinControls.UI.RadListControl();
this.rbtbAliases = new Telerik.WinControls.UI.RadButtonTextBox();
this.rgbLocation = new Telerik.WinControls.UI.RadGroupBox();
this.rpMap = new Telerik.WinControls.UI.RadPanel();
this.pbMap = new System.Windows.Forms.PictureBox();
this.rtrbZoom = new Telerik.WinControls.UI.RadTrackBar();
this.lblLocation = new System.Windows.Forms.Label();
this.lblVVirtuals = new System.Windows.Forms.Label();
this.lblVehicles = new System.Windows.Forms.Label();
this.lblVirtuals = new System.Windows.Forms.Label();
this.lblAliases = new System.Windows.Forms.Label();
this.lblLauncher = new System.Windows.Forms.Label();
this.lblSecondary = new System.Windows.Forms.Label();
this.lblHelmet = new System.Windows.Forms.Label();
this.lblVest = new System.Windows.Forms.Label();
this.lblGun = new System.Windows.Forms.Label();
this.lblMedicRank = new System.Windows.Forms.Label();
this.lblCopRank = new System.Windows.Forms.Label();
this.lblGang = new System.Windows.Forms.Label();
this.lblName = new System.Windows.Forms.Label();
this.lblKDR = new System.Windows.Forms.Label();
this.lblBounty = new System.Windows.Forms.Label();
this.lblBank = new System.Windows.Forms.Label();
this.lblCash = new System.Windows.Forms.Label();
this.rpPlayerLeft = new Telerik.WinControls.UI.RadPanel();
this.rpvPlayers = new Telerik.WinControls.UI.RadPageView();
this.rpvpAll = new Telerik.WinControls.UI.RadPageViewPage();
this.lbPlayersAll = new System.Windows.Forms.ListBox();
this.rpvpTargets = new Telerik.WinControls.UI.RadPageViewPage();
this.lbPlayersTargets = new System.Windows.Forms.ListBox();
this.rpvpVigiable = new Telerik.WinControls.UI.RadPageViewPage();
this.lbPlayersVigi = new System.Windows.Forms.ListBox();
this.rpvpWarTargets = new Telerik.WinControls.UI.RadPageViewPage();
this.lbPlayersWT = new System.Windows.Forms.ListBox();
this.rpvpHouses = new Telerik.WinControls.UI.RadPageViewPage();
this.rpvpGangs = new Telerik.WinControls.UI.RadPageViewPage();
this.rpBottom = new Telerik.WinControls.UI.RadPanel();
this.radStatusStrip1 = new Telerik.WinControls.UI.RadStatusStrip();
this.rbRefresh = new Telerik.WinControls.UI.RadButtonElement();
this.rtbRefresh = new Telerik.WinControls.UI.RadTrackBarElement();
this.rlRefresh = new Telerik.WinControls.UI.RadLabelElement();
this.commandBarSeparator1 = new Telerik.WinControls.UI.CommandBarSeparator();
this.rsbServer = new Telerik.WinControls.UI.RadSplitButtonElement();
this.rmiServer1 = new Telerik.WinControls.UI.RadMenuItem();
this.rmiServer2 = new Telerik.WinControls.UI.RadMenuItem();
this.rbMap = new Telerik.WinControls.UI.RadButtonElement();
this.rcb_disableAutoLocate = new Telerik.WinControls.UI.RadCheckBoxElement();
this.rpMain = new Telerik.WinControls.UI.RadPanel();
this.timerMain = new System.Windows.Forms.Timer(this.components);
this.bwPlayerTabRefresh = new System.ComponentModel.BackgroundWorker();
((System.ComponentModel.ISupportInitialize)(this.rpvMain)).BeginInit();
this.rpvMain.SuspendLayout();
this.rpvpPlayers.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.rtebVehicleInfo)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.rlvVirItems)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.rlcVehicles)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.rbtbAliases)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.rgbLocation)).BeginInit();
this.rgbLocation.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.rpMap)).BeginInit();
this.rpMap.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pbMap)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.rtrbZoom)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.rpPlayerLeft)).BeginInit();
this.rpPlayerLeft.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.rpvPlayers)).BeginInit();
this.rpvPlayers.SuspendLayout();
this.rpvpAll.SuspendLayout();
this.rpvpTargets.SuspendLayout();
this.rpvpVigiable.SuspendLayout();
this.rpvpWarTargets.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.rpBottom)).BeginInit();
this.rpBottom.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.radStatusStrip1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.rpMain)).BeginInit();
this.rpMain.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
this.SuspendLayout();
//
// rpvMain
//
this.rpvMain.Controls.Add(this.rpvpPlayers);
this.rpvMain.Controls.Add(this.rpvpHouses);
this.rpvMain.Controls.Add(this.rpvpGangs);
this.rpvMain.DefaultPage = this.rpvpPlayers;
this.rpvMain.Dock = System.Windows.Forms.DockStyle.Fill;
this.rpvMain.Location = new System.Drawing.Point(0, 0);
this.rpvMain.Name = "rpvMain";
this.rpvMain.SelectedPage = this.rpvpPlayers;
this.rpvMain.Size = new System.Drawing.Size(1046, 592);
this.rpvMain.TabIndex = 0;
this.rpvMain.ThemeName = "VisualStudio2012Dark";
((Telerik.WinControls.UI.RadPageViewStripElement)(this.rpvMain.GetChildAt(0))).StripAlignment = Telerik.WinControls.UI.StripViewAlignment.Left;
//
// rpvpPlayers
//
this.rpvpPlayers.Controls.Add(this.lblBM);
this.rpvpPlayers.Controls.Add(this.lblSteamID);
this.rpvpPlayers.Controls.Add(this.rtebVehicleInfo);
this.rpvpPlayers.Controls.Add(this.rlvVirItems);
this.rpvpPlayers.Controls.Add(this.rlcVehicles);
this.rpvpPlayers.Controls.Add(this.rbtbAliases);
this.rpvpPlayers.Controls.Add(this.rgbLocation);
this.rpvpPlayers.Controls.Add(this.lblVVirtuals);
this.rpvpPlayers.Controls.Add(this.lblVehicles);
this.rpvpPlayers.Controls.Add(this.lblVirtuals);
this.rpvpPlayers.Controls.Add(this.lblAliases);
this.rpvpPlayers.Controls.Add(this.lblLauncher);
this.rpvpPlayers.Controls.Add(this.lblSecondary);
this.rpvpPlayers.Controls.Add(this.lblHelmet);
this.rpvpPlayers.Controls.Add(this.lblVest);
this.rpvpPlayers.Controls.Add(this.lblGun);
this.rpvpPlayers.Controls.Add(this.lblMedicRank);
this.rpvpPlayers.Controls.Add(this.lblCopRank);
this.rpvpPlayers.Controls.Add(this.lblGang);
this.rpvpPlayers.Controls.Add(this.lblName);
this.rpvpPlayers.Controls.Add(this.lblKDR);
this.rpvpPlayers.Controls.Add(this.lblBounty);
this.rpvpPlayers.Controls.Add(this.lblBank);
this.rpvpPlayers.Controls.Add(this.lblCash);
this.rpvpPlayers.Controls.Add(this.rpPlayerLeft);
this.rpvpPlayers.ItemSize = new System.Drawing.SizeF(24F, 47F);
this.rpvpPlayers.Location = new System.Drawing.Point(30, 5);
this.rpvpPlayers.Name = "rpvpPlayers";
this.rpvpPlayers.Size = new System.Drawing.Size(1011, 582);
this.rpvpPlayers.Text = "Players";
//
// lblBM
//
this.lblBM.AutoSize = true;
this.lblBM.LinkColor = System.Drawing.Color.White;
this.lblBM.Location = new System.Drawing.Point(380, 118);
this.lblBM.Name = "lblBM";
this.lblBM.Size = new System.Drawing.Size(93, 13);
this.lblBM.TabIndex = 125;
this.lblBM.TabStop = true;
this.lblBM.Text = "BattleMetrics ID: ";
this.lblBM.VisitedLinkColor = System.Drawing.Color.Gray;
this.lblBM.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lblBM_LinkClicked);
//
// lblSteamID
//
this.lblSteamID.AutoSize = true;
this.lblSteamID.LinkColor = System.Drawing.Color.White;
this.lblSteamID.Location = new System.Drawing.Point(203, 118);
this.lblSteamID.Name = "lblSteamID";
this.lblSteamID.Size = new System.Drawing.Size(55, 13);
this.lblSteamID.TabIndex = 124;
this.lblSteamID.TabStop = true;
this.lblSteamID.Text = "Steam ID:";
this.lblSteamID.VisitedLinkColor = System.Drawing.Color.Gray;
this.lblSteamID.Click += new System.EventHandler(this.lblSteamID_Click);
//
// rtebVehicleInfo
//
this.rtebVehicleInfo.Location = new System.Drawing.Point(383, 339);
this.rtebVehicleInfo.Multiline = true;
this.rtebVehicleInfo.Name = "rtebVehicleInfo";
this.rtebVehicleInfo.ReadOnly = true;
//
//
//
this.rtebVehicleInfo.RootElement.StretchVertically = true;
this.rtebVehicleInfo.Size = new System.Drawing.Size(160, 226);
this.rtebVehicleInfo.TabIndex = 123;
this.rtebVehicleInfo.ThemeName = "VisualStudio2012Dark";
//
// rlvVirItems
//
this.rlvVirItems.AllowColumnResize = false;
listViewDetailColumn1.HeaderText = "Item";
listViewDetailColumn1.Width = 100F;
listViewDetailColumn2.HeaderText = "Amount";
listViewDetailColumn2.Width = 50F;
this.rlvVirItems.Columns.AddRange(new Telerik.WinControls.UI.ListViewDetailColumn[] {
listViewDetailColumn1,
listViewDetailColumn2});
this.rlvVirItems.HorizontalScrollState = Telerik.WinControls.UI.ScrollState.AlwaysHide;
this.rlvVirItems.ItemSpacing = -1;
this.rlvVirItems.Location = new System.Drawing.Point(216, 339);
this.rlvVirItems.Name = "rlvVirItems";
this.rlvVirItems.Size = new System.Drawing.Size(155, 226);
this.rlvVirItems.TabIndex = 120;
this.rlvVirItems.ThemeName = "VisualStudio2012Dark";
this.rlvVirItems.ViewType = Telerik.WinControls.UI.ListViewType.DetailsView;
//
// rlcVehicles
//
this.rlcVehicles.Location = new System.Drawing.Point(383, 169);
this.rlcVehicles.Name = "rlcVehicles";
this.rlcVehicles.Size = new System.Drawing.Size(160, 140);
this.rlcVehicles.TabIndex = 119;
this.rlcVehicles.ThemeName = "VisualStudio2012Dark";
//
// rbtbAliases
//
this.rbtbAliases.Location = new System.Drawing.Point(216, 169);
this.rbtbAliases.Multiline = true;
this.rbtbAliases.Name = "rbtbAliases";
this.rbtbAliases.ReadOnly = true;
//
//
//
this.rbtbAliases.RootElement.StretchVertically = true;
this.rbtbAliases.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.rbtbAliases.Size = new System.Drawing.Size(150, 140);
this.rbtbAliases.TabIndex = 118;
this.rbtbAliases.ThemeName = "VisualStudio2012Dark";
//
// rgbLocation
//
this.rgbLocation.AccessibleRole = System.Windows.Forms.AccessibleRole.Grouping;
this.rgbLocation.Controls.Add(this.rpMap);
this.rgbLocation.Controls.Add(this.rtrbZoom);
this.rgbLocation.Controls.Add(this.lblLocation);
this.rgbLocation.HeaderText = "Location";
this.rgbLocation.Location = new System.Drawing.Point(566, 156);
this.rgbLocation.Name = "rgbLocation";
this.rgbLocation.Size = new System.Drawing.Size(438, 409);
this.rgbLocation.TabIndex = 117;
this.rgbLocation.Text = "Location";
this.rgbLocation.ThemeName = "VisualStudio2012Dark";
//
// rpMap
//
this.rpMap.AutoScroll = true;
this.rpMap.Controls.Add(this.pbMap);
this.rpMap.Dock = System.Windows.Forms.DockStyle.Bottom;
this.rpMap.Location = new System.Drawing.Point(2, 51);
this.rpMap.Name = "rpMap";
this.rpMap.Size = new System.Drawing.Size(434, 356);
this.rpMap.TabIndex = 109;
//
// pbMap
//
this.pbMap.Image = global::TrackerClient.Properties.Resources.Altis3;
this.pbMap.InitialImage = global::TrackerClient.Properties.Resources.Altis3;
this.pbMap.Location = new System.Drawing.Point(0, 0);
this.pbMap.Name = "pbMap";
this.pbMap.Size = new System.Drawing.Size(3370, 3370);
this.pbMap.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pbMap.TabIndex = 108;
this.pbMap.TabStop = false;
this.pbMap.Paint += new System.Windows.Forms.PaintEventHandler(this.pbMap_Paint);
this.pbMap.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pbMap_MouseDown);
this.pbMap.MouseMove += new System.Windows.Forms.MouseEventHandler(this.pbMap_MouseMove);
this.pbMap.MouseUp += new System.Windows.Forms.MouseEventHandler(this.pbMap_MouseUp);
//
// rtrbZoom
//
this.rtrbZoom.AllowKeyNavigation = true;
this.rtrbZoom.LargeChange = 10;
this.rtrbZoom.Location = new System.Drawing.Point(219, 13);
this.rtrbZoom.Maximum = 250F;
this.rtrbZoom.Minimum = 50F;
this.rtrbZoom.Name = "rtrbZoom";
this.rtrbZoom.Size = new System.Drawing.Size(214, 32);
this.rtrbZoom.SnapMode = Telerik.WinControls.UI.TrackBarSnapModes.None;
this.rtrbZoom.TabIndex = 107;
this.rtrbZoom.ThemeName = "VisualStudio2012Dark";
this.rtrbZoom.Value = 250F;
this.rtrbZoom.ValueChanged += new System.EventHandler(this.rtrbZoom_ValueChanged);
//
// lblLocation
//
this.lblLocation.AutoSize = true;
this.lblLocation.Location = new System.Drawing.Point(28, 26);
this.lblLocation.Name = "lblLocation";
this.lblLocation.Size = new System.Drawing.Size(50, 13);
this.lblLocation.TabIndex = 106;
this.lblLocation.Text = "Coords: ";
//
// lblVVirtuals
//
this.lblVVirtuals.AutoSize = true;
this.lblVVirtuals.Location = new System.Drawing.Point(380, 323);
this.lblVVirtuals.Name = "lblVVirtuals";
this.lblVVirtuals.Size = new System.Drawing.Size(76, 13);
this.lblVVirtuals.TabIndex = 115;
this.lblVVirtuals.Text = "Vehicle Items:";
//
// lblVehicles
//
this.lblVehicles.AutoSize = true;
this.lblVehicles.Location = new System.Drawing.Point(380, 153);
this.lblVehicles.Name = "lblVehicles";
this.lblVehicles.Size = new System.Drawing.Size(51, 13);
this.lblVehicles.TabIndex = 113;
this.lblVehicles.Text = "Vehicles:";
//
// lblVirtuals
//
this.lblVirtuals.AutoSize = true;
this.lblVirtuals.Location = new System.Drawing.Point(213, 323);
this.lblVirtuals.Name = "lblVirtuals";
this.lblVirtuals.Size = new System.Drawing.Size(37, 13);
this.lblVirtuals.TabIndex = 111;
this.lblVirtuals.Text = "Items:";
//
// lblAliases
//
this.lblAliases.AutoSize = true;
this.lblAliases.Location = new System.Drawing.Point(213, 153);
this.lblAliases.Name = "lblAliases";
this.lblAliases.Size = new System.Drawing.Size(45, 13);
this.lblAliases.TabIndex = 110;
this.lblAliases.Text = "Aliases:";
//
// lblLauncher
//
this.lblLauncher.AutoSize = true;
this.lblLauncher.Location = new System.Drawing.Point(634, 66);
this.lblLauncher.Name = "lblLauncher";
this.lblLauncher.Size = new System.Drawing.Size(60, 13);
this.lblLauncher.TabIndex = 108;
this.lblLauncher.Text = "Launcher: ";
//
// lblSecondary
//
this.lblSecondary.AutoSize = true;
this.lblSecondary.Location = new System.Drawing.Point(631, 40);
this.lblSecondary.Name = "lblSecondary";
this.lblSecondary.Size = new System.Drawing.Size(63, 13);
this.lblSecondary.TabIndex = 107;
this.lblSecondary.Text = "Secondary:";
//
// lblHelmet
//
this.lblHelmet.AutoSize = true;
this.lblHelmet.Location = new System.Drawing.Point(646, 118);
this.lblHelmet.Name = "lblHelmet";
this.lblHelmet.Size = new System.Drawing.Size(49, 13);
this.lblHelmet.TabIndex = 105;
this.lblHelmet.Text = "Helmet: ";
//
// lblVest
//
this.lblVest.AutoSize = true;
this.lblVest.Location = new System.Drawing.Point(661, 92);
this.lblVest.Name = "lblVest";
this.lblVest.Size = new System.Drawing.Size(31, 13);
this.lblVest.TabIndex = 104;
this.lblVest.Text = "Vest:";
//
// lblGun
//
this.lblGun.AutoSize = true;
this.lblGun.Location = new System.Drawing.Point(645, 14);
this.lblGun.Name = "lblGun";
this.lblGun.Size = new System.Drawing.Size(50, 13);
this.lblGun.TabIndex = 103;
this.lblGun.Text = "Primary: ";
//
// lblMedicRank
//
this.lblMedicRank.AutoSize = true;
this.lblMedicRank.Location = new System.Drawing.Point(411, 92);
this.lblMedicRank.Name = "lblMedicRank";
this.lblMedicRank.Size = new System.Drawing.Size(62, 13);
this.lblMedicRank.TabIndex = 101;
this.lblMedicRank.Text = "R&&R Rank:";
//
// lblCopRank
//
this.lblCopRank.AutoSize = true;
this.lblCopRank.Location = new System.Drawing.Point(198, 92);
this.lblCopRank.Name = "lblCopRank";
this.lblCopRank.Size = new System.Drawing.Size(60, 13);
this.lblCopRank.TabIndex = 100;
this.lblCopRank.Text = "APD Rank:";
//
// lblGang
//
this.lblGang.AutoSize = true;
this.lblGang.Location = new System.Drawing.Point(435, 14);
this.lblGang.Name = "lblGang";
this.lblGang.Size = new System.Drawing.Size(38, 13);
this.lblGang.TabIndex = 99;
this.lblGang.Text = "Gang:";
//
// lblName
//
this.lblName.AutoSize = true;
this.lblName.Location = new System.Drawing.Point(219, 14);
this.lblName.Name = "lblName";
this.lblName.Size = new System.Drawing.Size(39, 13);
this.lblName.TabIndex = 95;
this.lblName.Text = "Name:";
//
// lblKDR
//
this.lblKDR.AutoSize = true;
this.lblKDR.Location = new System.Drawing.Point(431, 66);
this.lblKDR.Name = "lblKDR";
this.lblKDR.Size = new System.Drawing.Size(42, 13);
this.lblKDR.TabIndex = 94;
this.lblKDR.Text = "K/D/R: ";
//
// lblBounty
//
this.lblBounty.AutoSize = true;
this.lblBounty.Location = new System.Drawing.Point(212, 66);
this.lblBounty.Name = "lblBounty";
this.lblBounty.Size = new System.Drawing.Size(46, 13);
this.lblBounty.TabIndex = 98;
this.lblBounty.Text = "Bounty:";
//
// lblBank
//
this.lblBank.AutoSize = true;
this.lblBank.Location = new System.Drawing.Point(438, 40);
this.lblBank.Name = "lblBank";
this.lblBank.Size = new System.Drawing.Size(35, 13);
this.lblBank.TabIndex = 97;
this.lblBank.Text = "Bank:";
//
// lblCash
//
this.lblCash.AutoSize = true;
this.lblCash.Location = new System.Drawing.Point(223, 40);
this.lblCash.Name = "lblCash";
this.lblCash.Size = new System.Drawing.Size(35, 13);
this.lblCash.TabIndex = 96;
this.lblCash.Text = "Cash:";
//
// rpPlayerLeft
//
this.rpPlayerLeft.Controls.Add(this.rpvPlayers);
this.rpPlayerLeft.Dock = System.Windows.Forms.DockStyle.Left;
this.rpPlayerLeft.Location = new System.Drawing.Point(0, 0);
this.rpPlayerLeft.Name = "rpPlayerLeft";
this.rpPlayerLeft.Size = new System.Drawing.Size(192, 582);
this.rpPlayerLeft.TabIndex = 0;
this.rpPlayerLeft.ThemeName = "VisualStudio2012Dark";
//
// rpvPlayers
//
this.rpvPlayers.Controls.Add(this.rpvpAll);
this.rpvPlayers.Controls.Add(this.rpvpTargets);
this.rpvPlayers.Controls.Add(this.rpvpVigiable);
this.rpvPlayers.Controls.Add(this.rpvpWarTargets);
this.rpvPlayers.DefaultPage = this.rpvpAll;
this.rpvPlayers.Dock = System.Windows.Forms.DockStyle.Fill;
this.rpvPlayers.Location = new System.Drawing.Point(0, 0);
this.rpvPlayers.Name = "rpvPlayers";
this.rpvPlayers.SelectedPage = this.rpvpAll;
this.rpvPlayers.Size = new System.Drawing.Size(192, 582);
this.rpvPlayers.TabIndex = 0;
this.rpvPlayers.ThemeName = "VisualStudio2012Dark";
((Telerik.WinControls.UI.RadPageViewStripElement)(this.rpvPlayers.GetChildAt(0))).StripAlignment = Telerik.WinControls.UI.StripViewAlignment.Bottom;
//
// rpvpAll
//
this.rpvpAll.Controls.Add(this.lbPlayersAll);
this.rpvpAll.ItemSize = new System.Drawing.SizeF(25F, 24F);
this.rpvpAll.Location = new System.Drawing.Point(5, 5);
this.rpvpAll.Name = "rpvpAll";
this.rpvpAll.Size = new System.Drawing.Size(182, 547);
this.rpvpAll.Text = "All";
//
// lbPlayersAll
//
this.lbPlayersAll.Dock = System.Windows.Forms.DockStyle.Fill;
this.lbPlayersAll.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.lbPlayersAll.FormattingEnabled = true;
this.lbPlayersAll.Location = new System.Drawing.Point(0, 0);
this.lbPlayersAll.Name = "lbPlayersAll";
this.lbPlayersAll.Size = new System.Drawing.Size(182, 547);
this.lbPlayersAll.TabIndex = 1;
this.lbPlayersAll.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.ListBox_DrawItem);
this.lbPlayersAll.SelectedIndexChanged += new System.EventHandler(this.ListBox_SelectedIndexChanged);
this.lbPlayersAll.DoubleClick += new System.EventHandler(this.lbPlayersAll_DoubleClick);
this.lbPlayersAll.MouseEnter += new System.EventHandler(this.ListBox_MouseEnter);
//
// rpvpTargets
//
this.rpvpTargets.Controls.Add(this.lbPlayersTargets);
this.rpvpTargets.ItemSize = new System.Drawing.SizeF(49F, 24F);
this.rpvpTargets.Location = new System.Drawing.Point(5, 5);
this.rpvpTargets.Name = "rpvpTargets";
this.rpvpTargets.Size = new System.Drawing.Size(182, 547);
this.rpvpTargets.Text = "Targets";
//
// lbPlayersTargets
//
this.lbPlayersTargets.Dock = System.Windows.Forms.DockStyle.Fill;
this.lbPlayersTargets.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.lbPlayersTargets.FormattingEnabled = true;
this.lbPlayersTargets.Location = new System.Drawing.Point(0, 0);
this.lbPlayersTargets.Name = "lbPlayersTargets";
this.lbPlayersTargets.Size = new System.Drawing.Size(182, 547);
this.lbPlayersTargets.TabIndex = 0;
this.lbPlayersTargets.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.ListBox_DrawItem);
this.lbPlayersTargets.SelectedIndexChanged += new System.EventHandler(this.ListBox_SelectedIndexChanged);
this.lbPlayersTargets.MouseEnter += new System.EventHandler(this.ListBox_MouseEnter);
//
// rpvpVigiable
//
this.rpvpVigiable.Controls.Add(this.lbPlayersVigi);
this.rpvpVigiable.ItemSize = new System.Drawing.SizeF(31F, 24F);
this.rpvpVigiable.Location = new System.Drawing.Point(5, 5);
this.rpvpVigiable.Name = "rpvpVigiable";
this.rpvpVigiable.Size = new System.Drawing.Size(182, 547);
this.rpvpVigiable.Text = "Vigi";
//
// lbPlayersVigi
//
this.lbPlayersVigi.Dock = System.Windows.Forms.DockStyle.Fill;
this.lbPlayersVigi.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.lbPlayersVigi.FormattingEnabled = true;
this.lbPlayersVigi.Location = new System.Drawing.Point(0, 0);
this.lbPlayersVigi.Name = "lbPlayersVigi";
this.lbPlayersVigi.Size = new System.Drawing.Size(182, 547);
this.lbPlayersVigi.TabIndex = 1;
this.lbPlayersVigi.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.ListBox_DrawItem);
this.lbPlayersVigi.SelectedIndexChanged += new System.EventHandler(this.ListBox_SelectedIndexChanged);
this.lbPlayersVigi.MouseEnter += new System.EventHandler(this.ListBox_MouseEnter);
//
// rpvpWarTargets
//
this.rpvpWarTargets.Controls.Add(this.lbPlayersWT);
this.rpvpWarTargets.ItemSize = new System.Drawing.SizeF(29F, 24F);
this.rpvpWarTargets.Location = new System.Drawing.Point(5, 5);
this.rpvpWarTargets.Name = "rpvpWarTargets";
this.rpvpWarTargets.Size = new System.Drawing.Size(182, 547);
this.rpvpWarTargets.Text = "WT";
//
// lbPlayersWT
//
this.lbPlayersWT.Dock = System.Windows.Forms.DockStyle.Fill;
this.lbPlayersWT.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.lbPlayersWT.FormattingEnabled = true;
this.lbPlayersWT.Location = new System.Drawing.Point(0, 0);
this.lbPlayersWT.Name = "lbPlayersWT";
this.lbPlayersWT.Size = new System.Drawing.Size(182, 547);
this.lbPlayersWT.TabIndex = 2;
this.lbPlayersWT.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.ListBox_DrawItem);
this.lbPlayersWT.SelectedIndexChanged += new System.EventHandler(this.ListBox_SelectedIndexChanged);
this.lbPlayersWT.MouseEnter += new System.EventHandler(this.ListBox_MouseEnter);
//
// rpvpHouses
//
this.rpvpHouses.ItemSize = new System.Drawing.SizeF(24F, 49F);
this.rpvpHouses.Location = new System.Drawing.Point(30, 5);
this.rpvpHouses.Name = "rpvpHouses";
this.rpvpHouses.Size = new System.Drawing.Size(1011, 582);
this.rpvpHouses.Text = "Houses";
//
// rpvpGangs
//
this.rpvpGangs.ItemSize = new System.Drawing.SizeF(24F, 44F);
this.rpvpGangs.Location = new System.Drawing.Point(30, 5);
this.rpvpGangs.Name = "rpvpGangs";
this.rpvpGangs.Size = new System.Drawing.Size(1001, 547);
this.rpvpGangs.Text = "Gangs";
//
// rpBottom
//
this.rpBottom.Controls.Add(this.radStatusStrip1);
this.rpBottom.Dock = System.Windows.Forms.DockStyle.Bottom;
this.rpBottom.Location = new System.Drawing.Point(0, 592);
this.rpBottom.Name = "rpBottom";
this.rpBottom.Size = new System.Drawing.Size(1046, 29);
this.rpBottom.TabIndex = 1;
this.rpBottom.ThemeName = "VisualStudio2012Dark";
//
// radStatusStrip1
//
this.radStatusStrip1.Items.AddRange(new Telerik.WinControls.RadItem[] {
this.rbRefresh,
this.rtbRefresh,
this.rlRefresh,
this.commandBarSeparator1,
this.rsbServer,
this.rbMap,
this.rcb_disableAutoLocate});
this.radStatusStrip1.Location = new System.Drawing.Point(0, 3);
this.radStatusStrip1.Name = "radStatusStrip1";
this.radStatusStrip1.Padding = new System.Windows.Forms.Padding(2);
this.radStatusStrip1.Size = new System.Drawing.Size(1046, 26);
this.radStatusStrip1.TabIndex = 0;
this.radStatusStrip1.ThemeName = "VisualStudio2012Dark";
//
// rbRefresh
//
this.rbRefresh.AccessibleName = "rbRefresh";
this.rbRefresh.Margin = new System.Windows.Forms.Padding(0, 0, 5, 0);
this.rbRefresh.Name = "rbRefresh";
this.radStatusStrip1.SetSpring(this.rbRefresh, false);
this.rbRefresh.Text = "Refresh";
this.rbRefresh.Click += new System.EventHandler(this.rbRefresh_Click);
//
// rtbRefresh
//
this.rtbRefresh.AutoSize = false;
this.rtbRefresh.AutoToolTip = true;
this.rtbRefresh.Bounds = new System.Drawing.Rectangle(0, 0, 100, 18);
this.rtbRefresh.Comparer = null;
this.rtbRefresh.FitInAvailableSize = true;
this.rtbRefresh.Maximum = 180F;
this.rtbRefresh.MinSize = new System.Drawing.Size(100, 0);
this.rtbRefresh.Name = "rtbRefresh";
this.rtbRefresh.SmallChange = 5;
this.rtbRefresh.SmallTickFrequency = 5;
this.radStatusStrip1.SetSpring(this.rtbRefresh, false);
this.rtbRefresh.Text = "radTrackBarElement1";
this.rtbRefresh.ToolTipText = "15";
this.rtbRefresh.Value = 15F;
this.rtbRefresh.ValueChanged += new System.EventHandler(this.rtbRefresh_ValueChanged);
//
// rlRefresh
//
this.rlRefresh.AutoSize = false;
this.rlRefresh.Bounds = new System.Drawing.Rectangle(0, 0, 200, 18);
this.rlRefresh.Name = "rlRefresh";
this.radStatusStrip1.SetSpring(this.rlRefresh, false);
this.rlRefresh.Text = "radLabelElement1";
this.rlRefresh.TextWrap = true;
//
// commandBarSeparator1
//
this.commandBarSeparator1.Margin = new System.Windows.Forms.Padding(3);
this.commandBarSeparator1.Name = "commandBarSeparator1";
this.radStatusStrip1.SetSpring(this.commandBarSeparator1, false);
this.commandBarSeparator1.VisibleInOverflowMenu = false;
//
// rsbServer
//
this.rsbServer.ArrowButtonMinSize = new System.Drawing.Size(12, 12);
this.rsbServer.AutoSize = true;
this.rsbServer.DefaultItem = null;
this.rsbServer.DisplayStyle = Telerik.WinControls.DisplayStyle.Text;
this.rsbServer.DropDownDirection = Telerik.WinControls.UI.RadDirection.Up;
this.rsbServer.ExpandArrowButton = false;
this.rsbServer.Items.AddRange(new Telerik.WinControls.RadItem[] {
this.rmiServer1,
this.rmiServer2});
this.rsbServer.Margin = new System.Windows.Forms.Padding(3, 0, 5, 0);
this.rsbServer.Name = "rsbServer";
this.rsbServer.Padding = new System.Windows.Forms.Padding(-1);
this.radStatusStrip1.SetSpring(this.rsbServer, false);
this.rsbServer.Text = "Server";
//
// rmiServer1
//
this.rmiServer1.AccessibleName = "rmiServer1";
this.rmiServer1.Name = "rmiServer1";
this.rmiServer1.Text = "Server 1";
this.rmiServer1.Click += new System.EventHandler(this.rsbServer_Click);
//
// rmiServer2
//
this.rmiServer2.AccessibleName = "rmiServer2";
this.rmiServer2.Name = "rmiServer2";
this.rmiServer2.Text = "Server 2";
this.rmiServer2.Click += new System.EventHandler(this.rsbServer_Click);
//
// rbMap
//
this.rbMap.Name = "rbMap";
this.radStatusStrip1.SetSpring(this.rbMap, false);
this.rbMap.Text = "Map";
this.rbMap.Click += new System.EventHandler(this.rbMap_Click);
//
// rcb_disableAutoLocate
//
this.rcb_disableAutoLocate.Checked = false;
this.rcb_disableAutoLocate.Name = "rcb_disableAutoLocate";
this.rcb_disableAutoLocate.ReadOnly = false;
this.radStatusStrip1.SetSpring(this.rcb_disableAutoLocate, false);
this.rcb_disableAutoLocate.Text = "Disable Autolocate?";
this.rcb_disableAutoLocate.CheckStateChanged += new System.EventHandler(this.rcb_disableAutoLocate_CheckStateChanged);
//
// rpMain
//
this.rpMain.Controls.Add(this.rpvMain);
this.rpMain.Dock = System.Windows.Forms.DockStyle.Fill;
this.rpMain.Location = new System.Drawing.Point(0, 0);
this.rpMain.Name = "rpMain";
this.rpMain.Size = new System.Drawing.Size(1046, 592);
this.rpMain.TabIndex = 2;
this.rpMain.ThemeName = "VisualStudio2012Dark";
//
// timerMain
//
this.timerMain.Interval = 1000;
this.timerMain.Tick += new System.EventHandler(this.timerMain_Tick);
//
// bwPlayerTabRefresh
//
this.bwPlayerTabRefresh.WorkerReportsProgress = true;
this.bwPlayerTabRefresh.DoWork += new System.ComponentModel.DoWorkEventHandler(this.bwPlayerTabRefresh_DoWork);
this.bwPlayerTabRefresh.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.bwPlayerTabRefresh_RunWorkerCompleted);
//
// RfMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1046, 621);
this.Controls.Add(this.rpMain);
this.Controls.Add(this.rpBottom);
this.Name = "RfMain";
//
//
//
this.RootElement.ApplyShapeToControl = true;
this.Text = "";
this.ThemeName = "VisualStudio2012Dark";
this.Load += new System.EventHandler(this.rfMain_Load);
((System.ComponentModel.ISupportInitialize)(this.rpvMain)).EndInit();
this.rpvMain.ResumeLayout(false);
this.rpvpPlayers.ResumeLayout(false);
this.rpvpPlayers.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.rtebVehicleInfo)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.rlvVirItems)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.rlcVehicles)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.rbtbAliases)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.rgbLocation)).EndInit();
this.rgbLocation.ResumeLayout(false);
this.rgbLocation.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.rpMap)).EndInit();
this.rpMap.ResumeLayout(false);
this.rpMap.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pbMap)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.rtrbZoom)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.rpPlayerLeft)).EndInit();
this.rpPlayerLeft.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.rpvPlayers)).EndInit();
this.rpvPlayers.ResumeLayout(false);
this.rpvpAll.ResumeLayout(false);
this.rpvpTargets.ResumeLayout(false);
this.rpvpVigiable.ResumeLayout(false);
this.rpvpWarTargets.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.rpBottom)).EndInit();
this.rpBottom.ResumeLayout(false);
this.rpBottom.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.radStatusStrip1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.rpMain)).EndInit();
this.rpMain.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
this.ResumeLayout(false);
}
#endregion
private Telerik.WinControls.Themes.VisualStudio2012DarkTheme rtVSDark;
private Telerik.WinControls.UI.RadPageView rpvMain;
private Telerik.WinControls.UI.RadPanel rpBottom;
private Telerik.WinControls.UI.RadPanel rpMain;
private Telerik.WinControls.UI.RadPageViewPage rpvpPlayers;
private Telerik.WinControls.UI.RadPageViewPage rpvpHouses;
private Telerik.WinControls.UI.RadPageViewPage rpvpGangs;
private Telerik.WinControls.UI.RadPanel rpPlayerLeft;
private System.Windows.Forms.Label lblLauncher;
private System.Windows.Forms.Label lblSecondary;
private System.Windows.Forms.Label lblLocation;
private System.Windows.Forms.Label lblHelmet;
private System.Windows.Forms.Label lblVest;
private System.Windows.Forms.Label lblGun;
private System.Windows.Forms.Label lblMedicRank;
private System.Windows.Forms.Label lblCopRank;
private System.Windows.Forms.Label lblGang;
private System.Windows.Forms.Label lblName;
private System.Windows.Forms.Label lblKDR;
private System.Windows.Forms.Label lblBounty;
private System.Windows.Forms.Label lblBank;
private System.Windows.Forms.Label lblCash;
private System.Windows.Forms.Label lblVVirtuals;
private System.Windows.Forms.Label lblVehicles;
private System.Windows.Forms.Label lblVirtuals;
private System.Windows.Forms.Label lblAliases;
private Telerik.WinControls.UI.RadStatusStrip radStatusStrip1;
private Telerik.WinControls.UI.RadPageView rpvPlayers;
private Telerik.WinControls.UI.RadPageViewPage rpvpTargets;
private Telerik.WinControls.UI.RadListView rlvVirItems;
private Telerik.WinControls.UI.RadListControl rlcVehicles;
private Telerik.WinControls.UI.RadButtonTextBox rbtbAliases;
private Telerik.WinControls.UI.RadGroupBox rgbLocation;
private Telerik.WinControls.UI.RadTrackBar rtrbZoom;
private System.Windows.Forms.Timer timerMain;
private System.ComponentModel.BackgroundWorker bwPlayerTabRefresh;
private Telerik.WinControls.UI.RadButtonElement rbRefresh;
private Telerik.WinControls.UI.RadLabelElement rlRefresh;
private Telerik.WinControls.UI.CommandBarSeparator commandBarSeparator1;
private Telerik.WinControls.UI.RadSplitButtonElement rsbServer;
private Telerik.WinControls.UI.RadButtonElement rbMap;
private Telerik.WinControls.UI.RadTrackBarElement rtbRefresh;
private Telerik.WinControls.UI.RadMenuItem rmiServer1;
private Telerik.WinControls.UI.RadMenuItem rmiServer2;
private Telerik.WinControls.UI.RadPageViewPage rpvpAll;
private System.Windows.Forms.ListBox lbPlayersAll;
private System.Windows.Forms.ListBox lbPlayersTargets;
private Telerik.WinControls.UI.RadTextBox rtebVehicleInfo;
private System.Windows.Forms.LinkLabel lblSteamID;
private System.Windows.Forms.LinkLabel lblBM;
private System.Windows.Forms.PictureBox pbMap;
private Telerik.WinControls.UI.RadPanel rpMap;
private Telerik.WinControls.UI.RadPageViewPage rpvpVigiable;
private Telerik.WinControls.UI.RadPageViewPage rpvpWarTargets;
private System.Windows.Forms.ListBox lbPlayersWT;
private System.Windows.Forms.ListBox lbPlayersVigi;
private Telerik.WinControls.UI.RadCheckBoxElement rcb_disableAutoLocate;
}
}
| 51.898345 | 160 | 0.614495 | [
"MIT"
] | Raykazi/OT | TrackerClient/RadForm1.Designer.cs | 43,908 | C# |
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MyMovieDb.App.Controllers;
using MyMovieDb.Common.Constants;
namespace MyMovieDb.App.Areas.Moderator.Controllers
{
[Area("Moderator")]
[Authorize(Roles = "Admin, Moderator")]
public class HomeController : BaseController
{
[HttpGet]
public IActionResult Index()
{
return this.View();
}
}
} | 22.894737 | 51 | 0.671264 | [
"MIT"
] | IvelinMarinov/CSharp.MVC.Project.Assignment | MyMovieDb/MyMovieDb.App/Areas/Moderator/Controllers/HomeController.cs | 437 | C# |
namespace BashSoft.Contracts
{
using System.Collections.Generic;
public interface IDataFilter
{
void FilterAndTake(Dictionary<string, double> studentsWithMarks, string wantedFilter, int studentToTake);
}
}
| 23.2 | 113 | 0.737069 | [
"MIT"
] | maio246/BashSoft | BashSoft/Contracts/IDataFilter.cs | 234 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("GRASP2OptBest4QAP")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| 36.37037 | 82 | 0.744399 | [
"MIT"
] | yasserglez/metaheuristics | Problems/QAP/GRASP2OptBest4QAP/AssemblyInfo.cs | 982 | C# |
using System;
using ETModel;
using UnityEngine;
namespace ETHotfix
{
[ObjectSystem]
public class OperaComponentAwakeSystem : AwakeSystem<OperaComponent>
{
public override void Awake(OperaComponent self)
{
self.Awake();
}
}
[ObjectSystem]
public class OperaComponentUpdateSystem : UpdateSystem<OperaComponent>
{
public override void Update(OperaComponent self)
{
self.Update();
}
}
/// <summary>
/// map场景 运行组件
/// </summary>
public class OperaComponent: Component
{
public Vector3 ClickPoint;
public int mapMask;
public void Awake()
{
this.mapMask = LayerMask.GetMask("Map");
}
private readonly Frame_ClickMap frameClickMap = new Frame_ClickMap();
public void Update()
{
if (Input.GetMouseButtonDown(1))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 1000, this.mapMask))
{
this.ClickPoint = hit.point;
frameClickMap.X = this.ClickPoint.x;
frameClickMap.Y = this.ClickPoint.y;
frameClickMap.Z = this.ClickPoint.z;
ETModel.SessionComponent.Instance.Session.Send(frameClickMap);
// 测试actor rpc消息
this.TestActor().Coroutine();
}
}
}
public async ETVoid TestActor()
{
try
{
M2C_TestActorResponse response = (M2C_TestActorResponse)await SessionComponent.Instance.Session.Call(
new C2M_TestActorRequest() { Info = "actor rpc request" });
Log.Info(response.Info);
}
catch (Exception e)
{
Log.Error(e);
}
}
}
}
| 23.333333 | 108 | 0.601714 | [
"MIT"
] | Tqqingtian/ETFlashTest | Unity/Assets/Hotfix/Module/Demo/OtherComponent/OperaComponent.cs | 1,772 | C# |
using Kingmaker.Blueprints;
using System.Collections.Generic;
using System.Linq;
using HarmonyLib;
using Kingmaker.UnitLogic.Class.Kineticist;
using Kingmaker.UnitLogic;
using Kingmaker.EntitySystem.Entities;
using Kingmaker.Items.Slots;
using Kingmaker.UnitLogic.Buffs;
using Kingmaker.UnitLogic.FactLogic;
namespace DarkCodex
{
[PatchInfo(Severity.Harmony, "Patch: Kineticist Allow Opportunity Attack", "allows Attack of Opportunities with anything but standard Kinetic Blade; so that Kinetic Whip works; also allows natural attacks to be used, if Whip isn't available", false)]
[HarmonyPatch]
public class Patch_KineticistAllowOpportunityAttack
{
private static BlueprintGuid blade_p = BlueprintGuid.Parse("b05a206f6c1133a469b2f7e30dc970ef"); //KineticBlastPhysicalBlade
private static BlueprintGuid blade_e = BlueprintGuid.Parse("a15b2fb1d5dc4f247882a7148d50afb0"); //KineticBlastEnergyBlade
[HarmonyPatch(typeof(AddKineticistBlade), nameof(AddKineticistBlade.OnActivate))]
[HarmonyTranspiler]
public static IEnumerable<CodeInstruction> Transpiler1(IEnumerable<CodeInstruction> instr)
{
List<CodeInstruction> list = instr.ToList();
var original = AccessTools.Method(typeof(UnitState), nameof(UnitState.AddCondition));
for (int i = 0; i < list.Count; i++)
{
if (list[i].Calls(original))
{
Helper.PrintDebug("Patched at " + i);
list[i] = CodeInstruction.Call(typeof(Patch_KineticistAllowOpportunityAttack), nameof(NullReplacement));
}
}
return list;
}
public static void NullReplacement(UnitState state, UnitCondition condition, Buff sourceBuff, UnitConditionExceptions exceptions)
{
}
[HarmonyPatch(typeof(UnitHelper), nameof(UnitHelper.IsThreatHand))]
[HarmonyPrefix]
public static bool Prefix2(UnitEntityData unit, WeaponSlot hand, ref bool __result)
{
if (!hand.HasWeapon)
__result = false;
else if (!hand.Weapon.Blueprint.IsMelee && !unit.State.Features.SnapShot)
__result = false;
else if (hand.Weapon.Blueprint.IsUnarmed && !unit.Descriptor.State.Features.ImprovedUnarmedStrike)
__result = false;
else if ((hand.Weapon.Blueprint.Type.AssetGuid == blade_p || hand.Weapon.Blueprint.Type.AssetGuid == blade_e)
&& unit.Buffs.GetBuff(Resource.Cache.BuffKineticWhip) == null)
__result = false;
else
__result = true;
return false;
}
}
//[HarmonyPatch(typeof(KineticistController), nameof(KineticistController.TryRunKineticBladeActivationAction))]
//public class Patch_KineticistWhipReach
//{
// public static void Postfix(UnitPartKineticist kineticist, UnitCommand cmd, bool __result)
// {
// if (!__result)
// return;
// if (kineticist.Owner.Buffs.GetBuff(Patch_KineticistAllowOpportunityAttack2.whip_buff) == null)
// return;
// cmd.ApproachRadius += 5f * 0.3048f;
// }
//}
}
| 40.333333 | 254 | 0.657484 | [
"MIT"
] | Truinto/DarkCodex | DarkCodex/Patches/Patch_KineticistAllowOpportunityAttack.cs | 3,269 | C# |
#pragma warning disable CS1591
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.ComponentModel;
namespace Efl {
namespace Ui {
/// <summary>Tab Bar class</summary>
[Efl.Ui.TabBar.NativeMethods]
public class TabBar : Efl.Ui.LayoutBase, Efl.Eo.IWrapper,Efl.Ui.IClickable
{
///<summary>Pointer to the native class description.</summary>
public override System.IntPtr NativeClass
{
get
{
if (((object)this).GetType() == typeof(TabBar))
{
return GetEflClassStatic();
}
else
{
return Efl.Eo.ClassRegister.klassFromType[((object)this).GetType()];
}
}
}
[System.Runtime.InteropServices.DllImport(efl.Libs.Elementary)] internal static extern System.IntPtr
efl_ui_tab_bar_class_get();
/// <summary>Initializes a new instance of the <see cref="TabBar"/> class.</summary>
/// <param name="parent">Parent instance.</param>
/// <param name="style">The widget style to use. See <see cref="Efl.Ui.Widget.SetStyle"/></param>
public TabBar(Efl.Object parent
, System.String style = null) : base(efl_ui_tab_bar_class_get(), typeof(TabBar), parent)
{
if (Efl.Eo.Globals.ParamHelperCheck(style))
{
SetStyle(Efl.Eo.Globals.GetParamHelper(style));
}
FinishInstantiation();
}
/// <summary>Initializes a new instance of the <see cref="TabBar"/> class.
/// Internal usage: Constructs an instance from a native pointer. This is used when interacting with C code and should not be used directly.</summary>
/// <param name="raw">The native pointer to be wrapped.</param>
protected TabBar(System.IntPtr raw) : base(raw)
{
}
/// <summary>Initializes a new instance of the <see cref="TabBar"/> class.
/// Internal usage: Constructor to forward the wrapper initialization to the root class that interfaces with native code. Should not be used directly.</summary>
/// <param name="baseKlass">The pointer to the base native Eo class.</param>
/// <param name="managedType">The managed type of the public constructor that originated this call.</param>
/// <param name="parent">The Efl.Object parent of this instance.</param>
protected TabBar(IntPtr baseKlass, System.Type managedType, Efl.Object parent) : base(baseKlass, managedType, parent)
{
}
/// <summary>Verifies if the given object is equal to this one.</summary>
/// <param name="instance">The object to compare to.</param>
/// <returns>True if both objects point to the same native object.</returns>
public override bool Equals(object instance)
{
var other = instance as Efl.Object;
if (other == null)
{
return false;
}
return this.NativeHandle == other.NativeHandle;
}
/// <summary>Gets the hash code for this object based on the native pointer it points to.</summary>
/// <returns>The value of the pointer, to be used as the hash code of this object.</returns>
public override int GetHashCode()
{
return this.NativeHandle.ToInt32();
}
/// <summary>Turns the native pointer into a string representation.</summary>
/// <returns>A string with the type and the native pointer for this object.</returns>
public override String ToString()
{
return $"{this.GetType().Name}@[{this.NativeHandle.ToInt32():x}]";
}
/// <summary>Called when object is clicked</summary>
public event EventHandler ClickedEvt
{
add
{
lock (eventLock)
{
var wRef = new WeakReference(this);
Efl.EventCb callerCb = (IntPtr data, ref Efl.Event.NativeStruct evt) =>
{
var obj = wRef.Target as Efl.Eo.IWrapper;
if (obj != null)
{
EventArgs args = EventArgs.Empty;
try
{
value?.Invoke(obj, args);
}
catch (Exception e)
{
Eina.Log.Error(e.ToString());
Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION);
}
}
};
string key = "_EFL_UI_EVENT_CLICKED";
AddNativeEventHandler(efl.Libs.Efl, key, callerCb, value);
}
}
remove
{
lock (eventLock)
{
string key = "_EFL_UI_EVENT_CLICKED";
RemoveNativeEventHandler(efl.Libs.Efl, key, value);
}
}
}
///<summary>Method to raise event ClickedEvt.</summary>
public void OnClickedEvt(EventArgs e)
{
var key = "_EFL_UI_EVENT_CLICKED";
IntPtr desc = Efl.EventDescription.GetNative(efl.Libs.Efl, key);
if (desc == IntPtr.Zero)
{
Eina.Log.Error($"Failed to get native event {key}");
return;
}
Efl.Eo.Globals.efl_event_callback_call(this.NativeHandle, desc, IntPtr.Zero);
}
/// <summary>Called when object receives a double click</summary>
public event EventHandler ClickedDoubleEvt
{
add
{
lock (eventLock)
{
var wRef = new WeakReference(this);
Efl.EventCb callerCb = (IntPtr data, ref Efl.Event.NativeStruct evt) =>
{
var obj = wRef.Target as Efl.Eo.IWrapper;
if (obj != null)
{
EventArgs args = EventArgs.Empty;
try
{
value?.Invoke(obj, args);
}
catch (Exception e)
{
Eina.Log.Error(e.ToString());
Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION);
}
}
};
string key = "_EFL_UI_EVENT_CLICKED_DOUBLE";
AddNativeEventHandler(efl.Libs.Efl, key, callerCb, value);
}
}
remove
{
lock (eventLock)
{
string key = "_EFL_UI_EVENT_CLICKED_DOUBLE";
RemoveNativeEventHandler(efl.Libs.Efl, key, value);
}
}
}
///<summary>Method to raise event ClickedDoubleEvt.</summary>
public void OnClickedDoubleEvt(EventArgs e)
{
var key = "_EFL_UI_EVENT_CLICKED_DOUBLE";
IntPtr desc = Efl.EventDescription.GetNative(efl.Libs.Efl, key);
if (desc == IntPtr.Zero)
{
Eina.Log.Error($"Failed to get native event {key}");
return;
}
Efl.Eo.Globals.efl_event_callback_call(this.NativeHandle, desc, IntPtr.Zero);
}
/// <summary>Called when object receives a triple click</summary>
public event EventHandler ClickedTripleEvt
{
add
{
lock (eventLock)
{
var wRef = new WeakReference(this);
Efl.EventCb callerCb = (IntPtr data, ref Efl.Event.NativeStruct evt) =>
{
var obj = wRef.Target as Efl.Eo.IWrapper;
if (obj != null)
{
EventArgs args = EventArgs.Empty;
try
{
value?.Invoke(obj, args);
}
catch (Exception e)
{
Eina.Log.Error(e.ToString());
Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION);
}
}
};
string key = "_EFL_UI_EVENT_CLICKED_TRIPLE";
AddNativeEventHandler(efl.Libs.Efl, key, callerCb, value);
}
}
remove
{
lock (eventLock)
{
string key = "_EFL_UI_EVENT_CLICKED_TRIPLE";
RemoveNativeEventHandler(efl.Libs.Efl, key, value);
}
}
}
///<summary>Method to raise event ClickedTripleEvt.</summary>
public void OnClickedTripleEvt(EventArgs e)
{
var key = "_EFL_UI_EVENT_CLICKED_TRIPLE";
IntPtr desc = Efl.EventDescription.GetNative(efl.Libs.Efl, key);
if (desc == IntPtr.Zero)
{
Eina.Log.Error($"Failed to get native event {key}");
return;
}
Efl.Eo.Globals.efl_event_callback_call(this.NativeHandle, desc, IntPtr.Zero);
}
/// <summary>Called when object receives a right click</summary>
public event EventHandler<Efl.Ui.IClickableClickedRightEvt_Args> ClickedRightEvt
{
add
{
lock (eventLock)
{
var wRef = new WeakReference(this);
Efl.EventCb callerCb = (IntPtr data, ref Efl.Event.NativeStruct evt) =>
{
var obj = wRef.Target as Efl.Eo.IWrapper;
if (obj != null)
{
Efl.Ui.IClickableClickedRightEvt_Args args = new Efl.Ui.IClickableClickedRightEvt_Args();
args.arg = (Efl.Eo.Globals.CreateWrapperFor(evt.Info) as Efl.Object);
try
{
value?.Invoke(obj, args);
}
catch (Exception e)
{
Eina.Log.Error(e.ToString());
Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION);
}
}
};
string key = "_EFL_UI_EVENT_CLICKED_RIGHT";
AddNativeEventHandler(efl.Libs.Efl, key, callerCb, value);
}
}
remove
{
lock (eventLock)
{
string key = "_EFL_UI_EVENT_CLICKED_RIGHT";
RemoveNativeEventHandler(efl.Libs.Efl, key, value);
}
}
}
///<summary>Method to raise event ClickedRightEvt.</summary>
public void OnClickedRightEvt(Efl.Ui.IClickableClickedRightEvt_Args e)
{
var key = "_EFL_UI_EVENT_CLICKED_RIGHT";
IntPtr desc = Efl.EventDescription.GetNative(efl.Libs.Efl, key);
if (desc == IntPtr.Zero)
{
Eina.Log.Error($"Failed to get native event {key}");
return;
}
IntPtr info = e.arg.NativeHandle;
Efl.Eo.Globals.efl_event_callback_call(this.NativeHandle, desc, info);
}
/// <summary>Called when the object is pressed</summary>
public event EventHandler<Efl.Ui.IClickablePressedEvt_Args> PressedEvt
{
add
{
lock (eventLock)
{
var wRef = new WeakReference(this);
Efl.EventCb callerCb = (IntPtr data, ref Efl.Event.NativeStruct evt) =>
{
var obj = wRef.Target as Efl.Eo.IWrapper;
if (obj != null)
{
Efl.Ui.IClickablePressedEvt_Args args = new Efl.Ui.IClickablePressedEvt_Args();
args.arg = (Efl.Eo.Globals.CreateWrapperFor(evt.Info) as Efl.Object);
try
{
value?.Invoke(obj, args);
}
catch (Exception e)
{
Eina.Log.Error(e.ToString());
Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION);
}
}
};
string key = "_EFL_UI_EVENT_PRESSED";
AddNativeEventHandler(efl.Libs.Efl, key, callerCb, value);
}
}
remove
{
lock (eventLock)
{
string key = "_EFL_UI_EVENT_PRESSED";
RemoveNativeEventHandler(efl.Libs.Efl, key, value);
}
}
}
///<summary>Method to raise event PressedEvt.</summary>
public void OnPressedEvt(Efl.Ui.IClickablePressedEvt_Args e)
{
var key = "_EFL_UI_EVENT_PRESSED";
IntPtr desc = Efl.EventDescription.GetNative(efl.Libs.Efl, key);
if (desc == IntPtr.Zero)
{
Eina.Log.Error($"Failed to get native event {key}");
return;
}
IntPtr info = e.arg.NativeHandle;
Efl.Eo.Globals.efl_event_callback_call(this.NativeHandle, desc, info);
}
/// <summary>Called when the object is no longer pressed</summary>
public event EventHandler<Efl.Ui.IClickableUnpressedEvt_Args> UnpressedEvt
{
add
{
lock (eventLock)
{
var wRef = new WeakReference(this);
Efl.EventCb callerCb = (IntPtr data, ref Efl.Event.NativeStruct evt) =>
{
var obj = wRef.Target as Efl.Eo.IWrapper;
if (obj != null)
{
Efl.Ui.IClickableUnpressedEvt_Args args = new Efl.Ui.IClickableUnpressedEvt_Args();
args.arg = (Efl.Eo.Globals.CreateWrapperFor(evt.Info) as Efl.Object);
try
{
value?.Invoke(obj, args);
}
catch (Exception e)
{
Eina.Log.Error(e.ToString());
Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION);
}
}
};
string key = "_EFL_UI_EVENT_UNPRESSED";
AddNativeEventHandler(efl.Libs.Efl, key, callerCb, value);
}
}
remove
{
lock (eventLock)
{
string key = "_EFL_UI_EVENT_UNPRESSED";
RemoveNativeEventHandler(efl.Libs.Efl, key, value);
}
}
}
///<summary>Method to raise event UnpressedEvt.</summary>
public void OnUnpressedEvt(Efl.Ui.IClickableUnpressedEvt_Args e)
{
var key = "_EFL_UI_EVENT_UNPRESSED";
IntPtr desc = Efl.EventDescription.GetNative(efl.Libs.Efl, key);
if (desc == IntPtr.Zero)
{
Eina.Log.Error($"Failed to get native event {key}");
return;
}
IntPtr info = e.arg.NativeHandle;
Efl.Eo.Globals.efl_event_callback_call(this.NativeHandle, desc, info);
}
/// <summary>Called when the object receives a long press</summary>
public event EventHandler<Efl.Ui.IClickableLongpressedEvt_Args> LongpressedEvt
{
add
{
lock (eventLock)
{
var wRef = new WeakReference(this);
Efl.EventCb callerCb = (IntPtr data, ref Efl.Event.NativeStruct evt) =>
{
var obj = wRef.Target as Efl.Eo.IWrapper;
if (obj != null)
{
Efl.Ui.IClickableLongpressedEvt_Args args = new Efl.Ui.IClickableLongpressedEvt_Args();
args.arg = (Efl.Eo.Globals.CreateWrapperFor(evt.Info) as Efl.Object);
try
{
value?.Invoke(obj, args);
}
catch (Exception e)
{
Eina.Log.Error(e.ToString());
Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION);
}
}
};
string key = "_EFL_UI_EVENT_LONGPRESSED";
AddNativeEventHandler(efl.Libs.Efl, key, callerCb, value);
}
}
remove
{
lock (eventLock)
{
string key = "_EFL_UI_EVENT_LONGPRESSED";
RemoveNativeEventHandler(efl.Libs.Efl, key, value);
}
}
}
///<summary>Method to raise event LongpressedEvt.</summary>
public void OnLongpressedEvt(Efl.Ui.IClickableLongpressedEvt_Args e)
{
var key = "_EFL_UI_EVENT_LONGPRESSED";
IntPtr desc = Efl.EventDescription.GetNative(efl.Libs.Efl, key);
if (desc == IntPtr.Zero)
{
Eina.Log.Error($"Failed to get native event {key}");
return;
}
IntPtr info = e.arg.NativeHandle;
Efl.Eo.Globals.efl_event_callback_call(this.NativeHandle, desc, info);
}
/// <summary>Called when the object receives repeated presses/clicks</summary>
public event EventHandler RepeatedEvt
{
add
{
lock (eventLock)
{
var wRef = new WeakReference(this);
Efl.EventCb callerCb = (IntPtr data, ref Efl.Event.NativeStruct evt) =>
{
var obj = wRef.Target as Efl.Eo.IWrapper;
if (obj != null)
{
EventArgs args = EventArgs.Empty;
try
{
value?.Invoke(obj, args);
}
catch (Exception e)
{
Eina.Log.Error(e.ToString());
Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION);
}
}
};
string key = "_EFL_UI_EVENT_REPEATED";
AddNativeEventHandler(efl.Libs.Efl, key, callerCb, value);
}
}
remove
{
lock (eventLock)
{
string key = "_EFL_UI_EVENT_REPEATED";
RemoveNativeEventHandler(efl.Libs.Efl, key, value);
}
}
}
///<summary>Method to raise event RepeatedEvt.</summary>
public void OnRepeatedEvt(EventArgs e)
{
var key = "_EFL_UI_EVENT_REPEATED";
IntPtr desc = Efl.EventDescription.GetNative(efl.Libs.Efl, key);
if (desc == IntPtr.Zero)
{
Eina.Log.Error($"Failed to get native event {key}");
return;
}
Efl.Eo.Globals.efl_event_callback_call(this.NativeHandle, desc, IntPtr.Zero);
}
virtual public int GetCurrentTab() {
var _ret_var = Efl.Ui.TabBar.NativeMethods.efl_ui_tab_bar_current_tab_get_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle));
Eina.Error.RaiseIfUnhandledException();
return _ret_var;
}
virtual public void SetCurrentTab(int index) {
Efl.Ui.TabBar.NativeMethods.efl_ui_tab_bar_current_tab_set_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle),index);
Eina.Error.RaiseIfUnhandledException();
}
virtual public uint TabCount() {
var _ret_var = Efl.Ui.TabBar.NativeMethods.efl_ui_tab_bar_tab_count_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle));
Eina.Error.RaiseIfUnhandledException();
return _ret_var;
}
virtual public void AddTab(int index, System.String label, System.String icon) {
Efl.Ui.TabBar.NativeMethods.efl_ui_tab_bar_tab_add_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle),index, label, icon);
Eina.Error.RaiseIfUnhandledException();
}
virtual public void TabRemove(int index) {
Efl.Ui.TabBar.NativeMethods.efl_ui_tab_bar_tab_remove_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle),index);
Eina.Error.RaiseIfUnhandledException();
}
virtual public void SetTabLabel(int index, System.String label) {
Efl.Ui.TabBar.NativeMethods.efl_ui_tab_bar_tab_label_set_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle),index, label);
Eina.Error.RaiseIfUnhandledException();
}
virtual public void SetTabIcon(int index, System.String icon) {
Efl.Ui.TabBar.NativeMethods.efl_ui_tab_bar_tab_icon_set_ptr.Value.Delegate((inherited ? Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass) : this.NativeHandle),index, icon);
Eina.Error.RaiseIfUnhandledException();
}
public int CurrentTab {
get { return GetCurrentTab(); }
set { SetCurrentTab(value); }
}
private static IntPtr GetEflClassStatic()
{
return Efl.Ui.TabBar.efl_ui_tab_bar_class_get();
}
/// <summary>Wrapper for native methods and virtual method delegates.
/// For internal use by generated code only.</summary>
public new class NativeMethods : Efl.Ui.LayoutBase.NativeMethods
{
private static Efl.Eo.NativeModule Module = new Efl.Eo.NativeModule( efl.Libs.Elementary);
/// <summary>Gets the list of Eo operations to override.</summary>
/// <returns>The list of Eo operations to be overload.</returns>
public override System.Collections.Generic.List<Efl_Op_Description> GetEoOps(System.Type type)
{
var descs = new System.Collections.Generic.List<Efl_Op_Description>();
var methods = Efl.Eo.Globals.GetUserMethods(type);
if (efl_ui_tab_bar_current_tab_get_static_delegate == null)
{
efl_ui_tab_bar_current_tab_get_static_delegate = new efl_ui_tab_bar_current_tab_get_delegate(current_tab_get);
}
if (methods.FirstOrDefault(m => m.Name == "GetCurrentTab") != null)
{
descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(Module.Module, "efl_ui_tab_bar_current_tab_get"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_tab_bar_current_tab_get_static_delegate) });
}
if (efl_ui_tab_bar_current_tab_set_static_delegate == null)
{
efl_ui_tab_bar_current_tab_set_static_delegate = new efl_ui_tab_bar_current_tab_set_delegate(current_tab_set);
}
if (methods.FirstOrDefault(m => m.Name == "SetCurrentTab") != null)
{
descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(Module.Module, "efl_ui_tab_bar_current_tab_set"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_tab_bar_current_tab_set_static_delegate) });
}
if (efl_ui_tab_bar_tab_count_static_delegate == null)
{
efl_ui_tab_bar_tab_count_static_delegate = new efl_ui_tab_bar_tab_count_delegate(tab_count);
}
if (methods.FirstOrDefault(m => m.Name == "TabCount") != null)
{
descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(Module.Module, "efl_ui_tab_bar_tab_count"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_tab_bar_tab_count_static_delegate) });
}
if (efl_ui_tab_bar_tab_add_static_delegate == null)
{
efl_ui_tab_bar_tab_add_static_delegate = new efl_ui_tab_bar_tab_add_delegate(tab_add);
}
if (methods.FirstOrDefault(m => m.Name == "AddTab") != null)
{
descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(Module.Module, "efl_ui_tab_bar_tab_add"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_tab_bar_tab_add_static_delegate) });
}
if (efl_ui_tab_bar_tab_remove_static_delegate == null)
{
efl_ui_tab_bar_tab_remove_static_delegate = new efl_ui_tab_bar_tab_remove_delegate(tab_remove);
}
if (methods.FirstOrDefault(m => m.Name == "TabRemove") != null)
{
descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(Module.Module, "efl_ui_tab_bar_tab_remove"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_tab_bar_tab_remove_static_delegate) });
}
if (efl_ui_tab_bar_tab_label_set_static_delegate == null)
{
efl_ui_tab_bar_tab_label_set_static_delegate = new efl_ui_tab_bar_tab_label_set_delegate(tab_label_set);
}
if (methods.FirstOrDefault(m => m.Name == "SetTabLabel") != null)
{
descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(Module.Module, "efl_ui_tab_bar_tab_label_set"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_tab_bar_tab_label_set_static_delegate) });
}
if (efl_ui_tab_bar_tab_icon_set_static_delegate == null)
{
efl_ui_tab_bar_tab_icon_set_static_delegate = new efl_ui_tab_bar_tab_icon_set_delegate(tab_icon_set);
}
if (methods.FirstOrDefault(m => m.Name == "SetTabIcon") != null)
{
descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(Module.Module, "efl_ui_tab_bar_tab_icon_set"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_tab_bar_tab_icon_set_static_delegate) });
}
descs.AddRange(base.GetEoOps(type));
return descs;
}
/// <summary>Returns the Eo class for the native methods of this class.</summary>
/// <returns>The native class pointer.</returns>
public override IntPtr GetEflClass()
{
return Efl.Ui.TabBar.efl_ui_tab_bar_class_get();
}
#pragma warning disable CA1707, SA1300, SA1600
private delegate int efl_ui_tab_bar_current_tab_get_delegate(System.IntPtr obj, System.IntPtr pd);
public delegate int efl_ui_tab_bar_current_tab_get_api_delegate(System.IntPtr obj);
public static Efl.Eo.FunctionWrapper<efl_ui_tab_bar_current_tab_get_api_delegate> efl_ui_tab_bar_current_tab_get_ptr = new Efl.Eo.FunctionWrapper<efl_ui_tab_bar_current_tab_get_api_delegate>(Module, "efl_ui_tab_bar_current_tab_get");
private static int current_tab_get(System.IntPtr obj, System.IntPtr pd)
{
Eina.Log.Debug("function efl_ui_tab_bar_current_tab_get was called");
Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd);
if (wrapper != null)
{
int _ret_var = default(int);
try
{
_ret_var = ((TabBar)wrapper).GetCurrentTab();
}
catch (Exception e)
{
Eina.Log.Warning($"Callback error: {e.ToString()}");
Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION);
}
return _ret_var;
}
else
{
return efl_ui_tab_bar_current_tab_get_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)));
}
}
private static efl_ui_tab_bar_current_tab_get_delegate efl_ui_tab_bar_current_tab_get_static_delegate;
private delegate void efl_ui_tab_bar_current_tab_set_delegate(System.IntPtr obj, System.IntPtr pd, int index);
public delegate void efl_ui_tab_bar_current_tab_set_api_delegate(System.IntPtr obj, int index);
public static Efl.Eo.FunctionWrapper<efl_ui_tab_bar_current_tab_set_api_delegate> efl_ui_tab_bar_current_tab_set_ptr = new Efl.Eo.FunctionWrapper<efl_ui_tab_bar_current_tab_set_api_delegate>(Module, "efl_ui_tab_bar_current_tab_set");
private static void current_tab_set(System.IntPtr obj, System.IntPtr pd, int index)
{
Eina.Log.Debug("function efl_ui_tab_bar_current_tab_set was called");
Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd);
if (wrapper != null)
{
try
{
((TabBar)wrapper).SetCurrentTab(index);
}
catch (Exception e)
{
Eina.Log.Warning($"Callback error: {e.ToString()}");
Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION);
}
}
else
{
efl_ui_tab_bar_current_tab_set_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), index);
}
}
private static efl_ui_tab_bar_current_tab_set_delegate efl_ui_tab_bar_current_tab_set_static_delegate;
private delegate uint efl_ui_tab_bar_tab_count_delegate(System.IntPtr obj, System.IntPtr pd);
public delegate uint efl_ui_tab_bar_tab_count_api_delegate(System.IntPtr obj);
public static Efl.Eo.FunctionWrapper<efl_ui_tab_bar_tab_count_api_delegate> efl_ui_tab_bar_tab_count_ptr = new Efl.Eo.FunctionWrapper<efl_ui_tab_bar_tab_count_api_delegate>(Module, "efl_ui_tab_bar_tab_count");
private static uint tab_count(System.IntPtr obj, System.IntPtr pd)
{
Eina.Log.Debug("function efl_ui_tab_bar_tab_count was called");
Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd);
if (wrapper != null)
{
uint _ret_var = default(uint);
try
{
_ret_var = ((TabBar)wrapper).TabCount();
}
catch (Exception e)
{
Eina.Log.Warning($"Callback error: {e.ToString()}");
Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION);
}
return _ret_var;
}
else
{
return efl_ui_tab_bar_tab_count_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)));
}
}
private static efl_ui_tab_bar_tab_count_delegate efl_ui_tab_bar_tab_count_static_delegate;
private delegate void efl_ui_tab_bar_tab_add_delegate(System.IntPtr obj, System.IntPtr pd, int index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(Efl.Eo.StringKeepOwnershipMarshaler))] System.String label, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(Efl.Eo.StringKeepOwnershipMarshaler))] System.String icon);
public delegate void efl_ui_tab_bar_tab_add_api_delegate(System.IntPtr obj, int index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(Efl.Eo.StringKeepOwnershipMarshaler))] System.String label, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(Efl.Eo.StringKeepOwnershipMarshaler))] System.String icon);
public static Efl.Eo.FunctionWrapper<efl_ui_tab_bar_tab_add_api_delegate> efl_ui_tab_bar_tab_add_ptr = new Efl.Eo.FunctionWrapper<efl_ui_tab_bar_tab_add_api_delegate>(Module, "efl_ui_tab_bar_tab_add");
private static void tab_add(System.IntPtr obj, System.IntPtr pd, int index, System.String label, System.String icon)
{
Eina.Log.Debug("function efl_ui_tab_bar_tab_add was called");
Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd);
if (wrapper != null)
{
try
{
((TabBar)wrapper).AddTab(index, label, icon);
}
catch (Exception e)
{
Eina.Log.Warning($"Callback error: {e.ToString()}");
Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION);
}
}
else
{
efl_ui_tab_bar_tab_add_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), index, label, icon);
}
}
private static efl_ui_tab_bar_tab_add_delegate efl_ui_tab_bar_tab_add_static_delegate;
private delegate void efl_ui_tab_bar_tab_remove_delegate(System.IntPtr obj, System.IntPtr pd, int index);
public delegate void efl_ui_tab_bar_tab_remove_api_delegate(System.IntPtr obj, int index);
public static Efl.Eo.FunctionWrapper<efl_ui_tab_bar_tab_remove_api_delegate> efl_ui_tab_bar_tab_remove_ptr = new Efl.Eo.FunctionWrapper<efl_ui_tab_bar_tab_remove_api_delegate>(Module, "efl_ui_tab_bar_tab_remove");
private static void tab_remove(System.IntPtr obj, System.IntPtr pd, int index)
{
Eina.Log.Debug("function efl_ui_tab_bar_tab_remove was called");
Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd);
if (wrapper != null)
{
try
{
((TabBar)wrapper).TabRemove(index);
}
catch (Exception e)
{
Eina.Log.Warning($"Callback error: {e.ToString()}");
Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION);
}
}
else
{
efl_ui_tab_bar_tab_remove_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), index);
}
}
private static efl_ui_tab_bar_tab_remove_delegate efl_ui_tab_bar_tab_remove_static_delegate;
private delegate void efl_ui_tab_bar_tab_label_set_delegate(System.IntPtr obj, System.IntPtr pd, int index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(Efl.Eo.StringKeepOwnershipMarshaler))] System.String label);
public delegate void efl_ui_tab_bar_tab_label_set_api_delegate(System.IntPtr obj, int index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(Efl.Eo.StringKeepOwnershipMarshaler))] System.String label);
public static Efl.Eo.FunctionWrapper<efl_ui_tab_bar_tab_label_set_api_delegate> efl_ui_tab_bar_tab_label_set_ptr = new Efl.Eo.FunctionWrapper<efl_ui_tab_bar_tab_label_set_api_delegate>(Module, "efl_ui_tab_bar_tab_label_set");
private static void tab_label_set(System.IntPtr obj, System.IntPtr pd, int index, System.String label)
{
Eina.Log.Debug("function efl_ui_tab_bar_tab_label_set was called");
Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd);
if (wrapper != null)
{
try
{
((TabBar)wrapper).SetTabLabel(index, label);
}
catch (Exception e)
{
Eina.Log.Warning($"Callback error: {e.ToString()}");
Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION);
}
}
else
{
efl_ui_tab_bar_tab_label_set_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), index, label);
}
}
private static efl_ui_tab_bar_tab_label_set_delegate efl_ui_tab_bar_tab_label_set_static_delegate;
private delegate void efl_ui_tab_bar_tab_icon_set_delegate(System.IntPtr obj, System.IntPtr pd, int index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(Efl.Eo.StringKeepOwnershipMarshaler))] System.String icon);
public delegate void efl_ui_tab_bar_tab_icon_set_api_delegate(System.IntPtr obj, int index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(Efl.Eo.StringKeepOwnershipMarshaler))] System.String icon);
public static Efl.Eo.FunctionWrapper<efl_ui_tab_bar_tab_icon_set_api_delegate> efl_ui_tab_bar_tab_icon_set_ptr = new Efl.Eo.FunctionWrapper<efl_ui_tab_bar_tab_icon_set_api_delegate>(Module, "efl_ui_tab_bar_tab_icon_set");
private static void tab_icon_set(System.IntPtr obj, System.IntPtr pd, int index, System.String icon)
{
Eina.Log.Debug("function efl_ui_tab_bar_tab_icon_set was called");
Efl.Eo.IWrapper wrapper = Efl.Eo.Globals.PrivateDataGet(pd);
if (wrapper != null)
{
try
{
((TabBar)wrapper).SetTabIcon(index, icon);
}
catch (Exception e)
{
Eina.Log.Warning($"Callback error: {e.ToString()}");
Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION);
}
}
else
{
efl_ui_tab_bar_tab_icon_set_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), index, icon);
}
}
private static efl_ui_tab_bar_tab_icon_set_delegate efl_ui_tab_bar_tab_icon_set_static_delegate;
#pragma warning restore CA1707, SA1300, SA1600
}
}
}
}
| 42.040659 | 358 | 0.569569 | [
"Apache-2.0"
] | dalinui/TizenFX | internals/src/EflSharp/EflSharp/efl/efl_ui_tab_bar.eo.cs | 38,257 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
namespace Azure.AI.MetricsAdvisor.Models
{
/// <summary>
/// Used by <see cref="MetricChangePointFeedback"/> to indicate whether or not a set of data points should
/// be considered change points by the service.
/// </summary>
public readonly partial struct ChangePointValue
{
/// <summary>
/// Tells the service to disregard any previous change point feedback given to the set of data
/// points affected.
/// </summary>
public static ChangePointValue AutoDetect { get; } = new ChangePointValue(AutoDetectValue);
/// <summary>
/// The data points should have been labeled as change points.
/// </summary>
public static ChangePointValue ChangePoint { get; } = new ChangePointValue(ChangePointValue1);
/// <summary>
/// The data points should not have been labeled as change points.
/// </summary>
public static ChangePointValue NotChangePoint { get; } = new ChangePointValue(NotChangePointValue);
}
}
| 39.068966 | 110 | 0.661959 | [
"MIT"
] | 93mishra/azure-sdk-for-net | sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/Models/MetricFeedback/ChangePointValue.cs | 1,135 | C# |
namespace EasyCaching.Serialization.Protobuf
{
using EasyCaching.Core.Configurations;
/// <summary>
/// EasyCaching options extensions.
/// </summary>
public static class EasyCachingOptionsExtensions
{
/// <summary>
/// Withs the protobuf.
/// </summary>
/// <returns>The protobuf.</returns>
/// <param name="options">Options.</param>
public static EasyCachingOptions WithProtobuf(this EasyCachingOptions options)
{
options.RegisterExtension(new ProtobufOptionsExtension());
return options;
}
}
}
| 26.782609 | 86 | 0.616883 | [
"MIT"
] | appman-agm/EasyCaching | src/EasyCaching.Serialization.Protobuf/Configurations/EasyCachingOptionsExtensions.cs | 618 | C# |
//-----------------------------------------------------------------------------
// Torque Game Engine
//
// Copyright (c) 2001 GarageGames.Com
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Penalty and bonus times.
$Game::TimeTravelBonus = 5000;
// Item respawn values, only powerups currently respawn
$Item::RespawnTime = 7 * 1000;
$Item::PopTime = 10 * 1000;
// Game duration in secs, no limit if the duration is set to 0
$Game::Duration = 0;
// Pause while looking over the end game screen (in secs)
$Game::EndGamePause = 5;
//-----------------------------------------------------------------------------
// Variables extracted from the mission
$Game::GemCount = 0;
$Game::StartPad = 0;
$Game::EndPad = 0;
//-----------------------------------------------------------------------------
// Functions that implement game-play
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
function onServerCreated()
{
// Server::GameType is sent to the master server.
// This variable should uniquely identify your game and/or mod.
$Server::GameType = "Marble Game";
// Server::MissionType sent to the master server. Clients can
// filter servers based on mission type.
$Server::MissionType = "Deathmatch";
// GameStartTime is the sim time the game started. Used to calculated
// game elapsed time.
$Game::StartTime = 0;
// Load up all datablocks, objects etc. This function is called when
// a server is constructed.
exec("./audioProfiles.cs");
exec("./camera.cs");
exec("./markers.cs");
exec("./triggers.cs");
exec("./inventory.cs");
exec("./shapeBase.cs");
exec("./staticShape.cs");
exec("./item.cs");
// Basic items
exec("./marble.cs");
exec("./gems.cs");
exec("./powerUps.cs");
exec("./buttons.cs");
exec("./hazards.cs");
exec("./pads.cs");
exec("./bumpers.cs");
exec("./signs.cs");
exec("./fireworks.cs");
// Platforms and interior doors
exec("./pathedInteriors.cs");
// Keep track of when the game started
$Game::StartTime = $Sim::Time;
initMultiplayerServer();
}
function onServerDestroyed()
{
// Perform any game cleanup without actually ending the game
destroyGame();
}
//-----------------------------------------------------------------------------
function onMissionLoaded()
{
// Called by loadMission() once the mission is finished loading.
// Nothing special for now, just start up the game play.
$Game::GemCount = countGems(MissionGroup);
commandToAll('setGravityDir', "1 0 0 0 -1 0 0 0 -1", true);
// Start the game here if multiplayer...
if ($Server::ServerType $= "MultiPlayer") {
masterStartGame();
startGame();
if ($Server::Dedicated) {
switch$ ($platform) {
case "windows":
echo("----------------------------------");
if ($Dcon::Active)
echo(" For server help, type \"help\" ");
else
echo(" For server help, type \"help();\"");
echo("----------------------------------");
if ($Dcon::Active)
activatePackage(dcon);
case "macos":
echo("----------------------------------");
echo(" There\'s this odd bug in some");
echo(" Mac servers that makes console");
echo(" entry not work. We haven\'t found");
echo(" any solutions as of now, and are");
echo(" sorry for the inconvenience.");
echo("----------------------------------");
case "x86UNIX":
echo("-----------------------------------");
if ($Dcon::Active)
echo(" For server help, type \"help\"");
else
echo(" For server help, type \"help();\"");
echo();
echo(" Currently, linux servers are");
echo(" unsupported, but they will still");
echo(" work for any windows/linux clients");
echo("-----------------------------------");
if ($Dcon::Active)
activatePackage(dcon);
}
}
}
}
function onMissionEnded()
{
// Called by endMission(), right before the mission is destroyed
// This part of a normal mission cycling or end.
endGame();
}
function onMissionReset()
{
endFireWorks();
// Reset the players and inform them we're starting
for( %clientIndex = 0; %clientIndex < ClientGroup.getCount(); %clientIndex++ ) {
%cl = ClientGroup.getObject( %clientIndex );
commandToClient(%cl, 'GameStart');
%cl.resetStats();
}
// Start the game duration timer
if ($Game::Duration)
$Game::CycleSchedule = schedule($Game::Duration * 1000, 0, "onGameDurationEnd" );
$Game::Running = true;
$Game::EndPadGems = 0;
ServerGroup.onMissionReset();
// Set the initial state
if ($Server::ServerType $= "SinglePlayer")
setGameState("Start");
}
function SimGroup::onMissionReset(%this)
{
for(%i = 0; %i < %this.getCount(); %i++)
%this.getObject(%i).onMissionReset();
}
function SimObject::onMissionReset(%this)
{
}
function GameBase::onMissionReset(%this)
{
%this.getDataBlock().onMissionReset(%this);
}
//-----------------------------------------------------------------------------
function startGame()
{
if ($Game::Running) {
error("startGame: End the game first!");
return;
}
$Game::Running = true;
$Game::Qualified = false;
$Game::FirstSpawn = false;
onMissionReset();
// Matt: set the game state for everyone
if ($Server::ServerType $= "MultiPlayer")
setGameState("Waiting");
}
function endGame()
{
if (!$Game::Running) {
error("endGame: No game running!");
return;
}
destroyGame();
$Game::FirstSpawn = false;
// Inform the clients the game is over
for (%index = 0; %index < ClientGroup.getCount(); %index++) {
%client = ClientGroup.getObject(%index);
commandToClient(%client, 'EndGameTimes', %client.penaltyTime);
commandToClient(%client, 'GameEnd', %client.endPad && ($Game::GemCount > 0 ? %client.gemCount : true));
%client.stopTimer();
}
}
function pauseGame()
{
if ($Server::ServerType $= "SinglePlayer")
$gamePaused = true;
}
function resumeGame()
{
$gamePaused = false;
}
function destroyGame()
{
// Cancel any client timers
for (%index = 0; %index < ClientGroup.getCount(); %index++)
cancel(ClientGroup.getObject(%index).respawnSchedule);
// Perform cleanup to reset the game.
cancel($Game::CycleSchedule);
$Game::Running = false;
}
//-----------------------------------------------------------------------------
function onGameDurationEnd()
{
// This "redirect" is here so that we can abort the game cycle if
// the $Game::Duration variable has been cleared, without having
// to have a function to cancel the schedule.
if ($Game::Duration && !isObject(EditorGui))
cycleGame();
}
function cycleGame()
{
// This is setup as a schedule so that this function can be called
// directly from object callbacks. Object callbacks have to be
// carefull about invoking server functions that could cause
// their object to be deleted.
if (!$Game::Cycling) {
$Game::Cycling = true;
$Game::CycleSchedule = schedule(0, 0, "onCycleExec");
}
}
function onCycleExec()
{
// End the current game and start another one, we'll pause for a little
// so the end game victory screen can be examined by the clients.
endGame();
$Game::CycleSchedule = schedule($Game::EndGamePause * 1000, 0, "onCyclePauseEnd");
}
function onCyclePauseEnd()
{
$Game::Cycling = false;
loadNextMission();
}
function loadNextMission()
{
%nextMission = "";
// Cycle to the next level, or back to the start if there aren't
// any more levels.
for (%file = findFirstFile($Server::MissionFileSpec);
%file !$= ""; %file = findNextFile($Server::MissionFileSpec))
if (strStr(%file, "CVS/") == -1 && strStr(%file, "common/") == -1)
{
%mission = getMissionObject(%file);
if (%mission.type $= MissionInfo.type) {
if (%mission.level == 1)
%nextMission = %file;
if ((%mission.level + 0) == MissionInfo.level + 1) {
echo("Found one!");
%nextMission = %file;
break;
}
}
}
loadMission(%nextMission);
}
//-----------------------------------------------------------------------------
// GameConnection Methods
// These methods are extensions to the GameConnection class. Extending
// GameConnection make is easier to deal with some of this functionality,
// but these could also be implemented as stand-alone functions.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
function GameConnection::incPenaltyTime(%this,%dt)
{
%this.adjustTimer(%dt);
%this.penaltyTime += %dt;
}
function GameConnection::incBonusTime(%this,%dt)
{
%this.addBonusTime(%dt);
%this.bonusTime += %dt;
}
//-----------------------------------------------------------------------------
function GameConnection::onClientEnterGame(%this)
{
// Create a new camera object.
%this.camera = new Camera() {
dataBlock = Observer;
};
MissionCleanup.add( %this.camera );
%this.camera.scopeToClient(%this);
// Setup game parameters and create the player
%this.resetStats();
%this.spawnPlayer();
// Anchor the player to the start pad
%this.player.setMode(Start);
%this.resetTimer();
// Start the game here for single player
if ($Server::ServerType $= "SinglePlayer")
startGame();
else if ($HostingMP && !%this.isHost()) {
$Server::Ready[%this] = false;
%this.respawnPlayer();
if ($Game::FirstSpawn) {
commandToClient(%this, 'popPregame');
%this.setGameState("start");
} else
%this.setGameState("waiting");
}
}
function GameConnection::onClientLeaveGame(%this)
{
if (isObject(%this.camera))
%this.camera.delete();
if (isObject(%this.player))
%this.player.delete();
if (isObject(%this.ghost))
%this.ghost.delete();
%this.resetGems();
if ($Server::ServerType $= "SinglePlayer" || $Server::PlayerCount <= 1)
MissionGroup.onMissionReset();
}
function GameConnection::resetStats(%this)
{
// Reset game stats
%this.bonusTime = 0;
%this.penaltyTime = 0;
%this.gemCount = 0;
// Reset the checkpoint
if (isObject(%this.checkPoint))
%this.checkPoint.delete();
%this.checkPoint = new ScriptObject() {
pad = $Game::StartPad;
time = 0;
gemCount = 0;
penaltyTime = 0;
bonusTime = 0;
powerUp = 0;
};
}
//-----------------------------------------------------------------------------
function GameConnection::onEnterPad(%this)
{
if (%this.player.getPad() == $Game::EndPad) {
%this.endPad = true;
if ($Game::GemCount && %this.gemCount < $Game::GemCount) {
%this.play2d(MissingGemsSfx);
if ($Server::ServerType $= "MultiPlayer" && $Server::PlayerCount > 1) {
$Game::EndPadGems += %this.gemCount;
if ($Game::EndPadGems < $Game::GemCount) {
messageClient(%this, 'MsgMissingGems', '\c0Get the other players with gems on the finish pad to group finish!');
if (%this.gemCount > 0) {
for (%i = 0; %i < ClientGroup.getCount(); %i ++) {
%client = ClientGroup.getObject(%i);
if (!%client.endPad && %client.gemCount)
messageClient(%client, 'MsgMissingGems', '\c0%1 is waiting on the finish pad to group finish!', %this.namebase);
}
}
} else {
setGameState("endScreen");
for (%i = 0; %i < ClientGroup.getCount(); %i ++) {
%client = ClientGroup.getObject(%i);
if (%client.endPad && %client.gemCount) {
%client.player.setMode(Victory);
messageClient(%client, 'MsgRaceOver', '\c0Congratulations! You\'ve group finished!');
gameOver();
}
}
}
} else
messageClient(%this, 'MsgMissingGems', '\c0You can\'t finish without all the gems!!');
}
else {
setGameState("endScreen");
%this.player.setMode(Victory);
messageClient(%this, 'MsgRaceOver', '\c0Congratulations! You\'ve finished!');
gameOver();
}
}
}
function GameConnection::onLeavePad(%this)
{
%this.endPad = false;
if ($Server::ServerType $= "MultiPlayer") {
$Game::EndPadGems -= %this.gemCount;
}
}
//-----------------------------------------------------------------------------
function GameConnection::onOutOfBounds(%this)
{
if (%this.gameState $= "End")
return;
// Reset the player back to the last checkpoint
%this.setMessage("outOfBounds",2000);
%this.play2d(OutOfBoundsVoiceSfx);
%this.player.setOOB(true);
if(!isEventPending(%this.respawnSchedule))
%this.respawnSchedule = %this.schedule(2500, respawnPlayer);
}
function Marble::onOOBClick(%this) {
if ($HostingMP && %this.getOOB())
%this.client.respawnPlayer();
if ($Server::ServerType $= "SinglePlayer")
LocalClientConnection.respawnPlayer();
}
function GameConnection::onDestroyed(%this)
{
if (%this.gameState $= "End")
return;
// Reset the player back to the last checkpoint
%this.setMessage("destroyed",2000);
%client.play2d(DestroyedVoiceSfx);
%this.player.setOOB(true);
if(!isEventPending(%this.respawnSchedule))
%this.respawnSchedule = %this.schedule(2500, respawnPlayer);
}
function GameConnection::onFoundGem(%this,%amount)
{
%this.gemCount += %amount;
%remaining = $Game::gemCount - %this.gemCount;
if (%remaining <= 0) {
messageClient(%this, 'MsgHaveAllGems', '\c0You have all the gems, head for the finish!');
%this.play2d(GotAllGemsSfx);
%this.gemCount = $Game::GemCount;
}
else
{
if(%remaining == 1)
%msg = '\c0You picked up a gem. Only one gem to go!';
else
%msg = '\c0You picked up a gem. %1 gems to go!';
messageClient(%this, 'MsgItemPickup', %msg, %remaining);
%this.play2d(GotGemSfx);
}
%this.setGemCount(%this.gemCount);
}
//-----------------------------------------------------------------------------
function GameConnection::spawnPlayer(%this)
{
// Combination create player and drop him somewhere
%spawnPoint = %this.getCheckpointPos();
%this.createPlayer(%spawnPoint);
serverPlay2d(spawnSfx);
}
function restartLevel()
{
LocalClientConnection.respawnPlayer();
}
function GameConnection::respawnPlayer(%this)
{
//HiGuy: Don't respawn two people at the same place / time
// Wait 500ms in-between spawns
if (getRealTime() - $Game::LastRespawnTime < 500) {
%this.schedule(300, "respawnPlayer");
return;
}
$Game::LastRespawnTime = getRealTime();
%this.respawning = true;
cancelAll(%this.player);
cancelAll(%this.ghost);
%this.player.unmountImage(0);
%this.player.unmountImage(1);
%this.player.unmountImage(2);
%this.ghost.unmountImage(0);
%this.ghost.unmountImage(1);
%this.ghost.unmountImage(2);
%this.setGravityDir("1 0 0 0 -1 0 0 0 -1", true);
%this.resetGems();
%this.resetStats();
// Reset the player back to the last checkpoint
cancel(%this.respawnSchedule);
if ($Server::ServerType $= "SinglePlayer" || $Server::PlayerCount < 2)
onMissionReset();
%this.setGameState("Start"); // Matt
%this.player.setOOB(false);
%this.player.setMode(Start);
%this.player.setPosition(%this.getCheckpointPos(), 0.45);
%this.player.setPowerUp(%this.checkPoint.powerUp,true);
%this.gemCount = %this.checkPoint.gemCount;
%this.penaltyTime = %this.checkPoint.penaltyTime;
%this.bonusTime = %this.checkPoint.bonusTime;
%this.setTime(%this.checkPoint.time);
%this.setGemCount(%this.gemCount);
serverPlay2d(spawnSfx);
%this.respawning = false;
}
//-----------------------------------------------------------------------------
function GameConnection::createPlayer(%this, %spawnPoint)
{
// Matt: No Longer Needed
//if (%this.player > 0) {
//// The client should not have a player currently
//// assigned. Assigning a new one could result in
//// a player ghost.
//error( "Attempting to create an angus ghost!" );
//}
%player = new Marble() {
dataBlock = DefaultMarble;
client = %this;
};
MissionCleanup.add(%player);
// Player setup...
%player.setPosition(%spawnPoint, 0.45);
%player.setEnergyLevel(60);
%player.setShapeName(%this.name);
%player.client.status = 1;
// Update the camera to start with the player
%this.camera.setTransform(%player.getEyeTransform());
// Give the client control of the player
%this.player = %player;
%this.setControlObject(%player);
if ($Server::ServerType $= "Multiplayer") {
%playerSize = 1 - ($Game::MarbleCount / 10000);
%player.scale = %playerSize SPC %playerSize SPC %playerSize;
$Game::MarbleCount ++;
%this.createGhost();
%this.ghostSize = %playerSize;
commandToClient(%this, 'yourScale', %playerSize);
for (%i = 0; %i < ClientGroup.getCount(); %i ++) {
commandToClient(%this, 'newMarble', ClientGroup.getObject(%i).namebase, ClientGroup.getObject(%i).ghostSize);
}
commandToAll('newMarble', %this.nameBase, %playerSize);
}
}
//-----------------------------------------------------------------------------
function GameConnection::setCheckpoint(%this,%object)
{
// Store the last checkpoint which will be used to restore
// the player when he goes out of bounds.
if (%object != %this.checkPoint.pad) {
%this.checkPoint.delete();
%this.checkPoint = new ScriptObject() {
pad = %object;
time = PlayGUI.elapsedTime;
gemCount = %this.gemCount;
penaltyTime = %this.penaltyTime;
bonusTime = %this.bonusTime;
powerUp = %this.player.getPowerUp();
};
messageClient(%this, 'MsgCheckPoint', "\c0Check Point " @ %object.number @ " reached!");
}
}
//-----------------------------------------------------------------------------
// Support functions
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
function countGems(%group)
{
// Count up all gems out there are in the world
%gems = 0;
for (%i = 0; %i < %group.getCount(); %i++)
{
%object = %group.getObject(%i);
%type = %object.getClassName();
if (%type $= "SimGroup")
%gems += countGems(%object);
else
if (%type $= "Item" &&
%object.getDatablock().classname $= "Gem")
%gems++;
}
return %gems;
}
| 30.130827 | 137 | 0.530768 | [
"MIT"
] | PlatinumTeam/HaxPackage | marble/server/scripts/game.cs | 20,037 | C# |
using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
using ModernSlavery.BusinessDomain.Shared.Interfaces;
using ModernSlavery.BusinessDomain.Shared.Models;
using ModernSlavery.Core.Interfaces;
using ModernSlavery.Core.Interfaces.Downloadable;
using ModernSlavery.Core.Models;
namespace ModernSlavery.BusinessDomain.Admin
{
public class DownloadableFileBusinessLogic : IDownloadableFileBusinessLogic
{
private readonly IFileRepository _fileRepository;
public DownloadableFileBusinessLogic(IFileRepository fileRepository)
{
_fileRepository = fileRepository;
}
public async Task<DownloadableFileModel> GetFileRemovingSensitiveInformationAsync(string filePath)
{
var result = new DownloadableFileModel(filePath);
result.DataTable = await _fileRepository.ReadDataTableAsync(result.Filepath).ConfigureAwait(false);
RemoveColumnFromDataTable(result.DataTable, "SecurityCode");
RemoveColumnFromDataTable(result.DataTable, "SecurityCodeExpiryDateTime");
RemoveColumnFromDataTable(result.DataTable, "SecurityCodeCreatedDateTime");
return result;
}
public async Task<IEnumerable<IDownloadableItem>> GetListOfDownloadableItemsFromPathAsync(
string processedLogsPath)
{
var result = new List<IDownloadableItem>();
// As a minimum, the directory has the special parent folder '..' to go back up to.
var parentDirectoryFolderFileInfo = DownloadableDirectory.GetSpecialParentFolderInfo(processedLogsPath);
result.Add(parentDirectoryFolderFileInfo);
foreach (var dirPath in await _fileRepository.GetDirectoriesAsync(processedLogsPath).ConfigureAwait(false))
result.Add(new DownloadableDirectory(dirPath.Replace("\\", "/")));
foreach (var filePath in await _fileRepository.GetFilesAsync(processedLogsPath).ConfigureAwait(false))
result.Add(new DownloadableFile(filePath.Replace("\\", "/")));
return result;
}
private void RemoveColumnFromDataTable(DataTable dataTable, string columnName)
{
// Removal implemented as per Microsoft specification (see the example in "remove string" section) => https://docs.microsoft.com/en-us/dotnet/api/system.data.datacolumncollection.remove?view=netframework-4.8#System_Data_DataColumnCollection_Remove_System_String_
if (dataTable.Columns.Contains(columnName))
if (dataTable.Columns.CanRemove(dataTable.Columns[columnName]))
dataTable.Columns.Remove(columnName);
}
}
} | 44.590164 | 275 | 0.719118 | [
"MIT"
] | mccabesp/ModernSlavery-Beta | ModernSlavery.BusinessDomain.Admin/DownloadableFileBusinessLogic.cs | 2,722 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace System
{
/// <summary>
/// 表示一个异步任务的委托。
/// </summary>
/// <param name="job">异步任务。</param>
public delegate void AsyncJobHandler(IAsyncJob job);
/// <summary>
/// 表示一个异步任务的标识。
/// </summary>
public interface IAsyncJob
{
/// <summary>
/// 获取自定义数据。
/// </summary>
object State { get; }
/// <summary>
/// 获取关联的异步操作。
/// </summary>
System.Threading.Tasks.Task Task { get; }
/// <summary>
/// 获取一个值,指示任务是否已取消。
/// </summary>
bool IsCanceled { get; }
/// <summary>
/// 获取一个值,指示任务是否发生异常。
/// </summary>
bool IsFaulted { get; }
/// <summary>
/// 获取一个值,指示任务是否已成功完成。
/// </summary>
bool IsSuccessed { get; }
/// <summary>
/// 获取一个值,指示任务是否正在进行。
/// </summary>
bool IsRunning { get; }
/// <summary>
/// 立即取消异步任务。
/// </summary>
void Cancel();
/// <summary>
/// 等待完成执行过程。
/// </summary>
/// <param name="millisecondsTimeout">等待的毫秒数,或为 <see cref="System.Threading.Timeout.Infinite"/>(-1),表示无限期等待。</param>
/// <returns>如果在分配的时间内完成执行,则为 true;否则为 false。</returns>
bool Wait(int millisecondsTimeout = System.Threading.Timeout.Infinite);
/// <summary>
/// 延迟时间执行任务。
/// </summary>
/// <param name="millisecondsDelay">等待延迟的毫秒数。</param>
void Delay(int millisecondsDelay);
/// <summary>
/// 延迟时间执行任务。
/// </summary>
/// <param name="timeSpanDelay">等待延迟的间隔。</param>
void Delay(TimeSpan timeSpanDelay);
}
}
| 26.939394 | 124 | 0.514061 | [
"Apache-2.0"
] | jeenlee/Aoite | src/core/Aoite/System/Core/IAsyncJob.cs | 2,194 | C# |
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Square;
using Square.Utilities;
namespace Square.Models
{
public class OrderLineItemPricingBlocklists
{
public OrderLineItemPricingBlocklists(IList<Models.OrderLineItemPricingBlocklistsBlockedDiscount> blockedDiscounts = null,
IList<Models.OrderLineItemPricingBlocklistsBlockedTax> blockedTaxes = null)
{
BlockedDiscounts = blockedDiscounts;
BlockedTaxes = blockedTaxes;
}
/// <summary>
/// A list of discounts blocked from applying to the line item.
/// Discounts can be blocked by the `discount_uid` (for ad-hoc discounts) or
/// the `discount_catalog_object_id` (for catalog discounts).
/// </summary>
[JsonProperty("blocked_discounts", NullValueHandling = NullValueHandling.Ignore)]
public IList<Models.OrderLineItemPricingBlocklistsBlockedDiscount> BlockedDiscounts { get; }
/// <summary>
/// A list of taxes blocked from applying to the line item.
/// Taxes can be blocked by the `tax_uid` (for ad-hoc taxes) or
/// the `tax_catalog_object_id` (for catalog taxes).
/// </summary>
[JsonProperty("blocked_taxes", NullValueHandling = NullValueHandling.Ignore)]
public IList<Models.OrderLineItemPricingBlocklistsBlockedTax> BlockedTaxes { get; }
public override string ToString()
{
var toStringOutput = new List<string>();
this.ToString(toStringOutput);
return $"OrderLineItemPricingBlocklists : ({string.Join(", ", toStringOutput)})";
}
protected void ToString(List<string> toStringOutput)
{
toStringOutput.Add($"BlockedDiscounts = {(BlockedDiscounts == null ? "null" : $"[{ string.Join(", ", BlockedDiscounts)} ]")}");
toStringOutput.Add($"BlockedTaxes = {(BlockedTaxes == null ? "null" : $"[{ string.Join(", ", BlockedTaxes)} ]")}");
}
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
if (obj == this)
{
return true;
}
return obj is OrderLineItemPricingBlocklists other &&
((BlockedDiscounts == null && other.BlockedDiscounts == null) || (BlockedDiscounts?.Equals(other.BlockedDiscounts) == true)) &&
((BlockedTaxes == null && other.BlockedTaxes == null) || (BlockedTaxes?.Equals(other.BlockedTaxes) == true));
}
public override int GetHashCode()
{
int hashCode = 497511120;
if (BlockedDiscounts != null)
{
hashCode += BlockedDiscounts.GetHashCode();
}
if (BlockedTaxes != null)
{
hashCode += BlockedTaxes.GetHashCode();
}
return hashCode;
}
public Builder ToBuilder()
{
var builder = new Builder()
.BlockedDiscounts(BlockedDiscounts)
.BlockedTaxes(BlockedTaxes);
return builder;
}
public class Builder
{
private IList<Models.OrderLineItemPricingBlocklistsBlockedDiscount> blockedDiscounts;
private IList<Models.OrderLineItemPricingBlocklistsBlockedTax> blockedTaxes;
public Builder BlockedDiscounts(IList<Models.OrderLineItemPricingBlocklistsBlockedDiscount> blockedDiscounts)
{
this.blockedDiscounts = blockedDiscounts;
return this;
}
public Builder BlockedTaxes(IList<Models.OrderLineItemPricingBlocklistsBlockedTax> blockedTaxes)
{
this.blockedTaxes = blockedTaxes;
return this;
}
public OrderLineItemPricingBlocklists Build()
{
return new OrderLineItemPricingBlocklists(blockedDiscounts,
blockedTaxes);
}
}
}
} | 35.266129 | 144 | 0.58541 | [
"Apache-2.0"
] | HostMeApp/square-dotnet-sdk | Square/Models/OrderLineItemPricingBlocklists.cs | 4,373 | C# |
namespace JWLMerge.Models
{
using System.Windows.Media;
internal sealed class ColourDef
{
public ColourDef(int colourIndex, string name, string rgb)
{
ColourIndex = colourIndex;
Name = name;
RgbString = rgb;
}
public int ColourIndex { get; }
public string Name { get; }
public string RgbString { get; }
public Color Color => (Color)ColorConverter.ConvertFromString(RgbString);
}
}
| 21.521739 | 81 | 0.587879 | [
"MIT"
] | AntonyCorbett/JWLMerge | JWLMerge/Models/ColourDef.cs | 497 | C# |
namespace jsdal_server_core.Performance.Bucket
{
public class BucketPerSecond
{
}
} | 13.714286 | 46 | 0.71875 | [
"MIT"
] | pietie/jsdal-server-core | Performance/Bucket/BucketPerSecond.cs | 96 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Hosting;
using Orchard.Environment.Extensions.Loaders;
using Orchard.FileSystems.VirtualPath;
using Orchard.Logging;
namespace Orchard.FileSystems.Dependencies {
/// <summary>
/// The purpose of this virtual path provider is to add file dependencies to .csproj files
/// served from the "~/Modules" or "~/Themes" directory.
/// </summary>
public class DynamicModuleVirtualPathProvider : VirtualPathProvider, ICustomVirtualPathProvider {
private readonly IExtensionDependenciesManager _extensionDependenciesManager;
private readonly IEnumerable<IExtensionLoader> _loaders;
public DynamicModuleVirtualPathProvider(IExtensionDependenciesManager extensionDependenciesManager, IEnumerable<IExtensionLoader> loaders) {
_extensionDependenciesManager = extensionDependenciesManager;
_loaders = loaders;
Logger = NullLogger.Instance;
}
public ILogger Logger { get; set; }
public override string GetFileHash(string virtualPath, IEnumerable virtualPathDependencies) {
var result = GetFileHashWorker(virtualPath, virtualPathDependencies);
Logger.Debug("GetFileHash(\"{0}\"): {1}", virtualPath, result);
return result;
}
private string GetFileHashWorker(string virtualPath, IEnumerable virtualPathDependencies) {
virtualPath = VirtualPathUtility.ToAppRelative(virtualPath);
var desc = GetExtensionDescriptor(virtualPath);
if (desc != null) {
if (desc.VirtualPath.Equals(virtualPath, StringComparison.OrdinalIgnoreCase)) {
return desc.Hash;
}
}
return base.GetFileHash(virtualPath, virtualPathDependencies);
}
private ActivatedExtensionDescriptor GetExtensionDescriptor(string virtualPath) {
var prefix = PrefixMatch(virtualPath, DynamicExtensionLoader.ExtensionsVirtualPathPrefixes);
if (prefix == null)
return null;
var moduleId = ModuleMatch(virtualPath, prefix);
if (moduleId == null)
return null;
return _extensionDependenciesManager.GetDescriptor(moduleId);
}
private static string ModuleMatch(string virtualPath, string prefix) {
var index = virtualPath.IndexOf('/', prefix.Length, virtualPath.Length - prefix.Length);
if (index < 0)
return null;
var moduleId = virtualPath.Substring(prefix.Length, index - prefix.Length);
return (string.IsNullOrEmpty(moduleId) ? null : moduleId);
}
private static string PrefixMatch(string virtualPath, params string[] prefixes) {
return prefixes
.FirstOrDefault(p => virtualPath.StartsWith(p, StringComparison.OrdinalIgnoreCase));
}
VirtualPathProvider ICustomVirtualPathProvider.Instance {
get { return this; }
}
}
} | 42.131579 | 149 | 0.657402 | [
"BSD-3-Clause"
] | Lombiq/Dojo-Course-Orchard-demo | src/Orchard/FileSystems/Dependencies/DynamicModuleVirtualPathProvider.cs | 3,202 | C# |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// 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;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gallio.Framework;
using Gallio.Framework.Pattern;
using MbUnit.Framework;
using Rhino.Mocks;
using Gallio.Common.Reflection;
#pragma warning disable 0414
namespace Gallio.Tests.Framework.Pattern
{
[TestsOn(typeof(FixtureMemberInvoker<>))]
public class FixtureMemberInvokerTest
{
private IPatternScope ArrangeMockScope()
{
var mockScope = MockRepository.GenerateStub<IPatternScope>();
var mockTestBuilder = MockRepository.GenerateStub<ITestBuilder>();
mockScope.Stub(x => x.TestBuilder).Return(mockTestBuilder);
mockTestBuilder.Stub(x => x.CodeElement).Return(Reflector.Wrap(GetType()));
return mockScope;
}
[Test]
[Row(typeof(int), "PublicInstancePropertyInt32", null, 123)]
[Row(typeof(int), "PrivateInstancePropertyInt32", null, 123)]
[Row(typeof(int), "PublicInstanceMethodInt32", null, 123)]
[Row(typeof(int), "PrivateInstanceMethodInt32", null, 123)]
[Row(typeof(int), "PublicInstanceFieldInt32", null, 123)]
[Row(typeof(int), "PrivateInstanceFieldInt32", null, 123)]
[Row(typeof(int), "PublicStaticPropertyInt32", null, 123)]
[Row(typeof(int), "PrivateStaticPropertyInt32", null, 123)]
[Row(typeof(int), "PublicStaticMethodInt32", null, 123)]
[Row(typeof(int), "PrivateStaticMethodInt32", null, 123)]
[Row(typeof(int), "PublicStaticFieldInt32", null, 123)]
[Row(typeof(int), "PrivateStaticFieldInt32", null, 123)]
[Row(typeof(int), "PublicStaticPropertyInt32", typeof(Sample), 123)]
[Row(typeof(int), "PrivateStaticPropertyInt32", typeof(Sample), 123)]
[Row(typeof(int), "PublicStaticMethodInt32", typeof(Sample), 123)]
[Row(typeof(int), "PrivateStaticMethodInt32", typeof(Sample), 123)]
[Row(typeof(int), "PublicStaticFieldInt32", typeof(Sample), 123)]
[Row(typeof(int), "PrivateStaticFieldInt32", typeof(Sample), 123)]
[Row(typeof(string), "PublicInstancePropertyString", null, "Hello")]
[Row(typeof(string), "PrivateInstancePropertyString", null, "Hello")]
[Row(typeof(string), "PublicInstanceMethodString", null, "Hello")]
[Row(typeof(string), "PrivateInstanceMethodString", null, "Hello")]
[Row(typeof(string), "PublicInstanceFieldString", null, "Hello")]
[Row(typeof(string), "PrivateInstanceFieldString", null, "Hello")]
[Row(typeof(string), "PrivateStaticFieldString", null, "Hello")]
[Row(typeof(string), "PublicStaticPropertyString", null, "Hello")]
[Row(typeof(string), "PrivateStaticPropertyString", null, "Hello")]
[Row(typeof(string), "PublicStaticMethodString", null, "Hello")]
[Row(typeof(string), "PrivateStaticMethodString", null, "Hello")]
[Row(typeof(string), "PublicStaticFieldString", null, "Hello")]
[Row(typeof(string), "PrivateStaticFieldString", typeof(Sample), "Hello")]
[Row(typeof(string), "PublicStaticPropertyString", typeof(Sample), "Hello")]
[Row(typeof(string), "PrivateStaticPropertyString", typeof(Sample), "Hello")]
[Row(typeof(string), "PublicStaticMethodString", typeof(Sample), "Hello")]
[Row(typeof(string), "PrivateStaticMethodString", typeof(Sample), "Hello")]
[Row(typeof(string), "PublicStaticFieldString", typeof(Sample), "Hello")]
public void Invoke_argument_less_member<T>(string memberName, Type source, T expectedValue)
{
var mockScope = ArrangeMockScope();
var invoker = new FixtureMemberInvoker<T>(source, mockScope, memberName);
T actualValue = invoker.Invoke();
Assert.AreEqual<T>(expectedValue, actualValue);
}
[Test]
[Row(123, false)]
[Row(124, true)]
public void Invoke_member_with_argument(int input, bool expectedResult)
{
var mockScope = ArrangeMockScope();
var invoker = new FixtureMemberInvoker<bool>(null, mockScope, "IsOdd");
bool actualResult = invoker.Invoke(input);
Assert.AreEqual(expectedResult, actualResult);
}
[Test]
[Row(123.3d, false)]
[Row(123.7d, true)]
[Row(124.1d, true)]
[Row(124.6d, false)]
public void Invoke_member_with_converted_argument(double input, bool expectedResult)
{
var mockScope = ArrangeMockScope();
var invoker = new FixtureMemberInvoker<bool>(null, mockScope, "IsOdd");
bool actualResult = invoker.Invoke(input);
Assert.AreEqual(expectedResult, actualResult);
}
[Test]
public void Invoke_member_not_found_should_throw_exception()
{
var mockScope = ArrangeMockScope();
var invoker = new FixtureMemberInvoker<bool>(null, mockScope, "DoesNotExist");
Assert.Throws<PatternUsageErrorException>(() => invoker.Invoke());
}
[Test]
public void Invoke_member_with_invalid_number_of_arguments_should_throw_exception()
{
var mockScope = ArrangeMockScope();
var invoker = new FixtureMemberInvoker<bool>(null, mockScope, "Add");
Assert.Throws<PatternUsageErrorException>(() => invoker.Invoke(1, 2));
}
[Test]
public void Invoke_member_with_incompatible_argument_should_throw_exception()
{
var mockScope = ArrangeMockScope();
var invoker = new FixtureMemberInvoker<bool>(null, mockScope, "Add");
Assert.Throws<PatternUsageErrorException>(() => invoker.Invoke(1, new object(), 3));
}
#region Invocation samples
public int PublicInstanceFieldInt32 = 123;
public string PublicInstanceFieldString = "Hello";
#pragma warning disable 0414
private int PrivateInstanceFieldInt32 = 123;
private string PrivateInstanceFieldString = "Hello";
public static int PublicStaticFieldInt32 = 123;
public static string PublicStaticFieldString = "Hello";
private static int PrivateStaticFieldInt32 = 123;
private static string PrivateStaticFieldString = "Hello";
public int PublicInstancePropertyInt32
{
get
{
return 123;
}
}
public string PublicInstancePropertyString
{
get
{
return "Hello";
}
}
private int PrivateInstancePropertyInt32
{
get
{
return 123;
}
}
private string PrivateInstancePropertyString
{
get
{
return "Hello";
}
}
public static int PublicStaticPropertyInt32
{
get
{
return 123;
}
}
public static string PublicStaticPropertyString
{
get
{
return "Hello";
}
}
private static int PrivateStaticPropertyInt32
{
get
{
return 123;
}
}
private static string PrivateStaticPropertyString
{
get
{
return "Hello";
}
}
public int PublicInstanceMethodInt32()
{
return 123;
}
public string PublicInstanceMethodString()
{
return "Hello";
}
private int PrivateInstanceMethodInt32()
{
return 123;
}
private string PrivateInstanceMethodString()
{
return "Hello";
}
public static int PublicStaticMethodInt32()
{
return 123;
}
public static string PublicStaticMethodString()
{
return "Hello";
}
private static int PrivateStaticMethodInt32()
{
return 123;
}
private static string PrivateStaticMethodString()
{
return "Hello";
}
public bool IsOdd(int value)
{
return value % 2 == 0;
}
public int Add(int value1, int value2, int value3)
{
return value1 + value2 + value3;
}
private class Sample
{
public static int PublicStaticFieldInt32 = 123;
public static string PublicStaticFieldString = "Hello";
private static int PrivateStaticFieldInt32 = 123;
private static string PrivateStaticFieldString = "Hello";
public static int PublicStaticPropertyInt32
{
get
{
return 123;
}
}
public static string PublicStaticPropertyString
{
get
{
return "Hello";
}
}
private static int PrivateStaticPropertyInt32
{
get
{
return 123;
}
}
private static string PrivateStaticPropertyString
{
get
{
return "Hello";
}
}
public static int PublicStaticMethodInt32()
{
return 123;
}
public static string PublicStaticMethodString()
{
return "Hello";
}
private static int PrivateStaticMethodInt32()
{
return 123;
}
private static string PrivateStaticMethodString()
{
return "Hello";
}
}
public class GenericSample<T>
{
public T DefaultValue
{
get
{
return default(T);
}
}
}
#endregion
}
}
| 33.622754 | 100 | 0.5561 | [
"ECL-2.0",
"Apache-2.0"
] | Gallio/mbunit-v3 | src/Gallio/Gallio.Tests/Framework/Pattern/FixtureMemberInvokerTest.cs | 11,232 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Drawing.Internal;
using System.Runtime.InteropServices;
namespace System.Drawing.Printing
{
/// <summary>
/// Specifies settings that apply to a single page.
/// </summary>
public partial class PageSettings : ICloneable
{
internal PrinterSettings printerSettings;
private TriState _color = TriState.Default;
private PaperSize _paperSize;
private PaperSource _paperSource;
private PrinterResolution _printerResolution;
private TriState _landscape = TriState.Default;
private Margins _margins = new Margins();
/// <summary>
/// Initializes a new instance of the <see cref='PageSettings'/> class using the default printer.
/// </summary>
public PageSettings() : this(new PrinterSettings())
{
}
/// <summary>
/// Initializes a new instance of the <see cref='PageSettings'/> class using the specified printer.
/// </summary>
public PageSettings(PrinterSettings printerSettings)
{
Debug.Assert(printerSettings != null, "printerSettings == null");
this.printerSettings = printerSettings;
}
/// <summary>
/// Gets the bounds of the page, taking into account the Landscape property.
/// </summary>
public Rectangle Bounds
{
get
{
IntPtr modeHandle = printerSettings.GetHdevmode();
Rectangle pageBounds = GetBounds(modeHandle);
SafeNativeMethods.GlobalFree(new HandleRef(this, modeHandle));
return pageBounds;
}
}
/// <summary>
/// Gets or sets a value indicating whether the page is printed in color.
/// </summary>
public bool Color
{
get
{
if (_color.IsDefault)
return printerSettings.GetModeField(ModeField.Color, SafeNativeMethods.DMCOLOR_MONOCHROME) == SafeNativeMethods.DMCOLOR_COLOR;
else
return (bool)_color;
}
set { _color = value; }
}
/// <summary>
/// Returns the x dimension of the hard margin
/// </summary>
public float HardMarginX
{
get
{
float hardMarginX = 0;
DeviceContext dc = printerSettings.CreateDeviceContext(this);
try
{
int dpiX = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(dc, dc.Hdc), SafeNativeMethods.LOGPIXELSX);
int hardMarginX_DU = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(dc, dc.Hdc), SafeNativeMethods.PHYSICALOFFSETX);
hardMarginX = hardMarginX_DU * 100 / dpiX;
}
finally
{
dc.Dispose();
}
return hardMarginX;
}
}
/// <summary>
/// Returns the y dimension of the hard margin.
/// </summary>
public float HardMarginY
{
get
{
float hardMarginY = 0;
DeviceContext dc = printerSettings.CreateDeviceContext(this);
try
{
int dpiY = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(dc, dc.Hdc), SafeNativeMethods.LOGPIXELSY);
int hardMarginY_DU = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(dc, dc.Hdc), SafeNativeMethods.PHYSICALOFFSETY);
hardMarginY = hardMarginY_DU * 100 / dpiY;
}
finally
{
dc.Dispose();
}
return hardMarginY;
}
}
/// <summary>
/// Gets or sets a value indicating whether the page should be printed in landscape or portrait orientation.
/// </summary>
public bool Landscape
{
get
{
if (_landscape.IsDefault)
return printerSettings.GetModeField(ModeField.Orientation, SafeNativeMethods.DMORIENT_PORTRAIT) == SafeNativeMethods.DMORIENT_LANDSCAPE;
else
return (bool)_landscape;
}
set { _landscape = value; }
}
/// <summary>
/// Gets or sets a value indicating the margins for this page.
/// </summary>
public Margins Margins
{
get { return _margins; }
set { _margins = value; }
}
/// <summary>
/// Gets or sets the paper size.
/// </summary>
public PaperSize PaperSize
{
get
{
return GetPaperSize(IntPtr.Zero);
}
set { _paperSize = value; }
}
/// <summary>
/// Gets or sets a value indicating the paper source (i.e. upper bin).
/// </summary>
public PaperSource PaperSource
{
get
{
if (_paperSource == null)
{
IntPtr modeHandle = printerSettings.GetHdevmode();
IntPtr modePointer = SafeNativeMethods.GlobalLock(new HandleRef(this, modeHandle));
SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)UnsafeNativeMethods.PtrToStructure(modePointer, typeof(SafeNativeMethods.DEVMODE));
PaperSource result = PaperSourceFromMode(mode);
SafeNativeMethods.GlobalUnlock(new HandleRef(this, modeHandle));
SafeNativeMethods.GlobalFree(new HandleRef(this, modeHandle));
return result;
}
else
return _paperSource;
}
set { _paperSource = value; }
}
/// <summary>
/// Gets the PrintableArea for the printer. Units = 100ths of an inch.
/// </summary>
public RectangleF PrintableArea
{
get
{
RectangleF printableArea = new RectangleF();
DeviceContext dc = printerSettings.CreateInformationContext(this);
HandleRef hdc = new HandleRef(dc, dc.Hdc);
try
{
int dpiX = UnsafeNativeMethods.GetDeviceCaps(hdc, SafeNativeMethods.LOGPIXELSX);
int dpiY = UnsafeNativeMethods.GetDeviceCaps(hdc, SafeNativeMethods.LOGPIXELSY);
if (!Landscape)
{
//
// Need to convert the printable area to 100th of an inch from the device units
printableArea.X = (float)UnsafeNativeMethods.GetDeviceCaps(hdc, SafeNativeMethods.PHYSICALOFFSETX) * 100 / dpiX;
printableArea.Y = (float)UnsafeNativeMethods.GetDeviceCaps(hdc, SafeNativeMethods.PHYSICALOFFSETY) * 100 / dpiY;
printableArea.Width = (float)UnsafeNativeMethods.GetDeviceCaps(hdc, SafeNativeMethods.HORZRES) * 100 / dpiX;
printableArea.Height = (float)UnsafeNativeMethods.GetDeviceCaps(hdc, SafeNativeMethods.VERTRES) * 100 / dpiY;
}
else
{
//
// Need to convert the printable area to 100th of an inch from the device units
printableArea.Y = (float)UnsafeNativeMethods.GetDeviceCaps(hdc, SafeNativeMethods.PHYSICALOFFSETX) * 100 / dpiX;
printableArea.X = (float)UnsafeNativeMethods.GetDeviceCaps(hdc, SafeNativeMethods.PHYSICALOFFSETY) * 100 / dpiY;
printableArea.Height = (float)UnsafeNativeMethods.GetDeviceCaps(hdc, SafeNativeMethods.HORZRES) * 100 / dpiX;
printableArea.Width = (float)UnsafeNativeMethods.GetDeviceCaps(hdc, SafeNativeMethods.VERTRES) * 100 / dpiY;
}
}
finally
{
dc.Dispose();
}
return printableArea;
}
}
/// <summary>
/// Gets or sets the printer resolution for the page.
/// </summary>
public PrinterResolution PrinterResolution
{
get
{
if (_printerResolution == null)
{
IntPtr modeHandle = printerSettings.GetHdevmode();
IntPtr modePointer = SafeNativeMethods.GlobalLock(new HandleRef(this, modeHandle));
SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)UnsafeNativeMethods.PtrToStructure(modePointer, typeof(SafeNativeMethods.DEVMODE));
PrinterResolution result = PrinterResolutionFromMode(mode);
SafeNativeMethods.GlobalUnlock(new HandleRef(this, modeHandle));
SafeNativeMethods.GlobalFree(new HandleRef(this, modeHandle));
return result;
}
else
return _printerResolution;
}
set
{
_printerResolution = value;
}
}
/// <summary>
/// Gets or sets the associated printer settings.
/// </summary>
public PrinterSettings PrinterSettings
{
get { return printerSettings; }
set
{
if (value == null)
value = new PrinterSettings();
printerSettings = value;
}
}
/// <summary>
/// Copies the settings and margins.
/// </summary>
public object Clone()
{
PageSettings result = (PageSettings)MemberwiseClone();
result._margins = (Margins)_margins.Clone();
return result;
}
/// <summary>
/// Copies the relevant information out of the PageSettings and into the handle.
/// </summary>
public void CopyToHdevmode(IntPtr hdevmode)
{
IntPtr modePointer = SafeNativeMethods.GlobalLock(new HandleRef(null, hdevmode));
SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)UnsafeNativeMethods.PtrToStructure(modePointer, typeof(SafeNativeMethods.DEVMODE));
if (_color.IsNotDefault && ((mode.dmFields & SafeNativeMethods.DM_COLOR) == SafeNativeMethods.DM_COLOR))
mode.dmColor = unchecked((short)(((bool)_color) ? SafeNativeMethods.DMCOLOR_COLOR : SafeNativeMethods.DMCOLOR_MONOCHROME));
if (_landscape.IsNotDefault && ((mode.dmFields & SafeNativeMethods.DM_ORIENTATION) == SafeNativeMethods.DM_ORIENTATION))
mode.dmOrientation = unchecked((short)(((bool)_landscape) ? SafeNativeMethods.DMORIENT_LANDSCAPE : SafeNativeMethods.DMORIENT_PORTRAIT));
if (_paperSize != null)
{
if ((mode.dmFields & SafeNativeMethods.DM_PAPERSIZE) == SafeNativeMethods.DM_PAPERSIZE)
{
mode.dmPaperSize = unchecked((short)_paperSize.RawKind);
}
bool setWidth = false;
bool setLength = false;
if ((mode.dmFields & SafeNativeMethods.DM_PAPERLENGTH) == SafeNativeMethods.DM_PAPERLENGTH)
{
// dmPaperLength is always in tenths of millimeter but paperSizes are in hundredth of inch ..
// so we need to convert :: use PrinterUnitConvert.Convert(value, PrinterUnit.TenthsOfAMillimeter /*fromUnit*/, PrinterUnit.Display /*ToUnit*/)
int length = PrinterUnitConvert.Convert(_paperSize.Height, PrinterUnit.Display, PrinterUnit.TenthsOfAMillimeter);
mode.dmPaperLength = unchecked((short)length);
setLength = true;
}
if ((mode.dmFields & SafeNativeMethods.DM_PAPERWIDTH) == SafeNativeMethods.DM_PAPERWIDTH)
{
int width = PrinterUnitConvert.Convert(_paperSize.Width, PrinterUnit.Display, PrinterUnit.TenthsOfAMillimeter);
mode.dmPaperWidth = unchecked((short)width);
setWidth = true;
}
if (_paperSize.Kind == PaperKind.Custom)
{
if (!setLength)
{
mode.dmFields |= SafeNativeMethods.DM_PAPERLENGTH;
int length = PrinterUnitConvert.Convert(_paperSize.Height, PrinterUnit.Display, PrinterUnit.TenthsOfAMillimeter);
mode.dmPaperLength = unchecked((short)length);
}
if (!setWidth)
{
mode.dmFields |= SafeNativeMethods.DM_PAPERWIDTH;
int width = PrinterUnitConvert.Convert(_paperSize.Width, PrinterUnit.Display, PrinterUnit.TenthsOfAMillimeter);
mode.dmPaperWidth = unchecked((short)width);
}
}
}
if (_paperSource != null && ((mode.dmFields & SafeNativeMethods.DM_DEFAULTSOURCE) == SafeNativeMethods.DM_DEFAULTSOURCE))
{
mode.dmDefaultSource = unchecked((short)_paperSource.RawKind);
}
if (_printerResolution != null)
{
if (_printerResolution.Kind == PrinterResolutionKind.Custom)
{
if ((mode.dmFields & SafeNativeMethods.DM_PRINTQUALITY) == SafeNativeMethods.DM_PRINTQUALITY)
{
mode.dmPrintQuality = unchecked((short)_printerResolution.X);
}
if ((mode.dmFields & SafeNativeMethods.DM_YRESOLUTION) == SafeNativeMethods.DM_YRESOLUTION)
{
mode.dmYResolution = unchecked((short)_printerResolution.Y);
}
}
else
{
if ((mode.dmFields & SafeNativeMethods.DM_PRINTQUALITY) == SafeNativeMethods.DM_PRINTQUALITY)
{
mode.dmPrintQuality = unchecked((short)_printerResolution.Kind);
}
}
}
Marshal.StructureToPtr(mode, modePointer, false);
// It's possible this page has a DEVMODE for a different printer than the DEVMODE passed in here
// (Ex: occurs when Doc.DefaultPageSettings.PrinterSettings.PrinterName != Doc.PrinterSettings.PrinterName)
//
// if the passed in devmode has fewer bytes than our buffer for the extrainfo, we want to skip the merge as it will cause
// a buffer overrun
if (mode.dmDriverExtra >= ExtraBytes)
{
int retCode = SafeNativeMethods.DocumentProperties(NativeMethods.NullHandleRef, NativeMethods.NullHandleRef, printerSettings.PrinterName, modePointer, modePointer, SafeNativeMethods.DM_IN_BUFFER | SafeNativeMethods.DM_OUT_BUFFER);
if (retCode < 0)
{
SafeNativeMethods.GlobalFree(new HandleRef(null, modePointer));
}
}
SafeNativeMethods.GlobalUnlock(new HandleRef(null, hdevmode));
}
private short ExtraBytes
{
get
{
IntPtr modeHandle = printerSettings.GetHdevmodeInternal();
IntPtr modePointer = SafeNativeMethods.GlobalLock(new HandleRef(this, modeHandle));
SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)UnsafeNativeMethods.PtrToStructure(modePointer, typeof(SafeNativeMethods.DEVMODE));
short result = mode.dmDriverExtra;
SafeNativeMethods.GlobalUnlock(new HandleRef(this, modeHandle));
SafeNativeMethods.GlobalFree(new HandleRef(this, modeHandle));
return result;
}
}
// This function shows up big on profiles, so we need to make it fast
internal Rectangle GetBounds(IntPtr modeHandle)
{
Rectangle pageBounds;
PaperSize size = GetPaperSize(modeHandle);
if (GetLandscape(modeHandle))
pageBounds = new Rectangle(0, 0, size.Height, size.Width);
else
pageBounds = new Rectangle(0, 0, size.Width, size.Height);
return pageBounds;
}
private bool GetLandscape(IntPtr modeHandle)
{
if (_landscape.IsDefault)
return printerSettings.GetModeField(ModeField.Orientation, SafeNativeMethods.DMORIENT_PORTRAIT, modeHandle) == SafeNativeMethods.DMORIENT_LANDSCAPE;
else
return (bool)_landscape;
}
private PaperSize GetPaperSize(IntPtr modeHandle)
{
if (_paperSize == null)
{
bool ownHandle = false;
if (modeHandle == IntPtr.Zero)
{
modeHandle = printerSettings.GetHdevmode();
ownHandle = true;
}
IntPtr modePointer = SafeNativeMethods.GlobalLock(new HandleRef(null, modeHandle));
SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)UnsafeNativeMethods.PtrToStructure(modePointer, typeof(SafeNativeMethods.DEVMODE));
PaperSize result = PaperSizeFromMode(mode);
SafeNativeMethods.GlobalUnlock(new HandleRef(null, modeHandle));
if (ownHandle)
SafeNativeMethods.GlobalFree(new HandleRef(null, modeHandle));
return result;
}
else
return _paperSize;
}
private PaperSize PaperSizeFromMode(SafeNativeMethods.DEVMODE mode)
{
PaperSize[] sizes = printerSettings.Get_PaperSizes();
if ((mode.dmFields & SafeNativeMethods.DM_PAPERSIZE) == SafeNativeMethods.DM_PAPERSIZE)
{
for (int i = 0; i < sizes.Length; i++)
{
if ((int)sizes[i].RawKind == mode.dmPaperSize)
return sizes[i];
}
}
return new PaperSize(PaperKind.Custom, "custom",
//mode.dmPaperWidth, mode.dmPaperLength);
PrinterUnitConvert.Convert(mode.dmPaperWidth, PrinterUnit.TenthsOfAMillimeter, PrinterUnit.Display),
PrinterUnitConvert.Convert(mode.dmPaperLength, PrinterUnit.TenthsOfAMillimeter, PrinterUnit.Display));
}
private PaperSource PaperSourceFromMode(SafeNativeMethods.DEVMODE mode)
{
PaperSource[] sources = printerSettings.Get_PaperSources();
if ((mode.dmFields & SafeNativeMethods.DM_DEFAULTSOURCE) == SafeNativeMethods.DM_DEFAULTSOURCE)
{
for (int i = 0; i < sources.Length; i++)
{
// the dmDefaultSource == to the RawKind in the Papersource.. and Not the Kind...
// if the PaperSource is populated with CUSTOM values...
if (unchecked((short)sources[i].RawKind) == mode.dmDefaultSource)
{
return sources[i];
}
}
}
return new PaperSource((PaperSourceKind)mode.dmDefaultSource, "unknown");
}
private PrinterResolution PrinterResolutionFromMode(SafeNativeMethods.DEVMODE mode)
{
PrinterResolution[] resolutions = printerSettings.Get_PrinterResolutions();
for (int i = 0; i < resolutions.Length; i++)
{
if (mode.dmPrintQuality >= 0 && ((mode.dmFields & SafeNativeMethods.DM_PRINTQUALITY) == SafeNativeMethods.DM_PRINTQUALITY)
&& ((mode.dmFields & SafeNativeMethods.DM_YRESOLUTION) == SafeNativeMethods.DM_YRESOLUTION))
{
if (resolutions[i].X == unchecked((int)(PrinterResolutionKind)mode.dmPrintQuality)
&& resolutions[i].Y == unchecked((int)(PrinterResolutionKind)mode.dmYResolution))
return resolutions[i];
}
else
{
if ((mode.dmFields & SafeNativeMethods.DM_PRINTQUALITY) == SafeNativeMethods.DM_PRINTQUALITY)
{
if (resolutions[i].Kind == (PrinterResolutionKind)mode.dmPrintQuality)
return resolutions[i];
}
}
}
return new PrinterResolution(PrinterResolutionKind.Custom,
mode.dmPrintQuality, mode.dmYResolution);
}
/// <summary>
/// Copies the relevant information out of the handle and into the PageSettings.
/// </summary>
public void SetHdevmode(IntPtr hdevmode)
{
if (hdevmode == IntPtr.Zero)
throw new ArgumentException(SR.Format(SR.InvalidPrinterHandle, hdevmode));
IntPtr pointer = SafeNativeMethods.GlobalLock(new HandleRef(null, hdevmode));
SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)UnsafeNativeMethods.PtrToStructure(pointer, typeof(SafeNativeMethods.DEVMODE));
if ((mode.dmFields & SafeNativeMethods.DM_COLOR) == SafeNativeMethods.DM_COLOR)
{
_color = (mode.dmColor == SafeNativeMethods.DMCOLOR_COLOR);
}
if ((mode.dmFields & SafeNativeMethods.DM_ORIENTATION) == SafeNativeMethods.DM_ORIENTATION)
{
_landscape = (mode.dmOrientation == SafeNativeMethods.DMORIENT_LANDSCAPE);
}
_paperSize = PaperSizeFromMode(mode);
_paperSource = PaperSourceFromMode(mode);
_printerResolution = PrinterResolutionFromMode(mode);
SafeNativeMethods.GlobalUnlock(new HandleRef(null, hdevmode));
}
/// <summary>
/// Provides some interesting information about the PageSettings in String form.
/// </summary>
public override string ToString()
{
return "[PageSettings:"
+ " Color=" + Color.ToString()
+ ", Landscape=" + Landscape.ToString()
+ ", Margins=" + Margins.ToString()
+ ", PaperSize=" + PaperSize.ToString()
+ ", PaperSource=" + PaperSource.ToString()
+ ", PrinterResolution=" + PrinterResolution.ToString()
+ "]";
}
}
}
| 41.990909 | 246 | 0.55774 | [
"MIT"
] | dotnet40/corefx | src/System.Drawing.Common/src/System/Drawing/Printing/PageSettings.cs | 23,095 | C# |
using System.Linq;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using AmazonToo.Models;
namespace AmazonToo.Models {
public static class SeedData {
public static void EnsurePopulated(IApplicationBuilder app)
{
ApplicationDbContext context = app.ApplicationServices.GetService<ApplicationDbContext>();
context.Database.Migrate();
if (!context.Products.Any())
{
context.Products.AddRange(
new Product
{
Name = "Kayak",
Description = "A boat for one person",
Category = "Watersports",
Price = 275
},
new Product
{
Name = "Lifejacket",
Description = "Protective and fashionable",
Category = "Watersports",
Price = 48.95m
},
new Product
{
Name = "Soccer Ball",
Description = "FIFA-approved size and weight",
Category = "Soccer",
Price = 19.50m
},
new Product
{
Name = "Corner Flags",
Description = "Give your playing field a professional touch",
Category = "Soccer",
Price = 34.95m
},
new Product
{
Name = "Stadium",
Description = "Flat-packed 35,000-seat stadium",
Category = "Soccer",
Price = 79500
},
new Product
{
Name = "Thinking Cap",
Description = "Improve brain efficiency by 75%",
Category = "Chess",
Price = 16
},
new Product
{
Name = "Unsteady Chair",
Description = "Secretly give your opponent a disadvantage",
Category = "Chess",
Price = 29.95m
},
new Product
{
Name = "Human Chess Board",
Description = "A fun game for the family",
Category = "Chess",
Price = 75
},
new Product
{
Name = "Bling-Bling King",
Description = "Gold-plated, diamond-studded King",
Category = "Chess",
Price = 1200
},
new Product
{
Name = "Basketball",
Description = "NBA-approved size and weight",
Category = "Basketball",
Price = 49.50m
},
new Product
{
Name = "AMD Ryzen 5 3600 6-Core, 12-thread unlocked desktop processor with Wraith Stealth cooler.",
Description = "Lorem Ipsum",
Price = 244.99m,
Image = "https://images-na.ssl-images-amazon.com/images/I/71WPGXQLcLL._AC_SR300,300_.jpg",
Category = "Computers"
},
new Product
{
Name = "Razer Gaming Mouse Bungee v2: Drag-Free Wired Mouse Support - for Esports-Level Performance - Matte Black",
Description = "Lorem Ipsum",
Price = 19.99m,
Image = "https://images-na.ssl-images-amazon.com/images/I/61JasIJ-mwL._AC_SR300,300_.jpg",
Category = "Computers"
},
new Product
{
Name = "Razer Sphex V2 Gaming Mousepad",
Description = "Lorem Ipsum",
Price = 14.99m,
Image = "https://images-na.ssl-images-amazon.com/images/I/71wvjUf7tcL._AC_SR300,300_.jpg",
Category = "Computers"
},
new Product
{
Name = "AMD Ryzen 7 3700X 8-core, 16-thread processor with Wraith Prism LED Cooler",
Description = "Lorem Ipsum",
Price = 429.99m,
Image = "https://images-na.ssl-images-amazon.com/images/I/71TxPH4j0vL._AC_SR300,300_.jpg",
Category = "Computers"
},
new Product
{
Name = "Elgato Game Capture HD60 S - stream, record and share your gameplay in 1080p60, superior low latency technology, USB 3.0, for PS4, Xbox One and Nintendo Switch",
Description = "Lorem Ipsum",
Price = 159.95m,
Image = "https://images-na.ssl-images-amazon.com/images/I/51QXd5YcvcL._AC_SR300,300_.jpg",
Category = "Computers"
},
new Product
{
Name = "AMD Ryzen 7 2700X Processor with Wraith Prism LED Cooler - YD270XBGAFBOX",
Description = "Lorem Ipsum",
Price = 209.99m,
Image = "https://images-na.ssl-images-amazon.com/images/I/61wP16xC7tL._AC_SR300,300_.jpg",
Category = "Computers"
},
new Product
{
Name = "Razer Kraken Gaming Headset 2019: Lightweight Aluminum Frame - Retractable Noise Cancelling Mic - For PC, Xbox, PS4, Nintendo Switch - Black",
Description = "Lorem Ipsum",
Price = 69.99m,
Image = "https://images-na.ssl-images-amazon.com/images/I/61W9lG1pCXL._AC_SR300,300_.jpg",
Category = "Computers"
},
new Product
{
Name = "Razer Firefly Chroma Cloth Gaming Mousepad: Customizable Chroma RGB Lighting - 14\"x10\" - Balanced Control & Speed - Non-Slip Rubber Base",
Description = "Lorem Ipsum",
Price = 49.99m,
Image = "https://images-na.ssl-images-amazon.com/images/I/71J-IcWKGiL._AC_SR300,300_.jpg",
Category = "Computers"
},
new Product
{
Name = "Elgato Stream Deck - Live Content Creation Controller with 15 customizable LCD keys, adjustable stand, for Windows 10 and macOS 10.11 or later",
Description = "Lorem Ipsum",
Price = 139.95m,
Image = "https://images-na.ssl-images-amazon.com/images/I/710R9YpV9nL._AC_SR300,300_.jpg",
Category = "Computers"
},
new Product
{
Name = "Razer Kraken Gaming Headset 2019: Lightweight Aluminum Frame - Retractable Cardioid Mic - For PC, Xbox, PS4, Nintendo Switch - Green",
Description = "Lorem Ipsum",
Price = 69.99m,
Image = "https://images-na.ssl-images-amazon.com/images/I/61AMW91VjqL._AC_SR300,300_.jpg",
Category = "Computers"
},
new Product
{
Name = "Razer Huntsman: Opto-Mechanical Switch - Hybrid On-Board Memory & Cloud Storage - Durability of up to 100 Million Keystrokes - Light and Clicky Gaming Keyboard",
Description = "Lorem Ipsum",
Price = 139.99m,
Image = "https://images-na.ssl-images-amazon.com/images/I/71FJGmeJ2GL._AC_SR300,300_.jpg",
Category = "Computers"
},
new Product
{
Name = "Elgato Cam Link 4K — Broadcast Live, Record via DSLR, Camcorder, or Action cam, 1080p60 or 4K at 30 fps, Compact HDMI Capture Device, USB 3.0",
Description = "Lorem Ipsum",
Price = 139.95m,
Image = "https://images-na.ssl-images-amazon.com/images/I/61pWBRbG98L._AC_SR300,300_.jpg",
Category = "Computers"
},
new Product
{
Name = "Razer Goliathus Chroma Gaming Mousepad: Customizable Chroma RGB Lighting - Soft, Cloth Material - Balanced Control & Speed - Non-Slip Rubber Base - Matte Black",
Description = "Lorem Ipsum",
Price = 39.99m,
Image = "https://images-na.ssl-images-amazon.com/images/I/91G-JYStqwL._AC_SR300,300_.jpg",
Category = "Computers"
},
new Product
{
Name = "Razer Kraken Tournament Edition THX 7.1 Surround Sound Gaming Headset: Aluminum Frame - Retractable Noise Cancelling Mic - USB DAC Included - For PC, Xbox, PS4, Nintendo Switch - Green",
Description = "Lorem Ipsum",
Price = 79.99m,
Image = "https://images-na.ssl-images-amazon.com/images/I/61Ufzi3lugL._AC_SR300,300_.jpg",
Category = "Computers"
},
new Product
{
Name = "AMD Ryzen 7 3800X 8-core, 16-thread unlocked desktop processor with Wraith Prism LED Cooler",
Description = "Lorem Ipsum",
Price = 444.99m,
Image = "https://images-na.ssl-images-amazon.com/images/I/71S4mkgvGNL._AC_SR300,300_.jpg",
Category = "Computers"
},
new Product
{
Name = "Razer Mamba Elite Wired Gaming Mouse: 16,000 DPI Optical Sensor - Chroma RGB Lighting - 9 Programmable Buttons - Mechanical Switches",
Description = "Lorem Ipsum",
Price = 69.99m,
Image = "https://images-na.ssl-images-amazon.com/images/I/61pz6N01NJL._AC_SR300,300_.jpg",
Category = "Computers"
},
new Product
{
Name = "Razer Nari Wireless 7.1 Surround Sound Gaming Headset: THX Audio - Auto-Adjust Headband & Swivel Cups - Chroma RGB - Retractable Mic - for PC, PS4, Xbox One - Black",
Description = "Lorem Ipsum",
Price = 129.99m,
Image = "https://images-na.ssl-images-amazon.com/images/I/51CguHFmDqL._AC_SR300,300_.jpg",
Category = "Computers"
},
new Product
{
Name = "Razer BlackWidow Elite Mechanical Gaming Keyboard: Green Mechanical Switches - Tactile & Clicky - Chroma RGB Lighting - Magnetic Wrist Rest - Dedicated Media Keys & Dial - USB Passthrough",
Description = "Lorem Ipsum",
Price = 149.99m,
Image = "https://images-na.ssl-images-amazon.com/images/I/81oLMQUj4fL._AC_SR300,300_.jpg",
Category = "Computers"
},
new Product
{
Name = "MSI Optix AG32C Full HD Non-Flare Curve 32\" VA Panel 1ms 1920 x 1080 165HzFreeSync Gaming Monitor w/Height Adjustment, Super Narrow Bezel",
Description = "Lorem Ipsum",
Price = 349.99m,
Image = "https://images-na.ssl-images-amazon.com/images/I/61g6iwQPHXL._AC_SR300,300_.jpg",
Category = "Computers"
},
new Product
{
Name = "MSI Full HD Non-Glare Super Narrow Bezel 1ms 1920 X 1080 144Hz Refresh RateTrue Color FreeSync 27” Curved Gaming Monitor (OPTIX G27C2)",
Description = "Lorem Ipsum",
Price = 249.99m,
Image = "https://images-na.ssl-images-amazon.com/images/I/81R49k0FMYL._AC_SR300,300_.jpg",
Category = "Computers"
},
new Product
{
Name = "Razer Basilisk Gaming Mouse: 16,000 DPI Optical Sensor - Chroma RGB Lighting - 8 Programmable Buttons - Mechanical Switches - Customizable Scroll Resistance - Matte Black",
Description = "Lorem Ipsum",
Price = 59.99m,
Image = "https://images-na.ssl-images-amazon.com/images/I/71oYOFlv9rL._AC_SR300,300_.jpg",
Category = "Computers"
},
new Product
{
Name = "Razer BlackWidow Mechanical Gaming Keyboard 2019: Green Mechanical Switches- Tactile & Clicky - Chroma RGB Lighting - Anti-Ghosting - Programmable Macro Functionality",
Description = "Lorem Ipsum",
Price = 109.99m,
Image = "https://images-na.ssl-images-amazon.com/images/I/71sXzUqI9XL._AC_SR300,300_.jpg",
Category = "Computers"
},
new Product
{
Name = "Razer DeathAdder Essential Gaming Mouse: 6400 DPI Optical Sensor - Chroma RGB Lighting - 5 Programmable Buttons - Mechanical Switches - Rubber Side Grips - White",
Description = "Lorem Ipsum",
Price = 39.99m,
Image = "https://images-na.ssl-images-amazon.com/images/I/51O9tbUuOHL._AC_SR300,300_.jpg",
Category = "Computers"
},
new Product
{
Name = "Elgato Stream Deck XL - Live Content Creation Controller with 32 Customizable LCD Keys, Adjustable Stand, for Windows 10 and macOS 10.11 or Later",
Description = "Lorem Ipsum",
Price = 269.95m,
Image = "https://images-na.ssl-images-amazon.com/images/I/71aY+mfIxiL._AC_SR300,300_.jpg",
Category = "Computers"
},
new Product
{
Name = "MSI Force GC30 Wireless Rechargeable Dual Vibration Gaming Controller for PC, Android and Sony Playstation 4",
Description = "Lorem Ipsum",
Price = 39.99m,
Image = "https://images-na.ssl-images-amazon.com/images/I/51ZAA4YElTL._AC_SR300,300_.jpg",
Category = "Computers"
},
new Product
{
Name = "Razer BlackWidow Elite Mechanical Gaming Keyboard: Yellow Mechanical Switches - Linear & Silent - Chroma RGB Lighting - Magnetic Wrist Rest - Dedicated Media Keys & Dial - USB Passthrough",
Description = "Lorem Ipsum",
Price = 139.99m,
Image = "https://images-na.ssl-images-amazon.com/images/I/81oLMQUj4fL._AC_SR300,300_.jpg",
Category = "Computers"
},
new Product
{
Name = "Razer BlackWidow Elite Mechanical Gaming Keyboard: Orange Mechanical Switches - Tactile & Silent - Chroma RGB Lighting - Magnetic Wrist Rest - Dedicated Media Keys & Dial - USB Passthrough",
Description = "Lorem Ipsum",
Price = 139.99m,
Image = "https://images-na.ssl-images-amazon.com/images/I/81oLMQUj4fL._AC_SR300,300_.jpg",
Category = "Computers"
},
new Product
{
Name = "AOPEN 24MX1 bii 24-inch Full HD (1920 x 1080) Gaming Monitor with AMD Radeon FreeSync Technology (2 x HDMI & VGA Port), Black",
Description = "Lorem Ipsum",
Price = 126.99m,
Image = "https://images-na.ssl-images-amazon.com/images/I/71Br2w7Uo1L._AC_SR300,300_.jpg",
Category = "Computers"
},
new Product
{
Name = "Razer BlackWidow TE Chroma v2 Mechanical Gaming Keyboard: Green Key Switches - Tactile & Clicky - Chroma RGB Lighting - Magnetic Wrist Rest - Programmable Macro Functionality - Matte Black",
Description = "Lorem Ipsum",
Price = 139.99m,
Image = "https://images-na.ssl-images-amazon.com/images/I/81lxQgJ8B6L._AC_SR300,300_.jpg",
Category = "Computers"
},
new Product
{
Name = "Asus ROG Strix Hero II Gaming Laptop, 15.6” 144Hz IPS-Type Display, GTX1060 6GB, Core i7-8750H, 256GB SSD Plus 1TB HDD, 16GB DDR4 GL504GM-XS74",
Description = "Lorem Ipsum",
Price = 1079.00m,
Image = "https://images-na.ssl-images-amazon.com/images/I/81RIr5YR3QL._AC_SR300,300_.jpg",
Category = "Computers"
}
);
context.SaveChanges();
}
}
}
}
| 49.984536 | 222 | 0.442199 | [
"Apache-2.0"
] | SheridanCS/AmazonToo | Models/SeedData.cs | 19,402 | C# |
using Abp.EntityFramework;
using CityQuest.Entities.GameModule.Games.GameTasks.Conditions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CityQuest.EntityFramework.Repositories.GameModule
{
public class ConditionRepository : CityQuestRepositoryBase<Condition, long>, IConditionRepository
{
public ConditionRepository(IDbContextProvider<CityQuestDbContext> dbContextProvider)
: base(dbContextProvider) { }
}
}
| 30.705882 | 101 | 0.793103 | [
"Apache-2.0"
] | elrondsoft/city-quest | CityQuest.EntityFramework/EntityFramework/Repositories/GameModule/ConditionRepository.cs | 524 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Elastic.Elasticsearch.Xunit.XunitPlumbing;
using Elasticsearch.Net;
using FluentAssertions;
using Tests.Framework;
using static Elasticsearch.Net.VirtualizedCluster.Rules.TimesHelper;
using static Elasticsearch.Net.AuditEvent;
namespace Tests.ClientConcepts.ConnectionPooling.Sticky
{
public class Sticky
{
/** Sticky Connection Pool
* Each connection pool returns the first `live` node so that it is sticky between requests
*/
[U]
public void EachViewStartsAtNextPositionAndWrapsOver()
{
var numberOfNodes = 10;
var uris = Enumerable.Range(9200, numberOfNodes).Select(p => new Uri("http://localhost:" + p));
var pool = new StickyConnectionPool(uris);
/**
* Here we have setup a sticky connection pool seeded with 10 nodes.
* So what order we expect? Imagine the following:
*
* Thread A calls `.CreateView()` and gets returned the first live node
* Thread B calls `.CreateView()` and gets returned the same node, since the first
* node is still good
*/
var startingPositions = Enumerable.Range(0, numberOfNodes)
.Select(i => pool.CreateView().First())
.Select(n => n.Uri.Port)
.ToList();
var expectedOrder = Enumerable.Repeat(9200, numberOfNodes);
startingPositions.Should().ContainInOrder(expectedOrder);
}
}
}
| 32.653846 | 98 | 0.748528 | [
"Apache-2.0"
] | Brightspace/elasticsearch-net | tests/Tests/ClientConcepts/ConnectionPooling/Sticky/Sticky.doc.cs | 1,700 | C# |
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org)
// Copyright (c) 2018-2021 Stride and its contributors (https://stride3d.net)
// Copyright (c) 2011-2018 Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// See the LICENSE.md file in the project root for full license information.
using System;
using Stride.Core;
namespace Stride.Graphics
{
/// <summary>
/// Identify which components of each pixel of a render target are writable during blending.
/// </summary>
/// <remarks>
/// These flags can be combined with a bitwise OR and is used in <see cref="BlendState"/>.
/// </remarks>
[Flags]
[DataContract]
public enum ColorWriteChannels
{
/// <summary>
/// None of the data are stored.
/// </summary>
None = 0,
/// <summary>
/// Allow data to be stored in the red component.
/// </summary>
Red = 1,
/// <summary>
/// Allow data to be stored in the green component.
/// </summary>
Green = 2,
/// <summary>
/// Allow data to be stored in the blue component.
/// </summary>
Blue = 4,
/// <summary>
/// Allow data to be stored in the alpha component.
/// </summary>
Alpha = 8,
/// <summary>
/// Allow data to be stored in all components.
/// </summary>
All = Alpha | Blue | Green | Red,
}
}
| 27.811321 | 96 | 0.567164 | [
"MIT"
] | Ethereal77/stride | sources/engine/Stride.Graphics/ColorWriteChannels.cs | 1,474 | C# |
using Academy.Models;
using Academy.Models.Contracts;
using Academy.Models.Enums;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
namespace Academy.Tests.Models.SeasonTests
{
[TestClass]
public class SeasonListUsers_Should
{
[TestMethod]
public void ReturnListOfStudents_WhenTheCollectionIsNotEmpty()
{
// Arrange
var season = new Season(2017, 2017, Initiative.SoftwareAcademy);
var studentMock = new Mock<IStudent>();
studentMock.Setup(x => x.ToString());
season.Students.Add(studentMock.Object);
// Act
season.ListUsers();
// Assert
studentMock.Verify(x => x.ToString(), Times.Once);
}
[TestMethod]
public void ReturnListOfTrainers_WhenTheCollectionIsNotEmpty()
{
// Arrange
var season = new Season(2017, 2017, Initiative.SoftwareAcademy);
var trainerMock = new Mock<ITrainer>();
trainerMock.Setup(x => x.ToString());
season.Trainers.Add(trainerMock.Object);
// Act
season.ListUsers();
// Assert
trainerMock.Verify(x => x.ToString(), Times.Once);
}
[TestMethod]
public void ReturnAMessage_WhenCollectionIsEmpty()
{
// Arrange
var season = new Season(2017, 2017, Initiative.SoftwareAcademy);
// Act
var message = "There are no users in this season!";
var result = season.ListUsers();
// Assert
StringAssert.Contains(message, result);
}
}
}
| 28.360656 | 76 | 0.560116 | [
"MIT"
] | albozhinov/TelerikTasks | UnitTestingWorkshopAcademy/Skeleton/Academy.Tests/Models/SeasonTests/SeasonListUsers_Should.cs | 1,732 | C# |
using System.Collections;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(CollisionState))]
public abstract class PlayerBehaviour : MonoBehaviour {
protected static Rigidbody rb;
protected static CollisionState collisionState;
protected static PlayerSettings settings;
private static Player player;
protected virtual void Awake() {
rb = GetComponent<Rigidbody>();
player = GetComponent<Player>();
collisionState = GetComponent<CollisionState>();
Wake();
}
protected virtual void Start() {
settings = player.Settings;
Begin();
}
protected virtual void Update() {
Tick();
}
///<summary>replaces the Awake() method in EnemyComponents</summary>
protected virtual void Wake() { }
///<summary>replaces the Start() method in EnemyComponents</summary>
protected virtual void Begin() { }
///<summary>replaces the Update() method in EnemyComponents</summary>
protected virtual void Tick() { }
} | 29.857143 | 73 | 0.683254 | [
"MIT"
] | Wesselmast/UnityBugReportSystem | Assets/Scripts/Player/PlayerBehaviour/PlayerBehaviour.cs | 1,047 | C# |
using System;
using UnityEngine;
namespace AgatePris.Apuu {
[Serializable]
public struct NullableUShort {
[SerializeField] bool hasValue;
[SerializeField] ushort value;
public bool HasValue => hasValue;
public ushort Value => !hasValue
? throw new InvalidOperationException("Nullable object must have a value.") : value;
public NullableUShort(ushort value) {
hasValue = true;
this.value = value;
}
public override bool Equals(object other)
=> !hasValue ? other is null : value.Equals(other);
public override int GetHashCode() => !hasValue ? 0 : value.GetHashCode();
public ushort GetValueOrDefault() => !hasValue ? default : value;
public ushort GetValueOrDefault(ushort defaultValue) => !hasValue ? defaultValue : value;
public override string ToString() => !hasValue ? "" : value.ToString();
public static implicit operator NullableUShort(ushort value) => new NullableUShort(value);
public static explicit operator ushort(NullableUShort value) => value.Value;
}
}
| 39.137931 | 98 | 0.654626 | [
"CC0-1.0"
] | agate-pris/Apuu | Scripts/NullableUShort.cs | 1,137 | C# |
namespace Eventuous.EventStore;
public static class StreamRevisionExtensions {
public static StreamRevision AsStreamRevision(this ExpectedStreamVersion version)
=> StreamRevision.FromInt64(version.Value);
public static StreamPosition AsStreamPosition(this StreamTruncatePosition position)
=> StreamPosition.FromInt64(position.Value);
public static StreamPosition AsStreamPosition(this StreamReadPosition position)
=> StreamPosition.FromInt64(position.Value);
} | 42.333333 | 87 | 0.783465 | [
"MIT"
] | Eventuous/eventuous | src/EventStore/src/Eventuous.EventStore/StreamRevisionExtensions.cs | 508 | C# |
using System;
using System.Collections.Generic;
using System.Data;
namespace Velentr.Localizations
{
/// <summary>
/// Defines a language (a set of localized text and the locale it is a part of)
/// </summary>
internal class Localization
{
/// <summary>
/// The cache
/// </summary>
private Dictionary<string, string> _cache;
/// <summary>
/// Initializes a new instance of the <see cref="Localization" /> class.
/// </summary>
/// <param name="system">The system.</param>
/// <param name="locale">The locale.</param>
/// <param name="defaultLocale">The default locale.</param>
/// <param name="enableMachineTranslation">Whether to enable machine translations.</param>
internal Localization(LocalizationSystem system, string locale, string defaultLocale = null, bool enableMachineTranslation = false)
{
LocalizationSystem = system;
Locale = locale;
DefaultLocale = defaultLocale;
MachineTranslationEnabled = enableMachineTranslation;
_cache = new Dictionary<string, string>();
if (enableMachineTranslation)
{
// validate that the language pairs are valid!
if (!LocalizationSystem.Apertium.IsValidPair(locale, defaultLocale))
{
throw new Exception($"Invalid language pair! Valid Pairs: {system.Apertium.GetValidPairsString()}");
}
}
}
/// <summary>
/// Gets the localization system.
/// </summary>
/// <value>
/// The localization system.
/// </value>
internal LocalizationSystem LocalizationSystem { get; }
/// <summary>
/// Gets the locale.
/// </summary>
/// <value>
/// The locale.
/// </value>
internal string Locale { get; }
/// <summary>
/// Gets the default locale.
/// </summary>
/// <value>
/// The default locale.
/// </value>
internal string DefaultLocale { get; }
/// <summary>
/// Gets a value indicating whether the machine translation is enabled.
/// </summary>
///
/// <value>
/// True if machine translation enabled, false if not.
/// </value>
internal bool MachineTranslationEnabled { get; }
/// <summary>
/// Clears the cache.
/// </summary>
internal void ClearCache()
{
_cache.Clear();
}
/// <summary>
/// Adds the localization.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="text">The text.</param>
internal void AddLocalization(string key, string text)
{
_cache[key] = text;
}
/// <summary>
/// Adds the localizations.
/// </summary>
/// <param name="localizations">The localizations.</param>
/// <param name="loadMode">The load mode.</param>
/// <param name="conflictResolution">The conflict resolution.</param>
/// <exception cref="DuplicateNameException">A localization already exists in [{Locale}] for the key [{localization.Key}]!</exception>
internal void AddLocalizations(Dictionary<string, string> localizations, LocalizationLoadMode loadMode = LocalizationLoadMode.Truncate, ConflictResolution conflictResolution = ConflictResolution.RaiseException)
{
if (loadMode == LocalizationLoadMode.Truncate)
{
ClearCache();
}
foreach (var localization in localizations)
{
switch (conflictResolution)
{
case ConflictResolution.Override:
_cache[localization.Key] = localization.Value;
break;
case ConflictResolution.RaiseException:
case ConflictResolution.Skip:
if (_cache.ContainsKey(localization.Key))
{
if (conflictResolution == ConflictResolution.RaiseException)
{
throw new DuplicateNameException($"A localization already exists in [{Locale}] for the key [{localization.Key}]!");
}
break;
}
_cache[localization.Key] = localization.Value;
break;
}
}
}
/// <summary>
/// Adds the localization.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="text">The text.</param>
/// <param name="conflictResolution">The conflict resolution.</param>
/// <exception cref="DuplicateNameException">A localization already exists in [{Locale}] for the key [{key}]!</exception>
internal void AddLocalization(string key, string text, ConflictResolution conflictResolution = ConflictResolution.RaiseException)
{
if (_cache.ContainsKey(key))
{
switch (conflictResolution)
{
case ConflictResolution.RaiseException:
throw new DuplicateNameException($"A localization already exists in [{Locale}] for the key [{key}]!");
case ConflictResolution.Skip:
return;
}
}
_cache[key] = text;
}
/// <summary>
/// Gets a localization.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>The localization.</returns>
internal string GetLocalization(string key)
{
if (_cache.TryGetValue(key, out var value))
{
return value;
}
if (MachineTranslationEnabled)
{
var defaultLocaleLocalization = LocalizationSystem.GetLocalization(key, DefaultLocale);
var translation = LocalizationSystem.Apertium.Translate(defaultLocaleLocalization);
_cache.Add(key, translation);
return translation;
}
return LocalizationSystem.GetLocalization(key, DefaultLocale);
}
}
}
| 35.586957 | 218 | 0.529322 | [
"MIT"
] | vonderborch/Velentr.Localizations | Velentr.Localizations/Localization.cs | 6,550 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
namespace Swifter.RW
{
internal sealed class DictionaryRW<T> : IDataRW<object>, IDirectContent where T : IDictionary
{
public const int DefaultCapacity = 3;
internal T content;
public T Content => content;
public ValueCopyer<object> this[object key]=> new ValueCopyer<object>(this, key);
IValueRW IDataRW<object>.this[object key] => this[key];
IValueWriter IDataWriter<object>.this[object key]=> this[key];
IValueReader IDataReader<object>.this[object key]=> this[key];
public IEnumerable<object> Keys
{
get
{
// TODO:
return (IEnumerable<object>)content.Keys;
}
}
public int Count
{
get
{
return content.Count;
}
}
object IDirectContent.DirectContent
{
get
{
return content;
}
set
{
content = (T)value;
}
}
public object ReferenceToken
{
get
{
return content;
}
}
public void Initialize()
{
Initialize(DefaultCapacity);
}
public void Initialize(T content)
{
this.content = content;
}
public void Initialize(int capacity)
{
if (typeof(T) == typeof(Hashtable) || typeof(T).IsAssignableFrom(typeof(Hashtable)))
{
content = (T)(object)new Hashtable(capacity);
}
else
{
// TODO: Capacity
content = Activator.CreateInstance<T>();
}
}
public void OnReadAll(IDataWriter<object> dataWriter)
{
foreach (DictionaryEntry item in content)
{
ValueInterface.WriteValue(dataWriter[item.Key], item.Value);
}
}
public void OnReadValue(object key, IValueWriter valueWriter)
{
ValueInterface.WriteValue(valueWriter, content[key]);
}
public void OnWriteValue(object key, IValueReader valueReader)
{
content[key] = ValueInterface<object>.ReadValue(valueReader);
}
public void OnReadAll(IDataWriter<object> dataWriter, IValueFilter<object> valueFilter)
{
var valueInfo = new ValueFilterInfo<object>();
foreach (DictionaryEntry item in content)
{
ValueInterface.WriteValue(valueInfo.ValueCopyer, item.Value);
valueInfo.Key = item.Key;
valueInfo.Type = typeof(object);
if (valueFilter.Filter(valueInfo))
{
valueInfo.ValueCopyer.WriteTo(dataWriter[valueInfo.Key]);
}
}
}
public void OnWriteAll(IDataReader<object> dataReader)
{
var buckets = new KeyValuePair<object, object>[content.Count];
var index = 0;
foreach (var item in content.Keys)
{
buckets[index] = new KeyValuePair<object, object>(item, ValueInterface<object>.ReadValue(dataReader[item]));
++index;
}
content.Clear();
foreach (var item in buckets)
{
content.Add(item.Key, item.Value);
}
}
}
} | 25.216783 | 124 | 0.509429 | [
"MIT"
] | BenLampson/Swifter.Json | Swifter.Core/RW/Collection/DictionaryRW.cs | 3,608 | C# |
using UnityEngine;
using System.Collections;
/// <summary>
///
/// </summary>
public class AnimNofity : ScriptableObject
{
}
| 11.727273 | 42 | 0.689922 | [
"MIT"
] | kimsama/Unity-AnimatorEventHandler | Assets/AnimatorEventHandler/Scripts/AnimNofity.cs | 131 | C# |
namespace FancyServer.Logging {
public enum StdType {
//Input = 0,
Output = 1,
Error = 2,
}
public struct StdStruct {
public StdType type;
public string process;
public string content;
}
public static class StdClerk {
public static StdType StdLevel { get; set; } = StdType.Error;
public static void StdOutput(string process, string message) {
LoggingManager.Send(new StdStruct {
type = StdType.Output,
process = process,
content = message,
});
}
public static void StdError(string process, string message) {
LoggingManager.Send(new StdStruct {
type = StdType.Error,
process = process,
content = message,
});
}
}
} | 24.333333 | 70 | 0.523973 | [
"MIT"
] | MoeexT/FancyToys | Tools/FancyServer/Logging/StdClerk.cs | 876 | C# |
/*
* NatShare
* Copyright (c) 2020 Yusuf Olokoba.
*/
namespace NatShare.Internal {
using System;
using System.Runtime.InteropServices;
public static class Bridge {
private const string Assembly = @"__Internal";
public delegate void CompletionHandler (IntPtr context, bool success);
[DllImport(Assembly, EntryPoint = @"NSCreateSharePayload")]
public static extern IntPtr CreateSharePayload (CompletionHandler completionHandler, IntPtr context);
[DllImport(Assembly, EntryPoint = @"NSCreateSavePayload")]
public static extern IntPtr CreateSavePayload (string album, CompletionHandler completionHandler, IntPtr context);
[DllImport(Assembly, EntryPoint = @"NSCreatePrintPayload")]
public static extern IntPtr CreatePrintPayload (bool greyscale, bool landscape, CompletionHandler completionHandler, IntPtr context);
[DllImport(Assembly, EntryPoint = @"NSAddText")]
public static extern void AddText (this IntPtr payload, string text);
[DllImport(Assembly, EntryPoint = @"NSAddImage")]
public static extern void AddImage (this IntPtr payload, IntPtr pixelBuffer, int width, int height);
[DllImport(Assembly, EntryPoint = @"NSAddMedia")]
public static extern void AddMedia (this IntPtr payload, string uri);
[DllImport(Assembly, EntryPoint = @"NSCommit")]
public static extern void Commit (this IntPtr payload);
}
} | 47.193548 | 141 | 0.715653 | [
"MIT"
] | Klipi/NatShare-API | Assets/NatShare/Plugins/Managed/Internal/Bridge.cs | 1,463 | C# |
namespace GameEstate
{
public static class OpenGLPlatform
{
public static unsafe bool Startup()
{
try
{
EstatePlatform.Platform = "OpenGL";
EstatePlatform.GraphicFactory = source => new OpenGLGraphic(source);
EstateDebug.AssertFunc = x => System.Diagnostics.Debug.Assert(x);
EstateDebug.LogFunc = a => System.Diagnostics.Debug.Print(a);
EstateDebug.LogFormatFunc = (a, b) => System.Diagnostics.Debug.Print(a, b);
return true;
}
catch { return false; }
}
}
} | 34.526316 | 92 | 0.525915 | [
"MIT"
] | smorey2/GameEstate | src/GameEstate.App.OpenGL/OpenGLPlatform.cs | 658 | C# |
namespace Compiler.Instructions
{
class UnaryMinusInstruction : IInstruction
{
public void Execute(ExecutionEnvironment env) => env.PushNumber(env.PopNumber() * -1);
}
}
| 23.875 | 94 | 0.696335 | [
"Apache-2.0"
] | SilasDerProfi/simple-compiler | Compiler/Compiler/Instructions/UnaryMinusInstruction.cs | 193 | C# |
using System.Collections.Generic;
namespace Bfar.Repository.Core
{
public interface IBulkRepository
{
string AdHocCommand { get; set; }
int MinTimeOut { get; set; }
void BulkInsert<T>(IList<T> Data, string Name) where T : class;
}
}
| 22.583333 | 71 | 0.645756 | [
"Apache-2.0"
] | behnamfarnoushfar/Bfar | Bfar.Repository.Core/IBulkRepository.cs | 273 | C# |
namespace IgOutlook.Modules.Mail.Menus
{
/// <summary>
/// Interaction logic for HomeTab.xaml
/// </summary>
public partial class HomeTab
{
public HomeTab()
{
InitializeComponent();
}
}
}
| 16.666667 | 42 | 0.54 | [
"MIT"
] | Infragistics/wpf-samples | Applications/IGOutlook/IGOutlook/IgOutlook.Modules.Mail/Menus/HomeTab.xaml.cs | 252 | C# |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using OpenMetaverse;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using Caps = OpenSim.Framework.Capabilities.Caps;
using OpenMetaverse.StructuredData;
namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "VivoxVoiceModule")]
public class VivoxVoiceModule : ISharedRegionModule
{
// channel distance model values
public const int CHAN_DIST_NONE = 0; // no attenuation
public const int CHAN_DIST_INVERSE = 1; // inverse distance attenuation
public const int CHAN_DIST_LINEAR = 2; // linear attenuation
public const int CHAN_DIST_EXPONENT = 3; // exponential attenuation
public const int CHAN_DIST_DEFAULT = CHAN_DIST_LINEAR;
// channel type values
public static readonly string CHAN_TYPE_POSITIONAL = "positional";
public static readonly string CHAN_TYPE_CHANNEL = "channel";
public static readonly string CHAN_TYPE_DEFAULT = CHAN_TYPE_POSITIONAL;
// channel mode values
public static readonly string CHAN_MODE_OPEN = "open";
public static readonly string CHAN_MODE_LECTURE = "lecture";
public static readonly string CHAN_MODE_PRESENTATION = "presentation";
public static readonly string CHAN_MODE_AUDITORIUM = "auditorium";
public static readonly string CHAN_MODE_DEFAULT = CHAN_MODE_OPEN;
// unconstrained default values
public const double CHAN_ROLL_OFF_DEFAULT = 2.0; // rate of attenuation
public const double CHAN_ROLL_OFF_MIN = 1.0;
public const double CHAN_ROLL_OFF_MAX = 4.0;
public const int CHAN_MAX_RANGE_DEFAULT = 60; // distance at which channel is silent
public const int CHAN_MAX_RANGE_MIN = 0;
public const int CHAN_MAX_RANGE_MAX = 160;
public const int CHAN_CLAMPING_DISTANCE_DEFAULT = 10; // distance before attenuation applies
public const int CHAN_CLAMPING_DISTANCE_MIN = 0;
public const int CHAN_CLAMPING_DISTANCE_MAX = 160;
// Infrastructure
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly Object vlock = new Object();
// Control info, e.g. vivox server, admin user, admin password
private static bool m_pluginEnabled = false;
private static bool m_adminConnected = false;
private static string m_vivoxServer;
private static string m_vivoxSipUri;
private static string m_vivoxVoiceAccountApi;
private static string m_vivoxAdminUser;
private static string m_vivoxAdminPassword;
private static string m_authToken = String.Empty;
private static int m_vivoxChannelDistanceModel;
private static double m_vivoxChannelRollOff;
private static int m_vivoxChannelMaximumRange;
private static string m_vivoxChannelMode;
private static string m_vivoxChannelType;
private static int m_vivoxChannelClampingDistance;
private static Dictionary<string,string> m_parents = new Dictionary<string,string>();
private static bool m_dumpXml;
private IConfig m_config;
private object m_Lock;
public void Initialise(IConfigSource config)
{
MainConsole.Instance.Commands.AddCommand("vivox", false, "vivox debug", "vivox debug <on>|<off>", "Set vivox debugging", HandleDebug);
m_config = config.Configs["VivoxVoice"];
if (null == m_config)
return;
if (!m_config.GetBoolean("enabled", false))
return;
m_Lock = new object();
try
{
// retrieve configuration variables
m_vivoxServer = m_config.GetString("vivox_server", String.Empty);
m_vivoxSipUri = m_config.GetString("vivox_sip_uri", String.Empty);
m_vivoxAdminUser = m_config.GetString("vivox_admin_user", String.Empty);
m_vivoxAdminPassword = m_config.GetString("vivox_admin_password", String.Empty);
m_vivoxChannelDistanceModel = m_config.GetInt("vivox_channel_distance_model", CHAN_DIST_DEFAULT);
m_vivoxChannelRollOff = m_config.GetDouble("vivox_channel_roll_off", CHAN_ROLL_OFF_DEFAULT);
m_vivoxChannelMaximumRange = m_config.GetInt("vivox_channel_max_range", CHAN_MAX_RANGE_DEFAULT);
m_vivoxChannelMode = m_config.GetString("vivox_channel_mode", CHAN_MODE_DEFAULT).ToLower();
m_vivoxChannelType = m_config.GetString("vivox_channel_type", CHAN_TYPE_DEFAULT).ToLower();
m_vivoxChannelClampingDistance = m_config.GetInt("vivox_channel_clamping_distance",
CHAN_CLAMPING_DISTANCE_DEFAULT);
m_dumpXml = m_config.GetBoolean("dump_xml", false);
// Validate against constraints and default if necessary
if (m_vivoxChannelRollOff < CHAN_ROLL_OFF_MIN || m_vivoxChannelRollOff > CHAN_ROLL_OFF_MAX)
{
m_log.WarnFormat("[VivoxVoice] Invalid value for roll off ({0}), reset to {1}.",
m_vivoxChannelRollOff, CHAN_ROLL_OFF_DEFAULT);
m_vivoxChannelRollOff = CHAN_ROLL_OFF_DEFAULT;
}
if (m_vivoxChannelMaximumRange < CHAN_MAX_RANGE_MIN || m_vivoxChannelMaximumRange > CHAN_MAX_RANGE_MAX)
{
m_log.WarnFormat("[VivoxVoice] Invalid value for maximum range ({0}), reset to {1}.",
m_vivoxChannelMaximumRange, CHAN_MAX_RANGE_DEFAULT);
m_vivoxChannelMaximumRange = CHAN_MAX_RANGE_DEFAULT;
}
if (m_vivoxChannelClampingDistance < CHAN_CLAMPING_DISTANCE_MIN ||
m_vivoxChannelClampingDistance > CHAN_CLAMPING_DISTANCE_MAX)
{
m_log.WarnFormat("[VivoxVoice] Invalid value for clamping distance ({0}), reset to {1}.",
m_vivoxChannelClampingDistance, CHAN_CLAMPING_DISTANCE_DEFAULT);
m_vivoxChannelClampingDistance = CHAN_CLAMPING_DISTANCE_DEFAULT;
}
switch (m_vivoxChannelMode)
{
case "open" : break;
case "lecture" : break;
case "presentation" : break;
case "auditorium" : break;
default :
m_log.WarnFormat("[VivoxVoice] Invalid value for channel mode ({0}), reset to {1}.",
m_vivoxChannelMode, CHAN_MODE_DEFAULT);
m_vivoxChannelMode = CHAN_MODE_DEFAULT;
break;
}
switch (m_vivoxChannelType)
{
case "positional" : break;
case "channel" : break;
default :
m_log.WarnFormat("[VivoxVoice] Invalid value for channel type ({0}), reset to {1}.",
m_vivoxChannelType, CHAN_TYPE_DEFAULT);
m_vivoxChannelType = CHAN_TYPE_DEFAULT;
break;
}
// Admin interface required values
if (String.IsNullOrEmpty(m_vivoxServer) ||
String.IsNullOrEmpty(m_vivoxSipUri) ||
String.IsNullOrEmpty(m_vivoxAdminUser) ||
String.IsNullOrEmpty(m_vivoxAdminPassword))
{
m_log.Error("[VivoxVoice] plugin mis-configured");
m_log.Info("[VivoxVoice] plugin disabled: incomplete configuration");
return;
}
//m_vivoxVoiceAccountApi = String.Format("https://{0}:443/api2", m_vivoxServer);
m_vivoxVoiceAccountApi = String.Format("http://{0}/api2", m_vivoxServer); // fs <6.3 seems to not like https here
if (!Uri.TryCreate(m_vivoxVoiceAccountApi, UriKind.Absolute, out Uri accoutURI))
{
m_log.Error("[VivoxVoice] invalid vivox server");
return;
}
if (!Uri.TryCreate("http://" + m_vivoxSipUri, UriKind.Absolute, out Uri spiURI))
{
m_log.Error("[VivoxVoice] invalid vivox sip server");
return;
}
m_log.InfoFormat("[VivoxVoice] using vivox server {0}", m_vivoxServer);
// Get admin rights and cleanup any residual channel definition
DoAdminLogin();
m_pluginEnabled = true;
m_log.Info("[VivoxVoice] plugin enabled");
}
catch (Exception e)
{
m_log.ErrorFormat("[VivoxVoice] plugin initialization failed: {0}", e.Message);
m_log.DebugFormat("[VivoxVoice] plugin initialization failed: {0}", e.ToString());
return;
}
}
public void AddRegion(Scene scene)
{
if (m_pluginEnabled)
{
lock (vlock)
{
string channelId = String.Empty;
string sceneUUID = scene.RegionInfo.RegionID.ToString();
string sceneName = scene.RegionInfo.RegionName;
// Make sure that all local channels are deleted.
// So we have to search for the children, and then do an
// iteration over the set of chidren identified.
// This assumes that there is just one directory per
// region.
/* this is not working, can not fix without api spec that vivox is refusing
if (VivoxTryGetDirectory(sceneUUID + "D", out channelId))
{
m_log.DebugFormat("[VivoxVoice]: region {0}: uuid {1}: located directory id {2}",
sceneName, sceneUUID, channelId);
XmlElement children = VivoxListChildren(channelId);
string count;
if (XmlFind(children, "response.level0.channel-search.count", out count))
{
int cnum = Convert.ToInt32(count);
for (int i = 0; i < cnum; i++)
{
string id;
if (XmlFind(children, "response.level0.channel-search.channels.channels.level4.id", i, out id))
{
if (!IsOK(VivoxDeleteChannel(channelId, id)))
m_log.WarnFormat("[VivoxVoice] Channel delete failed {0}:{1}:{2}", i, channelId, id);
}
}
}
}
else
{
if (!VivoxTryCreateDirectory(sceneUUID + "D", sceneName, out channelId))
{
m_log.WarnFormat("[VivoxVoice] Create failed <{0}:{1}:{2}>",
"*", sceneUUID, sceneName);
channelId = String.Empty;
}
}
*/
// Create a dictionary entry unconditionally. This eliminates the
// need to check for a parent in the core code. The end result is
// the same, if the parent table entry is an empty string, then
// region channels will be created as first-level channels.
lock (m_parents)
{
if (m_parents.ContainsKey(sceneUUID))
{
RemoveRegion(scene);
m_parents.Add(sceneUUID, channelId);
}
else
{
m_parents.Add(sceneUUID, channelId);
}
}
}
// we need to capture scene in an anonymous method
// here as we need it later in the callbacks
scene.EventManager.OnRegisterCaps += delegate(UUID agentID, Caps caps)
{
OnRegisterCaps(scene, agentID, caps);
};
}
}
public void RegionLoaded(Scene scene)
{
// Do nothing.
}
public void RemoveRegion(Scene scene)
{
if (m_pluginEnabled)
{
lock (vlock)
{
string channelId;
string sceneUUID = scene.RegionInfo.RegionID.ToString();
string sceneName = scene.RegionInfo.RegionName;
// Make sure that all local channels are deleted.
// So we have to search for the children, and then do an
// iteration over the set of chidren identified.
// This assumes that there is just one directory per
// region.
if (VivoxTryGetDirectory(sceneUUID + "D", out channelId))
{
m_log.DebugFormat("[VivoxVoice]: region {0}: uuid {1}: located directory id {2}",
sceneName, sceneUUID, channelId);
XmlElement children = VivoxListChildren(channelId);
string count;
if (XmlFind(children, "response.level0.channel-search.count", out count))
{
int cnum = Convert.ToInt32(count);
for (int i = 0; i < cnum; i++)
{
string id;
if (XmlFind(children, "response.level0.channel-search.channels.channels.level4.id", i, out id))
{
if (!IsOK(VivoxDeleteChannel(channelId, id)))
m_log.WarnFormat("[VivoxVoice] Channel delete failed {0}:{1}:{2}", i, channelId, id);
}
}
}
if (!IsOK(VivoxDeleteChannel(null, channelId)))
m_log.WarnFormat("[VivoxVoice] Parent channel delete failed {0}:{1}:{2}", sceneName, sceneUUID, channelId);
}
// Remove the channel umbrella entry
lock (m_parents)
{
if (m_parents.ContainsKey(sceneUUID))
{
m_parents.Remove(sceneUUID);
}
}
}
}
}
public void PostInitialise()
{
// Do nothing.
}
public void Close()
{
if (m_pluginEnabled)
VivoxLogout();
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "VivoxVoiceModule"; }
}
public bool IsSharedModule
{
get { return true; }
}
// <summary>
// OnRegisterCaps is invoked via the scene.EventManager
// everytime OpenSim hands out capabilities to a client
// (login, region crossing). We contribute two capabilities to
// the set of capabilities handed back to the client:
// ProvisionVoiceAccountRequest and ParcelVoiceInfoRequest.
//
// ProvisionVoiceAccountRequest allows the client to obtain
// the voice account credentials for the avatar it is
// controlling (e.g., user name, password, etc).
//
// ParcelVoiceInfoRequest is invoked whenever the client
// changes from one region or parcel to another.
//
// Note that OnRegisterCaps is called here via a closure
// delegate containing the scene of the respective region (see
// Initialise()).
// </summary>
public void OnRegisterCaps(Scene scene, UUID agentID, Caps caps)
{
m_log.DebugFormat("[VivoxVoice] OnRegisterCaps: agentID {0} caps {1}", agentID, caps);
caps.RegisterSimpleHandler("ProvisionVoiceAccountRequest",
new SimpleStreamHandler("/" + UUID.Random(), delegate (IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
ProvisionVoiceAccountRequest(httpRequest, httpResponse, agentID, scene);
}));
caps.RegisterSimpleHandler("ParcelVoiceInfoRequest",
new SimpleStreamHandler("/" + UUID.Random(), delegate (IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
ParcelVoiceInfoRequest(httpRequest, httpResponse, agentID, scene);
}));
//caps.RegisterSimpleHandler("ChatSessionRequest",
// new SimpleStreamHandler("/" + UUID.Random(), delegate (IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
// {
// ChatSessionRequest(httpRequest, httpResponse, agentID, scene);
// }));
}
/// <summary>
/// Callback for a client request for Voice Account Details
/// </summary>
/// <param name="scene">current scene object of the client</param>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="agentID"></param>
/// <param name="caps"></param>
/// <returns></returns>
public void ProvisionVoiceAccountRequest(IOSHttpRequest request, IOSHttpResponse response, UUID agentID, Scene scene)
{
if(request.HttpMethod != "POST")
{
response.StatusCode = (int)HttpStatusCode.NotFound;
return;
}
response.StatusCode = (int)HttpStatusCode.OK;
try
{
ScenePresence avatar = null;
string avatarName = null;
if (scene == null)
{
response.RawBuffer = Util.UTF8.GetBytes("<llsd><undef /></llsd>");
return;
}
avatar = scene.GetScenePresence(agentID);
int nretries = 10;
while (avatar == null && nretries-- > 0)
{
Thread.Sleep(100);
avatar = scene.GetScenePresence(agentID);
}
if(avatar == null)
{
response.RawBuffer = Util.UTF8.GetBytes("<llsd><undef /></llsd>");
return;
}
avatarName = avatar.Name;
m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: scene = {0}, agentID = {1}", scene.Name, agentID);
// m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: request: {0}, path: {1}, param: {2}",
// request, path, param);
XmlElement resp;
bool retry = false;
string agentname = "x" + Convert.ToBase64String(agentID.GetBytes());
string password = new UUID(Guid.NewGuid()).ToString().Replace('-','Z').Substring(0,16);
string code = String.Empty;
agentname = agentname.Replace('+', '-').Replace('/', '_');
do
{
resp = VivoxGetAccountInfo(agentname);
if (XmlFind(resp, "response.level0.status", out code))
{
if (code != "OK")
{
if (XmlFind(resp, "response.level0.body.code", out code))
{
// If the request was recognized, then this should be set to something
switch (code)
{
case "201" : // Account expired
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : expired credentials",
avatarName);
m_adminConnected = false;
retry = DoAdminLogin();
break;
case "202" : // Missing credentials
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : missing credentials",
avatarName);
break;
case "212" : // Not authorized
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : not authorized",
avatarName);
break;
case "300" : // Required parameter missing
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : parameter missing",
avatarName);
break;
case "403" : // Account does not exist
resp = VivoxCreateAccount(agentname,password);
// Note: This REALLY MUST BE status. Create Account does not return code.
if (XmlFind(resp, "response.level0.status", out code))
{
switch (code)
{
case "201" : // Account expired
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : expired credentials",
avatarName);
m_adminConnected = false;
retry = DoAdminLogin();
break;
case "202" : // Missing credentials
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : missing credentials",
avatarName);
break;
case "212" : // Not authorized
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : not authorized",
avatarName);
break;
case "300" : // Required parameter missing
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : parameter missing",
avatarName);
break;
case "400" : // Create failed
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : create failed",
avatarName);
break;
}
}
break;
case "404" : // Failed to retrieve account
m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : retrieve failed");
// [AMW] Sleep and retry for a fixed period? Or just abandon?
break;
}
}
}
}
}
while (retry);
if (code != "OK")
{
m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: Get Account Request failed for \"{0}\"", avatarName);
response.RawBuffer = Util.UTF8.GetBytes("<llsd><undef /></llsd>");
return;
}
// Unconditionally change the password on each request
VivoxPassword(agentname, password);
// fast foward encode
osUTF8 lsl = LLSDxmlEncode2.Start();
LLSDxmlEncode2.AddMap(lsl);
LLSDxmlEncode2.AddElem("username", agentname, lsl);
LLSDxmlEncode2.AddElem("password", password, lsl);
LLSDxmlEncode2.AddElem("voice_sip_uri_hostname", m_vivoxSipUri, lsl);
LLSDxmlEncode2.AddElem("voice_account_server_name", m_vivoxVoiceAccountApi, lsl);
LLSDxmlEncode2.AddEndMap(lsl);
response.RawBuffer = LLSDxmlEncode2.EndToBytes(lsl);
return;
}
catch (Exception e)
{
m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: : {0} failed", e.ToString());
}
response.RawBuffer = osUTF8.GetASCIIBytes("<llsd><undef /></llsd>");
}
/// <summary>
/// Callback for a client request for ParcelVoiceInfo
/// </summary>
/// <param name="scene">current scene object of the client</param>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="agentID"></param>
/// <param name="caps"></param>
/// <returns></returns>
public void ParcelVoiceInfoRequest(IOSHttpRequest request, IOSHttpResponse response, UUID agentID, Scene scene)
{
if (request.HttpMethod != "POST")
{
response.StatusCode = (int)HttpStatusCode.NotFound;
return;
}
response.StatusCode = (int)HttpStatusCode.OK;
ScenePresence avatar = scene.GetScenePresence(agentID);
if(avatar == null)
{
response.RawBuffer = Util.UTF8.GetBytes("<llsd><undef /></llsd>");
return;
}
string avatarName = avatar.Name;
// - check whether we have a region channel in our cache
// - if not:
// create it and cache it
// - send it to the client
// - send channel_uri: as "sip:regionID@m_sipDomain"
try
{
string channel_uri;
if (scene.LandChannel == null)
{
m_log.ErrorFormat("region \"{0}\": avatar \"{1}\": land data not yet available",
scene.RegionInfo.RegionName, avatarName);
response.RawBuffer = Util.UTF8.GetBytes("<llsd><undef /></llsd>");
return;
}
// get channel_uri: check first whether estate
// settings allow voice, then whether parcel allows
// voice, if all do retrieve or obtain the parcel
// voice channel
LandData land = scene.GetLandData(avatar.AbsolutePosition);
if (land == null)
{
response.RawBuffer = Util.UTF8.GetBytes("<llsd><undef /></llsd>");
return;
}
// m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": request: {4}, path: {5}, param: {6}",
// scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName, request, path, param);
// m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: avatar \"{0}\": location: {1} {2} {3}",
// avatarName, avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y, avatar.AbsolutePosition.Z);
if (!scene.RegionInfo.EstateSettings.AllowVoice)
{
//m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": voice not enabled in estate settings",
// scene.RegionInfo.RegionName);
channel_uri = String.Empty;
}
else if (!scene.RegionInfo.EstateSettings.TaxFree && (land.Flags & (uint)ParcelFlags.AllowVoiceChat) == 0)
{
//m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": voice not enabled for parcel",
// scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName);
channel_uri = String.Empty;
}
else
{
channel_uri = RegionGetOrCreateChannel(scene, land);
}
// m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": {4}",
// scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName, r);
// fast foward encode
osUTF8 lsl = LLSDxmlEncode2.Start();
LLSDxmlEncode2.AddMap(lsl);
LLSDxmlEncode2.AddElem("parcel_local_id", land.LocalID, lsl);
LLSDxmlEncode2.AddElem("region_name", scene.Name, lsl);
LLSDxmlEncode2.AddMap("voice_credentials",lsl);
LLSDxmlEncode2.AddElem("channel_uri", channel_uri, lsl);
//LLSDxmlEncode2.AddElem("channel_credentials", channel_credentials, lsl);
LLSDxmlEncode2.AddEndMap(lsl);
LLSDxmlEncode2.AddEndMap(lsl);
response.RawBuffer = LLSDxmlEncode2.EndToBytes(lsl);
return;
}
catch (Exception e)
{
m_log.ErrorFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": avatar \"{1}\": {2}, retry later",
scene.RegionInfo.RegionName, avatarName, e.Message);
}
response.RawBuffer = Util.UTF8.GetBytes("<llsd><undef /></llsd>");
}
/// <summary>
/// Callback for a client request for a private chat channel
/// </summary>
/// <param name="scene">current scene object of the client</param>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="agentID"></param>
/// <param name="caps"></param>
/// <returns></returns>
public void ChatSessionRequest(IOSHttpRequest request, IOSHttpResponse response, UUID agentID, Scene scene)
{
if (request.HttpMethod != "POST")
{
response.StatusCode = (int)HttpStatusCode.NotFound;
return;
}
// ScenePresence avatar = scene.GetScenePresence(agentID);
// string avatarName = avatar.Name;
// m_log.DebugFormat("[VivoxVoice][CHATSESSION]: avatar \"{0}\": request: {1}, path: {2}, param: {3}",
// avatarName, request, path, param);
response.RawBuffer = Util.UTF8.GetBytes("<llsd>true</llsd>");
response.StatusCode = (int)HttpStatusCode.OK;
}
private string RegionGetOrCreateChannel(Scene scene, LandData land)
{
string channelUri = null;
string channelId = null;
string landUUID;
string landName;
string parentId;
lock (m_parents)
parentId = m_parents[scene.RegionInfo.RegionID.ToString()];
// Create parcel voice channel. If no parcel exists, then the voice channel ID is the same
// as the directory ID. Otherwise, it reflects the parcel's ID.
if ((land.Flags & (uint)ParcelFlags.UseEstateVoiceChan) == 0)
{
landName = String.Format("{0}:{1}", scene.RegionInfo.RegionName, land.Name);
landUUID = land.GlobalID.ToString();
m_log.DebugFormat("[VivoxVoice]: Region:Parcel \"{0}\": parcel id {1}: using channel name {2}",
landName, land.LocalID, landUUID);
}
else
{
landName = String.Format("{0}:{1}", scene.RegionInfo.RegionName, scene.RegionInfo.RegionName);
landUUID = scene.RegionInfo.RegionID.ToString();
m_log.DebugFormat("[VivoxVoice]: Region:Parcel \"{0}\": parcel id {1}: using channel name {2}",
landName, land.LocalID, landUUID);
}
lock (vlock)
{
// Added by Adam to help debug channel not availible errors.
if (VivoxTryGetChannel(parentId, landUUID, out channelId, out channelUri))
m_log.DebugFormat("[VivoxVoice] Found existing channel at " + channelUri);
else if (VivoxTryCreateChannel(parentId, landUUID, landName, out channelUri))
m_log.DebugFormat("[VivoxVoice] Created new channel at " + channelUri);
else
throw new Exception("vivox channel uri not available");
m_log.DebugFormat("[VivoxVoice]: Region:Parcel \"{0}\": parent channel id {1}: retrieved parcel channel_uri {2} ",
landName, parentId, channelUri);
}
return channelUri;
}
private static readonly string m_vivoxLoginPath = "https://{0}/api2/viv_signin.php?userid={1}&pwd={2}";
/// <summary>
/// Perform administrative login for Vivox.
/// Returns a hash table containing values returned from the request.
/// </summary>
private XmlElement VivoxLogin(string name, string password)
{
string requrl = String.Format(m_vivoxLoginPath, m_vivoxServer, name, password);
return VivoxCall(requrl, false);
}
private static readonly string m_vivoxLogoutPath = "https://{0}/api2/viv_signout.php?auth_token={1}";
/// <summary>
/// Perform administrative logout for Vivox.
/// </summary>
private XmlElement VivoxLogout()
{
string requrl = String.Format(m_vivoxLogoutPath, m_vivoxServer, m_authToken);
return VivoxCall(requrl, false);
}
private static readonly string m_vivoxGetAccountPath = "https://{0}/api2/viv_get_acct.php?auth_token={1}&user_name={2}";
/// <summary>
/// Retrieve account information for the specified user.
/// Returns a hash table containing values returned from the request.
/// </summary>
private XmlElement VivoxGetAccountInfo(string user)
{
string requrl = String.Format(m_vivoxGetAccountPath, m_vivoxServer, m_authToken, user);
return VivoxCall(requrl, true);
}
private static readonly string m_vivoxNewAccountPath = "https://{0}/api2/viv_adm_acct_new.php?username={1}&pwd={2}&auth_token={3}";
/// <summary>
/// Creates a new account.
/// For now we supply the minimum set of values, which
/// is user name and password. We *can* supply a lot more
/// demographic data.
/// </summary>
private XmlElement VivoxCreateAccount(string user, string password)
{
string requrl = String.Format(m_vivoxNewAccountPath, m_vivoxServer, user, password, m_authToken);
return VivoxCall(requrl, true);
}
private static readonly string m_vivoxPasswordPath = "https://{0}/api2/viv_adm_password.php?user_name={1}&new_pwd={2}&auth_token={3}";
/// <summary>
/// Change the user's password.
/// </summary>
private XmlElement VivoxPassword(string user, string password)
{
string requrl = String.Format(m_vivoxPasswordPath, m_vivoxServer, user, password, m_authToken);
return VivoxCall(requrl, true);
}
private static readonly string m_vivoxChannelPath = "https://{0}/api2/viv_chan_mod.php?mode={1}&chan_name={2}&auth_token={3}";
/// <summary>
/// Create a channel.
/// Once again, there a multitude of options possible. In the simplest case
/// we specify only the name and get a non-persistent cannel in return. Non
/// persistent means that the channel gets deleted if no-one uses it for
/// 5 hours. To accomodate future requirements, it may be a good idea to
/// initially create channels under the umbrella of a parent ID based upon
/// the region name. That way we have a context for side channels, if those
/// are required in a later phase.
///
/// In this case the call handles parent and description as optional values.
/// </summary>
private bool VivoxTryCreateChannel(string parent, string channelId, string description, out string channelUri)
{
string requrl = String.Format(m_vivoxChannelPath, m_vivoxServer, "create", channelId, m_authToken);
if (!string.IsNullOrEmpty(parent))
{
requrl = String.Format("{0}&chan_parent={1}", requrl, parent);
}
if (!string.IsNullOrEmpty(description))
{
requrl = String.Format("{0}&chan_desc={1}", requrl, description);
}
requrl = String.Format("{0}&chan_type={1}", requrl, m_vivoxChannelType);
requrl = String.Format("{0}&chan_mode={1}", requrl, m_vivoxChannelMode);
requrl = String.Format("{0}&chan_roll_off={1}", requrl, m_vivoxChannelRollOff);
requrl = String.Format("{0}&chan_dist_model={1}", requrl, m_vivoxChannelDistanceModel);
requrl = String.Format("{0}&chan_max_range={1}", requrl, m_vivoxChannelMaximumRange);
requrl = String.Format("{0}&chan_clamping_distance={1}", requrl, m_vivoxChannelClampingDistance);
XmlElement resp = VivoxCall(requrl, true);
if (XmlFind(resp, "response.level0.body.chan_uri", out channelUri))
return true;
channelUri = String.Empty;
return false;
}
/// <summary>
/// Create a directory.
/// Create a channel with an unconditional type of "dir" (indicating directory).
/// This is used to create an arbitrary name tree for partitioning of the
/// channel name space.
/// The parent and description are optional values.
/// </summary>
private bool VivoxTryCreateDirectory(string dirId, string description, out string channelId)
{
/* this is not working, and can not fix without api spec, that vivox is refusing me
string requrl = String.Format(m_vivoxChannelPath, m_vivoxServer, "create", dirId, m_authToken);
// if (parent != null && parent != String.Empty)
// {
// requrl = String.Format("{0}&chan_parent={1}", requrl, parent);
// }
if (!string.IsNullOrEmpty(description))
{
requrl = String.Format("{0}&chan_desc={1}", requrl, description);
}
requrl = String.Format("{0}&chan_type={1}", requrl, "dir");
XmlElement resp = VivoxCall(requrl, true);
if (IsOK(resp) && XmlFind(resp, "response.level0.body.chan_id", out channelId))
return true;
*/
channelId = String.Empty;
return false;
}
private static readonly string m_vivoxChannelSearchPath = "https://{0}/api2/viv_chan_search.php?cond_channame={1}&auth_token={2}";
/// <summary>
/// Retrieve a channel.
/// Once again, there a multitude of options possible. In the simplest case
/// we specify only the name and get a non-persistent cannel in return. Non
/// persistent means that the channel gets deleted if no-one uses it for
/// 5 hours. To accomodate future requirements, it may be a good idea to
/// initially create channels under the umbrella of a parent ID based upon
/// the region name. That way we have a context for side channels, if those
/// are required in a later phase.
/// In this case the call handles parent and description as optional values.
/// </summary>
private bool VivoxTryGetChannel(string channelParent, string channelName,
out string channelId, out string channelUri)
{
string count;
string requrl = String.Format(m_vivoxChannelSearchPath, m_vivoxServer, channelName, m_authToken);
XmlElement resp = VivoxCall(requrl, true);
if (XmlFind(resp, "response.level0.channel-search.count", out count))
{
int channels = Convert.ToInt32(count);
// Bug in Vivox Server r2978 where count returns 0
// Found by Adam
if (channels == 0)
{
for (int j=0;j<100;j++)
{
string tmpId;
if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.id", j, out tmpId))
break;
channels = j + 1;
}
}
for (int i = 0; i < channels; i++)
{
string name;
string id;
string type;
string uri;
string parent;
// skip if not a channel
if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.type", i, out type) ||
(type != "channel" && type != "positional_M"))
{
m_log.Debug("[VivoxVoice] Skipping Channel " + i + " as it's not a channel.");
continue;
}
// skip if not the name we are looking for
if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.name", i, out name) ||
name != channelName)
{
m_log.Debug("[VivoxVoice] Skipping Channel " + i + " as it has no name.");
continue;
}
// skip if parent does not match
if (channelParent != null && !XmlFind(resp, "response.level0.channel-search.channels.channels.level4.parent", i, out parent))
{
m_log.Debug("[VivoxVoice] Skipping Channel " + i + "/" + name + " as it's parent doesnt match");
continue;
}
// skip if no channel id available
if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.id", i, out id))
{
m_log.Debug("[VivoxVoice] Skipping Channel " + i + "/" + name + " as it has no channel ID");
continue;
}
// skip if no channel uri available
if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.uri", i, out uri))
{
m_log.Debug("[VivoxVoice] Skipping Channel " + i + "/" + name + " as it has no channel URI");
continue;
}
channelId = id;
channelUri = uri;
return true;
}
}
else
{
m_log.Debug("[VivoxVoice] No count element?");
}
channelId = String.Empty;
channelUri = String.Empty;
// Useful incase something goes wrong.
//m_log.Debug("[VivoxVoice] Could not find channel in XMLRESP: " + resp.InnerXml);
return false;
}
private bool VivoxTryGetDirectory(string directoryName, out string directoryId)
{
string count;
string requrl = String.Format(m_vivoxChannelSearchPath, m_vivoxServer, directoryName, m_authToken);
XmlElement resp = VivoxCall(requrl, true);
if (XmlFind(resp, "response.level0.channel-search.count", out count))
{
int channels = Convert.ToInt32(count);
for (int i = 0; i < channels; i++)
{
string name;
string id;
string type;
// skip if not a directory
if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.type", i, out type) ||
type != "dir")
continue;
// skip if not the name we are looking for
if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.name", i, out name) ||
name != directoryName)
continue;
// skip if no channel id available
if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.id", i, out id))
continue;
directoryId = id;
return true;
}
}
directoryId = String.Empty;
return false;
}
// private static readonly string m_vivoxChannelById = "https://{0}/api2/viv_chan_mod.php?mode={1}&chan_id={2}&auth_token={3}";
// private XmlElement VivoxGetChannelById(string parent, string channelid)
// {
// string requrl = String.Format(m_vivoxChannelById, m_vivoxServer, "get", channelid, m_authToken);
// if (parent != null && parent != String.Empty)
// return VivoxGetChild(parent, channelid);
// else
// return VivoxCall(requrl, true);
// }
private static readonly string m_vivoxChannelDel = "https://{0}/api2/viv_chan_mod.php?mode={1}&chan_id={2}&auth_token={3}";
/// <summary>
/// Delete a channel.
/// Once again, there a multitude of options possible. In the simplest case
/// we specify only the name and get a non-persistent cannel in return. Non
/// persistent means that the channel gets deleted if no-one uses it for
/// 5 hours. To accomodate future requirements, it may be a good idea to
/// initially create channels under the umbrella of a parent ID based upon
/// the region name. That way we have a context for side channels, if those
/// are required in a later phase.
/// In this case the call handles parent and description as optional values.
/// </summary>
private XmlElement VivoxDeleteChannel(string parent, string channelid)
{
string requrl = String.Format(m_vivoxChannelDel, m_vivoxServer, "delete", channelid, m_authToken);
if (!string.IsNullOrEmpty(parent))
{
requrl = String.Format("{0}&chan_parent={1}", requrl, parent);
}
return VivoxCall(requrl, true);
}
private static readonly string m_vivoxChannelSearch = "https://{0}/api2/viv_chan_search.php?&cond_chanparent={1}&auth_token={2}";
/// <summary>
/// Return information on channels in the given directory
/// </summary>
private XmlElement VivoxListChildren(string channelid)
{
string requrl = String.Format(m_vivoxChannelSearch, m_vivoxServer, channelid, m_authToken);
return VivoxCall(requrl, true);
}
// private XmlElement VivoxGetChild(string parent, string child)
// {
// XmlElement children = VivoxListChildren(parent);
// string count;
// if (XmlFind(children, "response.level0.channel-search.count", out count))
// {
// int cnum = Convert.ToInt32(count);
// for (int i = 0; i < cnum; i++)
// {
// string name;
// string id;
// if (XmlFind(children, "response.level0.channel-search.channels.channels.level4.name", i, out name))
// {
// if (name == child)
// {
// if (XmlFind(children, "response.level0.channel-search.channels.channels.level4.id", i, out id))
// {
// return VivoxGetChannelById(null, id);
// }
// }
// }
// }
// }
// // One we *know* does not exist.
// return VivoxGetChannel(null, Guid.NewGuid().ToString());
// }
/// <summary>
/// This method handles the WEB side of making a request over the
/// Vivox interface. The returned values are tansferred to a has
/// table which is returned as the result.
/// The outcome of the call can be determined by examining the
/// status value in the hash table.
/// </summary>
private XmlElement VivoxCall(string requrl, bool admin)
{
XmlDocument doc = null;
// If this is an admin call, and admin is not connected,
// and the admin id cannot be connected, then fail.
if (admin && !m_adminConnected && !DoAdminLogin())
return null;
doc = new XmlDocument();
// Let's serialize all calls to Vivox. Most of these are driven by
// the clients (CAPs), when the user arrives at the region. We don't
// want to issue many simultaneous http requests to Vivox, because mono
// doesn't like that
lock (m_Lock)
{
try
{
// Otherwise prepare the request
//m_log.DebugFormat("[VivoxVoice] Sending request <{0}>", requrl);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(requrl);
req.ServerCertificateValidationCallback = WebUtil.ValidateServerCertificateNoChecks; // vivox servers have invalid certs
// We are sending just parameters, no content
req.ContentLength = 0;
// Send request and retrieve the response
using (HttpWebResponse rsp = (HttpWebResponse)req.GetResponse())
using (Stream s = rsp.GetResponseStream())
using (XmlTextReader rdr = new XmlTextReader(s))
doc.Load(rdr);
}
catch (Exception e)
{
m_log.ErrorFormat("[VivoxVoice] Error in admin call : {0}", e.Message);
}
}
// If we're debugging server responses, dump the whole
// load now
if (m_dumpXml) XmlScanl(doc.DocumentElement,0);
return doc.DocumentElement;
}
/// <summary>
/// Just say if it worked.
/// </summary>
private bool IsOK(XmlElement resp)
{
string status;
XmlFind(resp, "response.level0.status", out status);
return (status == "OK");
}
/// <summary>
/// Login has been factored in this way because it gets called
/// from several places in the module, and we want it to work
/// the same way each time.
/// </summary>
private bool DoAdminLogin()
{
m_log.Debug("[VivoxVoice] Establishing admin connection");
lock (vlock)
{
if (!m_adminConnected)
{
string status = "Unknown";
XmlElement resp = null;
resp = VivoxLogin(m_vivoxAdminUser, m_vivoxAdminPassword);
if (XmlFind(resp, "response.level0.body.status", out status))
{
if (status == "Ok")
{
m_log.Info("[VivoxVoice] Admin connection established");
if (XmlFind(resp, "response.level0.body.auth_token", out m_authToken))
{
if (m_dumpXml) m_log.DebugFormat("[VivoxVoice] Auth Token <{0}>",
m_authToken);
m_adminConnected = true;
}
}
else
{
m_log.WarnFormat("[VivoxVoice] Admin connection failed, status = {0}",
status);
}
}
}
}
return m_adminConnected;
}
/// <summary>
/// The XmlScan routine is provided to aid in the
/// reverse engineering of incompletely
/// documented packets returned by the Vivox
/// voice server. It is only called if the
/// m_dumpXml switch is set.
/// </summary>
private void XmlScanl(XmlElement e, int index)
{
if (e.HasChildNodes)
{
m_log.DebugFormat("<{0}>".PadLeft(index+5), e.Name);
XmlNodeList children = e.ChildNodes;
foreach (XmlNode node in children)
switch (node.NodeType)
{
case XmlNodeType.Element :
XmlScanl((XmlElement)node, index+1);
break;
case XmlNodeType.Text :
m_log.DebugFormat("\"{0}\"".PadLeft(index+5), node.Value);
break;
default :
break;
}
m_log.DebugFormat("</{0}>".PadLeft(index+6), e.Name);
}
else
{
m_log.DebugFormat("<{0}/>".PadLeft(index+6), e.Name);
}
}
private static readonly char[] C_POINT = {'.'};
/// <summary>
/// The Find method is passed an element whose
/// inner text is scanned in an attempt to match
/// the name hierarchy passed in the 'tag' parameter.
/// If the whole hierarchy is resolved, the InnerText
/// value at that point is returned. Note that this
/// may itself be a subhierarchy of the entire
/// document. The function returns a boolean indicator
/// of the search's success. The search is performed
/// by the recursive Search method.
/// </summary>
private bool XmlFind(XmlElement root, string tag, int nth, out string result)
{
if (root == null || tag == null || tag == String.Empty)
{
result = String.Empty;
return false;
}
return XmlSearch(root,tag.Split(C_POINT),0, ref nth, out result);
}
private bool XmlFind(XmlElement root, string tag, out string result)
{
int nth = 0;
if (root == null || tag == null || tag == String.Empty)
{
result = String.Empty;
return false;
}
return XmlSearch(root,tag.Split(C_POINT),0, ref nth, out result);
}
/// <summary>
/// XmlSearch is initially called by XmlFind, and then
/// recursively called by itself until the document
/// supplied to XmlFind is either exhausted or the name hierarchy
/// is matched.
///
/// If the hierarchy is matched, the value is returned in
/// result, and true returned as the function's
/// value. Otherwise the result is set to the empty string and
/// false is returned.
/// </summary>
private bool XmlSearch(XmlElement e, string[] tags, int index, ref int nth, out string result)
{
if (index == tags.Length || e.Name != tags[index])
{
result = String.Empty;
return false;
}
if (tags.Length-index == 1)
{
if (nth == 0)
{
result = e.InnerText;
return true;
}
else
{
nth--;
result = String.Empty;
return false;
}
}
if (e.HasChildNodes)
{
XmlNodeList children = e.ChildNodes;
foreach (XmlNode node in children)
{
switch (node.NodeType)
{
case XmlNodeType.Element :
if (XmlSearch((XmlElement)node, tags, index+1, ref nth, out result))
return true;
break;
default :
break;
}
}
}
result = String.Empty;
return false;
}
private void HandleDebug(string module, string[] cmd)
{
if (cmd.Length < 3)
{
MainConsole.Instance.Output("Error: missing on/off flag");
return;
}
if (cmd[2] == "on")
m_dumpXml = true;
else if (cmd[2] == "off")
m_dumpXml = false;
else
MainConsole.Instance.Output("Error: only on and off are supported");
}
}
}
| 44.625987 | 158 | 0.508397 | [
"BSD-3-Clause"
] | AI-Grid/AI-Grid-2.0 | OpenSim/Region/OptionalModules/Avatar/Voice/VivoxVoice/VivoxVoiceModule.cs | 62,164 | C# |
namespace SoftUni.Models
{
using System;
using System.Collections.Generic;
public class Address
{
public Address()
{
this.Employees = new HashSet<Employee>();
}
public int AddressId { get; set; }
public string AddressText { get; set; }
public int? TownId { get; set; }
public Town Town { get; set; }
public ICollection<Employee> Employees { get; set; }
}
}
| 20 | 60 | 0.56087 | [
"MIT"
] | Ivelin153/SoftUni | C# DB/C# DB Advanced/IntroEfCore_DbFirst/Models/Address.cs | 462 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace Microsoft.Net.Http.Headers
{
/// <summary>
/// Provides HTTP header quality factors.
/// </summary>
public static class HeaderQuality
{
/// <summary>
/// Quality factor to indicate a perfect match.
/// </summary>
public const double Match = 1.0;
/// <summary>
/// Quality factor to indicate no match.
/// </summary>
public const double NoMatch = 0.0;
}
}
| 26.909091 | 71 | 0.603041 | [
"MIT"
] | 48355746/AspNetCore | src/Http/Headers/src/HeaderQuality.cs | 592 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using Common.Models;
using Newtonsoft.Json;
using Serilog;
namespace Common
{
public class IndexWorkspace : IIndexWorkspace
{
private readonly string _directory;
private IndexWorkspace(ChannelIndex index, string directory)
{
_directory = directory;
Index = index;
}
public static IndexWorkspace Create(string directory)
{
var index = Path.Combine(directory, "index.json");
if (!File.Exists(index))
{
return null;
}
return new IndexWorkspace(JsonConvert.DeserializeObject<ChannelIndex>(File.ReadAllText(index)), directory);
}
public ChannelIndex Index { get; }
public void SaveCaptions(string videoId, List<Caption> captions)
{
var captionDirectory = Path.Combine(_directory, "captions");
if (!Directory.Exists(captionDirectory))
{
Directory.CreateDirectory(captionDirectory);
}
var destination = Path.Combine(captionDirectory, $"{videoId}.json");
if (File.Exists(destination))
{
File.Delete(destination);
}
File.WriteAllText(destination, JsonConvert.SerializeObject(captions, Formatting.Indented));
}
public List<Video> GetVideos()
{
var result = new List<Video>();
var videosDirectory = Path.Combine(_directory, "videos");
if (!Directory.Exists(videosDirectory))
{
return result;
}
foreach (var file in Directory.GetFiles(videosDirectory, "*.json"))
{
result.Add(JsonConvert.DeserializeObject<Video>(File.ReadAllText(file)));
}
return result;
}
public VideoPath GetVideoPath(string id)
{
var mirrorDirectory = Path.Combine(_directory, "mirror");
if (!Directory.Exists(mirrorDirectory))
{
return VideoPath.None;
}
var localFile = Path.Combine(mirrorDirectory, $"{id}.mp4");
if (File.Exists(localFile))
{
return VideoPath.Local(localFile);
}
var mirrorFile = Path.Combine(mirrorDirectory, $"{id}.txt");
if (File.Exists(mirrorFile))
{
return VideoPath.External(File.ReadAllText(mirrorFile));
}
return VideoPath.None;
}
public void UpdateVideoPath(string id, VideoPathExternal path)
{
var mirrorDirectory = Path.Combine(_directory, "mirror");
if (!Directory.Exists(mirrorDirectory))
{
Directory.CreateDirectory(mirrorDirectory);
}
var localFile = Path.Combine(mirrorDirectory, $"{id}.mp4");
if (File.Exists(localFile))
{
File.Delete(localFile);
}
var mirrorFile = Path.Combine(mirrorDirectory, $"{id}.txt");
if (File.Exists(mirrorFile))
{
File.Delete(mirrorFile);
}
File.WriteAllText(mirrorFile, path.Url);
}
public Dictionary<string, List<Caption>> GetCaptions()
{
var result = new Dictionary<string, List<Caption>>();
var captionsDirectory = Path.Combine(_directory, "captions");
if (!Directory.Exists(captionsDirectory))
{
return result;
}
foreach (var file in Directory.GetFiles(captionsDirectory, "*.json").OrderBy(x => x))
{
result.Add(Path.GetFileNameWithoutExtension(file), JsonConvert.DeserializeObject<List<Caption>>(File.ReadAllText(file)));
}
return result;
}
public void DownloadVideo(string id, string url)
{
if (GetVideoPath(id).Type != VideoPathType.None)
{
throw new Exception("The video is already downloaded.");
}
var mirrorDirectory = Path.Combine(_directory, "mirror");
if (!Directory.Exists(mirrorDirectory))
{
Directory.CreateDirectory(mirrorDirectory);
}
using (var client = new WebClient())
{
var tmpFile = Path.Combine(mirrorDirectory, $"{Guid.NewGuid().ToString().Replace("-", "").Substring(0, 5)}-tmp.mp4");
if (File.Exists(tmpFile))
{
File.Delete(tmpFile);
}
try
{
client.DownloadFile(url, tmpFile);
}
catch (Exception)
{
if (File.Exists(tmpFile))
{
File.Delete(tmpFile);
}
throw;
}
File.Move(tmpFile, Path.Combine(mirrorDirectory, $"{id}.mp4"));
}
}
public Dictionary<string, TopicSearch> GetTopics()
{
var result = new Dictionary<string, TopicSearch>();
var topicsDirectory = Path.Combine(_directory, "topics");
if (!Directory.Exists(topicsDirectory))
{
return result;
}
foreach (var topicFile in Directory.GetFiles(topicsDirectory, "*.json"))
{
var topicKey = SanitizeTopic(Path.GetFileNameWithoutExtension(topicFile).ToLower());
result.Add(topicKey, JsonConvert.DeserializeObject<TopicSearch>(File.ReadAllText(topicFile)));
}
return result;
}
public TopicSearch FindTopic(string topic)
{
var topicKey = SanitizeTopic(topic);
var potential = Path.Combine(_directory, "topics", $"{topicKey}.json");
if (File.Exists(potential))
{
return JsonConvert.DeserializeObject<TopicSearch>(File.ReadAllText(potential));
}
return null;
}
public void SaveTopic(TopicSearch topicSearch)
{
var topicsDirectory = Path.Combine(_directory, "topics");
if (!Directory.Exists(topicsDirectory))
{
Directory.CreateDirectory(topicsDirectory);
}
var topicKey = SanitizeTopic(topicSearch.Topic);
var destination = Path.Combine(topicsDirectory, $"{topicKey}.json");
if (File.Exists(destination))
{
File.Delete(destination);
}
File.WriteAllText(destination, JsonConvert.SerializeObject(topicSearch, Formatting.Indented));
}
private string SanitizeTopic(string topic)
{
if (string.IsNullOrEmpty(topic))
{
throw new ArgumentException(nameof(topic));
}
foreach (var c in Path.GetInvalidFileNameChars())
{
topic = topic.Replace(c, '-');
}
return topic.Trim().Replace(' ', '-').ToLower();
}
}
} | 31.242678 | 137 | 0.52203 | [
"MIT"
] | pauldotknopf/youtube-archiver | src/Common/IndexWorkspace.cs | 7,467 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using FluentValidation;
namespace YL.Core.Entity.Fluent.Validation
{
public class StockInFluent : AbstractValidator<Wms_stockin>
{
public StockInFluent()
{
//RuleFor(x => x.StockInNo).NotNull().NotEmpty().WithMessage("入库单号不能为空").Length(1, 32).WithMessage("入库单号不能超过32");
RuleFor(x => x.Remark).MaximumLength(200).WithMessage("备注长度不能超过200");
}
}
} | 29.625 | 125 | 0.672996 | [
"MIT"
] | 1176955595/KopSoft | src/Entity/Fluent.Validation/StockInFluent.cs | 524 | C# |
// *** WARNING: this file was generated by pulumigen. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Kubernetes.Types.Outputs.Apps.V1Beta2
{
/// <summary>
/// ControllerRevision implements an immutable snapshot of state data. Clients are responsible for serializing and deserializing the objects that contain their internal state. Once a ControllerRevision has been successfully created, it can not be updated. The API Server will fail validation of all requests that attempt to mutate the Data field. ControllerRevisions may, however, be deleted. Note that, due to its use by both the DaemonSet and StatefulSet controllers for update and rollback, this object is beta. However, it may be subject to name and representation changes in future releases, and clients should not depend on its stability. It is primarily for internal use by controllers.
/// </summary>
[OutputType]
public sealed class ControllerRevision
{
/// <summary>
/// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
/// </summary>
public readonly string ApiVersion;
/// <summary>
/// Data is the serialized representation of the state.
/// </summary>
public readonly System.Text.Json.JsonElement Data;
/// <summary>
/// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
/// </summary>
public readonly string Kind;
/// <summary>
/// Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
/// </summary>
public readonly Pulumi.Kubernetes.Types.Outputs.Meta.V1.ObjectMeta Metadata;
/// <summary>
/// Revision indicates the revision of the state represented by Data.
/// </summary>
public readonly int Revision;
[OutputConstructor]
private ControllerRevision(
string apiVersion,
System.Text.Json.JsonElement data,
string kind,
Pulumi.Kubernetes.Types.Outputs.Meta.V1.ObjectMeta metadata,
int revision)
{
ApiVersion = apiVersion;
Data = data;
Kind = kind;
Metadata = metadata;
Revision = revision;
}
}
}
| 49.55 | 697 | 0.694585 | [
"Apache-2.0"
] | AaronFriel/pulumi-kubernetes | sdk/dotnet/Apps/V1Beta2/Outputs/ControllerRevision.cs | 2,973 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("AngleSharp")]
[assembly: AssemblyDescription("AngleSharp is the ultimate angle brackets parser library. It parses HTML5, CSS3, and XML to construct a DOM based on the official W3C specification.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("AngleSharp")]
[assembly: AssemblyProduct("AngleSharp.Core")]
[assembly: AssemblyCopyright("Copyright © AngleSharp, 2013-2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: InternalsVisibleToAttribute("AngleSharp.Core.Tests, PublicKey=002400000480000094000000060200000024000052534131000400000100010001adf274fa2b375134e8e4558d606f1a0f96f5cd0c6b99970f7cce9887477209d7c29f814e2508d8bd2526e99e8cd273bd1158a3984f1ea74830ec5329a77c6ff201a15edeb8b36ab046abd1bce211fe8dbb076d7d806f46b15bfda44def04ead0669971e96c5f666c9eda677f28824fff7aa90d32929ed91d529a7a41699893")]
[assembly: AssemblyVersion("0.9.9")]
[assembly: AssemblyFileVersion("0.9.9")] | 68.25 | 396 | 0.849817 | [
"MIT"
] | andmattia/AngleSharp | src/AngleSharp/Properties/AssemblyInfo.cs | 1,095 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class DayItemView : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler {
public Action<DayItemView> OnSelectDay;
public Text dayNumberText;
[SerializeField] Color hoverImageColor;
[SerializeField] Color selectImageColor;
[SerializeField] Color pressedImageColor;
[SerializeField] Color normalColor;
[SerializeField] Color inactiveTextColor;
private int dayNumber;
Image backgroundImage;
public bool IsSelect { get; set; }
public bool IsInactive { get; set; }
void Awake() {
GetComponent<Button>().onClick.AddListener( OnPointerClick );
backgroundImage = GetComponent<Image>();
}
public int DayNumber {
get { return dayNumber; }
set {
dayNumber = value;
dayNumberText.text = dayNumber.ToString();
}
}
public void OnPointerClick() {
if ( OnSelectDay != null && !IsInactive ) {
OnSelectDay( this );
}
}
public void OnPointerEnter( PointerEventData eventData ) {
if ( !IsSelect && !IsInactive ) {
backgroundImage.color = hoverImageColor;
}
}
public void OnPointerExit( PointerEventData eventData ) {
if ( !IsSelect && !IsInactive ) {
backgroundImage.color = normalColor;
}
}
public void SetSelectColor() {
if ( !IsInactive ) {
IsSelect = true;
backgroundImage.color = selectImageColor;
}
}
public void SetNormalColor() {
if ( !IsInactive ) {
IsSelect = false;
backgroundImage.color = normalColor;
}
}
public void SetInactiveState() {
IsInactive = true;
dayNumberText.color = inactiveTextColor;
}
public void SetActiveState() {
IsInactive = false;
SetNormalColor();
}
}
| 24.609756 | 85 | 0.621407 | [
"Unlicense"
] | pacatum/Helmbet-RPS | Assets/Scripts/Utils/Calendar/DayItemView.cs | 2,020 | C# |
using ParentLoadROSoftDelete.Business;
namespace ParentLoadROSoftDelete.Business.ERLevel
{
public partial class E08Level1111
{
#region Pseudo Event Handlers
//partial void OnFetchRead(DataPortalHookArgs args)
//{
// throw new System.Exception("The method or operation is not implemented.");
//}
#endregion
}
}
| 20.842105 | 89 | 0.626263 | [
"MIT"
] | CslaGenFork/CslaGenFork | tags/DeepLoad sample v.1.0.0/ParentLoadROSoftDelete.Business/ERLevel/E08Level1111.cs | 396 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
using CSharpServer;
using NDesk.Options;
namespace SslMulticastServer
{
class MulticastSession : SslSession
{
public MulticastSession(SslServer server) : base(server) {}
protected override bool OnSending(long size)
{
// Limit session send buffer to 1 megabyte
return BytesPending + size <= 1 * 1024 * 1024;
}
protected override void OnError(int error, string category, string message)
{
Console.WriteLine($"Session caught an error with code {error} and category '{category}': {message}");
}
}
class MulticastServer : SslServer
{
public MulticastServer(Service service, SslContext context, int port, InternetProtocol protocol) : base(service, context, port, protocol) {}
protected override SslSession CreateSession() { return new MulticastSession(this); }
protected override void OnError(int error, string category, string message)
{
Console.WriteLine($"Server caught an error with code {error} and category '{category}': {message}");
}
}
class Program
{
static void Main(string[] args)
{
bool help = false;
int port = 2222;
int threads = Environment.ProcessorCount;
int messagesRate = 1000000;
int messageSize = 32;
var options = new OptionSet()
{
{ "h|?|help", v => help = v != null },
{ "p|port=", v => port = int.Parse(v) },
{ "t|threads=", v => threads = int.Parse(v) },
{ "m|messages=", v => messagesRate = int.Parse(v) },
{ "s|size=", v => messageSize = int.Parse(v) }
};
try
{
options.Parse(args);
}
catch (OptionException e)
{
Console.Write("Command line error: ");
Console.WriteLine(e.Message);
Console.WriteLine("Try `--help' to get usage information.");
return;
}
if (help)
{
Console.WriteLine("Usage:");
options.WriteOptionDescriptions(Console.Out);
return;
}
Console.WriteLine($"Server port: {port}");
Console.WriteLine($"Working threads: {threads}");
Console.WriteLine($"Messages rate: {messagesRate}");
Console.WriteLine($"Message size: {messageSize}");
Console.WriteLine();
// Create a new service
var service = new Service(threads);
// Start the service
Console.Write("Service starting...");
service.Start();
Console.WriteLine("Done!");
// Create and prepare a new SSL server context
var context = new SslContext(SslMethod.TLSV12);
context.SetPassword("qwerty");
context.UseCertificateChainFile("server.pem");
context.UsePrivateKeyFile("server.pem", SslFileFormat.PEM);
context.UseTmpDHFile("dh4096.pem");
// Create a new echo server
var server = new MulticastServer(service, context, port, InternetProtocol.IPv4);
// server.SetupNoDelay(true);
server.SetupReuseAddress(true);
server.SetupReusePort(true);
// Start the server
Console.Write("Server starting...");
server.Start();
Console.WriteLine("Done!");
// Start the multicasting thread
bool multicasting = true;
var multicaster = Task.Factory.StartNew(() =>
{
// Prepare message to multicast
byte[] message = new byte[messageSize];
// Multicasting loop
while (multicasting)
{
var start = DateTime.UtcNow;
for (int i = 0; i < messagesRate; ++i)
server.Multicast(message);
var end = DateTime.UtcNow;
// Sleep for remaining time or yield
var milliseconds = (int)(end - start).TotalMilliseconds;
if (milliseconds < 1000)
Thread.Sleep(1000 - milliseconds);
else
Thread.Yield();
}
});
Console.WriteLine("Press Enter to stop the server or '!' to restart the server...");
// Perform text input
for (;;)
{
string line = Console.ReadLine();
if (line == string.Empty)
break;
// Restart the server
if (line == "!")
{
Console.Write("Server restarting...");
server.Restart();
Console.WriteLine("Done!");
}
}
// Stop the multicasting thread
multicasting = false;
multicaster.Wait();
// Stop the server
Console.Write("Server stopping...");
server.Stop();
Console.WriteLine("Done!");
// Stop the service
Console.Write("Service stopping...");
service.Stop();
Console.WriteLine("Done!");
}
}
}
| 33.174699 | 148 | 0.505175 | [
"MIT"
] | chronoxor/CSharpServer | performance/SslMulticastServer/Program.cs | 5,509 | C# |
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using System;
using TheHotelApp.Data;
namespace TheHotelApp.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.0.2-rtm-10011")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex")
.HasFilter("[NormalizedName] IS NOT NULL");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("TheHotelApp.Models.ApplicationUser", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("AccessFailedCount");
b.Property<string>("Address");
b.Property<string>("City");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed");
b.Property<string>("FullName");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasMaxLength(256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("ProfilePic");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex")
.HasFilter("[NormalizedUserName] IS NOT NULL");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("TheHotelApp.Models.Booking", b =>
{
b.Property<string>("ID")
.ValueGeneratedOnAdd();
b.Property<string>("ApplicationId");
b.Property<string>("ApplicationUserId");
b.Property<DateTime>("CheckIn");
b.Property<DateTime>("CheckOut");
b.Property<bool>("Completed");
b.Property<string>("CustomerAddress");
b.Property<string>("CustomerCity");
b.Property<string>("CustomerEmail");
b.Property<string>("CustomerName")
.IsRequired();
b.Property<string>("CustomerPhone");
b.Property<DateTime>("DateCreated");
b.Property<int>("Guests");
b.Property<string>("OtherRequests");
b.Property<bool>("Paid");
b.Property<string>("RoomID");
b.Property<decimal>("TotalFee");
b.HasKey("ID");
b.HasIndex("ApplicationId");
b.HasIndex("RoomID");
b.ToTable("Bookings");
});
modelBuilder.Entity("TheHotelApp.Models.Feature", b =>
{
b.Property<string>("ID")
.ValueGeneratedOnAdd();
b.Property<string>("Icon")
.IsRequired();
b.Property<string>("Name")
.IsRequired();
b.HasKey("ID");
b.ToTable("Features");
});
modelBuilder.Entity("TheHotelApp.Models.Image", b =>
{
b.Property<string>("ID")
.ValueGeneratedOnAdd();
b.Property<string>("FilePath");
b.Property<string>("ImageUrl");
b.Property<string>("Name");
b.Property<string>("RoomID");
b.Property<string>("Size");
b.HasKey("ID");
b.HasIndex("RoomID");
b.ToTable("Images");
});
modelBuilder.Entity("TheHotelApp.Models.ItemImage", b =>
{
b.Property<string>("ItemID");
b.Property<string>("ImageID");
b.HasKey("ItemID", "ImageID");
b.HasIndex("ImageID");
b.ToTable("ItemImageRelationships");
});
modelBuilder.Entity("TheHotelApp.Models.Review", b =>
{
b.Property<string>("ID")
.ValueGeneratedOnAdd();
b.Property<string>("Description");
b.Property<string>("ReviewerEmail");
b.Property<string>("ReviewerName");
b.Property<string>("RoomID");
b.HasKey("ID");
b.HasIndex("RoomID");
b.ToTable("Reviews");
});
modelBuilder.Entity("TheHotelApp.Models.Room", b =>
{
b.Property<string>("ID")
.ValueGeneratedOnAdd();
b.Property<bool>("Available");
b.Property<string>("Description")
.IsRequired();
b.Property<int>("MaximumGuests");
b.Property<int>("Number");
b.Property<decimal>("Price");
b.Property<string>("RoomTypeID");
b.HasKey("ID");
b.HasIndex("RoomTypeID");
b.ToTable("Rooms");
});
modelBuilder.Entity("TheHotelApp.Models.RoomFeature", b =>
{
b.Property<string>("RoomID");
b.Property<string>("FeatureID");
b.HasKey("RoomID", "FeatureID");
b.HasIndex("FeatureID");
b.ToTable("RoomFeatureRelationships");
});
modelBuilder.Entity("TheHotelApp.Models.RoomType", b =>
{
b.Property<string>("ID")
.ValueGeneratedOnAdd();
b.Property<decimal>("BasePrice");
b.Property<string>("Description")
.IsRequired();
b.Property<string>("Name")
.IsRequired();
b.HasKey("ID");
b.ToTable("RoomTypes");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("TheHotelApp.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("TheHotelApp.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("TheHotelApp.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("TheHotelApp.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("TheHotelApp.Models.Booking", b =>
{
b.HasOne("TheHotelApp.Models.ApplicationUser", "User")
.WithMany("Bookings")
.HasForeignKey("ApplicationId");
b.HasOne("TheHotelApp.Models.Room", "Room")
.WithMany("Bookings")
.HasForeignKey("RoomID");
});
modelBuilder.Entity("TheHotelApp.Models.Image", b =>
{
b.HasOne("TheHotelApp.Models.Room")
.WithMany("RoomImages")
.HasForeignKey("RoomID");
});
modelBuilder.Entity("TheHotelApp.Models.ItemImage", b =>
{
b.HasOne("TheHotelApp.Models.Image", "Image")
.WithMany()
.HasForeignKey("ImageID")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("TheHotelApp.Models.Review", b =>
{
b.HasOne("TheHotelApp.Models.Room", "Room")
.WithMany("Reviews")
.HasForeignKey("RoomID");
});
modelBuilder.Entity("TheHotelApp.Models.Room", b =>
{
b.HasOne("TheHotelApp.Models.RoomType", "RoomType")
.WithMany("Rooms")
.HasForeignKey("RoomTypeID")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("TheHotelApp.Models.RoomFeature", b =>
{
b.HasOne("TheHotelApp.Models.Feature", "Feature")
.WithMany("Rooms")
.HasForeignKey("FeatureID")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("TheHotelApp.Models.Room", "Room")
.WithMany("Features")
.HasForeignKey("RoomID")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}
| 32.113734 | 117 | 0.448313 | [
"MIT"
] | Johnesan/TheHotelApplication | TheHotelApp/Data/Migrations/ApplicationDbContextModelSnapshot.cs | 14,967 | C# |
using System.IO;
using CP77.CR2W.Reflection;
using FastMember;
using static CP77.CR2W.Types.Enums;
namespace CP77.CR2W.Types
{
[REDMeta]
public class SourceTypeHitPrereqCondition : BaseHitPrereqCondition
{
[Ordinal(0)] [RED("source")] public CName Source { get; set; }
public SourceTypeHitPrereqCondition(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
| 25.75 | 115 | 0.725728 | [
"MIT"
] | Eingin/CP77Tools | CP77.CR2W/Types/cp77/SourceTypeHitPrereqCondition.cs | 397 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace System.Fabric
{
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
/// <summary>
/// <para>Class for code package debug parameters.</para>
/// </summary>
[DataContract]
public class CodePackageDebugParameters
{
[DataMember]
internal string ServiceManifestName;
[DataMember]
internal string CodePackageName;
[DataMember]
internal string ConfigPackageName;
[DataMember]
internal string DataPackageName;
[DataMember]
internal string EntryPointType;
[DataMember]
internal string DebugExePath;
[DataMember]
internal string DebugArguments;
[DataMember]
internal string CodePackageLinkFolder;
[DataMember]
internal string ConfigPackageLinkFolder;
[DataMember]
internal string DataPackageLinkFolder;
[DataMember]
internal string LockFile;
[DataMember]
internal string WorkingFolder;
[DataMember]
internal string DebugParametersFile;
[DataMember]
internal string EnvironmentBlock;
[DataMember]
internal ContainerDebugParameters ContainerDebugParams;
internal CodePackageDebugParameters(
string serviceManifestName,
string codePackageName,
string configPackageName,
string dataPackageName,
string entryPointType,
string debugExePath,
string debugArguments,
string codePackageLinkFolder,
string configPackageLinkFolder,
string dataPackageLinkFolder,
string lockFile,
string workingFolder,
string debugParametersFile,
string environmentBlock,
ContainerDebugParameters containerDebugParams)
{
this.ServiceManifestName = serviceManifestName;
this.CodePackageName = codePackageName;
this.ConfigPackageName = configPackageName;
this.DataPackageName = dataPackageName;
this.EntryPointType = entryPointType;
this.DebugExePath = debugExePath;
this.DebugArguments = debugArguments;
this.CodePackageLinkFolder = codePackageLinkFolder;
this.ConfigPackageLinkFolder = configPackageLinkFolder;
this.DataPackageLinkFolder = dataPackageLinkFolder;
this.LockFile = lockFile;
this.WorkingFolder = workingFolder;
this.DebugParametersFile = debugParametersFile;
this.EnvironmentBlock = environmentBlock;
this.ContainerDebugParams = containerDebugParams;
}
internal static List<CodePackageDebugParameters> CreateFrom(string debugParameters)
{
var serializer = new DataContractJsonSerializer(typeof(CodePackageDebugParameters[]));
CodePackageDebugParameters[] parameterObj = null;
byte[] debugParams = Encoding.UTF8.GetBytes(debugParameters);
using (var strm = new MemoryStream(debugParams))
{
parameterObj = serializer.ReadObject(strm) as CodePackageDebugParameters[];
}
var debugParameterObjs = new List<CodePackageDebugParameters>();
if (parameterObj != null)
{
for (int i = 0; i < parameterObj.Length; i++)
{
debugParameterObjs.Add(parameterObj[i]);
}
}
return debugParameterObjs;
}
/// <summary>
/// <para>
/// Returns JSON string representing CodePackageDebugParameters passed in.
/// </para>
/// </summary>
/// <param name="debugParameters">
/// <para>Array of CodePackageDebugParameters that need to be serialized into JSON. </para>
/// </param>
/// <returns>
/// <para>String representation of the debug parameters.</para>
/// </returns>
public static string GetDebugParameters(CodePackageDebugParameters[] debugParameters)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(CodePackageDebugParameters[]));
using (MemoryStream stream = new MemoryStream())
{
serializer.WriteObject(stream, debugParameters);
return Encoding.UTF8.GetString(stream.ToArray());
}
}
}
/// <summary>
/// <para>Class for container debug parameters.</para>
/// </summary>
[DataContract]
public class ContainerDebugParameters
{
[DataMember]
internal string[] Entrypoint;
[DataMember]
internal string[] Volumes;
[DataMember]
internal string[] EnvVars;
[DataMember]
internal string[] Labels;
internal ContainerDebugParameters(
string[] entryPoints,
string[] volumes,
string[] envVars,
string[] labels)
{
this.Entrypoint = entryPoints;
this.EnvVars = envVars;
this.Volumes = volumes;
this.Labels = labels;
}
internal ContainerDebugParameters()
{
}
}
} | 32.357955 | 121 | 0.597893 | [
"MIT"
] | AlkisFortuneFish/service-fabric | src/prod/src/managed/Api/src/System/Fabric/Common/CodePackageDebugParameters.cs | 5,695 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using MediatR;
using SplitThatBill.Backend.Business.Dtos;
namespace SplitThatBill.Backend.Business.Requests.People
{
public class GetPeopleRequest: IRequest<List<PersonDto>>
{
}
}
| 20.076923 | 60 | 0.777778 | [
"MIT"
] | lhargil/split-that-bill-backend | src/SplitThatBill.Backend.Business/Requests/People/GetPeopleRequest.cs | 263 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BaseStarShot.Services
{
public enum ProductType
{
Unknown = 0,
NonConsumable = 1,
Consumable = 2,
}
}
| 16.625 | 33 | 0.669173 | [
"Apache-2.0"
] | StarshotSoftware/Base_XamarinForms | BaseStarShot/Services/InAppPurchase/ProductType.cs | 268 | C# |
using System;
using System.IO;
using NUnit.Framework;
using winsw;
namespace winswTests.Util
{
/// <summary>
/// Helper for WinSW CLI testing
/// </summary>
public static class CLITestHelper
{
public const string Id = "WinSW.Tests";
public const string Name = "WinSW Test Service";
private static readonly string SeedXml =
$@"<service>
<id>{Id}</id>
<name>{Name}</name>
<description>The service.</description>
<executable>node.exe</executable>
<arguments>My Arguments</arguments>
<logmode>rotate</logmode>
<workingdirectory>C:\winsw\workdir</workingdirectory>
<logpath>C:\winsw\logs</logpath>
</service>";
public static readonly ServiceDescriptor DefaultServiceDescriptor = ServiceDescriptor.FromXML(SeedXml);
/// <summary>
/// Runs a simle test, which returns the output CLI
/// </summary>
/// <param name="arguments">CLI arguments to be passed</param>
/// <param name="descriptor">Optional Service descriptor (will be used for initializationpurposes)</param>
/// <returns>STDOUT if there's no exceptions</returns>
/// <exception cref="Exception">Command failure</exception>
public static string CLITest(string[] arguments, ServiceDescriptor descriptor = null)
{
TextWriter tmpOut = Console.Out;
TextWriter tmpErr = Console.Error;
using StringWriter swOut = new StringWriter();
using StringWriter swErr = new StringWriter();
Console.SetOut(swOut);
Console.SetError(swErr);
try
{
WrapperService.Run(arguments, descriptor ?? DefaultServiceDescriptor);
}
finally
{
Console.SetOut(tmpOut);
Console.SetError(tmpErr);
}
Assert.That(swErr.GetStringBuilder().Length, Is.Zero);
Console.Write(swOut.ToString());
return swOut.ToString();
}
/// <summary>
/// Runs a simle test, which returns the output CLI
/// </summary>
/// <param name="arguments">CLI arguments to be passed</param>
/// <param name="descriptor">Optional Service descriptor (will be used for initializationpurposes)</param>
/// <returns>Test results</returns>
public static CLITestResult CLIErrorTest(string[] arguments, ServiceDescriptor descriptor = null)
{
Exception testEx = null;
TextWriter tmpOut = Console.Out;
TextWriter tmpErr = Console.Error;
using StringWriter swOut = new StringWriter();
using StringWriter swErr = new StringWriter();
Console.SetOut(swOut);
Console.SetError(swErr);
try
{
WrapperService.Run(arguments, descriptor ?? DefaultServiceDescriptor);
}
catch (Exception ex)
{
testEx = ex;
}
finally
{
Console.SetOut(tmpOut);
Console.SetError(tmpErr);
}
Console.WriteLine("\n>>> Output: ");
Console.Write(swOut.ToString());
Console.WriteLine("\n>>> Error: ");
Console.Write(swErr.ToString());
if (testEx != null)
{
Console.WriteLine("\n>>> Exception: ");
Console.WriteLine(testEx);
}
return new CLITestResult(swOut.ToString(), swErr.ToString(), testEx);
}
}
/// <summary>
/// Aggregated test report
/// </summary>
public class CLITestResult
{
public string Out { get; }
public string Error { get; }
public Exception Exception { get; }
public bool HasException => Exception != null;
public CLITestResult(string output, string error, Exception exception = null)
{
Out = output;
Error = error;
Exception = exception;
}
}
}
| 31.773438 | 114 | 0.570691 | [
"MIT"
] | cjh0613/winsw | src/Test/winswTests/Util/CLITestHelper.cs | 4,069 | C# |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RA.SamplesForDocumentation;
using RA.SamplesForDocumentation.Credentials;
namespace RA.SamplePublishingProject
{
[TestClass]
public class CredentialTesting
{
[TestMethod]
public void DoAFormatRequest()
{
//using simple post
new PublishCredential().PublishDetailedRecord( "format");
new PublishCredentialWithOutcomes().CredentialWithOutcomeData( "format" );
//temp
new KansasExamples().CredentialWithAggregateDataProfile( "format" );
}
[TestMethod]
public void DoAPublishRequest()
{
//using simple post
new PublishCredential().PublishDetailedRecord( "publish" );
}
[TestMethod]
public void CredentialWithOutcomeData()
{
//using simple post
new PublishCredentialWithOutcomes().CredentialWithOutcomeData( "publish" );
}
//
[TestMethod]
public void CredentialWithAlternativeConditions()
{
//using simple post
new PublishCredentialWithMultipleCampuses().PublishRecord( "publish" );
}
[TestMethod]
public void CareerBridgeCredentialsCredentialWithHoldersProfile()
{
//using simple post
new CareerBridgeCredentials().CredentialWithAggregateDataProfile( "publish" );
}
[TestMethod]
public void KansasCredentialWithAggregateData()
{
//using simple post
new KansasExamples().CredentialWithAggregateDataProfile( "publish" );
}
[TestMethod]
public void PublishQACredential()
{
//using simple post
new PublishQACredentialWithETPL().Publish( true );
}
[TestMethod]
public void PublishProPathCredential()
{
//
new ProPathExamples().CredentialWithAggregateDataProfile( "publish" );
//new ProPathExamples().CredentialWithHoldersProfile( "publish" );
//PublishProPathLearningOpportunity();
}
[TestMethod]
public void PublishProPathLearningOpportunity()
{
//
new ProPathExamples().RelatedLearningOpportunity( "publish" );
}
[TestMethod]
public void DoAPublishRequestFromExternalData()
{
var input = new SamplesForDocumentation.SampleModels.Credential()
{
Name="My internal credential",
Description="Description of my credential",
CTID="ce-" + Guid.NewGuid().ToString().ToLower(),
CredentialType = "BachelorDegree",
SubjectWebpage ="https://example.com?type=thisTest",
Keyword = new System.Collections.Generic.List<string>() { "Engineering","Mechanical Engineering","Bachelor"}
};
//using simple post
new PublishCredential().PublishFromInputClass( input ) ;
}
}
}
| 26.547368 | 112 | 0.73632 | [
"Apache-2.0"
] | CredentialEngine/Registry_Assistant | src/SamplePublishing/RA.SamplePublishingProject/CredentialTesting.cs | 2,524 | 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 codecommit-2015-04-13.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.CodeCommit.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.CodeCommit.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for AssociateApprovalRuleTemplateWithRepository operation
/// </summary>
public class AssociateApprovalRuleTemplateWithRepositoryResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
AssociateApprovalRuleTemplateWithRepositoryResponse response = new AssociateApprovalRuleTemplateWithRepositoryResponse();
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
if (errorResponse.Code != null && errorResponse.Code.Equals("ApprovalRuleTemplateDoesNotExistException"))
{
return new ApprovalRuleTemplateDoesNotExistException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ApprovalRuleTemplateNameRequiredException"))
{
return new ApprovalRuleTemplateNameRequiredException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("EncryptionIntegrityChecksFailedException"))
{
return new EncryptionIntegrityChecksFailedException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("EncryptionKeyAccessDeniedException"))
{
return new EncryptionKeyAccessDeniedException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("EncryptionKeyDisabledException"))
{
return new EncryptionKeyDisabledException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("EncryptionKeyNotFoundException"))
{
return new EncryptionKeyNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("EncryptionKeyUnavailableException"))
{
return new EncryptionKeyUnavailableException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidApprovalRuleTemplateNameException"))
{
return new InvalidApprovalRuleTemplateNameException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidRepositoryNameException"))
{
return new InvalidRepositoryNameException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("MaximumRuleTemplatesAssociatedWithRepositoryException"))
{
return new MaximumRuleTemplatesAssociatedWithRepositoryException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("RepositoryDoesNotExistException"))
{
return new RepositoryDoesNotExistException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("RepositoryNameRequiredException"))
{
return new RepositoryNameRequiredException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
return new AmazonCodeCommitException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
private static AssociateApprovalRuleTemplateWithRepositoryResponseUnmarshaller _instance = new AssociateApprovalRuleTemplateWithRepositoryResponseUnmarshaller();
internal static AssociateApprovalRuleTemplateWithRepositoryResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static AssociateApprovalRuleTemplateWithRepositoryResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 52.604478 | 197 | 0.704213 | [
"Apache-2.0"
] | NGL321/aws-sdk-net | sdk/src/Services/CodeCommit/Generated/Model/Internal/MarshallTransformations/AssociateApprovalRuleTemplateWithRepositoryResponseUnmarshaller.cs | 7,049 | C# |
using System;
namespace TruckManager.Application.Features.Motoristas
{
public partial class ConsultarMotoristasSemCarga
{
public class Query
{
public DateTime DataInicial { get; set; }
public DateTime DataFinal { get; set; }
}
}
}
| 19.6 | 54 | 0.619048 | [
"MIT"
] | gmurayama/truck-manager | src/Application/Features/Motoristas/ConsultarMotoristasSemCarga/Query.cs | 296 | C# |
using System;
using System.Diagnostics;
using Org.BouncyCastle.Math.Raw;
namespace Org.BouncyCastle.Math.EC.Custom.Sec
{
internal class SecT113Field
{
private const ulong M49 = ulong.MaxValue >> 15;
private const ulong M57 = ulong.MaxValue >> 7;
public static void Add(ulong[] x, ulong[] y, ulong[] z)
{
z[0] = x[0] ^ y[0];
z[1] = x[1] ^ y[1];
}
public static void AddExt(ulong[] xx, ulong[] yy, ulong[] zz)
{
zz[0] = xx[0] ^ yy[0];
zz[1] = xx[1] ^ yy[1];
zz[2] = xx[2] ^ yy[2];
zz[3] = xx[3] ^ yy[3];
}
public static void AddOne(ulong[] x, ulong[] z)
{
z[0] = x[0] ^ 1UL;
z[1] = x[1];
}
public static ulong[] FromBigInteger(BigInteger x)
{
ulong[] z = Nat128.FromBigInteger64(x);
Reduce15(z, 0);
return z;
}
public static void Invert(ulong[] x, ulong[] z)
{
if (Nat128.IsZero64(x))
throw new InvalidOperationException();
// Itoh-Tsujii inversion
ulong[] t0 = Nat128.Create64();
ulong[] t1 = Nat128.Create64();
Square(x, t0);
Multiply(t0, x, t0);
Square(t0, t0);
Multiply(t0, x, t0);
SquareN(t0, 3, t1);
Multiply(t1, t0, t1);
Square(t1, t1);
Multiply(t1, x, t1);
SquareN(t1, 7, t0);
Multiply(t0, t1, t0);
SquareN(t0, 14, t1);
Multiply(t1, t0, t1);
SquareN(t1, 28, t0);
Multiply(t0, t1, t0);
SquareN(t0, 56, t1);
Multiply(t1, t0, t1);
Square(t1, z);
}
public static void Multiply(ulong[] x, ulong[] y, ulong[] z)
{
ulong[] tt = Nat128.CreateExt64();
ImplMultiply(x, y, tt);
Reduce(tt, z);
}
public static void MultiplyAddToExt(ulong[] x, ulong[] y, ulong[] zz)
{
ulong[] tt = Nat128.CreateExt64();
ImplMultiply(x, y, tt);
AddExt(zz, tt, zz);
}
public static void Reduce(ulong[] xx, ulong[] z)
{
ulong x0 = xx[0], x1 = xx[1], x2 = xx[2], x3 = xx[3];
x1 ^= (x3 << 15) ^ (x3 << 24);
x2 ^= (x3 >> 49) ^ (x3 >> 40);
x0 ^= (x2 << 15) ^ (x2 << 24);
x1 ^= (x2 >> 49) ^ (x2 >> 40);
ulong t = x1 >> 49;
z[0] = x0 ^ t ^ (t << 9);
z[1] = x1 & M49;
}
public static void Reduce15(ulong[] z, int zOff)
{
ulong z1 = z[zOff + 1], t = z1 >> 49;
z[zOff ] ^= t ^ (t << 9);
z[zOff + 1] = z1 & M49;
}
public static void Sqrt(ulong[] x, ulong[] z)
{
ulong u0 = Interleave.Unshuffle(x[0]), u1 = Interleave.Unshuffle(x[1]);
ulong e0 = (u0 & 0x00000000FFFFFFFFUL) | (u1 << 32);
ulong c0 = (u0 >> 32) | (u1 & 0xFFFFFFFF00000000UL);
z[0] = e0 ^ (c0 << 57) ^ (c0 << 5);
z[1] = (c0 >> 7) ^ (c0 >> 59);
}
public static void Square(ulong[] x, ulong[] z)
{
ulong[] tt = Nat128.CreateExt64();
ImplSquare(x, tt);
Reduce(tt, z);
}
public static void SquareAddToExt(ulong[] x, ulong[] zz)
{
ulong[] tt = Nat128.CreateExt64();
ImplSquare(x, tt);
AddExt(zz, tt, zz);
}
public static void SquareN(ulong[] x, int n, ulong[] z)
{
Debug.Assert(n > 0);
ulong[] tt = Nat128.CreateExt64();
ImplSquare(x, tt);
Reduce(tt, z);
while (--n > 0)
{
ImplSquare(z, tt);
Reduce(tt, z);
}
}
public static uint Trace(ulong[] x)
{
// Non-zero-trace bits: 0
return (uint)(x[0]) & 1U;
}
protected static void ImplMultiply(ulong[] x, ulong[] y, ulong[] zz)
{
/*
* "Three-way recursion" as described in "Batch binary Edwards", Daniel J. Bernstein.
*/
ulong f0 = x[0], f1 = x[1];
f1 = ((f0 >> 57) ^ (f1 << 7)) & M57;
f0 &= M57;
ulong g0 = y[0], g1 = y[1];
g1 = ((g0 >> 57) ^ (g1 << 7)) & M57;
g0 &= M57;
ulong[] H = new ulong[6];
ImplMulw(f0, g0, H, 0); // H(0) 57/56 bits
ImplMulw(f1, g1, H, 2); // H(INF) 57/54 bits
ImplMulw(f0 ^ f1, g0 ^ g1, H, 4); // H(1) 57/56 bits
ulong r = H[1] ^ H[2];
ulong z0 = H[0],
z3 = H[3],
z1 = H[4] ^ z0 ^ r,
z2 = H[5] ^ z3 ^ r;
zz[0] = z0 ^ (z1 << 57);
zz[1] = (z1 >> 7) ^ (z2 << 50);
zz[2] = (z2 >> 14) ^ (z3 << 43);
zz[3] = (z3 >> 21);
}
protected static void ImplMulw(ulong x, ulong y, ulong[] z, int zOff)
{
Debug.Assert(x >> 57 == 0);
Debug.Assert(y >> 57 == 0);
ulong[] u = new ulong[8];
//u[0] = 0;
u[1] = y;
u[2] = u[1] << 1;
u[3] = u[2] ^ y;
u[4] = u[2] << 1;
u[5] = u[4] ^ y;
u[6] = u[3] << 1;
u[7] = u[6] ^ y;
uint j = (uint)x;
ulong g, h = 0, l = u[j & 7];
int k = 48;
do
{
j = (uint)(x >> k);
g = u[j & 7]
^ u[(j >> 3) & 7] << 3
^ u[(j >> 6) & 7] << 6;
l ^= (g << k);
h ^= (g >> -k);
}
while ((k -= 9) > 0);
h ^= ((x & 0x0100804020100800UL) & (ulong)(((long)y << 7) >> 63)) >> 8;
Debug.Assert(h >> 49 == 0);
z[zOff ] = l & M57;
z[zOff + 1] = (l >> 57) ^ (h << 7);
}
protected static void ImplSquare(ulong[] x, ulong[] zz)
{
Interleave.Expand64To128(x[0], zz, 0);
Interleave.Expand64To128(x[1], zz, 2);
}
}
}
| 28.619469 | 106 | 0.376469 | [
"Apache-2.0"
] | Arthurvdmerwe/-ISO-TC-68-SC-2-ISO20038 | Crypto/src/math/ec/custom/sec/SecT113Field.cs | 6,470 | C# |
// -----------------------------------------------------------------------
// <copyright file="TaskTime.cs" company="Nodine Legal, LLC">
// Licensed to Nodine Legal, LLC under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. Nodine Legal, LLC 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.
// </copyright>
// -----------------------------------------------------------------------
namespace OpenLawOffice.Data.DBOs.Tasks
{
using System;
using AutoMapper;
/// <summary>
/// Relates a time entry to a task
/// </summary>
[Common.Models.MapMe]
public class TaskTime : Core
{
[ColumnMapping(Name = "id")]
public Guid Id { get; set; }
[ColumnMapping(Name = "task_id")]
public long TaskId { get; set; }
[ColumnMapping(Name = "time_id")]
public Guid TimeId { get; set; }
public void BuildMappings()
{
Dapper.SqlMapper.SetTypeMap(typeof(TaskTime), new ColumnAttributeTypeMapper<TaskTime>());
Mapper.CreateMap<DBOs.Tasks.TaskTime, Common.Models.Tasks.TaskTime>()
.ForMember(dst => dst.IsStub, opt => opt.UseValue(false))
.ForMember(dst => dst.Created, opt => opt.ResolveUsing(db =>
{
return db.UtcCreated.ToSystemTime();
}))
.ForMember(dst => dst.Modified, opt => opt.ResolveUsing(db =>
{
return db.UtcModified.ToSystemTime();
}))
.ForMember(dst => dst.Disabled, opt => opt.ResolveUsing(db =>
{
return db.UtcDisabled.ToSystemTime();
}))
.ForMember(dst => dst.CreatedBy, opt => opt.ResolveUsing(db =>
{
return new Common.Models.Account.Users()
{
PId = db.CreatedByUserPId,
IsStub = true
};
}))
.ForMember(dst => dst.ModifiedBy, opt => opt.ResolveUsing(db =>
{
return new Common.Models.Account.Users()
{
PId = db.ModifiedByUserPId,
IsStub = true
};
}))
.ForMember(dst => dst.DisabledBy, opt => opt.ResolveUsing(db =>
{
if (!db.DisabledByUserPId.HasValue) return null;
return new Common.Models.Account.Users()
{
PId = db.DisabledByUserPId.Value,
IsStub = true
};
}))
.ForMember(dst => dst.Id, opt => opt.MapFrom(src => src.Id))
.ForMember(dst => dst.Task, opt => opt.ResolveUsing(db =>
{
return new Common.Models.Tasks.Task()
{
Id = db.TaskId,
IsStub = true
};
}))
.ForMember(dst => dst.Time, opt => opt.ResolveUsing(db =>
{
return new Common.Models.Timing.Time()
{
Id = db.TimeId,
IsStub = true
};
}));
Mapper.CreateMap<Common.Models.Tasks.TaskTime, DBOs.Tasks.TaskTime>()
.ForMember(dst => dst.UtcCreated, opt => opt.ResolveUsing(db =>
{
return db.Created.ToDbTime();
}))
.ForMember(dst => dst.UtcModified, opt => opt.ResolveUsing(db =>
{
return db.Modified.ToDbTime();
}))
.ForMember(dst => dst.UtcDisabled, opt => opt.ResolveUsing(db =>
{
return db.Disabled.ToDbTime();
}))
.ForMember(dst => dst.CreatedByUserPId, opt => opt.ResolveUsing(model =>
{
if (model.CreatedBy == null || !model.CreatedBy.PId.HasValue)
return Guid.Empty;
return model.CreatedBy.PId.Value;
}))
.ForMember(dst => dst.ModifiedByUserPId, opt => opt.ResolveUsing(model =>
{
if (model.ModifiedBy == null || !model.ModifiedBy.PId.HasValue)
return Guid.Empty;
return model.ModifiedBy.PId.Value;
}))
.ForMember(dst => dst.DisabledByUserPId, opt => opt.ResolveUsing(model =>
{
if (model.DisabledBy == null) return null;
return model.DisabledBy.PId;
}))
.ForMember(dst => dst.Id, opt => opt.MapFrom(src => src.Id))
.ForMember(dst => dst.TaskId, opt => opt.ResolveUsing(model =>
{
if (model.Task != null)
return model.Task.Id;
else
return null;
}))
.ForMember(dst => dst.TimeId, opt => opt.ResolveUsing(model =>
{
if (model.Time != null)
return model.Time.Id;
else
return null;
}));
}
}
} | 40.751678 | 101 | 0.461957 | [
"Apache-2.0"
] | NodineLegal/OpenLawOffice | OpenLawOffice.Data/DBOs/Tasks/TaskTime.cs | 6,074 | C# |
using System;
using AlphaDev.Web.Models;
using FluentAssertions;
using Optional;
using Xunit;
namespace AlphaDev.Web.Tests.Unit.Models
{
public class BlogEditorViewModelTests
{
[Fact]
public void ConstructorShouldInitializeAllProperties()
{
const string title = "title";
const string content = "content";
var dates = new DatesViewModel(new DateTime(2011, 1, 20), new DateTime(2013, 7, 14).Some()).Some();
var model = new BlogEditorViewModel(dates, content, title);
model.Should()
.BeEquivalentTo(new
{
Title = title,
Content = content,
Dates = dates
});
}
}
} | 26.931034 | 111 | 0.544174 | [
"Unlicense"
] | OlegKleyman/AlphaDev | tests/unit/AlphaDev.Web.Tests.Unit/Models/BlogEditorViewModelTests.cs | 783 | C# |
using System;
using clojure.lang;
namespace Arcadia
{
public static class ArrayHelper
{
public static T[] CountedArray<T>(Counted c){
T[] ar = new T[c.count()];
int i = 0;
foreach (T x in (System.Collections.IEnumerable) c) {
ar[i] = x;
i++;
}
return ar;
}
}
}
| 13.727273 | 56 | 0.582781 | [
"Apache-2.0"
] | max-lv/Arcadia | Helpers/ArrayHelper.cs | 304 | C# |
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
namespace RSql4Net.Models.Queries
{
public class RSqlQueryModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (!context.Metadata.ModelType.IsGenericType ||
(context.Metadata.ModelType.GetGenericTypeDefinition() != typeof(IRSqlQuery<>) &&
context.Metadata.ModelType.GetGenericTypeDefinition() != typeof(RSqlQuery<>)))
{
return null;
}
var entityType = context.Metadata.ModelType.GetGenericArguments()[0];
var modelBinderType = typeof(RSqlQueryModelBinder<>).MakeGenericType(entityType);
return new BinderTypeModelBinder(modelBinderType);
}
}
}
| 37.608696 | 97 | 0.671676 | [
"MIT"
] | gwendallg/RSql4Net | src/RSql4Net/Models/Queries/RSqlQueryModelBinderProvider.cs | 867 | 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.Threading.Tasks;
namespace Microsoft.Extensions.Logging.AzureAppServices.Test
{
internal class ManualIntervalControl
{
private TaskCompletionSource<object> _pauseCompletionSource = new TaskCompletionSource<object>();
private TaskCompletionSource<object> _resumeCompletionSource;
public Task Pause => _pauseCompletionSource.Task;
public void Resume()
{
_pauseCompletionSource = new TaskCompletionSource<object>();
_resumeCompletionSource.SetResult(null);
}
public async Task IntervalAsync()
{
_resumeCompletionSource = new TaskCompletionSource<object>();
_pauseCompletionSource.SetResult(null);
await _resumeCompletionSource.Task;
}
}
} | 31.2 | 105 | 0.694444 | [
"MIT"
] | 48355746/AspNetCore | src/Logging.AzureAppServices/test/ManualIntervalControl.cs | 936 | C# |
// SPDX-License-Identifier: Apache-2.0
// Licensed to the Ed-Fi Alliance under one or more agreements.
// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0.
// See the LICENSE and NOTICES files in the project root for more information.
using EdFi.Ods.AdminApp.Management.Database.Ods;
using NUnit.Framework;
using Shouldly;
using System.Linq;
using EdFi.Ods.AdminApp.Management.Instances;
namespace EdFi.Ods.AdminApp.Management.Tests.Database.Queries.Ods
{
[TestFixture]
public class GetAllLocalEducationAgenciesQueryTests : OdsDataTestBase
{
[Test]
public void ShouldRetrieveLocalEducationAgencies()
{
var id = GetNewLocalEducationAgencyId("Sample LEA");
var districts = new GetAllLocalEducationAgenciesQuery(TestConnectionProvider).Execute(CloudOdsDatabaseNames.ProductionOds, ApiMode.Sandbox);
districts.Single().Name.ShouldBe("Sample LEA");
districts.Single().LocalEducationAgencyId.ShouldBe(id);
}
}
}
| 38.481481 | 152 | 0.736285 | [
"Apache-2.0"
] | CSR2017/Ed-Fi-ODS-AdminApp | Application/EdFi.Ods.AdminApp.Management.Tests/Database/Queries/Ods/GetAllLocalEducationAgenciesQueryTests.cs | 1,041 | C# |
using Godot;
using System;
public class IngredientEntryEditor : HBoxContainer
{
[Signal]
public delegate void deleted(IngredientEntryEditor node);
[Signal]
public delegate void changed(IngredientEntryEditor node, string ingred, int amt);
public override void _Ready()
{
GetNode<LineEdit>("LineEdit").Connect("text_changed", this, nameof(Signal_OnIngredientChanged));
GetNode<SpinBox>("SpinBox").Connect("value_changed", this, nameof(Signal_OnQuantityChanged));
GetNode<Button>("DeleteButton").Connect("pressed", this, nameof(Signal_OnDelete));
}
private void Signal_OnDelete()
{
EmitSignal(nameof(deleted), this);
QueueFree();
}
private void Signal_OnIngredientChanged(string str)
{
var other = GetNode<SpinBox>("SpinBox");
EmitSignal(nameof(changed), this, str, (int)other.Value );
}
private void Signal_OnQuantityChanged(float value)
{
var other = GetNode<LineEdit>("LineEdit");
EmitSignal(nameof(changed), this, other.Text, (int)value);
}
}
| 28.057143 | 98 | 0.750509 | [
"MIT"
] | spacechase0/StardewEditor3 | JsonAssets/IngredientEntryEditor.cs | 982 | C# |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
namespace SpellAsYouTypeDemo
{
/// <summary>
/// Summary description for AYTEditBox.
/// </summary>
public class AYTTextBox : System.Windows.Forms.TextBox
{
float _extendDisplay=0.50f;
StringFormat _format=StringFormat.GenericDefault;
NetSpell.SpellChecker.Spelling _spell;
static System.Drawing.TextureBrush _spellBrush;
bool _spellUpdateNeeded=false;
ArrayList _wrongWord=new ArrayList();
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public struct WordInfo
{
public int start;
public string word;
public static WordInfo Zero
{
get
{
return new WordInfo();
}
}
}
static AYTTextBox()
{
Bitmap bmp=new Bitmap(4,2);
bmp.SetPixel(0,0,Color.Red);
bmp.SetPixel(1,1,Color.Red);
bmp.SetPixel(2,1,Color.Red);
bmp.SetPixel(3,0,Color.Red);
_spellBrush=new TextureBrush(bmp);
}
public AYTTextBox()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
_format.FormatFlags=StringFormatFlags.FitBlackBox;
_spell=new NetSpell.SpellChecker.Spelling();
Application.Idle+=new EventHandler(OnIdle);
}
private void OnIdle(object sender, EventArgs e)
{
if(_spellUpdateNeeded)
{
string str=Text;
string []words=str.Split(new char[]{' ', ',' , '\'' , '.', ':', '-', '!', '?'});
ArrayList wrongWordList=new ArrayList();
int l=0;
for(int i=0; i<str.Length; i++)
{
if(char.IsLetterOrDigit(str[i]))
{
l++;
}
else
{
if(l>0)
{
string word=str.Substring(i-l, l);
if(word.Length>0 && _spell.TestWord(word)==false )
{
WordInfo wi=new WordInfo();
wi.start=i-l;
wi.word=word;
wrongWordList.Add(wi);
}
}
l=0;
}
}
/* foreach(string word in words)
{
if(word.Length>0 && wrongWordList.Contains(word)==false
&& _spell.TestWord(word)==false )
{
wrongWordList.Add(word);
}
}*/
WrongWord=wrongWordList;
Invalidate();
}
_spellUpdateNeeded=false;
}
private void OnIgnoreWord(object sender, EventArgs e)
{
}
private void OnSuggestedWordClick(object sender, EventArgs e)
{
MenuItemEx mnu=sender as MenuItemEx;
WordInfo wi=(WordInfo)mnu.Tag;
int oldstart=SelectionStart;
int oldlength=SelectionLength;
Text=Text.Remove(wi.start, wi.word.Length);
Text=Text.Insert(wi.start, mnu.Text);
SelectionStart=oldstart + mnu.Text.Length - wi.word.Length;
SelectionLength=oldlength;
}
void UnderlineWord(Graphics g, int startpos, int length)
{
Point last_pt=new Point(0,0);
Point startpt=PosFromChar(startpos);
if(startpos + length >= TextLength) length--;
Point endpt=PosFromChar(startpos + length);
startpt.Y+=Font.Height;
endpt.Y+=Font.Height;
g.DrawLine(new Pen(_spellBrush, 2), startpt, endpt);
}
public int CharFromPos(Point pt)
{
int ptval=pt.Y & 0x0000FFFF;
ptval=ptval<<16;
ptval=ptval | (pt.X & 0x0000FFFF);
return NativeMethods.SendMessage(Handle, NativeMethods.EM_CHARFROMPOS, 0, ptval) & 0x0000FFFF;
}
public Point PosFromChar(int chr)
{
return new Point(NativeMethods.SendMessage(Handle, NativeMethods.EM_POSFROMCHAR, chr, 0));
}
public void UnderlineWord(Graphics g, WordInfo wi)
{
if(TextLength<=1) return;
UnderlineWord(g, wi.start, wi.word.Length);
}
public WordInfo WordFromPos(Point pt)
{
int charpos=CharFromPos(pt);
string str=Text;
if(!char.IsLetterOrDigit(str[charpos])) return WordInfo.Zero;
int start=charpos;
int end=charpos;
while(start>0 && char.IsLetterOrDigit(str[start-1]))
{
start--;
}
while(end<str.Length && char.IsLetterOrDigit(str[end]))
{
end++;
}
WordInfo wi=new WordInfo();
wi.word=str.Substring(start, end-start).Trim();
wi.start=start;
return wi;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if( components != null )
components.Dispose();
}
base.Dispose( disposing );
}
protected override void OnMouseDown(MouseEventArgs e)
{
if(e.Button==MouseButtons.Right)
{
WordInfo wi=WordFromPos(new Point(e.X, e.Y));
if(wi.word!=null)
{
if(_spell.TestWord(wi.word)==false)
{
_spell.Suggest(wi.word);
ContextMenu menu=new ContextMenu();
foreach(string str in _spell.Suggestions)
{
MenuItemEx mnuitem=new MenuItemEx(str);
mnuitem.Click+=new EventHandler(OnSuggestedWordClick);
mnuitem.Tag=wi;
menu.MenuItems.Add(mnuitem);
// show only 7 suggestion
if(menu.MenuItems.Count>6) break;
}
if(menu.MenuItems.Count==0)
{
MenuItem nosug=new MenuItem("No suggestion");
nosug.Enabled=false;
menu.MenuItems.Add(nosug);
}
menu.MenuItems.Add(new MenuItem("-"));
MenuItemEx mnuIgnore=new MenuItemEx("Ignore");
mnuIgnore.Tag=wi;
mnuIgnore.Click+=new EventHandler(OnIgnoreWord);
menu.MenuItems.Add(mnuIgnore);
Point pt=PosFromChar(wi.start);
pt.Y+=Font.Height +1 ;
menu.Show(this, pt);
}
}
}
Invalidate();
base.OnMouseDown (e);
}
protected override void OnMouseUp(MouseEventArgs e)
{
//Invalidate();
base.OnMouseUp (e);
}
protected override void OnPaint(PaintEventArgs pe)
{
foreach(WordInfo word in WrongWord)
{
UnderlineWord(pe.Graphics, word);
}
base.OnPaint(pe);
}
protected override void OnTextChanged(EventArgs e)
{
_spellUpdateNeeded=true;
//Invalidate();
base.OnTextChanged (e);
}
//bool isScrolling=false;
protected override void WndProc(ref Message m)
{
// TODO: Add AYTTextBox.WndProc implementation
if(m.Msg==0x000F)
{
base.WndProc (ref m);
Graphics g = base.CreateGraphics();
OnPaint(new PaintEventArgs(g, base.ClientRectangle));
g.Dispose();
return;
}
else if(m.Msg == 533)
{
//Invalidate();
}
else if(m.Msg == 277)
{
//Invalidate();
}
base.WndProc (ref m);
}
ArrayList WrongWord
{
get
{
return _wrongWord;
}
set
{
_wrongWord=value;
}
}
public Rectangle TextRectangle
{
get
{
Rectangle r=DisplayRectangle;
r.X+=(int)(Font.Size * _extendDisplay);
r.Width-=(int)(Font.Size * _extendDisplay * 2) + 1;
r.Y+=1;
return r;
}
}
public class MenuItemEx : MenuItem
{
object _tag;
public MenuItemEx(string text) : base(text)
{
}
public object Tag
{
get
{
return _tag;
}set
{
_tag=value;
}
}
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
//
// AYTTextBox
//
}
#endregion
}
}
| 27.057441 | 106 | 0.44051 | [
"MIT"
] | cristianst85/NetSpell | NetSpell/exp/SpellAsYouTypeDemo/AYTEditBox.cs | 10,363 | C# |
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace EUFA.Controls
{
public partial class TeamItem : UserControl
{
private TeamInGroup selected;
public TeamItem()
{
InitializeComponent();
}
public event EventHandler OnDropTeam;
[Description("GroupName"), Category("Data")]
public string GroupName
{
get
{
return lbDescription.Text;
}
set
{
lbDescription.Text = value;
}
}
[Description("Team"), Category("Data")]
public TeamInGroup Team
{
get
{
return selected;
}
set
{
if (value == null)
{
selected = null;
lbValue.Text = "-";
return;
}
selected = value;
value.GroupName = GroupName;
lbValue.Text = value.Name;
}
}
private void mainPanel_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetData(typeof(MoveItem)) is MoveItem old)
{
this.Team = old.From.Team;
old.From.Team = null;
this.OnDropTeam(this, new EventArgs());
return;
}
if (e.Data.GetData(typeof(TeamInGroup)) is TeamInGroup t)
{
Team = t;
}
else
{
Team = null;
}
this.OnDropTeam(this, new EventArgs());
}
private void mainPanel_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
}
private void mainPanel_MouseDown(object sender, MouseEventArgs e)
{
this.DoDragDrop(new MoveItem
{
From = this
}, DragDropEffects.Move);
}
}
}
| 23.426966 | 73 | 0.444125 | [
"MIT"
] | thomasgassmann/2017_ICT_Championships_Appli_SAMPLE | EUFA/EUFA/Controls/TeamItem.cs | 2,087 | C# |
using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Trailer.Search.Api.Controllers;
using Trailer.Search.Data.Services;
using Trailer.Search.Data.Services.SearchResults;
namespace Trailer.Search.Api.UnitTests.Controllers
{
[TestFixture]
public class SearchTrailersControllerTests
{
private MockRepository mockRepository;
private Mock<ISearchService> mockSearchService;
[SetUp]
public void SetUp()
{
this.mockRepository = new MockRepository(MockBehavior.Loose);
this.mockSearchService = this.mockRepository.Create<ISearchService>();
}
[TearDown]
public void TearDown()
{
}
private SearchTrailersController CreateSearchTrailersController()
{
return new SearchTrailersController(
this.mockSearchService.Object);
}
[Test]
public async Task Get_QueryIsEmpty_ReturnsBadRquest()
{
// Arrange
var searchTrailersController = this.CreateSearchTrailersController();
string query = string.Empty;
this.mockSearchService.Setup(x => x.Search(It.IsAny<string>())).ReturnsAsync(new List<TrailerSearchResult>());
// Act
var result = await searchTrailersController.Get(
query);
// Assert
result.Result.Should().BeOfType(typeof(BadRequestResult));
}
[Test]
public async Task Get_QueryFindsNoResults_ReturnsNotFound()
{
// Arrange
var searchTrailersController = this.CreateSearchTrailersController();
string query = "can't touch this :)";
this.mockSearchService.Setup(x => x.Search(It.IsAny<string>())).ReturnsAsync(new List<TrailerSearchResult>());
// Act
var result = await searchTrailersController.Get(
query);
// Assert
result.Result.Should().BeOfType(typeof(NotFoundResult));
}
[Test]
public async Task Get_QueryFindsResults_ReturnsOkResult()
{
// Arrange
var searchTrailersController = this.CreateSearchTrailersController();
string query = "deadpool";
this.mockSearchService.Setup(
x => x.Search(
It.IsAny<string>()))
.ReturnsAsync(
new List<TrailerSearchResult>() {
new TrailerSearchResult() {
ThumbnailUrl = "deadpool's Thumb",
Title = "Deadpool trailer",
Uid = "unique deadpool" ,
Url = "deadpool's url "
} });
// Act
var result = await searchTrailersController.Get(
query);
// Assert
result.Result.Should().BeOfType(typeof(OkObjectResult));
}
[Test]
public async Task Get_QueryFindsResults_ReturnsOkResultWithcorrectNumberOfItems()
{
// Arrange
var searchTrailersController = this.CreateSearchTrailersController();
string query = "deadpool";
this.mockSearchService.Setup(
x => x.Search(
It.IsAny<string>()))
.ReturnsAsync(
new List<TrailerSearchResult>() {
new TrailerSearchResult() {
ThumbnailUrl = "deadpool's Thumb",
Title = "Deadpool trailer",
Uid = "unique deadpool" ,
Url = "deadpool's url "
} });
// Act
var result = await searchTrailersController.Get(
query);
result.Result.Should().BeOfType(typeof(OkObjectResult));
var castResult = (OkObjectResult)result.Result;
var responseValue = (IEnumerable<TrailerSearchResult>)castResult.Value;
// Assert
responseValue.Should().HaveCount(1);
}
}
}
| 32.029851 | 122 | 0.552889 | [
"MIT"
] | claudiu-bruma/Trailer.SearchApi | Trailer.Search.Api/Trailer.Search.Api.UnitTests/Controllers/SearchTrailersControllerTests.cs | 4,292 | C# |
using System;
using System.ComponentModel.DataAnnotations;
namespace Com.ChatR.Core.Dtos
{
public class ChatRoomDto
{
public Guid Id { get; set; }
[StringLength(255)]
[Required]
public string Name { get; set; }
[StringLength(50)]
public string SecretKey { get; set; }
public bool IsPrivate { get; set; }
}
}
| 23.176471 | 46 | 0.576142 | [
"MIT"
] | davidsekar/ChatR | Com.ChatR.Core/Dtos/ChatRoomDto.cs | 396 | C# |
using System.Runtime.Serialization;
namespace GhostSharper.Models
{
/// <summary>
/// Defines the conditions under which stat modifications will be applied to a Character while participating in an objective.
/// </summary>
[DataContract]
public class DestinyObjectiveStatEntryDefinition
{
/// <summary>
/// The stat being modified, and the value used.
/// </summary>
[DataMember(Name = "stat", EmitDefaultValue = false)]
public DestinyItemInvestmentStatDefinition Stat { get; set; }
/// <summary>
/// Whether it will be applied as long as the objective is active, when it's completed, or until it's completed.
/// </summary>
[DataMember(Name = "style", EmitDefaultValue = false)]
public DestinyObjectiveGrantStyle Style { get; set; }
public override bool Equals(object input)
{
return this.Equals(input as DestinyObjectiveStatEntryDefinition);
}
public bool Equals(DestinyObjectiveStatEntryDefinition input)
{
if (input == null) return false;
return
(
Stat == input.Stat ||
(Stat != null && Stat.Equals(input.Stat))
) &&
(
Style == input.Style ||
(Style != null && Style.Equals(input.Style))
) ;
}
}
}
| 31.413043 | 129 | 0.564706 | [
"MIT",
"BSD-3-Clause"
] | joshhunt/GhostSharper | BungieNetApi/Models/DestinyObjectiveStatEntryDefinition.cs | 1,445 | C# |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.EssentialContacts.V1.Snippets
{
// [START essentialcontacts_v1_generated_EssentialContactsService_CreateContact_sync_flattened_resourceNames3]
using Google.Api.Gax.ResourceNames;
using Google.Cloud.EssentialContacts.V1;
public sealed partial class GeneratedEssentialContactsServiceClientSnippets
{
/// <summary>Snippet for CreateContact</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void CreateContactResourceNames3()
{
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = EssentialContactsServiceClient.Create();
// Initialize request argument(s)
OrganizationName parent = OrganizationName.FromOrganization("[ORGANIZATION]");
Contact contact = new Contact();
// Make the request
Contact response = essentialContactsServiceClient.CreateContact(parent, contact);
}
}
// [END essentialcontacts_v1_generated_EssentialContactsService_CreateContact_sync_flattened_resourceNames3]
}
| 43.511628 | 116 | 0.727953 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.EssentialContacts.V1/Google.Cloud.EssentialContacts.V1.GeneratedSnippets/EssentialContactsServiceClient.CreateContactResourceNames3Snippet.g.cs | 1,871 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using VirtualVoid.Networking;
using VirtualVoid.Networking.Client;
public class MessageSender : MonoBehaviour
{
public ClientInstance client;
private void Start()
{
client.OnConnectedToServer += SendMessage;
}
private void SendMessage()
{
client.SendMessageToServer("Hello from the client!");
}
}
| 20.190476 | 61 | 0.71934 | [
"MIT"
] | Tobogganeer/VVNetworking | Examples/Client/Assets/Scripts/MessageSender.cs | 426 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using TesteMVC.Models;
namespace TesteMVC.Controllers
{
public class JogoController : Controller
{
private DBContext db = new DBContext();
// GET: Jogo
public ActionResult Index()
{
if (Session["usuarioLogadoID"] != null)
{
return View(db.Jogos.ToList());
}
else
{
return RedirectToAction("login", "Home");
}
}
// GET: Jogo/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Jogo Jogo = db.Jogos.Find(id);
if (Jogo == null)
{
return HttpNotFound();
}
return View(Jogo);
}
// GET: Jogo/Create
public ActionResult Create()
{
return View();
}
// POST: Jogo/Create
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Titulo,Estilo,Lancamento")] Jogo Jogo)
{
if (ModelState.IsValid)
{
db.Jogos.Add(Jogo);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(Jogo);
}
// GET: Jogo/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Jogo Jogo = db.Jogos.Find(id);
if (Jogo == null)
{
return HttpNotFound();
}
return View(Jogo);
}
// POST: Jogo/Edit/5
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Titulo,Estilo,Lancamento")] Jogo Jogo)
{
if (ModelState.IsValid)
{
db.Entry(Jogo).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(Jogo);
}
// GET: Jogo/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Jogo Jogo = db.Jogos.Find(id);
if (Jogo == null)
{
return HttpNotFound();
}
return View(Jogo);
}
// POST: Jogo/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Jogo Jogo = db.Jogos.Find(id);
db.Jogos.Remove(Jogo);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
| 27.573529 | 113 | 0.5008 | [
"MIT"
] | andersonbellini/Teste-MVC | TesteMVC/Controllers/JogoController.cs | 3,756 | C# |
using SoulsFormats;
using System.Collections.Generic;
using System.Numerics;
namespace HKX2
{
public partial class hclClothContainer : hkReferencedObject
{
public override uint Signature { get => 890409259; }
public List<hclCollidable> m_collidables;
public List<hclClothData> m_clothDatas;
public override void Read(PackFileDeserializer des, BinaryReaderEx br)
{
base.Read(des, br);
m_collidables = des.ReadClassPointerArray<hclCollidable>(br);
m_clothDatas = des.ReadClassPointerArray<hclClothData>(br);
}
public override void Write(PackFileSerializer s, BinaryWriterEx bw)
{
base.Write(s, bw);
s.WriteClassPointerArray<hclCollidable>(bw, m_collidables);
s.WriteClassPointerArray<hclClothData>(bw, m_clothDatas);
}
}
}
| 31.206897 | 78 | 0.647514 | [
"MIT"
] | SyllabusGames/DSMapStudio | HKX2/Autogen/hclClothContainer.cs | 905 | C# |
namespace Agridea.Reports
{
public enum ReportColors
{
None,
Light,
Dark
}
}
| 10.454545 | 28 | 0.504348 | [
"MIT"
] | ni11c/AkkaJobs | AgrideaCore/Reports/ReportModel/Enums/ReportColors.cs | 117 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TPLPipeline.TestApp.Implementation.Simple
{
public delegate void Completed(object sender, EventArgs e);
class Job : BaseJob
{
public event Completed Completed;
public override void OnJobComplete()
{
//Console.WriteLine($"{this.Id} completed");
if (Completed != null)
{
Completed.Invoke(this, null);
}
}
public override void OnJobStart()
{
//Console.WriteLine($"{this.Id} started");
}
}
}
| 21.548387 | 63 | 0.586826 | [
"MIT"
] | ThomasBleijendaal/TPLPipeLine | TPLPipeline.TestApp/Implementation/Simple/Job.cs | 670 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using UnityEngine;
public class Silhouette : MonoBehaviour
{
public Sprite[] SilhouetteTemplates;
public float FailThreshold;
SpriteRenderer sr;
float match;
public void Randomize()
{
sr = GetComponent<SpriteRenderer>();
sr.sprite = SilhouetteTemplates.Shuffle().First();
}
void Update()
{
//if (Input.GetKeyDown(KeyCode.T))
//{
// Debug.Log("Matches to " + TestMatch() + "%");
//}
}
public float TestMatch()
{
var rt = RenderTexture.GetTemporary((int) sr.sprite.textureRect.width, (int) sr.sprite.textureRect.height, 24,
RenderTextureFormat.ARGB32,
RenderTextureReadWrite.Default, 1);
var cam = gameObject.AddComponent<Camera>();
cam.orthographic = true;
cam.orthographicSize = sr.sprite.textureRect.height / sr.sprite.pixelsPerUnit / 2.0f;
cam.nearClipPlane = -5;
cam.cullingMask = LayerMask.GetMask("Silhouette");
cam.targetTexture = rt;
cam.backgroundColor = new Color(0.0f, 0.0f, 0.0f, 0.0f);
cam.clearFlags = CameraClearFlags.SolidColor;
// snapshot just the silhouette
cam.Render();
RenderTexture.active = rt;
var silhouetteTex = new Texture2D(rt.width, rt.height, TextureFormat.ARGB32, false);
silhouetteTex.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
RenderTexture.active = null;
// snapshot the snax (only)
gameObject.layer = 0;
foreach (var snack in FindObjectsOfType<Snack>())
if (snack.placed)
SetLayerRecursively(snack.gameObject, LayerMask.NameToLayer("Silhouette"));
cam.Render();
RenderTexture.active = rt;
var snacksTex = new Texture2D(rt.width, rt.height, TextureFormat.ARGB32, false);
snacksTex.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
RenderTexture.active = null;
// revert
gameObject.layer = LayerMask.NameToLayer("Silhouette");
foreach (var snack in FindObjectsOfType<Snack>())
SetLayerRecursively(snack.gameObject, LayerMask.NameToLayer("Snacks"));
// cleanup
cam.targetTexture = null;
RenderTexture.ReleaseTemporary(rt);
Destroy(cam);
// debug
//byte[] bytes = silhouetteTex.EncodeToPNG();
//File.WriteAllBytes("C:\\silhouette.png", bytes);
//bytes = snacksTex.EncodeToPNG();
//File.WriteAllBytes("C:\\snacks.png", bytes);
// compare
float matchingPixellos = 0, expectedPixellos = 0;
for (int i = 0; i < silhouetteTex.width; i++)
for (int j = 0; j < silhouetteTex.height; j++)
{
var silhouettePixel = silhouetteTex.GetPixel(i, j).a != 0;
var snackPixel = snacksTex.GetPixel(i, j).a != 0;
if (silhouettePixel)
{
expectedPixellos++;
if (snackPixel)
matchingPixellos++;
}
else if (snackPixel)
matchingPixellos--;
}
// clean up textures
Destroy(silhouetteTex);
Destroy(snacksTex);
return (float) matchingPixellos / expectedPixellos;
}
public static void SetLayerRecursively(GameObject go, int layerNumber)
{
foreach (Transform trans in go.GetComponentsInChildren<Transform>(true))
trans.gameObject.layer = layerNumber;
}
}
| 28.267241 | 113 | 0.668801 | [
"MIT"
] | renaudbedard/cooldogs_tojam10 | Assets/Scripts/Silhouette.cs | 3,281 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ApiCopListenerBase.cs" company="Catel development team">
// Copyright (c) 2008 - 2014 Catel development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Catel.ApiCop
{
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Base class for ApiCop listeners.
/// </summary>
public abstract class ApiCopListenerBase : IApiCopListener
{
/// <summary>
/// Initializes a new instance of the <see cref="ApiCopListenerBase"/> class.
/// </summary>
protected ApiCopListenerBase()
{
Grouping = ApiCopListenerGrouping.Tag;
}
/// <summary>
/// Gets or sets the grouping for this listener.
/// </summary>
/// <value>The grouping.</value>
public ApiCopListenerGrouping Grouping { get; set; }
/// <summary>
/// Writes the results of the ApiCop feature.
/// <para />
/// Note that this will only contain invalid results. Valid results are not written to the
/// listeners.
/// </summary>
/// <param name="results">The results.</param>
public void WriteResults(IEnumerable<IApiCopResult> results)
{
Argument.IsNotNull("results", results);
BeginWriting();
List<IApiCopResult> sortedResults;
switch (Grouping)
{
case ApiCopListenerGrouping.Cop:
sortedResults = (from result in results
orderby result.Cop.TargetType.FullName
select result).ToList();
break;
case ApiCopListenerGrouping.Rule:
sortedResults = (from result in results
orderby result.Rule.Name
select result).ToList();
break;
case ApiCopListenerGrouping.Tag:
sortedResults = (from result in results
orderby result.Tag
select result).ToList();
break;
default:
throw new ArgumentOutOfRangeException();
}
WriteSummary(sortedResults);
string previousGroupName = string.Empty;
foreach (var result in sortedResults)
{
var groupName = GetGroupName(result);
if (!string.Equals(previousGroupName, groupName))
{
if (!string.IsNullOrEmpty(previousGroupName))
{
EndWritingOfGroup(previousGroupName);
}
previousGroupName = groupName;
BeginWritingOfGroup(groupName);
}
WriteResult(result);
}
if (!string.IsNullOrEmpty(previousGroupName))
{
EndWritingOfGroup(previousGroupName);
}
EndWriting();
}
private string GetGroupName(IApiCopResult result)
{
switch (Grouping)
{
case ApiCopListenerGrouping.Cop:
return result.Cop.TargetType.FullName;
case ApiCopListenerGrouping.Rule:
return result.Rule.Name;
case ApiCopListenerGrouping.Tag:
return result.Tag;
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Called when the listener is about to write the results.
/// </summary>
protected virtual void BeginWriting()
{
}
/// <summary>
/// Writes the summary, called before any groups are written.
/// </summary>
/// <param name="results">The results.</param>
protected virtual void WriteSummary(IEnumerable<IApiCopResult> results)
{
}
/// <summary>
/// Begins the writing of a specific group.
/// </summary>
/// <param name="groupName">Name of the group.</param>
protected virtual void BeginWritingOfGroup(string groupName)
{
}
/// <summary>
/// Writes the result to the listener target.
/// </summary>
/// <param name="result">The result.</param>
protected abstract void WriteResult(IApiCopResult result);
/// <summary>
/// Ends the writing of a specific group.
/// </summary>
/// <param name="groupName">Name of the group.</param>
protected virtual void EndWritingOfGroup(string groupName)
{
}
/// <summary>
/// Called when the listener has finished writing all the results.
/// </summary>
protected virtual void EndWriting()
{
}
}
} | 31.801205 | 120 | 0.490055 | [
"MIT"
] | IvanKupriyanov/Catel | src/Catel.Core/Catel.Core.Shared/ApiCop/ApiCopListenerBase.cs | 5,281 | C# |
//
// Mono.Facebook.PeopleList.cs:
//
// Authors:
// George Talusan (george@convolve.ca)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Xml.Serialization;
namespace Mono.Facebook
{
public class PeopleList
{
[XmlElement ("uid")]
public long[] uid_array;
public long[] UIds
{
get { return uid_array ?? new long[0]; }
}
}
}
| 33.02381 | 73 | 0.740447 | [
"MIT"
] | NguyenMatthieu/f-spot | src/Extensions/Exporters/FSpot.Exporters.Facebook/Mono.Facebook/PeopleList.cs | 1,387 | C# |
// RTM.Tools
// RTM.Component.CameraImageViewer
// ImageProvider.cs
//
// Created by Bartosz Rachwal.
// Copyright (c) 2015 Bartosz Rachwal. The National Institute of Advanced Industrial Science and Technology, Japan. All rights reserved.
using System;
using OpenRTM.Core;
using RTM.Converter.CameraImage;
using RTM.Images.Factory;
namespace RTM.Component.CameraImageViewer.ImageProvider
{
public class ImageProvider : IImageProvider
{
private readonly ICameraImageConverter converter;
private Image image;
public event EventHandler NewImage;
public ImageProvider(ICameraImageConverter cameraImageConverter)
{
converter = cameraImageConverter;
}
public Image Image
{
get { return image; }
set
{
image = value;
NewImage?.Invoke(this, EventArgs.Empty);
}
}
public void SetImage(CameraImage cameraImage)
{
Image = converter.ToImage(cameraImage);
}
}
} | 24.883721 | 137 | 0.634579 | [
"MIT"
] | rachwal/RTM-Tools | RTM.Component.CameraImageViewer/ImageProvider/ImageProvider.cs | 1,070 | C# |
using API.Middleware;
using Application.Activities;
using Application.Interfaces;
using AutoMapper;
using Domain;
using FluentValidation.AspNetCore;
using Infrastructure.Photos;
using Infrastructure.Security;
using MediatR;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Persistence;
using System.Text;
namespace API
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DataContext>(opt =>
{
opt.UseLazyLoadingProxies();
opt.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
});
services.AddCors(opt =>
{
opt.AddPolicy("CorsPolicy", policy =>
{
policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("http://localhost:3000");
});
});
services.AddMediatR(typeof(List.Handler).Assembly);
services.AddAutoMapper(typeof(List.Handler));
services.AddMvc(opt =>
{
var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
opt.Filters.Add(new AuthorizeFilter(policy));
})
.AddFluentValidation(cfg => cfg.RegisterValidatorsFromAssemblyContaining<Create>())
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
var builder = services.AddIdentityCore<AppUser>();
var identityBuilder = new IdentityBuilder(builder.UserType, builder.Services);
identityBuilder.AddEntityFrameworkStores<DataContext>();
identityBuilder.AddSignInManager<SignInManager<AppUser>>();
services.AddAuthorization(opt =>
{
opt.AddPolicy("IsActivityHost", policy =>
{
policy.Requirements.Add(new IsHostRequirement());
});
});
services.AddTransient<IAuthorizationHandler, IsHostRequirementHandler>();
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["TokenKey"]));
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(opt =>
{
opt.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = key,
ValidateAudience = false,
ValidateIssuer = false
};
});
services.AddScoped<IJwtGenerator, JwtGenerator>();
services.AddScoped<IUserAccessor, UserAccessor>();
services.AddScoped<IPhotoAccessor, PhotoAccessor>();
services.Configure<CloudinarySettings>(Configuration.GetSection("Cloudinary"));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMiddleware<ErrorHandlingMiddleware>();
if (env.IsDevelopment())
{
//app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
//app.UseHsts();
}
//app.UseHttpsRedirection();
app.UseAuthentication();
app.UseCors("CorsPolicy");
app.UseMvc();
}
}
}
| 38.289474 | 143 | 0.617182 | [
"MIT"
] | Huray-hub/Cyrple-Social-Network | API/Startup.cs | 4,367 | C# |
class Class : System.Collections.Generic.IEnumerable<Interface> {
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => null;
public System.Collections.Generic.IEnumerator<Interface> GetEnumerator() => null;
} | 59.5 | 87 | 0.815126 | [
"MIT"
] | DevSnicket/Eunice | csharp/Tests/TestCases/MembersLevel/Valid/Generic/Class/Base/IEnumerable/Class.cs | 238 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace StatisticsAlerter
{
public class EmailAlert : IAlerter
{
public bool emailSent = false;
public EmailAlert()
{
emailSent = true;
}
public bool Alert()
{
return emailSent;
}
}
public class LEDAlert : IAlerter
{
public bool ledGlows = false;
public LEDAlert()
{
ledGlows = true;
}
public bool Alert()
{
return ledGlows;
}
}
}
| 18.3125 | 38 | 0.508532 | [
"MIT"
] | Engin-Boot/stats-unit-shashibhushan00 | Statistics Solution Folder/StatisticsAlerter/AlertClass.cs | 588 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Maya.Amazon.Helpers
{
/// <summary>
/// Map a file's extention to a MIME type
/// </summary>
public static class MimeTypeMap
{
private static readonly Lazy<IDictionary<string, string>> _mappings = new Lazy<IDictionary<string, string>>(BuildMappings);
private static IDictionary<string, string> BuildMappings()
{
var mappings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
#region Big fucking list of mime types
// maps both ways,
// extension -> mime type
// and
// mime type -> extension
//
// any mime types on left side not pre-loaded on right side, are added automatically
// some mime types can map to multiple extensions, so to get a deterministic mapping,
// add those to the dictionary specifically
//
// combination of values from Windows 7 Registry and
// from C:\Windows\System32\inetsrv\config\applicationHost.config
// some added, including .7z and .dat
//
// Some added based on http://www.iana.org/assignments/media-types/media-types.xhtml
// which lists mime types, but not extensions
//
{".323", "text/h323"},
{".3g2", "video/3gpp2"},
{".3gp", "video/3gpp"},
{".3gp2", "video/3gpp2"},
{".3gpp", "video/3gpp"},
{".7z", "application/x-7z-compressed"},
{".aa", "audio/audible"},
{".AAC", "audio/aac"},
{".aaf", "application/octet-stream"},
{".aax", "audio/vnd.audible.aax"},
{".ac3", "audio/ac3"},
{".aca", "application/octet-stream"},
{".accda", "application/msaccess.addin"},
{".accdb", "application/msaccess"},
{".accdc", "application/msaccess.cab"},
{".accde", "application/msaccess"},
{".accdr", "application/msaccess.runtime"},
{".accdt", "application/msaccess"},
{".accdw", "application/msaccess.webapplication"},
{".accft", "application/msaccess.ftemplate"},
{".acx", "application/internet-property-stream"},
{".AddIn", "text/xml"},
{".ade", "application/msaccess"},
{".adobebridge", "application/x-bridge-url"},
{".adp", "application/msaccess"},
{".ADT", "audio/vnd.dlna.adts"},
{".ADTS", "audio/aac"},
{".afm", "application/octet-stream"},
{".ai", "application/postscript"},
{".aif", "audio/aiff"},
{".aifc", "audio/aiff"},
{".aiff", "audio/aiff"},
{".air", "application/vnd.adobe.air-application-installer-package+zip"},
{".amc", "application/mpeg"},
{".anx", "application/annodex"},
{".apk", "application/vnd.android.package-archive"},
{".application", "application/x-ms-application"},
{".art", "image/x-jg"},
{".asa", "application/xml"},
{".asax", "application/xml"},
{".ascx", "application/xml"},
{".asd", "application/octet-stream"},
{".asf", "video/x-ms-asf"},
{".ashx", "application/xml"},
{".asi", "application/octet-stream"},
{".asm", "text/plain"},
{".asmx", "application/xml"},
{".aspx", "application/xml"},
{".asr", "video/x-ms-asf"},
{".asx", "video/x-ms-asf"},
{".atom", "application/atom+xml"},
{".au", "audio/basic"},
{".avi", "video/x-msvideo"},
{".axa", "audio/annodex"},
{".axs", "application/olescript"},
{".axv", "video/annodex"},
{".bas", "text/plain"},
{".bcpio", "application/x-bcpio"},
{".bin", "application/octet-stream"},
{".bmp", "image/bmp"},
{".c", "text/plain"},
{".cab", "application/octet-stream"},
{".caf", "audio/x-caf"},
{".calx", "application/vnd.ms-office.calx"},
{".cat", "application/vnd.ms-pki.seccat"},
{".cc", "text/plain"},
{".cd", "text/plain"},
{".cdda", "audio/aiff"},
{".cdf", "application/x-cdf"},
{".cer", "application/x-x509-ca-cert"},
{".cfg", "text/plain"},
{".chm", "application/octet-stream"},
{".class", "application/x-java-applet"},
{".clp", "application/x-msclip"},
{".cmd", "text/plain"},
{".cmx", "image/x-cmx"},
{".cnf", "text/plain"},
{".cod", "image/cis-cod"},
{".config", "application/xml"},
{".contact", "text/x-ms-contact"},
{".coverage", "application/xml"},
{".cpio", "application/x-cpio"},
{".cpp", "text/plain"},
{".crd", "application/x-mscardfile"},
{".crl", "application/pkix-crl"},
{".crt", "application/x-x509-ca-cert"},
{".cs", "text/plain"},
{".csdproj", "text/plain"},
{".csh", "application/x-csh"},
{".csproj", "text/plain"},
{".css", "text/css"},
{".csv", "text/csv"},
{".cur", "application/octet-stream"},
{".cxx", "text/plain"},
{".dat", "application/octet-stream"},
{".datasource", "application/xml"},
{".dbproj", "text/plain"},
{".dcr", "application/x-director"},
{".def", "text/plain"},
{".deploy", "application/octet-stream"},
{".der", "application/x-x509-ca-cert"},
{".dgml", "application/xml"},
{".dib", "image/bmp"},
{".dif", "video/x-dv"},
{".dir", "application/x-director"},
{".disco", "text/xml"},
{".divx", "video/divx"},
{".dll", "application/x-msdownload"},
{".dll.config", "text/xml"},
{".dlm", "text/dlm"},
{".doc", "application/msword"},
{".docm", "application/vnd.ms-word.document.macroEnabled.12"},
{".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
{".dot", "application/msword"},
{".dotm", "application/vnd.ms-word.template.macroEnabled.12"},
{".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"},
{".dsp", "application/octet-stream"},
{".dsw", "text/plain"},
{".dtd", "text/xml"},
{".dtsConfig", "text/xml"},
{".dv", "video/x-dv"},
{".dvi", "application/x-dvi"},
{".dwf", "drawing/x-dwf"},
{".dwg", "application/acad"},
{".dwp", "application/octet-stream"},
{".dxf", "application/x-dxf"},
{".dxr", "application/x-director"},
{".eml", "message/rfc822"},
{".emz", "application/octet-stream"},
{".eot", "application/vnd.ms-fontobject"},
{".eps", "application/postscript"},
{".etl", "application/etl"},
{".etx", "text/x-setext"},
{".evy", "application/envoy"},
{".exe", "application/octet-stream"},
{".exe.config", "text/xml"},
{".fdf", "application/vnd.fdf"},
{".fif", "application/fractals"},
{".filters", "application/xml"},
{".fla", "application/octet-stream"},
{".flac", "audio/flac"},
{".flr", "x-world/x-vrml"},
{".flv", "video/x-flv"},
{".fsscript", "application/fsharp-script"},
{".fsx", "application/fsharp-script"},
{".generictest", "application/xml"},
{".gif", "image/gif"},
{".gpx", "application/gpx+xml"},
{".group", "text/x-ms-group"},
{".gsm", "audio/x-gsm"},
{".gtar", "application/x-gtar"},
{".gz", "application/x-gzip"},
{".h", "text/plain"},
{".hdf", "application/x-hdf"},
{".hdml", "text/x-hdml"},
{".hhc", "application/x-oleobject"},
{".hhk", "application/octet-stream"},
{".hhp", "application/octet-stream"},
{".hlp", "application/winhlp"},
{".hpp", "text/plain"},
{".hqx", "application/mac-binhex40"},
{".hta", "application/hta"},
{".htc", "text/x-component"},
{".htm", "text/html"},
{".html", "text/html"},
{".htt", "text/webviewhtml"},
{".hxa", "application/xml"},
{".hxc", "application/xml"},
{".hxd", "application/octet-stream"},
{".hxe", "application/xml"},
{".hxf", "application/xml"},
{".hxh", "application/octet-stream"},
{".hxi", "application/octet-stream"},
{".hxk", "application/xml"},
{".hxq", "application/octet-stream"},
{".hxr", "application/octet-stream"},
{".hxs", "application/octet-stream"},
{".hxt", "text/html"},
{".hxv", "application/xml"},
{".hxw", "application/octet-stream"},
{".hxx", "text/plain"},
{".i", "text/plain"},
{".ico", "image/x-icon"},
{".ics", "application/octet-stream"},
{".idl", "text/plain"},
{".ief", "image/ief"},
{".iii", "application/x-iphone"},
{".inc", "text/plain"},
{".inf", "application/octet-stream"},
{".ini", "text/plain"},
{".inl", "text/plain"},
{".ins", "application/x-internet-signup"},
{".ipa", "application/x-itunes-ipa"},
{".ipg", "application/x-itunes-ipg"},
{".ipproj", "text/plain"},
{".ipsw", "application/x-itunes-ipsw"},
{".iqy", "text/x-ms-iqy"},
{".isp", "application/x-internet-signup"},
{".ite", "application/x-itunes-ite"},
{".itlp", "application/x-itunes-itlp"},
{".itms", "application/x-itunes-itms"},
{".itpc", "application/x-itunes-itpc"},
{".IVF", "video/x-ivf"},
{".jar", "application/java-archive"},
{".java", "application/octet-stream"},
{".jck", "application/liquidmotion"},
{".jcz", "application/liquidmotion"},
{".jfif", "image/pjpeg"},
{".jnlp", "application/x-java-jnlp-file"},
{".jpb", "application/octet-stream"},
{".jpe", "image/jpeg"},
{".jpeg", "image/jpeg"},
{".jpg", "image/jpeg"},
{".js", "application/javascript"},
{".json", "application/json"},
{".jsx", "text/jscript"},
{".jsxbin", "text/plain"},
{".latex", "application/x-latex"},
{".library-ms", "application/windows-library+xml"},
{".lit", "application/x-ms-reader"},
{".loadtest", "application/xml"},
{".lpk", "application/octet-stream"},
{".lsf", "video/x-la-asf"},
{".lst", "text/plain"},
{".lsx", "video/x-la-asf"},
{".lzh", "application/octet-stream"},
{".m13", "application/x-msmediaview"},
{".m14", "application/x-msmediaview"},
{".m1v", "video/mpeg"},
{".m2t", "video/vnd.dlna.mpeg-tts"},
{".m2ts", "video/vnd.dlna.mpeg-tts"},
{".m2v", "video/mpeg"},
{".m3u", "audio/x-mpegurl"},
{".m3u8", "audio/x-mpegurl"},
{".m4a", "audio/m4a"},
{".m4b", "audio/m4b"},
{".m4p", "audio/m4p"},
{".m4r", "audio/x-m4r"},
{".m4v", "video/x-m4v"},
{".mac", "image/x-macpaint"},
{".mak", "text/plain"},
{".man", "application/x-troff-man"},
{".manifest", "application/x-ms-manifest"},
{".map", "text/plain"},
{".master", "application/xml"},
{".mbox", "application/mbox"},
{".mda", "application/msaccess"},
{".mdb", "application/x-msaccess"},
{".mde", "application/msaccess"},
{".mdp", "application/octet-stream"},
{".me", "application/x-troff-me"},
{".mfp", "application/x-shockwave-flash"},
{".mht", "message/rfc822"},
{".mhtml", "message/rfc822"},
{".mid", "audio/mid"},
{".midi", "audio/mid"},
{".mix", "application/octet-stream"},
{".mk", "text/plain"},
{".mk3d", "video/x-matroska-3d"},
{".mka", "audio/x-matroska"},
{".mkv", "video/x-matroska"},
{".mmf", "application/x-smaf"},
{".mno", "text/xml"},
{".mny", "application/x-msmoney"},
{".mod", "video/mpeg"},
{".mov", "video/quicktime"},
{".movie", "video/x-sgi-movie"},
{".mp2", "video/mpeg"},
{".mp2v", "video/mpeg"},
{".mp3", "audio/mpeg"},
{".mp4", "video/mp4"},
{".mp4v", "video/mp4"},
{".mpa", "video/mpeg"},
{".mpe", "video/mpeg"},
{".mpeg", "video/mpeg"},
{".mpf", "application/vnd.ms-mediapackage"},
{".mpg", "video/mpeg"},
{".mpp", "application/vnd.ms-project"},
{".mpv2", "video/mpeg"},
{".mqv", "video/quicktime"},
{".ms", "application/x-troff-ms"},
{".msg", "application/vnd.ms-outlook"},
{".msi", "application/octet-stream"},
{".mso", "application/octet-stream"},
{".mts", "video/vnd.dlna.mpeg-tts"},
{".mtx", "application/xml"},
{".mvb", "application/x-msmediaview"},
{".mvc", "application/x-miva-compiled"},
{".mxp", "application/x-mmxp"},
{".nc", "application/x-netcdf"},
{".nsc", "video/x-ms-asf"},
{".nws", "message/rfc822"},
{".ocx", "application/octet-stream"},
{".oda", "application/oda"},
{".odb", "application/vnd.oasis.opendocument.database"},
{".odc", "application/vnd.oasis.opendocument.chart"},
{".odf", "application/vnd.oasis.opendocument.formula"},
{".odg", "application/vnd.oasis.opendocument.graphics"},
{".odh", "text/plain"},
{".odi", "application/vnd.oasis.opendocument.image"},
{".odl", "text/plain"},
{".odm", "application/vnd.oasis.opendocument.text-master"},
{".odp", "application/vnd.oasis.opendocument.presentation"},
{".ods", "application/vnd.oasis.opendocument.spreadsheet"},
{".odt", "application/vnd.oasis.opendocument.text"},
{".oga", "audio/ogg"},
{".ogg", "audio/ogg"},
{".ogv", "video/ogg"},
{".ogx", "application/ogg"},
{".one", "application/onenote"},
{".onea", "application/onenote"},
{".onepkg", "application/onenote"},
{".onetmp", "application/onenote"},
{".onetoc", "application/onenote"},
{".onetoc2", "application/onenote"},
{".opus", "audio/ogg"},
{".orderedtest", "application/xml"},
{".osdx", "application/opensearchdescription+xml"},
{".otf", "application/font-sfnt"},
{".otg", "application/vnd.oasis.opendocument.graphics-template"},
{".oth", "application/vnd.oasis.opendocument.text-web"},
{".otp", "application/vnd.oasis.opendocument.presentation-template"},
{".ots", "application/vnd.oasis.opendocument.spreadsheet-template"},
{".ott", "application/vnd.oasis.opendocument.text-template"},
{".oxt", "application/vnd.openofficeorg.extension"},
{".p10", "application/pkcs10"},
{".p12", "application/x-pkcs12"},
{".p7b", "application/x-pkcs7-certificates"},
{".p7c", "application/pkcs7-mime"},
{".p7m", "application/pkcs7-mime"},
{".p7r", "application/x-pkcs7-certreqresp"},
{".p7s", "application/pkcs7-signature"},
{".pbm", "image/x-portable-bitmap"},
{".pcast", "application/x-podcast"},
{".pct", "image/pict"},
{".pcx", "application/octet-stream"},
{".pcz", "application/octet-stream"},
{".pdf", "application/pdf"},
{".pfb", "application/octet-stream"},
{".pfm", "application/octet-stream"},
{".pfx", "application/x-pkcs12"},
{".pgm", "image/x-portable-graymap"},
{".pic", "image/pict"},
{".pict", "image/pict"},
{".pkgdef", "text/plain"},
{".pkgundef", "text/plain"},
{".pko", "application/vnd.ms-pki.pko"},
{".pls", "audio/scpls"},
{".plist", "text/plain"},
{".pma", "application/x-perfmon"},
{".pmc", "application/x-perfmon"},
{".pml", "application/x-perfmon"},
{".pmr", "application/x-perfmon"},
{".pmw", "application/x-perfmon"},
{".png", "image/png"},
{".pnm", "image/x-portable-anymap"},
{".pnt", "image/x-macpaint"},
{".pntg", "image/x-macpaint"},
{".pnz", "image/png"},
{".pot", "application/vnd.ms-powerpoint"},
{".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12"},
{".potx", "application/vnd.openxmlformats-officedocument.presentationml.template"},
{".ppa", "application/vnd.ms-powerpoint"},
{".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12"},
{".ppm", "image/x-portable-pixmap"},
{".pps", "application/vnd.ms-powerpoint"},
{".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"},
{".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"},
{".ppt", "application/vnd.ms-powerpoint"},
{".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"},
{".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
{".prf", "application/pics-rules"},
{".prm", "application/octet-stream"},
{".prx", "application/octet-stream"},
{".ps", "application/postscript"},
{".psc1", "application/PowerShell"},
{".psd", "application/octet-stream"},
{".psess", "application/xml"},
{".psm", "application/octet-stream"},
{".psp", "application/octet-stream"},
{".pst", "application/vnd.ms-outlook"},
{".pub", "application/x-mspublisher"},
{".pwz", "application/vnd.ms-powerpoint"},
{".qht", "text/x-html-insertion"},
{".qhtm", "text/x-html-insertion"},
{".qt", "video/quicktime"},
{".qti", "image/x-quicktime"},
{".qtif", "image/x-quicktime"},
{".qtl", "application/x-quicktimeplayer"},
{".qxd", "application/octet-stream"},
{".ra", "audio/x-pn-realaudio"},
{".ram", "audio/x-pn-realaudio"},
{".rar", "application/x-rar-compressed"},
{".ras", "image/x-cmu-raster"},
{".rat", "application/rat-file"},
{".rc", "text/plain"},
{".rc2", "text/plain"},
{".rct", "text/plain"},
{".rdlc", "application/xml"},
{".reg", "text/plain"},
{".resx", "application/xml"},
{".rf", "image/vnd.rn-realflash"},
{".rgb", "image/x-rgb"},
{".rgs", "text/plain"},
{".rm", "application/vnd.rn-realmedia"},
{".rmi", "audio/mid"},
{".rmp", "application/vnd.rn-rn_music_package"},
{".roff", "application/x-troff"},
{".rpm", "audio/x-pn-realaudio-plugin"},
{".rqy", "text/x-ms-rqy"},
{".rtf", "application/rtf"},
{".rtx", "text/richtext"},
{".rvt", "application/octet-stream"},
{".ruleset", "application/xml"},
{".s", "text/plain"},
{".safariextz", "application/x-safari-safariextz"},
{".scd", "application/x-msschedule"},
{".scr", "text/plain"},
{".sct", "text/scriptlet"},
{".sd2", "audio/x-sd2"},
{".sdp", "application/sdp"},
{".sea", "application/octet-stream"},
{".searchConnector-ms", "application/windows-search-connector+xml"},
{".setpay", "application/set-payment-initiation"},
{".setreg", "application/set-registration-initiation"},
{".settings", "application/xml"},
{".sgimb", "application/x-sgimb"},
{".sgml", "text/sgml"},
{".sh", "application/x-sh"},
{".shar", "application/x-shar"},
{".shtml", "text/html"},
{".sit", "application/x-stuffit"},
{".sitemap", "application/xml"},
{".skin", "application/xml"},
{".skp", "application/x-koan"},
{".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12"},
{".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"},
{".slk", "application/vnd.ms-excel"},
{".sln", "text/plain"},
{".slupkg-ms", "application/x-ms-license"},
{".smd", "audio/x-smd"},
{".smi", "application/octet-stream"},
{".smx", "audio/x-smd"},
{".smz", "audio/x-smd"},
{".snd", "audio/basic"},
{".snippet", "application/xml"},
{".snp", "application/octet-stream"},
{".sol", "text/plain"},
{".sor", "text/plain"},
{".spc", "application/x-pkcs7-certificates"},
{".spl", "application/futuresplash"},
{".spx", "audio/ogg"},
{".src", "application/x-wais-source"},
{".srf", "text/plain"},
{".SSISDeploymentManifest", "text/xml"},
{".ssm", "application/streamingmedia"},
{".sst", "application/vnd.ms-pki.certstore"},
{".stl", "application/vnd.ms-pki.stl"},
{".sv4cpio", "application/x-sv4cpio"},
{".sv4crc", "application/x-sv4crc"},
{".svc", "application/xml"},
{".svg", "image/svg+xml"},
{".swf", "application/x-shockwave-flash"},
{".step", "application/step"},
{".stp", "application/step"},
{".t", "application/x-troff"},
{".tar", "application/x-tar"},
{".tcl", "application/x-tcl"},
{".testrunconfig", "application/xml"},
{".testsettings", "application/xml"},
{".tex", "application/x-tex"},
{".texi", "application/x-texinfo"},
{".texinfo", "application/x-texinfo"},
{".tgz", "application/x-compressed"},
{".thmx", "application/vnd.ms-officetheme"},
{".thn", "application/octet-stream"},
{".tif", "image/tiff"},
{".tiff", "image/tiff"},
{".tlh", "text/plain"},
{".tli", "text/plain"},
{".toc", "application/octet-stream"},
{".tr", "application/x-troff"},
{".trm", "application/x-msterminal"},
{".trx", "application/xml"},
{".ts", "video/vnd.dlna.mpeg-tts"},
{".tsv", "text/tab-separated-values"},
{".ttf", "application/font-sfnt"},
{".tts", "video/vnd.dlna.mpeg-tts"},
{".txt", "text/plain"},
{".u32", "application/octet-stream"},
{".uls", "text/iuls"},
{".user", "text/plain"},
{".ustar", "application/x-ustar"},
{".vb", "text/plain"},
{".vbdproj", "text/plain"},
{".vbk", "video/mpeg"},
{".vbproj", "text/plain"},
{".vbs", "text/vbscript"},
{".vcf", "text/x-vcard"},
{".vcproj", "application/xml"},
{".vcs", "text/plain"},
{".vcxproj", "application/xml"},
{".vddproj", "text/plain"},
{".vdp", "text/plain"},
{".vdproj", "text/plain"},
{".vdx", "application/vnd.ms-visio.viewer"},
{".vml", "text/xml"},
{".vscontent", "application/xml"},
{".vsct", "text/xml"},
{".vsd", "application/vnd.visio"},
{".vsi", "application/ms-vsi"},
{".vsix", "application/vsix"},
{".vsixlangpack", "text/xml"},
{".vsixmanifest", "text/xml"},
{".vsmdi", "application/xml"},
{".vspscc", "text/plain"},
{".vss", "application/vnd.visio"},
{".vsscc", "text/plain"},
{".vssettings", "text/xml"},
{".vssscc", "text/plain"},
{".vst", "application/vnd.visio"},
{".vstemplate", "text/xml"},
{".vsto", "application/x-ms-vsto"},
{".vsw", "application/vnd.visio"},
{".vsx", "application/vnd.visio"},
{".vtx", "application/vnd.visio"},
{".wasm", "application/wasm"},
{".wav", "audio/wav"},
{".wave", "audio/wav"},
{".wax", "audio/x-ms-wax"},
{".wbk", "application/msword"},
{".wbmp", "image/vnd.wap.wbmp"},
{".wcm", "application/vnd.ms-works"},
{".wdb", "application/vnd.ms-works"},
{".wdp", "image/vnd.ms-photo"},
{".webarchive", "application/x-safari-webarchive"},
{".webm", "video/webm"},
{".webp", "image/webp"}, /* https://en.wikipedia.org/wiki/WebP */
{".webtest", "application/xml"},
{".wiq", "application/xml"},
{".wiz", "application/msword"},
{".wks", "application/vnd.ms-works"},
{".WLMP", "application/wlmoviemaker"},
{".wlpginstall", "application/x-wlpg-detect"},
{".wlpginstall3", "application/x-wlpg3-detect"},
{".wm", "video/x-ms-wm"},
{".wma", "audio/x-ms-wma"},
{".wmd", "application/x-ms-wmd"},
{".wmf", "application/x-msmetafile"},
{".wml", "text/vnd.wap.wml"},
{".wmlc", "application/vnd.wap.wmlc"},
{".wmls", "text/vnd.wap.wmlscript"},
{".wmlsc", "application/vnd.wap.wmlscriptc"},
{".wmp", "video/x-ms-wmp"},
{".wmv", "video/x-ms-wmv"},
{".wmx", "video/x-ms-wmx"},
{".wmz", "application/x-ms-wmz"},
{".woff", "application/font-woff"},
{".woff2", "application/font-woff2"},
{".wpl", "application/vnd.ms-wpl"},
{".wps", "application/vnd.ms-works"},
{".wri", "application/x-mswrite"},
{".wrl", "x-world/x-vrml"},
{".wrz", "x-world/x-vrml"},
{".wsc", "text/scriptlet"},
{".wsdl", "text/xml"},
{".wvx", "video/x-ms-wvx"},
{".x", "application/directx"},
{".xaf", "x-world/x-vrml"},
{".xaml", "application/xaml+xml"},
{".xap", "application/x-silverlight-app"},
{".xbap", "application/x-ms-xbap"},
{".xbm", "image/x-xbitmap"},
{".xdr", "text/plain"},
{".xht", "application/xhtml+xml"},
{".xhtml", "application/xhtml+xml"},
{".xla", "application/vnd.ms-excel"},
{".xlam", "application/vnd.ms-excel.addin.macroEnabled.12"},
{".xlc", "application/vnd.ms-excel"},
{".xld", "application/vnd.ms-excel"},
{".xlk", "application/vnd.ms-excel"},
{".xll", "application/vnd.ms-excel"},
{".xlm", "application/vnd.ms-excel"},
{".xls", "application/vnd.ms-excel"},
{".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"},
{".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12"},
{".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{".xlt", "application/vnd.ms-excel"},
{".xltm", "application/vnd.ms-excel.template.macroEnabled.12"},
{".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"},
{".xlw", "application/vnd.ms-excel"},
{".xml", "text/xml"},
{".xmp", "application/octet-stream"},
{".xmta", "application/xml"},
{".xof", "x-world/x-vrml"},
{".XOML", "text/plain"},
{".xpm", "image/x-xpixmap"},
{".xps", "application/vnd.ms-xpsdocument"},
{".xrm-ms", "text/xml"},
{".xsc", "application/xml"},
{".xsd", "text/xml"},
{".xsf", "text/xml"},
{".xsl", "text/xml"},
{".xslt", "text/xml"},
{".xsn", "application/octet-stream"},
{".xss", "application/xml"},
{".xspf", "application/xspf+xml"},
{".xtp", "application/octet-stream"},
{".xwd", "image/x-xwindowdump"},
{".z", "application/x-compress"},
{".zip", "application/zip"},
{"application/fsharp-script", ".fsx"},
{"application/msaccess", ".adp"},
{"application/msword", ".doc"},
{"application/octet-stream", ".bin"},
{"application/onenote", ".one"},
{"application/postscript", ".eps"},
{"application/step", ".step"},
{"application/vnd.ms-excel", ".xls"},
{"application/vnd.ms-powerpoint", ".ppt"},
{"application/vnd.ms-works", ".wks"},
{"application/vnd.visio", ".vsd"},
{"application/x-director", ".dir"},
{"application/x-shockwave-flash", ".swf"},
{"application/x-x509-ca-cert", ".cer"},
{"application/x-zip-compressed", ".zip"},
{"application/xhtml+xml", ".xhtml"},
{
"application/xml", ".xml"
}, // anomoly, .xml -> text/xml, but application/xml -> many thingss, but all are xml, so safest is .xml
{"audio/aac", ".AAC"},
{"audio/aiff", ".aiff"},
{"audio/basic", ".snd"},
{"audio/mid", ".midi"},
{"audio/wav", ".wav"},
{"audio/x-m4a", ".m4a"},
{"audio/x-mpegurl", ".m3u"},
{"audio/x-pn-realaudio", ".ra"},
{"audio/x-smd", ".smd"},
{"image/bmp", ".bmp"},
{"image/jpeg", ".jpg"},
{"image/pict", ".pic"},
{"image/png", ".png"},
{"image/tiff", ".tiff"},
{"image/x-macpaint", ".mac"},
{"image/x-quicktime", ".qti"},
{"message/rfc822", ".eml"},
{"text/html", ".html"},
{"text/plain", ".txt"},
{"text/scriptlet", ".wsc"},
{"text/xml", ".xml"},
{"video/3gpp", ".3gp"},
{"video/3gpp2", ".3gp2"},
{"video/mp4", ".mp4"},
{"video/mpeg", ".mpg"},
{"video/quicktime", ".mov"},
{"video/vnd.dlna.mpeg-tts", ".m2t"},
{"video/x-dv", ".dv"},
{"video/x-la-asf", ".lsf"},
{"video/x-ms-asf", ".asf"},
{"x-world/x-vrml", ".xof"},
#endregion
};
var cache = mappings.ToList();
foreach (var mapping in cache)
{
if (!mappings.ContainsKey(mapping.Value))
{
mappings.Add(mapping.Value, mapping.Key);
}
}
return mappings;
}
/// <summary>
/// Get the MIME type associated with a file extension.
/// </summary>
/// <param name="extension"> The extension to search for. </param>
/// <returns> Returns the MIME type if found. </returns>
/// <exception cref="ArgumentNullException"> Will throw if `extension` is null. </exception>
public static string GetMimeType(string extension)
{
if (extension == null)
throw new ArgumentNullException(nameof(extension));
if (!extension.StartsWith("."))
extension = "." + extension;
return _mappings.Value.TryGetValue(extension, out var mime) ? mime : "application/octet-stream";
}
/// <summary>
/// Get the file extension associated with a MIME type.
/// </summary>
/// <param name="mimeType"> The MIME type to search for. </param>
/// <returns> Returns the extension if found. </returns>
public static string GetExtension(string mimeType)
{
return GetExtension(mimeType, true);
}
/// <summary>
/// Get the file extension associated with a MIME type.
/// </summary>
/// <param name="mimeType"> The MIME type to search for. </param>
/// <param name="throwErrorIfNotFound"> If true, will throw `ArgumentException`. </param>
/// <returns> Returns the extension if found. </returns>
/// <exception cref="ArgumentNullException"> Will throw if `mimeType` is null. </exception>
/// <exception cref="ArgumentException"> Will throw if `mimeType` is not found or registered if `throwErrorIfNotFound` is true. </exception>
public static string GetExtension(string mimeType, bool throwErrorIfNotFound)
{
if (mimeType == null)
throw new ArgumentNullException(nameof(mimeType));
if (mimeType.StartsWith("."))
throw new ArgumentException("Requested mime type is not valid: " + mimeType);
if (_mappings.Value.TryGetValue(mimeType, out var extension))
return extension;
if (throwErrorIfNotFound)
throw new ArgumentException("Requested mime type is not registered: " + mimeType);
return string.Empty;
}
}
}
| 48.367056 | 148 | 0.437961 | [
"MIT"
] | multinerd/Maya | Maya.Amazon/Helpers/MimeTypeMap.cs | 37,293 | C# |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace toofz.Data
{
/// <summary>
/// Contains extension methods for <see cref="ILeaderboardsStoreClient"/>.
/// </summary>
public static class ILeaderboardsStoreClientExtensions
{
/// <summary>
///
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="storeClient"></param>
/// <param name="items"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static Task<int> BulkUpsertAsync<TEntity>(
this ILeaderboardsStoreClient storeClient,
IEnumerable<TEntity> items,
CancellationToken cancellationToken)
where TEntity : class
{
if (storeClient == null)
throw new ArgumentNullException(nameof(storeClient));
return storeClient.BulkUpsertAsync(items, null, cancellationToken);
}
}
}
| 30.647059 | 79 | 0.607486 | [
"MIT"
] | leonard-thieu/toofz-data | src/toofz.Data/ILeaderboardsStoreClientExtensions.cs | 1,044 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace AkkaCLientApp
{
[Table("t1")]
public class Product
{
[Key]
public long Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public string Summary { get; set; }
public string Description { get; set; }
public string ImageFile { get; set; }
public decimal Price { get; set; }
public int Status { get; set; }
// [Dapper.Contrib.Extensions.Write(false)]
public DateTime CreateTime { get; set; }
// public List<Blog> Blogs { get; set; }
public Product()
{
// this.Blogs = new List<Blog>();
}
}
[Table("Blogs")]
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public int Rating { get; set; }
public string Path { get; set; }
}
[Table("Users")]
public class User
{
public long Id { get; set; }
public string UserName { get; set; }
public int Age { get; set; }
public User()
{
this.Roles = new List<Role>();
}
//public long RoleId { get; set; }
// [NotMapped]
public List<Role> Roles { get; set; }
}
[Table("Roles")]
public class Role
{
public Role(string name)
{
Name = name;
}
public Role ChangeName(string name)
{
this.Name = name;
return this;
}
[Key]
public long Id { get; private set; }
public string Name { get; private set; }
}
public class UserRole
{
public User User { get; set; }
public Role Role { get;
set;}
}
}
| 19.888889 | 51 | 0.511935 | [
"MIT"
] | fzf003/dockerfordotnet5 | dotnetapi/AkkaServer/AkkaCLientApp/Product.cs | 1,971 | C# |
// Copyright (c) Costin Morariu. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Reflection;
namespace MvvmToolkit.Utils
{
/// <summary>
/// Helper methods for Type reflection
/// </summary>
/// <remarks>
/// Try to minimize the use of this class. When compiling in Release, reflection is tricky due
/// to .NET Native toolchain see https://msdn.microsoft.com/en-us/library/dn600640(v=vs.110).aspx
/// </remarks>
public static class ReflectionExtensions
{
/// <summary>
/// Returns a value that indicates whether current type can be assigned to specified type
/// </summary>
/// <param name="type">Current type</param>
/// <param name="baseType">The type that supports the assignment</param>
/// <returns>True if the assignment is possible, otherwise false</returns>
public static bool IsAssignableFrom(this Type type, Type baseType)
{
return type.GetTypeInfo().IsAssignableFrom(baseType.GetTypeInfo());
}
/// <summary>
/// Returns a value that indicates wheather current type is generic
/// </summary>
/// <param name="type">Current type</param>
/// <returns>True if current type is generic, otherwise false</returns>
public static bool IsGenericType(this Type type)
{
return type.GetTypeInfo().IsGenericType;
}
/// <summary>
/// Returns the assembly where the current type is defined
/// </summary>
/// <param name="type">Current type</param>
/// <returns>The assembly in wich the type is defined</returns>
public static Assembly GetAssembly(this Type type)
{
return type.GetTypeInfo().Assembly;
}
/// <summary>
/// Returns method info of the current type matching the name and the type of parameters
/// </summary>
/// <param name="type">Current type</param>
/// <param name="name">The name of the method</param>
/// <param name="parametersTypes">Method parameter types</param>
/// <returns>Method info or null in case no match</returns>
public static MethodInfo GetMethod(this Type type, string name, Type[] parametersTypes)
{
var methods = type.GetMethods(name);
foreach (var method in methods)
{
var match = true;
var parameters = method.GetParameters();
foreach (var param in parameters)
{
var valid = true;
if (parametersTypes != null)
{
foreach (var ptype in parametersTypes)
{
valid &= (ptype == param.ParameterType);
}
}
match &= valid;
}
if (match)
{
return method;
}
}
return null;
}
/// <summary>
/// Returns the public methods exposed by the current type matching specified name
/// </summary>
/// <param name="type">Current type</param>
/// <param name="name">The name of the methods</param>
/// <returns>Matching method names</returns>
public static IEnumerable<MethodInfo> GetMethods(this Type type, string name)
{
return type.GetTypeInfo().GetDeclaredMethods(name);
}
/// <summary>
/// Returns interfaces implemented by the current type
/// </summary>
/// <param name="type">Current type</param>
/// <returns>The types of the interfaces</returns>
public static IEnumerable<Type> GetInterfaces(this Type type)
{
return type.GetTypeInfo().ImplementedInterfaces;
}
/// <summary>
/// Returns generic argument types of the current type
/// </summary>
/// <param name="type">Current type</param>
/// <returns>An array containing the types of generic arguments</returns>
public static Type[] GetGenericArguments(this Type type)
{
return type.GetTypeInfo().GenericTypeArguments;
}
}
} | 38.284483 | 101 | 0.568791 | [
"MIT"
] | stonemonkey/Wontstop | MvvmToolkit/Utils/ReflectionExtensions.cs | 4,441 | C# |
namespace Sportify.Services.Interfaces
{
using System.Collections.Generic;
using Data.Models;
using Data.ViewModels.Countries;
using Data.ViewModels.Events;
public interface IEventsService
{
Event Create(CreateEventViewModel model);
IEnumerable<EventViewModel> GetAllEvents();
IEnumerable<EventViewModel> GetAllEventsInCountry(SearchCountryViewModel model);
EventViewModel GetEventById(int id);
bool IsUserParticipate(string userId, int eventId);
Participant JoinUserToEvent(string userId, int eventId);
void LeaveUserFromEvent(string userId, int eventId);
IEnumerable<EventViewModel> GetEventsByUser(string username);
UpdateEventViewModel GetEventForUpdateById(int id);
UpdateEventViewModel UpdateEvent(UpdateEventViewModel model);
void DeleteEvent(EventViewModel model);
bool CheckForFreeSpace(int eventId);
}
} | 27.4 | 88 | 0.72367 | [
"MIT"
] | dobroslav-atanasov/Sportify | src/Services/Sportify.Services/Interfaces/IEventsService.cs | 961 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace AttendanceRegisterService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
public class AttendanceRegister : IAttendanceRegister
{
public List<Ward> GetWards()
{
DataAccess ds = new DataAccess();
return ds.GetWards();
}
public void InsertWard(Ward ward)
{
DataAccess ds = new DataAccess();
ds.InsertWard(ward);
}
public void InsertParishioner(Parishioner parishioner)
{
DataAccess ds = new DataAccess();
ds.InsertParishioner(parishioner);
}
}
} | 32.030303 | 165 | 0.663198 | [
"MIT"
] | georgesebastian/AttendanceRegister | AttendanceRegisterService/AttendanceRegister.svc.cs | 1,059 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using Microsoft.DotNet.XHarness.Common.Logging;
using Xunit;
namespace Microsoft.DotNet.XHarness.Common.Tests.Logging
{
[CollectionDefinition("ConsoleLogTest", DisableParallelization = true)]
public class ConsoleLogTest : IDisposable
{
private readonly string _testFile;
private readonly TextWriter _sdoutWriter;
private readonly ConsoleLog _log;
public ConsoleLogTest()
{
_testFile = Path.GetTempFileName();
_log = new ConsoleLog();
_sdoutWriter = Console.Out;
}
[Fact(Skip = "Flakey test that gets in the way by messing around with Console.Out")]
public void TestWrite()
{
var message = "This is a log message";
using (var testStream = new FileStream(_testFile, FileMode.OpenOrCreate, FileAccess.Write))
using (var writer = new StreamWriter(testStream))
{
Console.SetOut(writer);
// simply test that we do write in the file. We need to close the stream to be able to read it
_log.WriteLine(message);
}
using (var testStream = new FileStream(_testFile, FileMode.OpenOrCreate, FileAccess.Read))
using (var reader = new StreamReader(testStream))
{
var line = reader.ReadLine();
Assert.EndsWith(message, line); // consider the time stamp
}
}
public void Dispose()
{
_log.Dispose();
Console.SetOut(_sdoutWriter); // get back to write to the console
File.Delete(_testFile);
GC.SuppressFinalize(this);
}
}
}
| 34.589286 | 110 | 0.614868 | [
"MIT"
] | billwert/xharness | tests/Microsoft.DotNet.XHarness.Common.Tests/Logging/ConsoleLogTest.cs | 1,939 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace NiceHashMinerLegacy.Extensions
{
public static class DateTimeExt
{
private static readonly DateTime UnixStart = new DateTime(1970, 1, 1);
public static ulong GetUnixTime(this DateTime time)
{
return (ulong) (time.ToUniversalTime() - UnixStart).TotalMilliseconds;
}
}
}
| 23.823529 | 82 | 0.681481 | [
"MIT"
] | Danil2511/NiceHashMinerLegacy | src/NiceHashMinerLegacy.Extensions/DateTimeExt.cs | 407 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace Form.Examples
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
| 24.208333 | 99 | 0.586919 | [
"MIT"
] | matteoinno/Form.Examples | Form.Examples/App_Start/RouteConfig.cs | 583 | C# |
using JetBrains.ReSharper.Plugins.Json.Psi.Tree;
using JetBrains.ReSharper.Psi.ExtensionsAPI.Resolve;
using JetBrains.ReSharper.Psi.Resolve;
using JetBrains.ReSharper.Psi.Tree;
#nullable enable
namespace JetBrains.ReSharper.Plugins.Unity.AsmDef.Psi.Resolve
{
public class AsmRefNameReferenceFactory : IReferenceFactory
{
public ReferenceCollection GetReferences(ITreeNode element, ReferenceCollection oldReferences)
{
if (ResolveUtil.CheckThatAllReferencesBelongToElement<AsmDefNameReference>(oldReferences, element))
return oldReferences;
return element.IsReferencePropertyValue()
? new ReferenceCollection(new AsmDefNameReference((IJsonNewLiteralExpression)element))
: ReferenceCollection.Empty;
}
public bool HasReference(ITreeNode element, IReferenceNameContainer names)
{
if (element is IJsonNewLiteralExpression literal && literal.ConstantValueType == ConstantValueTypes.String)
return names.Contains(literal.GetStringValue() ?? string.Empty);
return false;
}
}
} | 39.517241 | 119 | 0.71815 | [
"Apache-2.0"
] | rwx788/resharper-unity | resharper/resharper-unity/src/Unity/AsmDef/Psi/Resolve/AsmRefNameReferenceFactory.cs | 1,148 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using UnityEngine;
using UnityEngine.Events;
public static class ChunkIO
{
public const char COMMA = ',';
public const char NULL_ERROR = '?';
public static string GetFileName(int chunkX, int chunkY)
{
return chunkX + ", " + chunkY + ".chunk";
}
public static void SaveChunk(string reality, string layer, BaseTile[][] tiles, int chunkX, int chunkY, int chunkSize, UnityAction<object[]> done)
{
string path = OutputUtils.RealitySaveDirectory + reality + OutputUtils.RealityLayersDirectory + layer + OutputUtils.RealityChunksDirectory + GetFileName(chunkX, chunkY);
Thread thread = new Thread(() =>
{
string toSave = MakeString(tiles, chunkX, chunkY, chunkSize);
// Run RLE
float efficiency;
toSave = RLE(toSave, out efficiency);
//Debug.Log("Chunk RLE efficiency: " + (int)(efficiency * 100f) + "%");
string dir = Path.GetDirectoryName(path);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
File.WriteAllText(path, toSave);
//Debug.Log("Saved chunk @ " + chunkX + ", " + chunkY);
Threader.Instance.PostAction(done, chunkX, chunkY, layer, reality, path);
});
thread.Start();
// TODO add a unity event system, with params, that executes in main thread.
}
public static void GetChunkForNet_Loaded(GameObject targetPlayer, BaseTile[][] tiles, int chunkX, int chunkY, int chunkSize, UnityAction<object[]> done, bool rle = true)
{
Thread thread = new Thread(() =>
{
string basic = MakeString(tiles, chunkX, chunkY, chunkSize);
if (basic == null)
{
Debug.LogError("Chunk string could not be made when requested for Net!");
Threader.Instance.PostAction(done, false, null, chunkX, chunkY);
return;
}
string final;
if (rle)
{
float eff;
final = RLE(basic, out eff);
}
else
{
final = basic;
}
Threader.Instance.PostAction(done, true, final, chunkX, chunkY, targetPlayer);
});
thread.Start();
}
public static void GetChunkForNet_Unloaded(GameObject target, string reality, string layer, int chunkX, int chunkY, int chunkSize, UnityAction<object[]> done, UnityAction<string> error = null)
{
Thread thread = new Thread(() =>
{
string path = GetPathForChunk(reality, layer, chunkX, chunkY);
if (!IsChunkSaved(path))
{
if (error != null)
error.Invoke("A file for that chunk could not be found! (" + GetPathForChunk(reality, layer, chunkX, chunkY));
return;
}
// Read all data
string text = File.ReadAllText(path);
text = text.Trim();
if (string.IsNullOrEmpty(text))
{
if (error != null)
error.Invoke("File existed, but text was null or empty!");
return;
}
// RLE:
// If the chunk is saved using rle, it is sent using rle, and if it is not, then it isn't.
Threader.Instance.PostAction(done, text, chunkX, chunkY, target);
});
thread.Start();
}
public static string MakeString(BaseTile[][] tiles, int chunkX, int chunkY, int chunkSize)
{
if (tiles == null)
{
Debug.LogError("Tiles input is null.");
return null;
}
StringBuilder str = new StringBuilder();
for (int y = chunkY * chunkSize; y < chunkY * chunkSize + chunkSize; y++)
{
for (int x = chunkX * chunkSize; x < chunkX * chunkSize + chunkSize; x++)
{
BaseTile tile = tiles[x][y];
if(tile == null)
{
str.Append(NULL_ERROR);
bool last = (x == (chunkX * chunkSize + chunkSize) - 1) && (y == (chunkY * chunkSize + chunkSize) - 1);
if (!last)
str.Append(COMMA);
}
else
{
str.Append(tiles[x][y].Prefab.Trim());
bool last = (x == (chunkX * chunkSize + chunkSize) - 1) && (y == (chunkY * chunkSize + chunkSize) - 1);
if (!last)
str.Append(COMMA);
}
}
}
return str.ToString();
}
public static bool IsChunkSaved(string reality, string layer, int chunkX, int chunkY)
{
string path = GetPathForChunk(reality, layer, chunkX, chunkY);
return IsChunkSaved(path);
}
public static bool IsChunkSaved(string path)
{
return File.Exists(path);
}
public static string GetPathForChunk(string reality, string layer, int chunkX, int chunkY)
{
return OutputUtils.RealitySaveDirectory + reality + OutputUtils.RealityLayersDirectory + layer + OutputUtils.RealityChunksDirectory + GetFileName(chunkX, chunkY); ;
}
public static void LoadChunk(string reality, string layer, int chunkX, int chunkY, int chunkSize, UnityAction<object[]> done, UnityAction<string> error = null, bool rle = true)
{
Thread thread = new Thread(() =>
{
string path = GetPathForChunk(reality, layer, chunkX, chunkY);
if (!IsChunkSaved(path))
{
if (error != null)
error.Invoke("A file for that chunk could not be found! (" + GetPathForChunk(reality, layer, chunkX, chunkY));
return;
}
// Read all data
string text = File.ReadAllText(path);
text = text.Trim();
if (string.IsNullOrEmpty(text))
{
if (error != null)
error.Invoke("File existed, but text was null or empty!");
return;
}
if (rle)
{
// Un-RLE this, to return it to its former inefficient glory!
text = UnRLE(text);
}
//Debug.Log("Loaded chunk @ " + chunkX + ", " + chunkY);
BaseTile[][] tiles = MakeChunk(text, chunkSize, error, false); // Already done in previous step.
if (tiles == null)
{
if (error != null)
{
error.Invoke("Tile 2D array creation failed.");
return;
}
Threader.Instance.PostAction(done, false, chunkX, chunkY, null, layer, reality);
}
Threader.Instance.PostAction(done, true, chunkX, chunkY, tiles, layer, reality);
});
thread.Start();
}
public static void MergeAllToFile(string reality, string layer, int chunkSize, int widthInChunks, Dictionary<int, List<NetPendingTile>> operations, UnityAction<object[]> done, bool rle = true)
{
// Merges all pending operations to file, saving them forever.
Thread thread = new Thread(() =>
{
foreach (int index in operations.Keys)
{
int chunkX = index % widthInChunks;
int chunkY = index / widthInChunks;
MergeToFile(reality, layer, chunkX, chunkY, chunkSize, operations[index], rle);
}
Threader.Instance.PostAction(done);
});
thread.Start();
}
public static void MergeToFile(string reality, string layer, int chunkX, int chunkY, int chunkSize, List<NetPendingTile> operations, bool rle = true, char sep = ',', char join = '|')
{
// Synchronous. Threaded done in different method.
// Validate.
if(!IsChunkSaved(reality, layer, chunkX, chunkY))
{
Debug.LogError("Could not merge to file, chunk is not saved! " + reality + ", " + layer + ", (" + chunkX + ", " + chunkY + ")");
return;
}
// Get path.
string path = GetPathForChunk(reality, layer, chunkX, chunkY);
// Read from file.
string text = File.ReadAllText(path);
// Merge the file with the pending operations.
string merged = Merge(text, operations, chunkSize, rle);
// Write back to file.
File.WriteAllText(path, merged);
}
public static string Merge(string data, List<NetPendingTile> operations, int chunkSize, bool rle = true, char separator = ',', char join = '|')
{
// Data is a string that is an array that is either plain text or compressed using rle.
if (rle)
{
data = UnRLE(data, separator, join);
}
// Split into parts.
string[] split = data.Split(separator);
foreach(NetPendingTile op in operations)
{
int index = op.X + chunkSize * op.Y;
split[index] = op.PrefabIsNull() ? NULL_ERROR.ToString() : op.Prefab.Trim();
}
// Make back into stirng.
StringBuilder str = new StringBuilder();
for(int i = 0; i < split.Length; i++)
{
str.Append(split[i]);
if(i != split.Length - 1)
str.Append(separator);
}
string final = str.ToString();
// RLE again if necessary.
if (rle)
{
float eff;
final = RLE(final, out eff, separator, join);
}
return final;
}
public static string RLE(string original, out float efficiency, char separator = ',', char join = '|', bool trim = true)
{
StringBuilder builder = new StringBuilder();
// Uses Run Length Encoding to compress long repetitive strings.
// Efficiency is expressed as follows: A value of 1 means a 100% reduction in string size, and a value of zero means a 0% reduction.
string[] split = original.Split(separator);
if(split == null || split.Length == 0)
{
Debug.LogError("The original string to RLE (below) did not contain the following separator char '" + separator + "'. It must contain at least one.\n" + original);
efficiency = 0;
return null;
}
builder.Length = 0;
string last = null;
int index = 0;
int run = 1;
foreach(string s in split)
{
if(index == split.Length - 1)
{
if (s == last)
{
// Just add one to the run count.
run++;
if (last != null)
{
if (run > 1)
{
builder.Append(run);
builder.Append(join);
}
builder.Append(Format(last, trim));
}
break;
}
else
{
// Last one is different from the previous ones, save the previous ones and then save the last one.
if (last != null)
{
if (run > 1)
{
builder.Append(run);
builder.Append(join);
}
builder.Append(Format(last, trim));
builder.Append(separator);
}
// Now save the last item.
// We know that it is only one because it is the last item and it is different from the previous item, may that be null or not.
builder.Append(Format(s, trim));
break;
}
}
if(s == last)
{
run++;
}
else
{
if(last == null)
{
run = 1;
}
else
{
if(run > 1)
{
builder.Append(run);
builder.Append(join);
}
builder.Append(Format(last, trim));
builder.Append(separator);
run = 1;
}
}
last = s;
index++;
}
string str = builder.ToString();
builder.Length = 0;
int oldSize = original.Length;
int newSize = str.Length;
float fraction = newSize / (float)oldSize;
efficiency = 1f - fraction;
//string debug = UnRLE(str, separator, join, trim);
//if(debug != original)
//{
// Debug.LogError("RLE check failed!\nORIGINAL:\n" + original + "\nUN_RLE:\n" + debug + "\nRLE:\n" + str);
//}
return str;
}
public static string UnRLE(string rle, char separator = ',', char join = '|', bool trim = true)
{
StringBuilder builder = new StringBuilder();
string[] split = rle.Split(separator);
if (split == null || split.Length == 0)
{
Debug.LogError("The original string to RLE (below) did not contain the following separator char '" + separator + "'. It must contain at least one.\n" + rle);
return null;
}
builder.Length = 0;
int index = 0;
foreach(string s in split)
{
bool last = index == split.Length - 1;
if (s.Contains(join))
{
string[] subSplit = s.Split(join);
if(subSplit.Length != 2)
{
Debug.LogError("RLE parsing error at segment '" + s + "' @ " + index + "/" + split.Length + ", incorrect format: Wrong number of joined parts. Expected 2 got " + subSplit.Length + ".");
return null;
}
string countString = subSplit[0];
int count;
bool worked = int.TryParse(countString, out count);
if (!worked)
{
Debug.LogError("RLE parsing error at segment '" + s + "', invalid input: '" + countString + "' is not a number, expect count value.");
return null;
}
string value = Format(subSplit[1], trim);
for (int i = 0; i < count; i++)
{
builder.Append(value);
bool veryLast = last && i == count - 1;
if(!veryLast)
builder.Append(separator);
}
}
else
{
builder.Append(Format(s, trim));
if(!last)
builder.Append(separator);
}
index++;
}
string str = builder.ToString();
builder.Length = 0;
return str;
}
private static string Format(string s, bool trim)
{
if (s != null && trim)
return s.Trim();
return s;
}
public static BaseTile[][] MakeChunk(string str, int chunkSize, UnityAction<string> error = null, bool rle = true)
{
BaseTile[][] chunk = new BaseTile[chunkSize][];
if(rle && str != null)
{
str = UnRLE(str);
}
string[] parts = str.Split(',');
if(parts.Length != chunkSize * chunkSize)
{
if (error != null)
error.Invoke("Incorrect number of tiles for chunk: found " + parts.Length + " when " + chunkSize * chunkSize + " were expected.");
return null;
}
for (int x = 0; x < chunkSize; x++)
{
chunk[x] = new BaseTile[chunkSize];
for (int y = 0; y < chunkSize; y++)
{
int index = x + chunkSize * y;
string prefab = parts[index].Trim();
if (prefab == NULL_ERROR.ToString())
continue;
if (BaseTile.ContainsTile(prefab))
{
chunk[x][y] = BaseTile.GetTile(prefab);
}
else
{
if(error != null)
error.Invoke("Tile '" + prefab + "' not found @ local position " + x + ", " + y + ".");
}
}
}
return chunk;
}
} | 32.445076 | 206 | 0.480649 | [
"MIT"
] | Epicguru/NotQuiteDead | Assets/Scripts/Map/Chunk/ChunkIO.cs | 17,133 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SignNow.Net.Internal.Extensions;
using SignNow.Net.Model;
using SignNow.Net.Test;
using UnitTests;
namespace AcceptanceTests
{
[TestClass]
public partial class DocumentServiceTest : AuthorizedApiTestBase
{
[TestMethod]
public void ShouldGetDocumentInfo()
{
var response = SignNowTestContext.Documents.GetDocumentAsync(TestPdfDocumentId).Result;
Assert.AreEqual(TestPdfDocumentId, response.Id);
Assert.AreEqual(1, response.PageCount);
Assert.AreEqual(PdfFileName, response.OriginalName);
Assert.AreEqual("DocumentUpload", response.Name);
Assert.IsNotNull(response.UserId.ValidateId());
Assert.IsNotNull(response.Created);
Assert.IsNotNull(response.Updated);
Assert.IsNull(response.OriginDocumentId);
Assert.IsNull(response.OriginUserId);
Assert.IsFalse(response.IsTemplate);
}
[TestMethod]
public void MergeDocuments()
{
var doc1 = SignNowTestContext.Documents.GetDocumentAsync(TestPdfDocumentId).Result;
var doc2 = SignNowTestContext.Documents.GetDocumentAsync(TestPdfDocumentIdWithFields).Result;
var documents = new List<SignNowDocument> {doc1, doc2};
var merged = SignNowTestContext.Documents
.MergeDocumentsAsync("merged-document.pdf", documents).Result;
Assert.AreEqual("merged-document.pdf", merged.Filename);
Assert.That.StreamIsPdf(merged.Document);
}
[TestMethod]
public void DocumentHistory()
{
var response = SignNowTestContext.Documents
.GetDocumentHistoryAsync(TestPdfDocumentIdWithFields)
.Result;
Assert.IsTrue(response.All(itm => itm.Id.Length == 40));
Assert.IsTrue(response.All(itm => itm.DocumentId == TestPdfDocumentIdWithFields));
}
[TestMethod]
public void CreateOneTimeDocumentDownloadLink()
{
var link = SignNowTestContext.Documents
.CreateOneTimeDownloadLinkAsync(TestPdfDocumentId).Result;
Assert.IsNotNull(link.Url);
StringAssert.Contains(link.Url.Host, "signnow.com");
}
}
}
| 33.680556 | 105 | 0.654845 | [
"MIT"
] | question4ever/SignNow.NET | SignNow.Net.Test/AcceptanceTests/DocumentServiceTest.cs | 2,425 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CurrencyConverter
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter Sum = ");
double sum = double.Parse(Console.ReadLine());
Console.Write("Enter Currency1: ");
string cur1 = Console.ReadLine();
Console.Write("Enter Currency2: ");
string cur2 = Console.ReadLine();
double bgn = 1;
double usd = 1.79549;
double eur = 1.95583;
double gbp = 2.53405;
double sum2;
if (cur1 == "BGN")
{
if (cur2 == "USD")
{
sum2 = sum / usd;
Console.WriteLine(Math.Round(sum2, 2));
}
else if (cur2 == "EUR")
{
sum2 = sum / eur;
Console.WriteLine(Math.Round(sum2, 2));
}
else if (cur2 == "GBP")
{
sum2 = sum / gbp;
Console.WriteLine(Math.Round(sum2, 2));
}
}
if (cur1 =="USD")
{
if (cur2 =="BGN")
{
sum2 = sum * usd;
Console.WriteLine(Math.Round(sum2, 2));
}
else if (cur2 == "EUR")
{
sum2 = sum * (usd / eur);
Console.WriteLine(Math.Round(sum2, 2));
}
else if (cur2 == "GBP")
{
sum2 = sum * (usd / gbp);
Console.WriteLine(Math.Round(sum2, 2));
}
}
if (cur1 == "EUR")
{
if (cur2 == "BGN")
{
sum2 = sum * eur;
Console.WriteLine(Math.Round(sum2, 2));
}
else if (cur2 == "USD")
{
sum2 = sum * (eur / usd);
Console.WriteLine(Math.Round(sum2, 2));
}
else if (cur2 == "GBP")
{
sum2 = sum * (eur / gbp);
Console.WriteLine(Math.Round(sum2, 2));
}
}
if (cur1 == "GBP")
{
if (cur2 == "BGN")
{
sum2 = sum * bgn;
Console.WriteLine(Math.Round(sum2, 2));
}
else if (cur2 == "USD")
{
sum2 = sum * (gbp / usd);
Console.WriteLine(Math.Round(sum2, 2));
}
else if (cur2 == "EUR")
{
sum2 = sum * (gbp / eur);
Console.WriteLine(Math.Round(sum2, 2));
}
}
}
}
}
| 31.919192 | 60 | 0.333228 | [
"MIT"
] | valkin88/Programming-Basics | Programming Basics - Simple Calculations/CurrencyConverter/CurrencyConverter/Program.cs | 3,162 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace JustFood.Models
{
using System;
using System.Collections.Generic;
public partial class QuantityConversation
{
public byte QuantityConversationID { get; set; }
public byte QuantityTypeID { get; set; }
public byte ConvertedTypeID { get; set; }
public decimal Difference { get; set; }
public virtual QuantityType QuantityType { get; set; }
public virtual QuantityType QuantityType1 { get; set; }
}
}
| 34.846154 | 84 | 0.555188 | [
"MIT"
] | aukgit/StoreManament | JustFood/Models/Garbage/QuantityConversation.cs | 906 | C# |
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using UnityEngine;
using UnityEditor;
using System;
namespace AmplifyShaderEditor
{
[Serializable]
[NodeAttributes( "Component Mask", "Vector Operators", "Mask certain channels from vectors/color components", null, KeyCode.K )]
public sealed class ComponentMaskNode : ParentNode
{
private const string OutputLocalVarName = "componentMask";
[SerializeField]
private bool[] m_selection = { true, true, true, true };
[SerializeField]
private int m_outputPortCount = 4;
[SerializeField]
private string[] m_labels;
private int m_cachedOrderId = -1;
private int m_cachedSingularId = -1;
protected override void CommonInit( int uniqueId )
{
base.CommonInit( uniqueId );
AddInputPort( WirePortDataType.FLOAT4, false, Constants.EmptyPortValue );
AddOutputPort( WirePortDataType.FLOAT4, Constants.EmptyPortValue );
m_useInternalPortData = true;
m_autoWrapProperties = true;
m_selectedLocation = PreviewLocation.TopCenter;
m_labels = new string[] { "X", "Y", "Z", "W" };
m_previewShaderGUID = "b78e2b295c265cd439c80d218fb3e88e";
SetAdditonalTitleText( "Value( XYZW )" );
}
public override void SetPreviewInputs()
{
base.SetPreviewInputs();
Vector4 order = new Vector4(-1,-1,-1,-1);
int lastIndex = 0;
int singularId = -1;
var datatype = m_inputPorts[ 0 ].DataType;
if( m_selection[ 0 ] )
{
order.Set( lastIndex, order.y, order.z, order.w );
lastIndex++;
singularId = 0;
}
if( m_selection[ 1 ] && datatype >= WirePortDataType.FLOAT2 )
{
order.Set( order.x, lastIndex, order.z, order.w );
lastIndex++;
singularId = 1;
}
if( m_selection[ 2 ] && datatype >= WirePortDataType.FLOAT3 )
{
order.Set( order.x, order.y, lastIndex, order.w );
lastIndex++;
singularId = 2;
}
if( m_selection[ 3 ] && datatype == WirePortDataType.FLOAT4 )
{
order.Set( order.x, order.y, order.z, lastIndex );
lastIndex++;
singularId = 3;
}
if ( lastIndex != 1 )
singularId = -1;
if ( m_cachedOrderId == -1 )
m_cachedOrderId = Shader.PropertyToID( "_Order" );
if ( m_cachedSingularId == -1 )
m_cachedSingularId = Shader.PropertyToID( "_Singular" );
PreviewMaterial.SetVector( m_cachedOrderId, order );
PreviewMaterial.SetFloat( m_cachedSingularId, singularId );
}
public override void OnInputPortConnected( int portId, int otherNodeId, int otherPortId, bool activateNode = true )
{
base.OnInputPortConnected( portId, otherNodeId, otherPortId, activateNode );
UpdatePorts();
UpdateTitle();
}
public override void OnConnectedOutputNodeChanges( int outputPortId, int otherNodeId, int otherPortId, string name, WirePortDataType type )
{
base.OnConnectedOutputNodeChanges( outputPortId, otherNodeId, otherPortId, name, type );
UpdatePorts();
UpdateTitle();
}
public override void OnInputPortDisconnected( int portId )
{
base.OnInputPortDisconnected( portId );
UpdateTitle();
}
void UpdatePorts()
{
m_inputPorts[ 0 ].MatchPortToConnection();
int count = 0;
switch ( m_inputPorts[ 0 ].DataType )
{
case WirePortDataType.FLOAT4:
case WirePortDataType.OBJECT:
case WirePortDataType.COLOR:
{
count = 4;
}
break;
case WirePortDataType.FLOAT3:
{
count = 3;
}
break;
case WirePortDataType.FLOAT2:
{
count = 2;
}
break;
case WirePortDataType.FLOAT:
case WirePortDataType.INT:
case WirePortDataType.FLOAT3x3:
case WirePortDataType.FLOAT4x4:
{ }
break;
}
int activeCount = 0;
if ( count > 0 )
{
for ( int i = 0; i < count; i++ )
{
if ( m_selection[ i ] )
activeCount += 1;
}
}
m_outputPortCount = activeCount;
switch ( activeCount )
{
case 0: ChangeOutputType( m_inputPorts[ 0 ].DataType, false ); break;
case 1: ChangeOutputType( WirePortDataType.FLOAT, false ); break;
case 2: ChangeOutputType( WirePortDataType.FLOAT2, false ); break;
case 3: ChangeOutputType( WirePortDataType.FLOAT3, false ); break;
case 4: ChangeOutputType( m_inputPorts[ 0 ].DataType, false ); break;
}
}
private void UpdateTitle()
{
int count = 0;
string additionalText = string.Empty;
switch ( m_inputPorts[ 0 ].DataType )
{
case WirePortDataType.FLOAT4:
case WirePortDataType.OBJECT:
case WirePortDataType.COLOR:
{
count = 4;
}
break;
case WirePortDataType.FLOAT3:
{
count = 3;
}
break;
case WirePortDataType.FLOAT2:
{
count = 2;
}
break;
case WirePortDataType.FLOAT:
case WirePortDataType.INT:
{
count = 0;
}
break;
case WirePortDataType.FLOAT3x3:
case WirePortDataType.FLOAT4x4:
{ }
break;
}
if ( count > 0 )
{
for ( int i = 0; i < count; i++ )
{
if ( m_selection[ i ] )
{
additionalText += UIUtils.GetComponentForPosition( i, m_inputPorts[ 0 ].DataType ).ToUpper();
}
}
}
if ( additionalText.Length > 0 )
SetAdditonalTitleText( "Value( " + additionalText + " )" );
else
SetAdditonalTitleText( string.Empty );
}
public override void DrawProperties()
{
base.DrawProperties();
EditorGUILayout.BeginVertical();
int count = 0;
switch ( m_inputPorts[ 0 ].DataType )
{
case WirePortDataType.FLOAT4:
case WirePortDataType.OBJECT:
case WirePortDataType.COLOR:
{
count = 4;
}
break;
case WirePortDataType.FLOAT3:
{
count = 3;
}
break;
case WirePortDataType.FLOAT2:
{
count = 2;
}
break;
case WirePortDataType.FLOAT:
case WirePortDataType.INT:
case WirePortDataType.FLOAT3x3:
case WirePortDataType.FLOAT4x4:
{ }
break;
}
int activeCount = 0;
if ( count > 0 )
{
for ( int i = 0; i < count; i++ )
{
m_selection[ i ] = EditorGUILayoutToggleLeft( m_labels[i], m_selection[ i ] );
m_labels[ i ] = UIUtils.GetComponentForPosition( i, m_inputPorts[ 0 ].DataType ).ToUpper();
if ( m_selection[ i ] )
{
activeCount += 1;
}
}
}
if ( activeCount != m_outputPortCount )
{
m_outputPortCount = activeCount;
switch ( activeCount )
{
case 0: ChangeOutputType( m_inputPorts[ 0 ].DataType, false ); break;
case 1: ChangeOutputType( WirePortDataType.FLOAT, false ); break;
case 2: ChangeOutputType( WirePortDataType.FLOAT2, false ); break;
case 3: ChangeOutputType( WirePortDataType.FLOAT3, false ); break;
case 4: ChangeOutputType( m_inputPorts[ 0 ].DataType, false ); break;
}
UpdateTitle();
SetSaveIsDirty();
}
EditorGUILayout.EndVertical();
}
public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalVar )
{
if( m_outputPorts[ 0 ].IsLocalValue( dataCollector.PortCategory ) )
return m_outputPorts[ 0 ].LocalValue( dataCollector.PortCategory );
string value = m_inputPorts[ 0 ].GeneratePortInstructions( ref dataCollector );
int count = 0;
switch ( m_inputPorts[ 0 ].DataType )
{
case WirePortDataType.FLOAT4:
case WirePortDataType.OBJECT:
case WirePortDataType.COLOR:
{
count = 4;
}
break;
case WirePortDataType.FLOAT3:
{
count = 3;
}
break;
case WirePortDataType.FLOAT2:
{
count = 2;
}
break;
case WirePortDataType.FLOAT:
case WirePortDataType.INT:
{
count = 0;
}
break;
case WirePortDataType.FLOAT3x3:
case WirePortDataType.FLOAT4x4:
{ }
break;
}
if ( count > 0 )
{
bool firstElement = true;
value = string.Format("({0})",value);
for ( int i = 0; i < count; i++ )
{
if ( m_selection[ i ] )
{
if( firstElement )
{
firstElement = false;
value += ".";
}
value += UIUtils.GetComponentForPosition( i, m_inputPorts[ 0 ].DataType );
}
}
}
return CreateOutputLocalVariable( 0, value, ref dataCollector );
}
public string GetComponentForPosition( int i )
{
switch ( i )
{
case 0:
{
return ( ( m_outputPorts[ 0 ].DataType == WirePortDataType.COLOR ) ? "r" : "x" );
}
case 1:
{
return ( ( m_outputPorts[ 0 ].DataType == WirePortDataType.COLOR ) ? "g" : "y" );
}
case 2:
{
return ( ( m_outputPorts[ 0 ].DataType == WirePortDataType.COLOR ) ? "b" : "z" );
}
case 3:
{
return ( ( m_outputPorts[ 0 ].DataType == WirePortDataType.COLOR ) ? "a" : "w" );
}
}
return string.Empty;
}
public override void ReadFromString( ref string[] nodeParams )
{
base.ReadFromString( ref nodeParams );
for ( int i = 0; i < 4; i++ )
{
m_selection[ i ] = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) );
}
UpdateTitle();
}
public override void WriteToString( ref string nodeInfo, ref string connectionsInfo )
{
base.WriteToString( ref nodeInfo, ref connectionsInfo );
for ( int i = 0; i < 4; i++ )
{
IOUtils.AddFieldValueToString( ref nodeInfo, m_selection[ i ] );
}
}
}
}
| 24.174935 | 141 | 0.635058 | [
"MIT"
] | AzeeSoft/Forge-Networking-Test | Assets/AmplifyShaderEditor/Plugins/Editor/Nodes/Operators/ComponentMaskNode.cs | 9,259 | C# |
using System.Collections.Generic;
namespace LinqFasterer
{
/// <summary>
/// Provides a set of <see langword="static"/> methods for querying objects that implement <see cref="IList{T}"/>.
/// </summary>
public static partial class EnumerableF
{ }
} | 27 | 118 | 0.67037 | [
"MIT"
] | Zaczero/LinqFaster | LinqFasterer/Enumerable.cs | 272 | C# |
namespace Tekla.Structures
{
using System.Drawing;
using Microsoft.Win32;
/// <summary>
/// Provides access to application registry keys and values.
/// </summary>
internal class Registry : IRegistry
{
#region Fields
/// <summary>
/// Registry key for current version.
/// </summary>
private RegistryKey currentVersion;
/// <summary>
/// Application root key.
/// </summary>
private RegistryKey root;
#endregion
#region Public Properties
/// <summary>
/// Gets the registry key for current application version.
/// </summary>
/// <value> Registry key.</value>
public RegistryKey CurrentVersion
{
get
{
if (this.currentVersion == null)
{
this.currentVersion = this.GetVersion(TeklaStructures.Version);
}
return this.currentVersion;
}
}
/// <summary>
/// Gets the application root registry key.
/// </summary>
/// <value> Registry key.</value>
public RegistryKey Root
{
get
{
if (this.root == null)
{
this.root = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Tekla\Structures");
}
return this.root;
}
}
#endregion
#region Public Methods and Operators
/// <summary>
/// Gets the registry key for the specified version.
/// </summary>
/// <param name="version">
/// Version string.
/// </param>
/// <returns>
/// Registry key.
/// </returns>
public RegistryKey GetVersion(string version)
{
// Ftrs and TPs write registry values to Next branch
if (version.ToLower().Contains("99.") || version.ToLower().Contains("test package"))
{
version = "Next";
}
else if (version.IndexOf(' ') > 0)
{
version = version.Split(' ')[0];
}
if (version.Contains("."))
{
var parts = version.Split('.');
var major = parts[0];
var minor = parts[1];
version = major + "." + minor;
}
return this.Root.OpenSubKey(version);
}
/// <summary>
/// Loads dialog bounds rectangle from registry.
/// </summary>
/// <param name="dialogName">
/// Dialog name.
/// </param>
/// <returns>
/// Loaded dialog bounds or <see cref="Rectangle.Empty"/> if not available.
/// </returns>
public Rectangle LoadDialogBounds(string dialogName)
{
return this.LoadDialogBounds(dialogName, TeklaStructures.Version);
}
/// <summary>
/// Loads dialog bounds rectangle from registry.
/// </summary>
/// <param name="dialogName">
/// Dialog name.
/// </param>
/// <param name="version">
/// Version string.
/// </param>
/// <returns>
/// Loaded dialog bounds or <see cref="Rectangle.Empty"/> if not available.
/// </returns>
public Rectangle LoadDialogBounds(string dialogName, string version)
{
using (var versionRoot = this.GetVersion(version))
{
using (var dialogs = versionRoot.OpenSubKey("Dialogs"))
{
using (var key = dialogs.OpenSubKey(dialogName))
{
var bounds = Rectangle.Empty;
if (key != null)
{
bounds.X = (int)key.GetValue("x", 0);
bounds.Y = (int)key.GetValue("y", 0);
bounds.Width = (int)key.GetValue("width", 0);
bounds.Height = (int)key.GetValue("height", 0);
}
return bounds;
}
}
}
}
/// <summary>
/// Saves dialog bounds rectangle to registry.
/// </summary>
/// <param name="dialogName">
/// Dialog name.
/// </param>
/// <param name="bounds">
/// Bounds rectangle.
/// </param>
public void SaveDialogBounds(string dialogName, Rectangle bounds)
{
this.SaveDialogBounds(dialogName, TeklaStructures.Version, bounds);
}
/// <summary>
/// Saves dialog bounds rectangle to registry.
/// </summary>
/// <param name="dialogName">
/// Dialog name.
/// </param>
/// <param name="version">
/// Version string.
/// </param>
/// <param name="bounds">
/// Bounds rectangle.
/// </param>
public void SaveDialogBounds(string dialogName, string version, Rectangle bounds)
{
using (var versionRoot = this.GetVersion(version))
{
using (var dialogs = versionRoot.OpenSubKey("Dialogs", true))
{
using (var key = dialogs.CreateSubKey(dialogName))
{
key.SetValue("x", bounds.X);
key.SetValue("y", bounds.Y);
key.SetValue("width", bounds.Width);
key.SetValue("height", bounds.Height);
}
}
}
}
#endregion
}
} | 29.819588 | 110 | 0.460501 | [
"Apache-2.0"
] | TeklaCorp/TeklaApplicationLibrary | Library/Registry.cs | 5,785 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class TopicHandler : MonoBehaviour
{
public string topicName = "";
public abstract void OnTopic(OscMessage message);
public abstract void OnDisconnect();
public abstract void OnConnect();
}
| 20.4 | 53 | 0.754902 | [
"MIT"
] | gehnri/MqttOSC_UnityBridge | Mqtt_OSC_Bridge_Unity/Assets/OSC_MQTT_Bridge/TopicHandler.cs | 308 | C# |
using StardewModdingAPI;
using StardewModdingAPI.Events;
using StardewValley;
using System.IO;
using System.Linq;
using MailFrameworkMod;
using System.Runtime.InteropServices.ComTypes;
using Microsoft.Xna.Framework;
using StardewValley.Objects;
using System.Collections.Generic;
namespace SDVMod
{
public class ModEntry : Mod, IAssetLoader
{
internal static ModEntry Instance { get; private set; }
//internal JsonAssets jsonAssets { get; private set; }
private IModHelper _helper;
class ModData
{
public long TMELD { get; set; } = Game1.player.totalMoneyEarned;
}
public class Config
{
public bool showcrops { get; set; } = false;
public bool sendrecipes { get; set; } = false;
}
public Config config;
public class RandomColorWidgetState
{
public Color color;
}
public override void Entry(IModHelper helper)
{
helper.Events.Input.ButtonPressed += OnButtonPressed;
helper.Events.GameLoop.DayStarted += DayStart;
helper.Events.GameLoop.DayEnding += DayEnd;
helper.Events.GameLoop.GameLaunched += GameLaunch;
helper.Events.GameLoop.SaveLoaded += OnSaveLoaded;
helper.Events.Player.Warped += OnWarped;
//helper.Events.GameLoop.GameLaunched += onGameLaunched;
}
private void OnWarped(object sender, WarpedEventArgs e)
{
if (e.NewLocation.Name.Equals("LostWoods"))
{
Game1.changeMusicTrack("woodsTheme");
}
}
private void OnSaveLoaded(object sender, SaveLoadedEventArgs args)
{
string LWK = this.Helper.Content.GetActualAssetKey("assets/LostWoods.tbin", ContentSource.ModFolder);
GameLocation LW = new GameLocation(LWK, "LostWoods") { IsOutdoors = false, IsFarm = false };
Game1.locations.Add(LW);
string LWHK = this.Helper.Content.GetActualAssetKey("assets/LWH.tbin", ContentSource.ModFolder);
GameLocation LWH = new GameLocation(LWHK, "LostWoodsHouse1") { IsOutdoors = false, IsFarm = false };
Game1.locations.Add(LWH);
}
public bool CanLoad<T>(IAssetInfo asset)
{
return asset.AssetNameEquals(@"Maps/Beach");
}
/// <summary>Load a matched asset.</summary>
/// <param name="asset">Basic metadata about the asset being loaded.</param>
public T Load<T>(IAssetInfo asset)
{
//if (asset.AssetNameEquals(@"Maps/Beach"))
return this.Helper.Content.Load<T>(@"assets/Beach.tbin");
}
public string GetCurrentRecipeId()
{
int whichWeek = (((int)(Game1.stats.DaysPlayed % 224u / 7u)) % 32) + 1;
Dictionary<string, string> cookingRecipeChannel = Game1.temporaryContent.Load<Dictionary<string, string>>("Data\\TV\\CookingChannel");
return cookingRecipeChannel[whichWeek.ToString()].Split('/')[0];
}
private void GameLaunch(object sender, GameLaunchedEventArgs e)
{
config = Helper.ReadConfig<Config>();
var api = Helper.ModRegistry.GetApi<GenericModConfigMenuAPI>("spacechase0.GenericModConfigMenu");
api.RegisterModConfig(ModManifest, () => config = new Config(), () => Helper.WriteConfig(config));
api.RegisterSimpleOption(ModManifest, "Show Total Crops at daystart", "Checking this will show your total crops on your farm every morning!", () => config.showcrops, (bool val) => config.showcrops = val);
api.RegisterSimpleOption(ModManifest, "Send QOFTS Recipes", "Checking this will send every queen of the sauce recipe you dont have to your mail!", () => config.sendrecipes, (bool val) => config.sendrecipes = val);
}
// dawprivate void onGameLaunched (object _sender, GameLaunchedEventArgs _e)
//{
// Load the Json Assets content pack.
//jsonAssets = Helper.ModRegistry.GetApi<JsonAssets.IApi>("spacechase0.JsonAssets");
//if (jsonAssets == null)
//{
//Monitor.LogOnce ("Could not connect to Json Assets. It may not be installed or working properly",
//LogLevel.Error);
//return;
//}
//jsonAssets.LoadAssets (Path.Combine (Helper.DirectoryPath,
//"assets", "JA"));
// Set up Generic Mod Config Menu, if it is available.
//}
private void OnButtonPressed(object sender, ButtonPressedEventArgs e)
{
if (!Context.IsWorldReady)
return;
uint totalEarnings = Game1.player.totalMoneyEarned;
//if (totalEarnings > 500000)
//if (Game1.currentSeason.Equals("spring"))
//MailDao.SaveLetter(
//new Letter(
//"Raik1",
//"Hey, i send you this recipe:^Season Salad (Spring) have fun^^-Raik",
//"Seasonal Salad (Spring)",
//(l) => !Game1.player.cookingRecipes.ContainsKey(l.Recipe)
//)
//);
//if (Game1.currentSeason.Equals("summer"))
//MailDao.SaveLetter(
//new Letter(
//"Raik2",
//"Hey, i send you this recipe:^Season Salad (Summer) have fun^^-Raik",
//"Seasonal Salad (Summer)",
//(l) => !Game1.player.cookingRecipes.ContainsKey(l.Recipe)
//)
//);
}
public void DayEnd(object sender, DayEndingEventArgs d)
{
}
private void DayStart(object sender, DayStartedEventArgs d)
{
int Crops = Game1.getFarm().terrainFeatures.Values.Count((tf) => tf is StardewValley.TerrainFeatures.HoeDirt hd && hd.crop != null);
if (config.showcrops.Equals(true))
{
Game1.addHUDMessage(new HUDMessage($"Crops on Farm: {Crops}", 2));
if (Game1.dayOfMonth.Equals(28))
{
}
}
if (config.sendrecipes.Equals(true))
{
// string[] weeklyRecipe = Helper.Reflection.GetMethod(new TV(), "getWeeklyRecipe").Invoke<string[]>();
// string Recipe = weeklyRecipe[1].Replace(".", ""); // string.Join("", weeklyRecipe).Substring(0, string.Join("", weeklyRecipe).IndexOf("!") + 1).Replace("!", "");
// if (!Recipe.StartsWith("You already know how to cook "))
// this.Monitor.Log($"Recipe: {Recipe}", LogLevel.Debug);
string Recipe = GetCurrentRecipeId();
this.Monitor.Log($"Recipe: {Recipe}",LogLevel.Debug);
if (Recipe != "")
MailDao.SaveLetter(
new Letter(
$"{Recipe}",
$"Weekly Recipe: {Recipe}^Instructions to cook included^^-Queen of the sauce leader",
$"{Recipe}",
(l) => !Game1.player.cookingRecipes.ContainsKey(l.Recipe)
)
);
}
}
}
} | 45.185185 | 225 | 0.56694 | [
"MIT"
] | Raik176/Lost-Woods | ModEntry.cs | 7,322 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.