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 MicMute
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.icon = new System.Windows.Forms.NotifyIcon(this.components);
this.iconContextMenu = new System.Windows.Forms.ContextMenuStrip(this.components);
this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem();
this.hotkeyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.hotkeyTextBox = new Shortcut.Forms.HotkeyTextBox();
this.label1 = new System.Windows.Forms.Label();
this.buttonReset = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.muteTextBox = new Shortcut.Forms.HotkeyTextBox();
this.muteReset = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.unmuteReset = new System.Windows.Forms.Button();
this.unmuteTextBox = new Shortcut.Forms.HotkeyTextBox();
this.iconContextMenu.SuspendLayout();
this.SuspendLayout();
//
// icon
//
this.icon.ContextMenuStrip = this.iconContextMenu;
this.icon.Text = "<Initializing>";
this.icon.Visible = true;
this.icon.MouseClick += new System.Windows.Forms.MouseEventHandler(this.Icon_MouseClick);
//
// iconContextMenu
//
this.iconContextMenu.ImageScalingSize = new System.Drawing.Size(32, 32);
this.iconContextMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripMenuItem2,
this.hotkeyToolStripMenuItem,
this.toolStripMenuItem1});
this.iconContextMenu.Name = "iconContextMenu";
this.iconContextMenu.Size = new System.Drawing.Size(200, 118);
//
// toolStripMenuItem2
//
this.toolStripMenuItem2.Name = "toolStripMenuItem2";
this.toolStripMenuItem2.Size = new System.Drawing.Size(199, 38);
this.toolStripMenuItem2.Text = "Select mic";
this.toolStripMenuItem2.Click += new System.EventHandler(this.toolStripMenuItem2_Click);
//
// hotkeyToolStripMenuItem
//
this.hotkeyToolStripMenuItem.Name = "hotkeyToolStripMenuItem";
this.hotkeyToolStripMenuItem.Size = new System.Drawing.Size(199, 38);
this.hotkeyToolStripMenuItem.Text = "Hotkey";
this.hotkeyToolStripMenuItem.Click += new System.EventHandler(this.HotkeyToolStripMenuItem_Click);
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.Size = new System.Drawing.Size(199, 38);
this.toolStripMenuItem1.Text = "Exit";
this.toolStripMenuItem1.Click += new System.EventHandler(this.ExitMenuItem_Click);
//
// hotkeyTextBox
//
this.hotkeyTextBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.hotkeyTextBox.Hotkey = null;
this.hotkeyTextBox.Location = new System.Drawing.Point(24, 78);
this.hotkeyTextBox.Margin = new System.Windows.Forms.Padding(6);
this.hotkeyTextBox.Name = "hotkeyTextBox";
this.hotkeyTextBox.Size = new System.Drawing.Size(494, 44);
this.hotkeyTextBox.TabIndex = 1;
this.hotkeyTextBox.Text = "None";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.label1.Location = new System.Drawing.Point(26, 32);
this.label1.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(647, 37);
this.label1.TabIndex = 2;
this.label1.Text = "Register toggle hotkey (auto saved on close)";
//
// buttonReset
//
this.buttonReset.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.buttonReset.Location = new System.Drawing.Point(530, 75);
this.buttonReset.Margin = new System.Windows.Forms.Padding(6);
this.buttonReset.Name = "buttonReset";
this.buttonReset.Size = new System.Drawing.Size(154, 50);
this.buttonReset.TabIndex = 3;
this.buttonReset.Text = "reset";
this.buttonReset.UseVisualStyleBackColor = true;
this.buttonReset.Click += new System.EventHandler(this.ButtonReset_Click);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.label2.Location = new System.Drawing.Point(26, 148);
this.label2.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(631, 37);
this.label2.TabIndex = 4;
this.label2.Text = "Register mute hotkey (auto saved on close)";
//
// muteTextBox
//
this.muteTextBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.muteTextBox.Hotkey = null;
this.muteTextBox.Location = new System.Drawing.Point(24, 201);
this.muteTextBox.Margin = new System.Windows.Forms.Padding(6);
this.muteTextBox.Name = "muteTextBox";
this.muteTextBox.Size = new System.Drawing.Size(494, 44);
this.muteTextBox.TabIndex = 5;
this.muteTextBox.Text = "None";
//
// muteReset
//
this.muteReset.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.muteReset.Location = new System.Drawing.Point(530, 201);
this.muteReset.Margin = new System.Windows.Forms.Padding(6);
this.muteReset.Name = "muteReset";
this.muteReset.Size = new System.Drawing.Size(154, 50);
this.muteReset.TabIndex = 6;
this.muteReset.Text = "reset";
this.muteReset.UseVisualStyleBackColor = true;
this.muteReset.Click += new System.EventHandler(this.muteReset_Click);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.label3.Location = new System.Drawing.Point(26, 267);
this.label3.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(667, 37);
this.label3.TabIndex = 7;
this.label3.Text = "Register unmute hotkey (auto saved on close)";
//
// unmuteReset
//
this.unmuteReset.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.unmuteReset.Location = new System.Drawing.Point(530, 310);
this.unmuteReset.Margin = new System.Windows.Forms.Padding(6);
this.unmuteReset.Name = "unmuteReset";
this.unmuteReset.Size = new System.Drawing.Size(154, 50);
this.unmuteReset.TabIndex = 9;
this.unmuteReset.Text = "reset";
this.unmuteReset.UseVisualStyleBackColor = true;
this.unmuteReset.Click += new System.EventHandler(this.unmuteReset_Click);
//
// unmuteTextBox
//
this.unmuteTextBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.unmuteTextBox.Hotkey = null;
this.unmuteTextBox.Location = new System.Drawing.Point(24, 310);
this.unmuteTextBox.Margin = new System.Windows.Forms.Padding(6);
this.unmuteTextBox.Name = "unmuteTextBox";
this.unmuteTextBox.Size = new System.Drawing.Size(494, 44);
this.unmuteTextBox.TabIndex = 8;
this.unmuteTextBox.Text = "None";
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(12F, 25F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(699, 377);
this.Controls.Add(this.unmuteReset);
this.Controls.Add(this.unmuteTextBox);
this.Controls.Add(this.label3);
this.Controls.Add(this.muteReset);
this.Controls.Add(this.muteTextBox);
this.Controls.Add(this.label2);
this.Controls.Add(this.buttonReset);
this.Controls.Add(this.label1);
this.Controls.Add(this.hotkeyTextBox);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Margin = new System.Windows.Forms.Padding(6);
this.Name = "MainForm";
this.Text = "MicMute";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_FormClosing);
this.Load += new System.EventHandler(this.MainForm_Load);
this.iconContextMenu.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.NotifyIcon icon;
private System.Windows.Forms.ContextMenuStrip iconContextMenu;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem1;
private Shortcut.Forms.HotkeyTextBox hotkeyTextBox;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.ToolStripMenuItem hotkeyToolStripMenuItem;
private System.Windows.Forms.Button buttonReset;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem2;
private System.Windows.Forms.Label label2;
private Shortcut.Forms.HotkeyTextBox muteTextBox;
private System.Windows.Forms.Button muteReset;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Button unmuteReset;
private Shortcut.Forms.HotkeyTextBox unmuteTextBox;
}
}
| 52.32766 | 175 | 0.617386 | [
"MIT"
] | Anc813/MicMute | MainForm.Designer.cs | 12,299 | C# |
using AutoFixture.AutoEF.Interception;
using Castle.DynamicProxy;
using FluentAssertions;
using AutoFixture.Xunit2;
using Theory = Xunit.TheoryAttribute;
using Xunit.Extensions;
namespace AutoFixture.AutoEF.Tests.Interception
{
public class NullInterceptorTest
{
[Theory, AutoData]
public void SutIsInterceptor(NullInterceptor sut)
{
sut.Should().BeAssignableTo<IInterceptor>();
}
}
}
| 23.315789 | 57 | 0.715576 | [
"MIT"
] | alexfoxgill/AutoFixture.AutoEntityFramework | src/AutoFixture.AutoEF.Tests/Interception/NullInterceptorTest.cs | 445 | C# |
/* Copyright (c) Citrix Systems Inc.
* All rights reserved.
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "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 COPYRIGHT HOLDER OR
* 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.Collections.Generic;
using System.Windows.Forms;
using XenAdmin.Actions;
using XenAdmin.Core;
using XenAdmin.Dialogs;
using XenAPI;
using XenAdmin.Actions.VMActions;
namespace XenAdmin.Commands
{
/// <summary>
/// Deletes the selected VMs. Shows a confirmation dialog.
/// </summary>
internal class DeleteVMCommand : Command
{
/// <summary>
/// Initializes a new instance of this Command. The parameter-less constructor is required in the derived
/// class if it is to be attached to a ToolStrip menu item or button. It should not be used in any other scenario.
/// </summary>
public DeleteVMCommand()
{
}
public DeleteVMCommand(IMainWindow mainWindow, IEnumerable<SelectedItem> selection)
: base(mainWindow, selection)
{
}
public DeleteVMCommand(IMainWindow mainWindow, SelectedItem selection)
: base(mainWindow, selection)
{
}
public DeleteVMCommand(IMainWindow mainWindow, VM vm)
: base(mainWindow, vm)
{
}
private AsyncAction GetAction(VM vm, List<VBD> deleteDisks, List<VM> deleteSnapshots)
{
return new VMDestroyAction(vm, deleteDisks, deleteSnapshots);
}
protected sealed override void ExecuteCore(SelectedItemCollection selection)
{
ConfirmVMDeleteDialog dialog = new ConfirmVMDeleteDialog(selection.AsXenObjects<VM>());
if (MainWindowCommandInterface.RunInAutomatedTestMode || dialog.ShowDialog(Parent) == DialogResult.Yes)
{
CommandErrorDialog errorDialog = null;
Dictionary<SelectedItem, string> cantExecuteReasons = GetCantExecuteReasons();
if (cantExecuteReasons.Count > 0)
{
errorDialog = new CommandErrorDialog(ErrorDialogTitle, ErrorDialogText, GetCantExecuteReasons());
}
List<AsyncAction> actions = new List<AsyncAction>();
foreach (VM vm in selection.AsXenObjects<VM>(CanExecute))
{
var snapshotsToDelete = dialog.DeleteSnapshots.FindAll(x => x.Connection.Resolve(x.snapshot_of) == vm);
actions.Add(GetAction(vm, dialog.DeleteDisks, snapshotsToDelete));
}
RunMultipleActions(actions, Messages.ACTION_VMS_DESTROYING_TITLE, Messages.ACTION_VM_DESTROYING, Messages.ACTION_VM_DESTROYED, true);
if (errorDialog != null)
{
errorDialog.ShowDialog(Parent);
}
}
}
protected virtual bool CanExecute(VM vm)
{
return vm != null && !vm.is_a_template && !vm.Locked && vm.allowed_operations != null && vm.allowed_operations.Contains(vm_operations.destroy);
}
protected sealed override bool CanExecuteCore(SelectedItemCollection selection)
{
return selection.AllItemsAre<VM>() && selection.AtLeastOneXenObjectCan<VM>(CanExecute);
}
public override string MenuText
{
get
{
if (GetSelection().Count > 1)
{
return Messages.MAINWINDOW_DELETE_OBJECTS;
}
return Messages.MAINWINDOW_DELETE_VM;
}
}
protected virtual string ErrorDialogText
{
get
{
return Messages.ERROR_DIALOG_DELETE_VM_TEXT;
}
}
protected virtual string ErrorDialogTitle
{
get
{
return Messages.ERROR_DIALOG_DELETE_VM_TITLE;
}
}
protected override string GetCantExecuteReasonCore(SelectedItem item)
{
VM vm = item.XenObject as VM;
if (vm == null)
{
return base.GetCantExecuteReasonCore(item);
}
if (!vm.is_a_template && vm.power_state != vm_power_state.Halted)
{
return Messages.VM_NOT_SHUT_DOWN;
}
else if (vm.is_a_template && vm.DefaultTemplate)
{
return Messages.CANNOT_DELETE_DEFAULT_TEMPLATE;
}
return base.GetCantExecuteReasonCore(item);
}
}
}
| 35.640244 | 155 | 0.621386 | [
"BSD-2-Clause"
] | wdxgy136/xenadmin-yeesan | XenAdmin/Commands/DeleteVMCommand.cs | 5,847 | 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.
//
// Produced by Entity Framework Visual Editor v2.0.5.7
// Source: https://github.com/msawczyn/EFDesigner
// Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner
// Documentation: https://msawczyn.github.io/EFDesigner/
// License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Data.Entity.Infrastructure.Annotations;
namespace MultiContext.Context2
{
/// <inheritdoc/>
public partial class Context2 : DbContext
{
#region DbSets
public virtual System.Data.Entity.DbSet<global::MultiContext.Context2.Base> Bases { get; set; }
public virtual System.Data.Entity.DbSet<global::MultiContext.Context2.Entity1> Entity1 { get; set; }
public virtual System.Data.Entity.DbSet<global::MultiContext.Context2.Entity2> Entity2 { get; set; }
public virtual System.Data.Entity.DbSet<global::MultiContext.Context2.Entity3> Entity3 { get; set; }
#endregion DbSets
#region Constructors
partial void CustomInit();
#warning Default constructor not generated for Context2 since no default connection string was specified in the model
/// <inheritdoc />
public Context2(string connectionString) : base(connectionString)
{
Configuration.LazyLoadingEnabled = true;
Configuration.ProxyCreationEnabled = true;
System.Data.Entity.Database.SetInitializer<Context2>(new Context2DatabaseInitializer());
CustomInit();
}
/// <inheritdoc />
public Context2(string connectionString, System.Data.Entity.Infrastructure.DbCompiledModel model) : base(connectionString, model)
{
Configuration.LazyLoadingEnabled = true;
Configuration.ProxyCreationEnabled = true;
System.Data.Entity.Database.SetInitializer<Context2>(new Context2DatabaseInitializer());
CustomInit();
}
/// <inheritdoc />
public Context2(System.Data.Common.DbConnection existingConnection, bool contextOwnsConnection) : base(existingConnection, contextOwnsConnection)
{
Configuration.LazyLoadingEnabled = true;
Configuration.ProxyCreationEnabled = true;
System.Data.Entity.Database.SetInitializer<Context2>(new Context2DatabaseInitializer());
CustomInit();
}
/// <inheritdoc />
public Context2(System.Data.Common.DbConnection existingConnection, System.Data.Entity.Infrastructure.DbCompiledModel model, bool contextOwnsConnection) : base(existingConnection, model, contextOwnsConnection)
{
Configuration.LazyLoadingEnabled = true;
Configuration.ProxyCreationEnabled = true;
System.Data.Entity.Database.SetInitializer<Context2>(new Context2DatabaseInitializer());
CustomInit();
}
/// <inheritdoc />
public Context2(System.Data.Entity.Infrastructure.DbCompiledModel model) : base(model)
{
Configuration.LazyLoadingEnabled = true;
Configuration.ProxyCreationEnabled = true;
System.Data.Entity.Database.SetInitializer<Context2>(new Context2DatabaseInitializer());
CustomInit();
}
/// <inheritdoc />
public Context2(System.Data.Entity.Core.Objects.ObjectContext objectContext, bool dbContextOwnsObjectContext) : base(objectContext, dbContextOwnsObjectContext)
{
Configuration.LazyLoadingEnabled = true;
Configuration.ProxyCreationEnabled = true;
System.Data.Entity.Database.SetInitializer<Context2>(new Context2DatabaseInitializer());
CustomInit();
}
#endregion Constructors
partial void OnModelCreatingImpl(System.Data.Entity.DbModelBuilder modelBuilder);
partial void OnModelCreatedImpl(System.Data.Entity.DbModelBuilder modelBuilder);
/// <inheritdoc />
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
OnModelCreatingImpl(modelBuilder);
modelBuilder.HasDefaultSchema("dbo");
modelBuilder.Entity<global::MultiContext.Context2.Base>().ToTable("Bases").HasKey(t => t.Id);
modelBuilder.Entity<global::MultiContext.Context2.Base>().Property(t => t.Id).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<global::MultiContext.Context2.Entity1>().ToTable("Entity1").HasKey(t => t.Id);
modelBuilder.Entity<global::MultiContext.Context2.Entity1>().Property(t => t.Id).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<global::MultiContext.Context2.Entity1>().HasMany(x => x.Entity3).WithMany().Map(x => { x.ToTable("Entity1_x_Entity3"); x.MapLeftKey("Entity1_Id"); x.MapRightKey("Entity3_Id"); });
modelBuilder.Entity<global::MultiContext.Context2.Entity2>().ToTable("Entity2").HasKey(t => t.Id);
modelBuilder.Entity<global::MultiContext.Context2.Entity2>().Property(t => t.Id).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<global::MultiContext.Context2.Entity2>().HasMany(x => x.Entity3).WithRequired().Map(x => x.MapKey("Entity2.Entity3_Id"));
OnModelCreatedImpl(modelBuilder);
}
}
}
| 44.701613 | 211 | 0.743099 | [
"MIT"
] | BigHam/EFDesigner | src/Testing/Sandbox/Sandbox_EF6/Generated/Context/Context2.generated.cs | 5,543 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace PizzaBox.Storing.Migrations
{
public partial class toppinggonefix7 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Toppings_Pizzas_APizzaEntityId",
table: "Toppings");
migrationBuilder.DropIndex(
name: "IX_Toppings_APizzaEntityId",
table: "Toppings");
migrationBuilder.DropColumn(
name: "APizzaEntityId",
table: "Toppings");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<long>(
name: "APizzaEntityId",
table: "Toppings",
type: "bigint",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_Toppings_APizzaEntityId",
table: "Toppings",
column: "APizzaEntityId");
migrationBuilder.AddForeignKey(
name: "FK_Toppings_Pizzas_APizzaEntityId",
table: "Toppings",
column: "APizzaEntityId",
principalTable: "Pizzas",
principalColumn: "EntityId",
onDelete: ReferentialAction.Restrict);
}
}
}
| 31.311111 | 71 | 0.555713 | [
"MIT"
] | cyoung7749/project-pizzabox | PizzaBox.Storing/Migrations/20210430033758_topping gone fix7.cs | 1,411 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("Pub2PDF")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("Pub2PDF")]
[assembly: System.Reflection.AssemblyTitleAttribute("Pub2PDF")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 40.458333 | 80 | 0.643666 | [
"MIT"
] | therealatreides/TechScripts | C Sharp/Conversion Tools/VisualStudio/Pub2PDF/Pub2PDF/obj/Debug/netcoreapp3.1/Pub2PDF.AssemblyInfo.cs | 971 | C# |
////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using EnsureThat;
using Core;
////////////////////////////////////////////////////////////////////////////////////////////////////
namespace ExistsAcceptingPath
{
using NCGraphType = TypedDAG<NestedCommsGraphNodeInfo, StdEdgeInfo>;
public class CheckDataStructuresTheSameFrom : CheckDataStructures
{
#region public members
public override void CheckTASGNodesHaveTheSameSymbol(MEAPContext meapContext)
{
log.Info("CheckTASGNodesHaveTheSameSymbolFrom");
foreach (KeyValuePair<long, DAGNode> itemPair in meapContext.TArbSeqCFG.NodeEnumeration)
{
long vNodeId = itemPair.Key;
if (vNodeId == meapContext.TArbSeqCFG.GetSinkNodeId())
{
continue;
}
DAGNode vNode = itemPair.Value;
ComputationStep vCompStep = meapContext.TArbSeqCFG.IdToNodeInfoMap[vNodeId].CompStep;
bool firstEdge = true;
int sFrom = OneTapeTuringMachine.blankSymbol;
foreach (DAGEdge e in vNode.InEdges)
{
long uNodeId = e.FromNode.Id;
ComputationStep uCompStep = meapContext.TArbSeqCFG.IdToNodeInfoMap[uNodeId].CompStep;
if (uNodeId == meapContext.TArbSeqCFG.GetSourceNodeId())
{
continue;
}
if (firstEdge)
{
sFrom = uCompStep.sNext;
firstEdge = false;
}
else
{
Ensure.That(uCompStep.sNext).Is(sFrom);
}
}
}
}
public override void CheckNCGNodesHaveTheSameSymbol(MEAPContext meapContext)
{
log.Info("CheckNCGNodesHaveTheSameSymbolFrom");
foreach (KeyValuePair<long, FwdBkwdNCommsGraphPair> ncgItemPair in
meapContext.muToNestedCommsGraphPair)
{
NCGraphType fwdNestedCommsGraph = ncgItemPair.Value.FwdNestedCommsGraph;
foreach (KeyValuePair<long, DAGNode> ncgNodeItemPair in fwdNestedCommsGraph.NodeEnumeration)
{
long uNCGNodeId = ncgNodeItemPair.Key;
DAGNode uNCGNode = ncgNodeItemPair.Value;
if (!meapContext.Commodities.TryGetValue(uNCGNodeId, out Commodity? uComm))
{
continue;
}
long uNodeId = uComm.sNodeId;
ComputationStep uCompStep = meapContext.TArbSeqCFG.IdToNodeInfoMap[uNodeId].CompStep;
if (uNodeId == meapContext.TArbSeqCFG.GetSourceNodeId())
{
continue;
}
bool firstEdge = true;
int sFrom = OneTapeTuringMachine.blankSymbol;
foreach (DAGEdge e in uNCGNode.OutEdges)
{
long vNCGNodeId = e.FromNode.Id;
Commodity vComm = meapContext.Commodities[vNCGNodeId];
long vNodeId = vComm.sNodeId;
ComputationStep vCompStep = meapContext.TArbSeqCFG.IdToNodeInfoMap[vNodeId].CompStep;
if (firstEdge)
{
sFrom = vCompStep.sNext;
firstEdge = false;
}
else
{
Ensure.That(vCompStep.sNext).Is(sFrom);
}
}
}
}
}
#endregion
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
| 28.890756 | 101 | 0.563991 | [
"MIT"
] | SergeyVYakhontov/PeqNPApp | app.verify/B.MExistsAccPaths/10.Components.Common/CheckDataStructures.TheSameFrom.cs | 3,440 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ModuleNoteTaker
{
public partial class AssessmentsList : Form
{
public AssessmentsList(List<string> AssignmentItems)
{
InitializeComponent();
AssignmentListBox.DataSource = AssignmentItems;
}
}
}
| 21.909091 | 60 | 0.713693 | [
"Apache-2.0"
] | jdon/ModularNoteTaker | AssessmentsList.cs | 484 | C# |
namespace gp
{
/// <summary>
/// 代码元素接口。
/// </summary>
public interface ICodeElement
{
/// <summary>
/// 排序Id。
/// </summary>
int Index { get; set; }
/// <summary>
/// 类型。
/// </summary>
CodeType Type { get; }
/// <summary>
/// 父级元素。
/// </summary>
ICodeElement Parent { get; }
}
} | 17.608696 | 36 | 0.395062 | [
"Apache-2.0"
] | onetcore/gc | gp/CodeDom/ICodeElement.cs | 443 | C# |
#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEditor.IMGUI.Controls;
using UnityEditor.ShortcutManagement;
////TODO: Add "Revert" button
////TODO: add helpers to very quickly set up certain common configs (e.g. "FPS Controls" in add-action context menu;
//// "WASD Control" in add-binding context menu)
////REVIEW: should we listen for Unity project saves and save dirty .inputactions assets along with it?
////FIXME: when saving, processor/interaction selection is cleared
namespace UnityEngine.InputSystem.Editor
{
/// <summary>
/// An editor window to edit .inputactions assets.
/// </summary>
/// <remarks>
/// The .inputactions editor code does not really separate between model and view. Selection state is contained
/// in the tree views and persistent across domain reloads via <see cref="TreeViewState"/>.
/// </remarks>
internal class InputActionEditorWindow : EditorWindow, IDisposable
{
/// <summary>
/// Open window if someone clicks on an .inputactions asset or an action inside of it or
/// if someone hits the "Edit Asset" button in the importer inspector.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "line", Justification = "line parameter required by OnOpenAsset attribute")]
[OnOpenAsset]
public static bool OnOpenAsset(int instanceId, int line)
{
var path = AssetDatabase.GetAssetPath(instanceId);
if (!path.EndsWith(k_FileExtension, StringComparison.InvariantCultureIgnoreCase))
return false;
string mapToSelect = null;
string actionToSelect = null;
// Grab InputActionAsset.
var obj = EditorUtility.InstanceIDToObject(instanceId);
var asset = obj as InputActionAsset;
if (asset == null)
{
// Check if the user clicked on an action inside the asset.
var actionReference = obj as InputActionReference;
if (actionReference != null)
{
asset = actionReference.asset;
mapToSelect = actionReference.action.actionMap.name;
actionToSelect = actionReference.action.name;
}
else
return false;
}
////REVIEW: It'd be great if the window got docked by default but the public EditorWindow API doesn't allow that
//// to be done for windows that aren't singletons (GetWindow<T>() will only create one window and it's the
//// only way to get programmatic docking with the current API).
// See if we have an existing editor window that has the asset open.
var window = FindEditorForAsset(asset);
if (window == null)
{
// No, so create a new window.
window = CreateInstance<InputActionEditorWindow>();
window.SetAsset(asset);
}
window.Show();
window.Focus();
// If user clicked on an action inside the asset, focus on that action (if we can find it).
if (actionToSelect != null && window.m_ActionMapsTree.TrySelectItem(mapToSelect))
{
window.OnActionMapTreeSelectionChanged();
window.m_ActionsTree.SelectItem(actionToSelect);
}
return true;
}
public static InputActionEditorWindow FindEditorForAsset(InputActionAsset asset)
{
var windows = Resources.FindObjectsOfTypeAll<InputActionEditorWindow>();
return windows.FirstOrDefault(w => w.m_ActionAssetManager.ImportedAssetObjectEquals(asset));
}
public static InputActionEditorWindow FindEditorForAssetWithGUID(string guid)
{
var windows = Resources.FindObjectsOfTypeAll<InputActionEditorWindow>();
return windows.FirstOrDefault(w => w.m_ActionAssetManager.guid == guid);
}
public static void RefreshAllOnAssetReimport()
{
if (s_RefreshPending)
return;
// We don't want to refresh right away but rather wait for the next editor update
// to then do one pass of refreshing action editor windows.
EditorApplication.delayCall += RefreshAllOnAssetReimportCallback;
s_RefreshPending = true;
}
public void SaveChangesToAsset()
{
m_ActionAssetManager.SaveChangesToAsset();
}
public void AddNewActionMap()
{
m_ActionMapsTree.AddNewActionMap();
}
public void AddNewAction()
{
// Make sure we have an action map. If we don't have an action map selected,
// refuse the operation.
var actionMapItem = m_ActionMapsTree.GetSelectedItems().OfType<ActionMapTreeItem>().FirstOrDefault();
if (actionMapItem == null)
{
EditorApplication.Beep();
return;
}
m_ActionsTree.AddNewAction(actionMapItem.property);
}
public void AddNewBinding()
{
// Make sure we have an action selected.
var actionItems = m_ActionsTree.GetSelectedItems().OfType<ActionTreeItem>();
if (!actionItems.Any())
{
EditorApplication.Beep();
return;
}
foreach (var item in actionItems)
m_ActionsTree.AddNewBinding(item.property, item.actionMapProperty);
}
private static void RefreshAllOnAssetReimportCallback()
{
s_RefreshPending = false;
// When the asset is modified outside of the editor
// and the importer settings are visible in the inspector
// the asset references in the importer inspector need to be force rebuild
// (otherwise we gets lots of exceptions)
ActiveEditorTracker.sharedTracker.ForceRebuild();
var windows = Resources.FindObjectsOfTypeAll<InputActionEditorWindow>();
foreach (var window in windows)
window.ReloadAssetFromFileIfNotDirty();
}
private bool ConfirmSaveChangesIfNeeded()
{
// Ask for confirmation if we have unsaved changes.
if (!m_ForceQuit && m_ActionAssetManager.dirty)
{
var result = EditorUtility.DisplayDialogComplex("Input Action Asset has been modified",
$"Do you want to save the changes you made in:\n{m_ActionAssetManager.path}\n\nYour changes will be lost if you don't save them.", "Save", "Cancel", "Don't Save");
switch (result)
{
case 0: // Save
m_ActionAssetManager.SaveChangesToAsset();
m_ActionAssetManager.Cleanup();
break;
case 1: // Cancel
Instantiate(this).Show();
// Cancel editor quit.
return false;
case 2: // Don't save, don't ask again.
m_ForceQuit = true;
break;
}
}
return true;
}
private bool EditorWantsToQuit()
{
return ConfirmSaveChangesIfNeeded();
}
private void OnEnable()
{
minSize = new Vector2(600, 300);
// Initialize toolbar. We keep the toolbar across domain reloads but we
// will lose the delegates.
if (m_Toolbar == null)
m_Toolbar = new InputActionEditorToolbar();
m_Toolbar.onSearchChanged = OnToolbarSearchChanged;
m_Toolbar.onSelectedSchemeChanged = OnControlSchemeSelectionChanged;
m_Toolbar.onSelectedDeviceChanged = OnControlSchemeSelectionChanged;
m_Toolbar.onSave = SaveChangesToAsset;
m_Toolbar.onControlSchemesChanged = OnControlSchemesModified;
m_Toolbar.onControlSchemeRenamed = OnControlSchemeRenamed;
m_Toolbar.onControlSchemeDeleted = OnControlSchemeDeleted;
EditorApplication.wantsToQuit += EditorWantsToQuit;
// Initialize after assembly reload.
if (m_ActionAssetManager != null)
{
if (!m_ActionAssetManager.Initialize())
{
// The asset we want to edit no longer exists.
Close();
return;
}
m_ActionAssetManager.onDirtyChanged = OnDirtyChanged;
InitializeTrees();
}
}
private void OnDestroy()
{
ConfirmSaveChangesIfNeeded();
EditorApplication.wantsToQuit -= EditorWantsToQuit;
}
// Set asset would usually only be called when the window is open
private void SetAsset(InputActionAsset asset)
{
m_ActionAssetManager = new InputActionAssetManager(asset) {onDirtyChanged = OnDirtyChanged};
m_ActionAssetManager.Initialize();
InitializeTrees();
LoadControlSchemes();
// Select first action map in asset.
m_ActionMapsTree.SelectFirstToplevelItem();
UpdateWindowTitle();
}
private void UpdateWindowTitle()
{
var title = m_ActionAssetManager.name + " (Input Actions)";
m_Title = new GUIContent(title);
m_DirtyTitle = new GUIContent("(*) " + m_Title.text);
titleContent = m_Title;
}
private void LoadControlSchemes()
{
TransferControlSchemes(save: false);
}
private void TransferControlSchemes(bool save)
{
// The easiest way to load and save control schemes is using SerializedProperties to just transfer the data
// between the InputControlScheme array in the toolbar and the one in the asset. Doing it this way rather than
// just overwriting the array in m_AssetManager.m_AssetObjectForEditing directly will make undo work.
using (var editorWindowObject = new SerializedObject(this))
using (var controlSchemesArrayPropertyInWindow = editorWindowObject.FindProperty("m_Toolbar.m_ControlSchemes"))
using (var controlSchemesArrayPropertyInAsset = m_ActionAssetManager.serializedObject.FindProperty("m_ControlSchemes"))
{
Debug.Assert(controlSchemesArrayPropertyInWindow != null, $"Cannot find m_ControlSchemes in window");
Debug.Assert(controlSchemesArrayPropertyInAsset != null, $"Cannot find m_ControlSchemes in asset");
if (save)
{
var json = controlSchemesArrayPropertyInWindow.CopyToJson();
controlSchemesArrayPropertyInAsset.RestoreFromJson(json);
editorWindowObject.ApplyModifiedProperties();
}
else
{
// Load.
var json = controlSchemesArrayPropertyInAsset.CopyToJson();
controlSchemesArrayPropertyInWindow.RestoreFromJson(json);
editorWindowObject.ApplyModifiedPropertiesWithoutUndo();
}
}
}
private void OnControlSchemeSelectionChanged()
{
OnToolbarSearchChanged();
LoadPropertiesForSelection();
}
private void OnControlSchemesModified()
{
TransferControlSchemes(save: true);
// Control scheme changes may affect the search filter.
OnToolbarSearchChanged();
ApplyAndReloadTrees();
}
private void OnControlSchemeRenamed(string oldBindingGroup, string newBindingGroup)
{
InputActionSerializationHelpers.ReplaceBindingGroup(m_ActionAssetManager.serializedObject,
oldBindingGroup, newBindingGroup);
ApplyAndReloadTrees();
}
private void OnControlSchemeDeleted(string name, string bindingGroup)
{
Debug.Assert(!string.IsNullOrEmpty(name), "Control scheme name should not be empty");
Debug.Assert(!string.IsNullOrEmpty(bindingGroup), "Binding group should not be empty");
var asset = m_ActionAssetManager.m_AssetObjectForEditing;
var bindingMask = InputBinding.MaskByGroup(bindingGroup);
var schemeHasBindings = asset.actionMaps.Any(m => m.bindings.Any(b => bindingMask.Matches(ref b)));
if (!schemeHasBindings)
return;
////REVIEW: offer to do nothing and leave all bindings as is?
var deleteBindings =
EditorUtility.DisplayDialog("Delete Bindings?",
$"Delete bindings for '{name}' as well? If you select 'No', the bindings will only "
+ $"be unassigned from the '{name}' control scheme but otherwise left as is. Note that bindings "
+ $"that are assigned to '{name}' but also to other control schemes will be left in place either way.",
"Yes", "No");
InputActionSerializationHelpers.ReplaceBindingGroup(m_ActionAssetManager.serializedObject, bindingGroup, "",
deleteOrphanedBindings: deleteBindings);
ApplyAndReloadTrees();
}
private void InitializeTrees()
{
// We persist tree view states (most importantly, they contain our selection states),
// so only create those if we don't have any yet.
if (m_ActionMapsTreeState == null)
m_ActionMapsTreeState = new TreeViewState();
if (m_ActionsTreeState == null)
m_ActionsTreeState = new TreeViewState();
// Create tree in middle pane showing actions and bindings. We initially
// leave this tree empty and populate it by selecting an action map in the
// left pane tree.
m_ActionsTree = new InputActionTreeView(m_ActionAssetManager.serializedObject, m_ActionsTreeState)
{
onSelectionChanged = OnActionTreeSelectionChanged,
onSerializedObjectModified = ApplyAndReloadTrees,
drawMinusButton = false,
title = "Actions",
};
// Create tree in left pane showing action maps.
m_ActionMapsTree = new InputActionTreeView(m_ActionAssetManager.serializedObject, m_ActionMapsTreeState)
{
onBuildTree = () =>
InputActionTreeView.BuildWithJustActionMapsFromAsset(m_ActionAssetManager.serializedObject),
onSelectionChanged = OnActionMapTreeSelectionChanged,
onSerializedObjectModified = ApplyAndReloadTrees,
onHandleAddNewAction = m_ActionsTree.AddNewAction,
drawMinusButton = false,
title = "Action Maps",
};
m_ActionMapsTree.Reload();
m_ActionMapsTree.ExpandAll();
RebuildActionTree();
LoadPropertiesForSelection();
// Sync current search status in toolbar.
OnToolbarSearchChanged();
}
/// <summary>
/// Synchronize the search filter applied to the trees.
/// </summary>
/// <remarks>
/// Note that only filter the action tree. The action map tree remains unfiltered.
/// </remarks>
private void OnToolbarSearchChanged()
{
// Rather than adding FilterCriterion instances directly, we go through the
// string-based format here. This allows typing queries directly into the search bar.
var searchStringBuffer = new StringBuilder();
// Plain-text search.
if (!string.IsNullOrEmpty(m_Toolbar.searchText))
searchStringBuffer.Append(m_Toolbar.searchText);
// Filter by binding group of selected control scheme.
if (m_Toolbar.selectedControlScheme != null)
{
searchStringBuffer.Append(" \"");
searchStringBuffer.Append(InputActionTreeView.FilterCriterion.k_BindingGroupTag);
searchStringBuffer.Append(m_Toolbar.selectedControlScheme.Value.bindingGroup);
searchStringBuffer.Append('\"');
}
// Filter by device layout.
if (m_Toolbar.selectedDeviceRequirement != null)
{
searchStringBuffer.Append(" \"");
searchStringBuffer.Append(InputActionTreeView.FilterCriterion.k_DeviceLayoutTag);
searchStringBuffer.Append(InputControlPath.TryGetDeviceLayout(m_Toolbar.selectedDeviceRequirement.Value.controlPath));
searchStringBuffer.Append('\"');
}
var searchString = searchStringBuffer.ToString();
if (string.IsNullOrEmpty(searchString))
m_ActionsTree.ClearItemSearchFilterAndReload();
else
m_ActionsTree.SetItemSearchFilterAndReload(searchStringBuffer.ToString());
// Have trees create new bindings with the right binding group.
var currentBindingGroup = m_Toolbar.selectedControlScheme?.bindingGroup;
m_ActionsTree.bindingGroupForNewBindings = currentBindingGroup;
m_ActionMapsTree.bindingGroupForNewBindings = currentBindingGroup;
}
/// <summary>
/// Synchronize the display state to the currently selected action map.
/// </summary>
private void OnActionMapTreeSelectionChanged()
{
// Re-configure action tree (middle pane) for currently select action map.
RebuildActionTree();
// If there's no actions in the selected action map or if there is no action map
// selected, make sure we wipe the property pane.
if (!m_ActionMapsTree.HasSelection() || !m_ActionsTree.rootItem.hasChildren)
{
LoadPropertiesForSelection();
}
else
{
// Otherwise select first action in map.
m_ActionsTree.SelectFirstToplevelItem();
}
}
private void RebuildActionTree()
{
var selectedActionMapItem =
m_ActionMapsTree.GetSelectedItems().OfType<ActionMapTreeItem>().FirstOrDefault();
if (selectedActionMapItem == null)
{
// Nothing selected. Wipe middle and right pane.
m_ActionsTree.onBuildTree = () => new TreeViewItem(0, -1, "");
}
else
{
m_ActionsTree.onBuildTree = () =>
InputActionTreeView.BuildWithJustActionsAndBindingsFromMap(selectedActionMapItem.property);
}
// Rebuild tree.
m_ActionsTree.Reload();
m_ActionsTree.ExpandAll();
}
private void OnActionTreeSelectionChanged()
{
LoadPropertiesForSelection();
}
private void LoadPropertiesForSelection()
{
m_BindingPropertyView = null;
m_ActionPropertyView = null;
////TODO: preserve interaction/processor selection when reloading
// Nothing else to do if we don't have a selection in the middle pane or if
// multiple items are selected (we don't currently have the ability to multi-edit).
if (!m_ActionsTree.HasSelection() || m_ActionsTree.GetSelection().Count != 1)
return;
var item = m_ActionsTree.GetSelectedItems().FirstOrDefault();
if (item is BindingTreeItem)
{
// Grab the action for the binding and see if we have an expected control layout
// set on it. Pass that on to the control picking machinery.
var isCompositePartBinding = item is PartOfCompositeBindingTreeItem;
var actionItem = (isCompositePartBinding ? item.parent.parent : item.parent) as ActionTreeItem;
Debug.Assert(actionItem != null);
if (m_ControlPickerViewState == null)
m_ControlPickerViewState = new InputControlPickerState();
// The toolbar may constrain the set of devices we're currently interested in by either
// having one specific device selected from the current scheme or having at least a control
// scheme selected.
IEnumerable<string> controlPathsToMatch;
if (m_Toolbar.selectedDeviceRequirement != null)
{
// Single device selected from set of devices in control scheme.
controlPathsToMatch = new[] {m_Toolbar.selectedDeviceRequirement.Value.controlPath};
}
else if (m_Toolbar.selectedControlScheme != null)
{
// Constrain to devices from current control scheme.
controlPathsToMatch =
m_Toolbar.selectedControlScheme.Value.deviceRequirements.Select(x => x.controlPath);
}
else
{
// If there's no device filter coming from a control scheme, filter by supported
// devices as given by settings.
controlPathsToMatch = InputSystem.settings.supportedDevices;
}
// Show properties for binding.
m_BindingPropertyView =
new InputBindingPropertiesView(
item.property,
change =>
{
if (change == InputBindingPropertiesView.k_PathChanged ||
change == InputBindingPropertiesView.k_CompositePartAssignmentChanged ||
change == InputBindingPropertiesView.k_CompositeTypeChanged ||
change == InputBindingPropertiesView.k_GroupsChanged)
{
ApplyAndReloadTrees();
}
else
{
// Simple property change that doesn't affect the rest of the UI.
Apply();
}
},
m_ControlPickerViewState,
expectedControlLayout: item.expectedControlLayout,
controlSchemes: m_Toolbar.controlSchemes,
controlPathsToMatch: controlPathsToMatch);
}
else if (item is ActionTreeItem actionItem)
{
// Show properties for action.
m_ActionPropertyView =
new InputActionPropertiesView(
actionItem.property,
// Apply without reload is enough here as modifying the properties of an action will
// never change the structure of the data.
change => Apply());
}
}
private void ApplyAndReloadTrees()
{
Apply();
// This path here is meant to catch *any* edits made to the serialized data. I.e. also
// any arbitrary undo that may have changed some misc bit not visible in the trees.
m_ActionMapsTree.Reload();
RebuildActionTree();
m_ActionAssetManager.UpdateAssetDirtyState();
LoadControlSchemes();
LoadPropertiesForSelection();
}
private void Apply()
{
m_ActionAssetManager.ApplyChanges();
// Update dirty count, otherwise ReloadIfSerializedObjectHasBeenChanged will trigger a full ApplyAndReloadTrees
m_ActionMapsTree.UpdateSerializedObjectDirtyCount();
m_ActionsTree.UpdateSerializedObjectDirtyCount();
// If auto-save is active, immediately flush out the changes to disk. Otherwise just
// put us into dirty state.
if (InputEditorUserSettings.autoSaveInputActionAssets)
{
m_ActionAssetManager.SaveChangesToAsset();
}
else
{
m_ActionAssetManager.SetAssetDirty();
titleContent = m_DirtyTitle;
}
}
private void OnGUI()
{
// If the actions tree has lost the filters (because they would not match an item it tried to highlight),
// update the Toolbar UI to remove them.
if (!m_ActionsTree.hasFilter)
m_Toolbar.ResetSearchFilters();
// Allow switching between action map tree and action tree using arrow keys.
ToggleFocusUsingKeyboard(KeyCode.RightArrow, m_ActionMapsTree, m_ActionsTree);
ToggleFocusUsingKeyboard(KeyCode.LeftArrow, m_ActionsTree, m_ActionMapsTree);
// Route copy-paste events to tree views if they have focus.
if (m_ActionsTree.HasFocus())
m_ActionsTree.HandleCopyPasteCommandEvent(Event.current);
else if (m_ActionMapsTree.HasFocus())
m_ActionMapsTree.HandleCopyPasteCommandEvent(Event.current);
// Draw toolbar.
EditorGUILayout.BeginVertical();
m_Toolbar.OnGUI();
EditorGUILayout.Space();
// Draw columns.
EditorGUILayout.BeginHorizontal();
var columnAreaWidth = position.width - InputActionTreeView.Styles.backgroundWithBorder.margin.left -
InputActionTreeView.Styles.backgroundWithBorder.margin.left -
InputActionTreeView.Styles.backgroundWithBorder.margin.right;
var oldType = Event.current.type;
DrawActionMapsColumn(columnAreaWidth * 0.22f);
if (Event.current.type == EventType.Used && oldType != Event.current.type)
{
// When renaming an item, TreeViews will capture all mouse Events, and process any clicks outside the item
// being renamed to end the renaming process. However, since we have two TreeViews, if the action column is
// renaming an item, and then you double click on an item in the action map column, the action map column will
// get to use the mouse event before the action collumn gets to see it, which would cause the action map column
// to enter rename mode and use the event, before the action column gets a chance to see it and exit rename mode.
// Then we end up with two active renaming sessions, which does not work correctly.
// (See https://fogbugz.unity3d.com/f/cases/1140869/).
// Now, our fix to this problem is to force-end and accept any renaming session on the action column if we see
// that the action map column had processed the current event. This is not particularly elegant, but I cannot think
// of a better solution as we are limited by the public APIs exposed by TreeView.
m_ActionsTree.EndRename(forceAccept: true);
}
DrawActionsColumn(columnAreaWidth * 0.38f);
DrawPropertiesColumn(columnAreaWidth * 0.40f);
EditorGUILayout.EndHorizontal();
// Bottom margin.
GUILayout.Space(3);
EditorGUILayout.EndVertical();
}
private static void ToggleFocusUsingKeyboard(KeyCode key, InputActionTreeView fromTree,
InputActionTreeView toTree)
{
var uiEvent = Event.current;
if (uiEvent.type == EventType.KeyDown && uiEvent.keyCode == key && fromTree.HasFocus())
{
if (!toTree.HasSelection())
toTree.SelectFirstToplevelItem();
toTree.SetFocus();
uiEvent.Use();
}
}
private void DrawActionMapsColumn(float width)
{
DrawColumnWithTreeView(m_ActionMapsTree, width, true);
}
private void DrawActionsColumn(float width)
{
DrawColumnWithTreeView(m_ActionsTree, width, false);
}
private static void DrawColumnWithTreeView(TreeView treeView, float width, bool fixedWidth)
{
EditorGUILayout.BeginVertical(InputActionTreeView.Styles.backgroundWithBorder,
fixedWidth ? GUILayout.MaxWidth(width) : GUILayout.MinWidth(width),
GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
GUILayout.FlexibleSpace();
EditorGUILayout.EndVertical();
var columnRect = GUILayoutUtility.GetLastRect();
treeView.OnGUI(columnRect);
}
private void DrawPropertiesColumn(float width)
{
EditorGUILayout.BeginVertical(InputActionTreeView.Styles.backgroundWithBorder, GUILayout.Width(width));
var rect = GUILayoutUtility.GetRect(0,
EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing * 2,
GUILayout.ExpandWidth(true));
rect.x -= 2;
rect.y -= 1;
rect.width += 4;
EditorGUI.LabelField(rect, GUIContent.none, InputActionTreeView.Styles.backgroundWithBorder);
var headerRect = new Rect(rect.x + 1, rect.y + 1, rect.width - 2, rect.height - 2);
EditorGUI.LabelField(headerRect, "Properties", InputActionTreeView.Styles.columnHeaderLabel);
if (m_BindingPropertyView != null)
{
m_PropertiesScroll = EditorGUILayout.BeginScrollView(m_PropertiesScroll);
m_BindingPropertyView.OnGUI();
EditorGUILayout.EndScrollView();
}
else if (m_ActionPropertyView != null)
{
m_PropertiesScroll = EditorGUILayout.BeginScrollView(m_PropertiesScroll);
m_ActionPropertyView.OnGUI();
EditorGUILayout.EndScrollView();
}
else
{
GUILayout.FlexibleSpace();
}
EditorGUILayout.EndVertical();
}
private void ReloadAssetFromFileIfNotDirty()
{
if (m_ActionAssetManager.dirty)
return;
// Don't touch the UI state if the serialized data is still the same.
if (!m_ActionAssetManager.ReInitializeIfAssetHasChanged())
return;
// Unfortunately, on this path we lose the selection state of the interactions and processors lists
// in the properties view.
InitializeTrees();
LoadPropertiesForSelection();
Repaint();
}
////TODO: add shortcut to focus search box
////TODO: show shortcuts in tooltips
////FIXME: the shortcuts seem to have focus problems; often requires clicking away and then back to the window
[Shortcut("Input Action Editor/Save", typeof(InputActionEditorWindow), KeyCode.S, ShortcutModifiers.Alt)]
private static void SaveShortcut(ShortcutArguments arguments)
{
var window = (InputActionEditorWindow)arguments.context;
window.SaveChangesToAsset();
}
[Shortcut("Input Action Editor/Add Action Map", typeof(InputActionEditorWindow), KeyCode.M, ShortcutModifiers.Alt)]
private static void AddActionMapShortcut(ShortcutArguments arguments)
{
var window = (InputActionEditorWindow)arguments.context;
window.AddNewActionMap();
}
[Shortcut("Input Action Editor/Add Action", typeof(InputActionEditorWindow), KeyCode.A, ShortcutModifiers.Alt)]
private static void AddActionShortcut(ShortcutArguments arguments)
{
var window = (InputActionEditorWindow)arguments.context;
window.AddNewAction();
}
[Shortcut("Input Action Editor/Add Binding", typeof(InputActionEditorWindow), KeyCode.B, ShortcutModifiers.Alt)]
private static void AddBindingShortcut(ShortcutArguments arguments)
{
var window = (InputActionEditorWindow)arguments.context;
window.AddNewBinding();
}
private void OnDirtyChanged(bool dirty)
{
titleContent = dirty ? m_DirtyTitle : m_Title;
m_Toolbar.isDirty = dirty;
}
public void Dispose()
{
m_BindingPropertyView?.Dispose();
}
[SerializeField] private TreeViewState m_ActionMapsTreeState;
[SerializeField] private TreeViewState m_ActionsTreeState;
[SerializeField] private InputControlPickerState m_ControlPickerViewState;
[SerializeField] private InputActionAssetManager m_ActionAssetManager;
[SerializeField] private InputActionEditorToolbar m_Toolbar;
[SerializeField] private GUIContent m_DirtyTitle;
[SerializeField] private GUIContent m_Title;
private InputBindingPropertiesView m_BindingPropertyView;
private InputActionPropertiesView m_ActionPropertyView;
private InputActionTreeView m_ActionMapsTree;
private InputActionTreeView m_ActionsTree;
private static bool s_RefreshPending;
private static readonly string k_FileExtension = "." + InputActionAsset.Extension;
private Vector2 m_PropertiesScroll;
private bool m_ForceQuit;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Intantiated through reflection by Unity")]
private class ProcessAssetModifications : UnityEditor.AssetModificationProcessor
{
// Handle .inputactions asset being deleted.
// ReSharper disable once UnusedMember.Local
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "options", Justification = "options parameter required by Unity API")]
public static AssetDeleteResult OnWillDeleteAsset(string path, RemoveAssetOptions options)
{
if (!path.EndsWith(k_FileExtension, StringComparison.InvariantCultureIgnoreCase))
return default;
// See if we have an open window.
var guid = AssetDatabase.AssetPathToGUID(path);
var window = FindEditorForAssetWithGUID(guid);
if (window != null)
{
// If there's unsaved changes, ask for confirmation.
if (window.m_ActionAssetManager.dirty)
{
var result = EditorUtility.DisplayDialog("Unsaved changes",
$"You have unsaved changes for '{path}'. Do you want to discard the changes and delete the asset?",
"Yes, Delete", "No, Cancel");
if (!result)
{
// User canceled. Stop the deletion.
return AssetDeleteResult.FailedDelete;
}
window.m_ForceQuit = true;
}
window.Close();
}
return default;
}
// Handle .inputactions asset being moved.
// ReSharper disable once UnusedMember.Local
public static AssetMoveResult OnWillMoveAsset(string sourcePath, string destinationPath)
{
if (!sourcePath.EndsWith(k_FileExtension, StringComparison.InvariantCultureIgnoreCase))
return default;
var guid = AssetDatabase.AssetPathToGUID(sourcePath);
var window = FindEditorForAssetWithGUID(guid);
if (window != null)
{
window.m_ActionAssetManager.path = destinationPath;
window.UpdateWindowTitle();
}
return default;
}
}
}
}
#endif // UNITY_EDITOR
| 43.352179 | 197 | 0.598163 | [
"MIT"
] | DeStiCap/Dim-Mind | Global Game Jam 2020/Library/PackageCache/com.unity.inputsystem@1.0.0-preview.4/InputSystem/Editor/AssetEditor/InputActionEditorWindow.cs | 36,806 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.WafRegional
{
/// <summary>
/// Provides a WAF Regional Regex Pattern Set Resource
///
/// > This content is derived from https://github.com/terraform-providers/terraform-provider-aws/blob/master/website/docs/r/wafregional_regex_pattern_set.html.markdown.
/// </summary>
public partial class RegexPatternSet : Pulumi.CustomResource
{
/// <summary>
/// The name or description of the Regex Pattern Set.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// A list of regular expression (regex) patterns that you want AWS WAF to search for, such as `B[a@]dB[o0]t`.
/// </summary>
[Output("regexPatternStrings")]
public Output<ImmutableArray<string>> RegexPatternStrings { get; private set; } = null!;
/// <summary>
/// Create a RegexPatternSet resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public RegexPatternSet(string name, RegexPatternSetArgs? args = null, CustomResourceOptions? options = null)
: base("aws:wafregional/regexPatternSet:RegexPatternSet", name, args ?? ResourceArgs.Empty, MakeResourceOptions(options, ""))
{
}
private RegexPatternSet(string name, Input<string> id, RegexPatternSetState? state = null, CustomResourceOptions? options = null)
: base("aws:wafregional/regexPatternSet:RegexPatternSet", name, state, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing RegexPatternSet resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="state">Any extra arguments used during the lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static RegexPatternSet Get(string name, Input<string> id, RegexPatternSetState? state = null, CustomResourceOptions? options = null)
{
return new RegexPatternSet(name, id, state, options);
}
}
public sealed class RegexPatternSetArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The name or description of the Regex Pattern Set.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
[Input("regexPatternStrings")]
private InputList<string>? _regexPatternStrings;
/// <summary>
/// A list of regular expression (regex) patterns that you want AWS WAF to search for, such as `B[a@]dB[o0]t`.
/// </summary>
public InputList<string> RegexPatternStrings
{
get => _regexPatternStrings ?? (_regexPatternStrings = new InputList<string>());
set => _regexPatternStrings = value;
}
public RegexPatternSetArgs()
{
}
}
public sealed class RegexPatternSetState : Pulumi.ResourceArgs
{
/// <summary>
/// The name or description of the Regex Pattern Set.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
[Input("regexPatternStrings")]
private InputList<string>? _regexPatternStrings;
/// <summary>
/// A list of regular expression (regex) patterns that you want AWS WAF to search for, such as `B[a@]dB[o0]t`.
/// </summary>
public InputList<string> RegexPatternStrings
{
get => _regexPatternStrings ?? (_regexPatternStrings = new InputList<string>());
set => _regexPatternStrings = value;
}
public RegexPatternSetState()
{
}
}
}
| 40.862903 | 175 | 0.625025 | [
"ECL-2.0",
"Apache-2.0"
] | dixler/pulumi-aws | sdk/dotnet/Wafregional/RegexPatternSet.cs | 5,067 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Text;
using Aurora.Profiles.Generic_Application;
using Aurora.Profiles.Overlays;
using Aurora.Profiles.Overlays.SkypeOverlay;
using Aurora.Profiles;
using Newtonsoft.Json.Serialization;
namespace Aurora.Settings
{
/// <summary>
/// Enum list for the percent effect type
/// </summary>
public enum PercentEffectType
{
/// <summary>
/// All at once
/// </summary>
[Description("All at once")]
AllAtOnce = 0,
/// <summary>
/// Progressive
/// </summary>
[Description("Progressive")]
Progressive = 1,
/// <summary>
/// Progressive (Gradual)
/// </summary>
[Description("Progressive (Gradual)")]
Progressive_Gradual = 2
}
public enum IdleEffects
{
[Description("None")]
None = 0,
[Description("Dim")]
Dim = 1,
[Description("Color Breathing")]
ColorBreathing = 2,
[Description("Rainbow Shift (Horizontal)")]
RainbowShift_Horizontal = 3,
[Description("Rainbow Shift (Vertical)")]
RainbowShift_Vertical = 4,
[Description("Star Fall")]
StarFall = 5,
[Description("Rain Fall")]
RainFall = 6,
[Description("Blackout")]
Blackout = 7,
[Description("Matrix")]
Matrix = 8
}
/// <summary>
/// Enum list for the layer effects
/// </summary>
public enum LayerEffects
{
/// <summary>
/// None
/// </summary>
[Description("None")]
None = 0,
/// <summary>
/// Single Color Overlay
/// </summary>
[Description("Single Color Overlay")]
ColorOverlay = 1,
/// <summary>
/// Color Breathing
/// </summary>
[Description("Color Breathing")]
ColorBreathing = 2,
/// <summary>
/// Rainbow Shift (Horizontal)
/// </summary>
[Description("Rainbow Shift (Horizontal)")]
RainbowShift_Horizontal = 3,
/// <summary>
/// Rainbow Shift (Vertical)
/// </summary>
[Description("Rainbow Shift (Vertical)")]
RainbowShift_Vertical = 4,
/// <summary>
/// Rainbow Shift (Diagonal)
/// </summary>
[Description("Rainbow Shift (Diagonal)")]
RainbowShift_Diagonal = 5,
/// <summary>
/// Rainbow Shift (Other Diagonal)
/// </summary>
[Description("Rainbow Shift (Other Diagonal)")]
RainbowShift_Diagonal_Other = 6,
/// <summary>
/// Rainbow Shift (Custom Angle)
/// </summary>
[Description("Rainbow Shift (Custom Angle)")]
RainbowShift_Custom_Angle = 7,
/// <summary>
/// Gradient Shift (Custom Angle)
/// </summary>
[Description("Gradient Shift (Custom Angle)")]
GradientShift_Custom_Angle = 8,
}
public enum AppExitMode
{
[Description("Always Ask")]
Ask = 0,
[Description("Always Minimize")]
Minimize = 1,
[Description("Always Exit")]
Exit = 2
}
public enum MouseOrientationType
{
[Description("Right Handed")]
RightHanded = 1,
[Description("Left Handed")]
LeftHanded = 2
}
public enum PreferredKeyboard
{
[Description("None")]
None = 0,
[Description("Generic Laptop")]
GenericLaptop = 1,
[Description("Generic Laptop (Numpad)")]
GenericLaptopNumpad = 2,
/*
[Description("Logitech")]
Logitech = 1,
[Description("Corsair")]
Corsair = 2,
[Description("Razer")]
Razer = 3,
[Description("Clevo")]
Clevo = 4,
[Description("Cooler Master")]
CoolerMaster = 5,
*/
//Logitech range is 100-199
[Description("Logitech - G910")]
Logitech_G910 = 100,
[Description("Logitech - G410")]
Logitech_G410 = 101,
[Description("Logitech - G810")]
Logitech_G810 = 102,
[Description("Logitech - GPRO")]
Logitech_GPRO = 103,
//Corsair range is 200-299
[Description("Corsair - K95")]
Corsair_K95 = 200,
[Description("Corsair - K70")]
Corsair_K70 = 201,
[Description("Corsair - K65")]
Corsair_K65 = 202,
[Description("Corsair - STRAFE")]
Corsair_STRAFE = 203,
[Description("Corsair - K95 Platinum")]
Corsair_K95_PL = 204,
[Description("Corsair - K68")]
Corsair_K68 = 205,
[Description("Corsair - K70 MK2")]
Corsair_K70MK2 = 206
,
//Razer range is 300-399
[Description("Razer - Blackwidow")]
Razer_Blackwidow = 300,
[Description("Razer - Blackwidow X")]
Razer_Blackwidow_X = 301,
[Description("Razer - Blackwidow Tournament Edition")]
Razer_Blackwidow_TE = 302,
[Description("Razer - Blade")]
Razer_Blade = 303,
//Clevo range is 400-499
//Cooler Master range is 500-599
[Description("Cooler Master - Masterkeys Pro L")]
Masterkeys_Pro_L = 500,
[Description("Cooler Master - Masterkeys Pro S")]
Masterkeys_Pro_S = 501,
[Description("Cooler Master - Masterkeys Pro M")]
Masterkeys_Pro_M = 502,
[Description("Cooler Master - Masterkeys MK750")]
Masterkeys_MK750 = 503,
//Roccat range is 600-699
[Description("Roccat Ryos")]
Roccat_Ryos = 600,
//Steelseries range is 700-799
[Description("SteelSeries Apex M800")]
SteelSeries_Apex_M800 = 700,
[Description("SteelSeries Apex M750")]
SteelSeries_Apex_M750 = 701,
[Description("SteelSeries Apex M750 TKL")]
SteelSeries_Apex_M750_TKL = 702,
[Description("Wooting One")]
Wooting_One = 800,
[Description("Asus Strix Flare")]
Asus_Strix_Flare = 900,
//Drevo range is 1000-1099
[Description("Drevo BladeMaster")]
Drevo_BladeMaster = 1000,
//Creative range is 1100-1199
[Description("SoundBlasterX VanguardK08")]
SoundBlasterX_Vanguard_K08 = 1100,
}
public enum PreferredKeyboardLocalization
{
[Description("Automatic Detection")]
None = 0,
[Description("International")]
intl = 1,
[Description("United States")]
us = 2,
[Description("United Kingdom")]
uk = 3,
[Description("Russian")]
ru = 4,
[Description("French")]
fr = 5,
[Description("Deutsch")]
de = 6,
[Description("Japanese")]
jpn = 7,
[Description("Turkish")]
tr = 8,
[Description("Nordic")]
nordic = 9,
[Description("Swiss")]
swiss = 10,
[Description("Portuguese (Brazilian ABNT2)")]
abnt2 = 11,
[Description("DVORAK (US)")]
dvorak = 12,
[Description("DVORAK (INT)")]
dvorak_int = 13,
[Description("Hungarian")]
hu = 14
}
public enum PreferredMouse
{
[Description("None")]
None = 0,
[Description("Generic Peripheral")]
Generic_Peripheral = 1,
[Description("Razer/Corsair Mousepad + Mouse")]
Generic_Mousepad = 2,
//Logitech range is 100-199
[Description("Logitech - G900")]
Logitech_G900 = 100,
[Description("Logitech - G502")]
Logitech_G502 = 101,
//Corsair range is 200-299
[Description("Corsair - Sabre")]
Corsair_Sabre = 200,
[Description("Corsair - M65")]
Corsair_M65 = 201,
[Description("Corsair - Katar")]
Corsair_Katar = 202,
//Razer range is 300-399
//Clevo range is 400-499
[Description("Clevo - Touchpad")]
Clevo_Touchpad = 400,
//Cooler Master range is 500-599
//Roccat range is 600-699
//Steelseries range is 700-799
[Description("SteelSeries - Rival 300")]
SteelSeries_Rival_300 = 700,
[Description("SteelSeries - Rival 300 HP OMEN Edition")]
SteelSeries_Rival_300_HP_OMEN_Edition = 701,
//Asus range is 900-999
[Description("Asus - Pugio")]
Asus_Pugio = 900
}
public enum KeycapType
{
[Description("Default")]
Default = 0,
[Description("Default (with Backglow)")]
Default_backglow = 1,
[Description("Default (Backglow only)")]
Default_backglow_only = 2,
[Description("Colorized")]
Colorized = 3,
[Description("Colorized (blank)")]
Colorized_blank = 4
}
public enum ApplicationDetectionMode
{
[Description("Windows Events (Default)")]
WindowsEvents = 0,
[Description("Foreground App Scan")]
ForegroroundApp = 1
}
public enum BitmapAccuracy
{
Best = 1,
Great = 3,
Good = 6,
Okay = 9,
Fine = 12
}
public class Configuration : Settings
{
//First Time Installs
public bool redist_first_time;
public bool logitech_first_time;
public bool corsair_first_time;
public bool razer_first_time;
public bool steelseries_first_time;
public bool dualshock_first_time;
public bool roccat_first_time;
//General Program Settings
public bool allow_peripheral_devices;
public bool allow_wrappers_in_background;
public bool allow_all_logitech_bitmaps;
private bool useVolumeAsBrightness = false;
[JsonProperty(PropertyName = "use_volume_as_brightness")]
public bool UseVolumeAsBrightness { get { return useVolumeAsBrightness; } set { useVolumeAsBrightness = value; InvokePropertyChanged(); } }
private float globalBrightness = 1.0f;
[JsonProperty(PropertyName = "global_brightness")]
public float GlobalBrightness { get { return globalBrightness; } set { globalBrightness = value; InvokePropertyChanged(); } }
private float keyboardBrightness = 1.0f;
[JsonProperty(PropertyName = "keyboard_brightness_modifier")]
public float KeyboardBrightness { get { return keyboardBrightness; } set { keyboardBrightness = value; InvokePropertyChanged(); } }
private float peripheralBrightness = 1.0f;
[JsonProperty(PropertyName = "peripheral_brightness_modifier")]
public float PeripheralBrightness { get { return peripheralBrightness; } set { peripheralBrightness = value; InvokePropertyChanged(); } }
private bool getDevReleases = false;
public bool GetDevReleases { get { return getDevReleases; } set { getDevReleases = value; InvokePropertyChanged(); } }
private bool highPriority = false;
public bool HighPriority { get { return highPriority; } set { highPriority = value; InvokePropertyChanged(); } }
private BitmapAccuracy bitmapAccuracy = BitmapAccuracy.Okay;
public BitmapAccuracy BitmapAccuracy { get { return bitmapAccuracy; } set { bitmapAccuracy = value; InvokePropertyChanged(); } }
public bool updates_check_on_start_up;
public bool start_silently;
public AppExitMode close_mode;
public MouseOrientationType mouse_orientation;
public PreferredKeyboard keyboard_brand;
public PreferredKeyboardLocalization keyboard_localization;
public PreferredMouse mouse_preference;
public KeycapType virtualkeyboard_keycap_type;
public ApplicationDetectionMode detection_mode;
public HashSet<String> excluded_programs;
public bool devices_disable_keyboard;
public bool devices_disable_mouse;
public bool devices_disable_headset;
public bool unified_hid_disabled = false;
public HashSet<Type> devices_disabled;
public bool OverlaysInPreview;
//Blackout and Night theme
public bool time_based_dimming_enabled;
public bool time_based_dimming_affect_games;
public int time_based_dimming_start_hour;
public int time_based_dimming_start_minute;
public int time_based_dimming_end_hour;
public int time_based_dimming_end_minute;
public bool nighttime_enabled;
public int nighttime_start_hour;
public int nighttime_start_minute;
public int nighttime_end_hour;
public int nighttime_end_minute;
// Idle Effects
public IdleEffects idle_type;
public int idle_delay;
public float idle_speed;
public Color idle_effect_primary_color;
public Color idle_effect_secondary_color;
public int idle_amount;
public float idle_frequency;
public VariableRegistry VarRegistry;
//Overlay Settings
public VolumeOverlaySettings volume_overlay_settings;
public SkypeOverlaySettings skype_overlay_settings;
public List<string> ProfileOrder { get; set; } = new List<string>();
public Configuration()
{
//First Time Installs
redist_first_time = true;
logitech_first_time = true;
corsair_first_time = true;
razer_first_time = true;
steelseries_first_time = true;
dualshock_first_time = true;
//General Program Settings
allow_peripheral_devices = true;
UseVolumeAsBrightness = false;
allow_wrappers_in_background = true;
allow_all_logitech_bitmaps = true;
GlobalBrightness = 1.0f;
KeyboardBrightness = 1.0f;
peripheralBrightness = 1.0f;
updates_check_on_start_up = true;
start_silently = false;
close_mode = AppExitMode.Ask;
mouse_orientation = MouseOrientationType.RightHanded;
keyboard_brand = PreferredKeyboard.None;
keyboard_localization = PreferredKeyboardLocalization.None;
mouse_preference = PreferredMouse.None;
virtualkeyboard_keycap_type = KeycapType.Default;
detection_mode = ApplicationDetectionMode.WindowsEvents;
excluded_programs = new HashSet<string>();
//additional_profiles = new Dictionary<string, GenericApplicationProfileManager>();
devices_disable_keyboard = false;
devices_disable_mouse = false;
devices_disable_headset = false;
devices_disabled = new HashSet<Type>();
devices_disabled.Add(typeof(Devices.Dualshock.DualshockDevice));
devices_disabled.Add(typeof(Devices.AtmoOrbDevice.AtmoOrbDevice));
OverlaysInPreview = false;
//Blackout and Night theme
time_based_dimming_enabled = false;
time_based_dimming_affect_games = false;
time_based_dimming_start_hour = 21;
time_based_dimming_start_minute = 0;
time_based_dimming_end_hour = 8;
time_based_dimming_end_minute = 0;
nighttime_enabled = false;
nighttime_start_hour = 20;
nighttime_start_minute = 0;
nighttime_end_hour = 7;
nighttime_end_minute = 0;
//// Idle Effects
idle_type = IdleEffects.None;
idle_delay = 5;
idle_speed = 1.0f;
idle_effect_primary_color = Color.FromArgb(0, 255, 0);
idle_effect_secondary_color = Color.FromArgb(0, 0, 0);
idle_amount = 5;
idle_frequency = 2.5f;
//Overlay Settings
volume_overlay_settings = new VolumeOverlaySettings();
skype_overlay_settings = new SkypeOverlaySettings();
//ProfileOrder = new List<string>(ApplicationProfiles.Keys);
VarRegistry = new VariableRegistry();
}
}
public class ConfigManager
{
private static string ConfigPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Aurora", "Config");
private const string ConfigExtension = ".json";
private static long _last_save_time = 0L;
private readonly static long _save_interval = 1000L;
public static Configuration Load()
{
var configPath = ConfigPath + ConfigExtension;
if (!File.Exists(configPath))
return CreateDefaultConfigurationFile();
string content = File.ReadAllText(configPath, Encoding.UTF8);
if (String.IsNullOrWhiteSpace(content))
return CreateDefaultConfigurationFile();
Configuration config = JsonConvert.DeserializeObject<Configuration>(content, new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace, TypeNameHandling = TypeNameHandling.All, SerializationBinder = Aurora.Utils.JSONUtils.SerializationBinder, Error = DeserializeErrorHandler });
if (!config.unified_hid_disabled)
{
config.devices_disabled.Add(typeof(Devices.UnifiedHID.UnifiedHIDDevice));
config.unified_hid_disabled = true;
}
return config;
}
private static void DeserializeErrorHandler(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs e)
{
if (e.ErrorContext.Error.Message.Contains("Aurora.Devices.SteelSeriesHID.SteelSeriesHIDDevice") && e.CurrentObject is HashSet<Type> dd)
{
dd.Add(typeof(Aurora.Devices.UnifiedHID.UnifiedHIDDevice));
e.ErrorContext.Handled = true;
}
}
public static void Save(Configuration configuration)
{
long current_time = Utils.Time.GetMillisecondsSinceEpoch();
if (_last_save_time + _save_interval > current_time)
return;
else
_last_save_time = current_time;
var configPath = ConfigPath + ConfigExtension;
string content = JsonConvert.SerializeObject(configuration, Formatting.Indented, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All, Binder = Aurora.Utils.JSONUtils.SerializationBinder });
Directory.CreateDirectory(System.IO.Path.GetDirectoryName(configPath));
File.WriteAllText(configPath, content, Encoding.UTF8);
}
private static Configuration CreateDefaultConfigurationFile()
{
Configuration config = new Configuration();
var configData = JsonConvert.SerializeObject(config, Formatting.Indented, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All, Binder = Aurora.Utils.JSONUtils.SerializationBinder });
var configPath = ConfigPath + ConfigExtension;
Directory.CreateDirectory(System.IO.Path.GetDirectoryName(configPath));
File.WriteAllText(configPath, configData, Encoding.UTF8);
return config;
}
}
}
| 34.314879 | 318 | 0.596148 | [
"MIT"
] | DarthAffe/Aurora | Project-Aurora/Project-Aurora/Settings/Configuration.cs | 19,260 | C# |
using _07.MilitaryElite.Enums;
using _07.MilitaryElite.Interfaces;
using System.Collections.Generic;
using System.Text;
namespace _07.MilitaryElite.Models
{
public class Engineer : SpecialisedSoldier, IEngineer
{
private List<IRepair> repairs;
public Engineer(string id, string firstName, string lastName, decimal salary, Corps corps)
: base(id, firstName, lastName, salary, corps)
{
this.repairs = new List<IRepair>();
}
public IReadOnlyCollection<IRepair> Repairs => this.repairs.AsReadOnly();
public void AddRepair(IRepair repair)
{
this.repairs.Add(repair);
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(base.ToString());
sb.AppendLine("Repairs:");
foreach (IRepair repair in this.Repairs)
{
sb.AppendLine($" {repair}");
}
return sb.ToString().TrimEnd();
}
}
}
| 25.804878 | 99 | 0.589792 | [
"MIT"
] | LyubomirRashkov/Software-University-SoftUni | C#OOP/ProjectsAndSolutionsFromLecturesAndExercises/03ex-InterfacesAndAbstraction/07.MilitaryElite/Models/Engineer.cs | 1,060 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using FakeItEasy;
using Squidex.Domain.Apps.Core.Contents;
using Squidex.Domain.Apps.Core.Schemas;
using Squidex.Domain.Apps.Entities.Contents.Repositories;
using Squidex.Domain.Apps.Entities.Schemas;
using Squidex.Domain.Apps.Entities.TestHelpers;
using Squidex.Infrastructure;
using Squidex.Infrastructure.Reflection;
using Squidex.Infrastructure.Security;
using Squidex.Shared;
using Squidex.Shared.Identity;
using Xunit;
namespace Squidex.Domain.Apps.Entities.Contents.Queries
{
public class ContentQueryServiceTests
{
private readonly IAppProvider appProvider = A.Fake<IAppProvider>();
private readonly IContentEnricher contentEnricher = A.Fake<IContentEnricher>();
private readonly IContentRepository contentRepository = A.Fake<IContentRepository>();
private readonly IContentLoader contentVersionLoader = A.Fake<IContentLoader>();
private readonly ISchemaEntity schema;
private readonly NamedId<DomainId> appId = NamedId.Of(DomainId.NewGuid(), "my-app");
private readonly NamedId<DomainId> schemaId = NamedId.Of(DomainId.NewGuid(), "my-schema");
private readonly ContentData contentData = new ContentData();
private readonly ContentQueryParser queryParser = A.Fake<ContentQueryParser>();
private readonly ContentQueryService sut;
public ContentQueryServiceTests()
{
var schemaDef =
new Schema(schemaId.Name)
.SetScripts(new SchemaScripts { Query = "<query-script>" });
schema = Mocks.Schema(appId, schemaId, schemaDef);
SetupEnricher();
A.CallTo(() => appProvider.GetSchemaAsync(appId.Id, schemaId.Name, A<bool>._))
.Returns(schema);
A.CallTo(() => appProvider.GetSchemasAsync(appId.Id))
.Returns(new List<ISchemaEntity> { schema });
A.CallTo(() => queryParser.ParseAsync(A<Context>._, A<Q>._, A<ISchemaEntity?>._))
.ReturnsLazily(c => Task.FromResult(c.GetArgument<Q>(1)!));
sut = new ContentQueryService(
appProvider,
contentEnricher,
contentRepository,
contentVersionLoader,
queryParser);
}
[Fact]
public async Task Should_get_schema_from_guid_string()
{
var input = schemaId.Id.ToString();
var requestContext = CreateContext();
A.CallTo(() => appProvider.GetSchemaAsync(appId.Id, schemaId.Id, true))
.Returns(schema);
var result = await sut.GetSchemaOrThrowAsync(requestContext, input);
Assert.Equal(schema, result);
}
[Fact]
public async Task Should_get_schema_from_name()
{
var input = schemaId.Name;
var requestContext = CreateContext();
A.CallTo(() => appProvider.GetSchemaAsync(appId.Id, schemaId.Name, true))
.Returns(schema);
var result = await sut.GetSchemaOrThrowAsync(requestContext, input);
Assert.Equal(schema, result);
}
[Fact]
public async Task Should_throw_notfound_exception_if_schema_to_get_not_found()
{
var requestContext = CreateContext();
A.CallTo(() => appProvider.GetSchemaAsync(A<DomainId>._, A<string>._, true))
.Returns((ISchemaEntity?)null);
await Assert.ThrowsAsync<DomainObjectNotFoundException>(() => sut.GetSchemaOrThrowAsync(requestContext, schemaId.Name));
}
[Fact]
public async Task Should_throw_permission_exception_if_content_to_find_is_restricted()
{
var requestContext = CreateContext(allowSchema: false);
var content = CreateContent(DomainId.NewGuid());
A.CallTo(() => contentRepository.FindContentAsync(requestContext.App, schema, content.Id, A<SearchScope>._))
.Returns(CreateContent(DomainId.NewGuid()));
await Assert.ThrowsAsync<DomainForbiddenException>(() => sut.FindAsync(requestContext, schemaId.Name, content.Id));
}
[Fact]
public async Task Should_return_null_if_content_by_id_dannot_be_found()
{
var requestContext = CreateContext();
var content = CreateContent(DomainId.NewGuid());
A.CallTo(() => contentRepository.FindContentAsync(requestContext.App, schema, content.Id, A<SearchScope>._))
.Returns<IContentEntity?>(null);
Assert.Null(await sut.FindAsync(requestContext, schemaId.Name, content.Id));
}
[Theory]
[InlineData(1, 0, SearchScope.All)]
[InlineData(1, 1, SearchScope.All)]
[InlineData(0, 1, SearchScope.All)]
[InlineData(0, 0, SearchScope.Published)]
public async Task Should_return_content_by_id(int isFrontend, int unpublished, SearchScope scope)
{
var requestContext = CreateContext(isFrontend, isUnpublished: unpublished);
var content = CreateContent(DomainId.NewGuid());
A.CallTo(() => contentRepository.FindContentAsync(requestContext.App, schema, content.Id, scope))
.Returns(content);
var result = await sut.FindAsync(requestContext, schemaId.Name, content.Id);
AssertContent(content, result);
}
[Fact]
public async Task Should_return_content_by_id_and_version()
{
var requestContext = CreateContext();
var content = CreateContent(DomainId.NewGuid());
A.CallTo(() => contentVersionLoader.GetAsync(appId.Id, content.Id, 13))
.Returns(content);
var result = await sut.FindAsync(requestContext, schemaId.Name, content.Id, 13);
AssertContent(content, result);
}
[Fact]
public async Task Should_throw_exception_if_user_has_no_permission_to_query_content()
{
var requestContext = CreateContext(allowSchema: false);
await Assert.ThrowsAsync<DomainForbiddenException>(() => sut.QueryAsync(requestContext, schemaId.Name, Q.Empty));
}
[Theory]
[InlineData(1, 0, SearchScope.All)]
[InlineData(1, 1, SearchScope.All)]
[InlineData(0, 1, SearchScope.All)]
[InlineData(0, 0, SearchScope.Published)]
public async Task Should_query_contents(int isFrontend, int unpublished, SearchScope scope)
{
var requestContext = CreateContext(isFrontend, isUnpublished: unpublished);
var content1 = CreateContent(DomainId.NewGuid());
var content2 = CreateContent(DomainId.NewGuid());
var q = Q.Empty.WithReference(DomainId.NewGuid());
A.CallTo(() => contentRepository.QueryAsync(requestContext.App, schema, q, scope))
.Returns(ResultList.CreateFrom(5, content1, content2));
var result = await sut.QueryAsync(requestContext, schemaId.Name, q);
Assert.Equal(5, result.Total);
AssertContent(content1, result[0]);
AssertContent(content2, result[1]);
}
[Theory]
[InlineData(1, 0, SearchScope.All)]
[InlineData(1, 1, SearchScope.All)]
[InlineData(0, 1, SearchScope.All)]
[InlineData(0, 0, SearchScope.Published)]
public async Task Should_query_contents_by_ids(int isFrontend, int unpublished, SearchScope scope)
{
var requestContext = CreateContext(isFrontend, isUnpublished: unpublished);
var ids = Enumerable.Range(0, 5).Select(x => DomainId.NewGuid()).ToList();
var contents = ids.Select(CreateContent).ToList();
var q = Q.Empty.WithIds(ids);
A.CallTo(() => contentRepository.QueryAsync(requestContext.App,
A<List<ISchemaEntity>>.That.Matches(x => x.Count == 1), q, scope))
.Returns(ResultList.Create(5, contents));
var result = await sut.QueryAsync(requestContext, q);
Assert.Equal(5, result.Total);
for (var i = 0; i < contents.Count; i++)
{
AssertContent(contents[i], result[i]);
}
}
[Fact]
public async Task Should_query_contents_with_matching_permissions()
{
var requestContext = CreateContext(allowSchema: false);
var ids = Enumerable.Range(0, 5).Select(x => DomainId.NewGuid()).ToList();
var q = Q.Empty.WithIds(ids);
A.CallTo(() => contentRepository.QueryAsync(requestContext.App,
A<List<ISchemaEntity>>.That.Matches(x => x.Count == 0), q, SearchScope.All))
.Returns(ResultList.Create(0, ids.Select(CreateContent)));
var result = await sut.QueryAsync(requestContext, q);
Assert.Empty(result);
}
[Fact]
public async Task Should_query_contents_from_user_if_user_has_only_own_permission()
{
var requestContext = CreateContext(permissionId: Permissions.AppContentsReadOwn);
await sut.QueryAsync(requestContext, schemaId.Name, Q.Empty);
A.CallTo(() => contentRepository.QueryAsync(requestContext.App, schema,
A<Q>.That.Matches(x => Equals(x.CreatedBy, requestContext.User.Token())), SearchScope.Published))
.MustHaveHappened();
}
[Fact]
public async Task Should_query_all_contents_if_user_has_read_permission()
{
var requestContext = CreateContext(permissionId: Permissions.AppContentsRead);
await sut.QueryAsync(requestContext, schemaId.Name, Q.Empty);
A.CallTo(() => contentRepository.QueryAsync(requestContext.App, schema,
A<Q>.That.Matches(x => x.CreatedBy == null), SearchScope.Published))
.MustHaveHappened();
}
private void SetupEnricher()
{
A.CallTo(() => contentEnricher.EnrichAsync(A<IEnumerable<IContentEntity>>._, A<Context>._))
.ReturnsLazily(x =>
{
var input = x.GetArgument<IEnumerable<IContentEntity>>(0)!;
return Task.FromResult<IReadOnlyList<IEnrichedContentEntity>>(input.Select(c => SimpleMapper.Map(c, new ContentEntity())).ToList());
});
}
private Context CreateContext(
int isFrontend = 0,
int isUnpublished = 0,
bool allowSchema = true,
string permissionId = Permissions.AppContentsRead)
{
var claimsIdentity = new ClaimsIdentity();
var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
claimsIdentity.AddClaim(new Claim(OpenIdClaims.Subject, "user1"));
if (isFrontend == 1)
{
claimsIdentity.AddClaim(new Claim(OpenIdClaims.ClientId, DefaultClients.Frontend));
}
if (allowSchema)
{
var concretePermission = Permissions.ForApp(permissionId, appId.Name, schemaId.Name).Id;
claimsIdentity.AddClaim(new Claim(SquidexClaimTypes.Permissions, concretePermission));
}
return new Context(claimsPrincipal, Mocks.App(appId)).Clone(b => b.WithUnpublished(isUnpublished == 1));
}
private static void AssertContent(IContentEntity source, IEnrichedContentEntity? result)
{
Assert.NotNull(result);
Assert.NotSame(source, result);
Assert.Same(source.Data, result?.Data);
Assert.Equal(source.Id, result?.Id);
}
private IContentEntity CreateContent(DomainId id)
{
var content = new ContentEntity
{
Id = id,
Data = contentData,
SchemaId = schemaId,
Status = Status.Published
};
return content;
}
}
} | 37.951515 | 152 | 0.608991 | [
"MIT"
] | Jaben/squidex | backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Queries/ContentQueryServiceTests.cs | 12,526 | C# |
///\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\///
/// ///
/// File name : GunVisualiser.cs ///
/// ///
/// Author : Peter Phillips ///
/// ///
/// Date created : 14.05.2019 ///
/// ///
/// Last Modified : 14.05.2019 ///
/// ///
/// Brief : Script to control the colour and size of the gun visualiser. ///
/// ///
///\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\///
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GunVisualiser : MonoBehaviour
{
[SerializeField] public Transform[] _audioVisualiserBars; /// The array for our audio visualiser bars.
[SerializeField] private Transform[] _audioVisualiserShadow; /// The array for our audio visualiser shadow.
[SerializeField] private float _sizeMultiplier = 100000; /// Determines the amount by which the audio visualiser bars expand based on input.
// Samples = # of bands * 2^8.
[SerializeField] private int _numberOfSamples = 4096; /// Number of audio samples taken (determines frequency range for each frequency band).
[SerializeField] private FFTWindow _fftWindow; /// Different window options reduce signal leakage across frequency bands by different methods.
[SerializeField] private float _stepSize = .2f; /// The amount by which the lerp function will move what it's lerping (lower values give smoother/slower motion).
[SerializeField] private GameObject _maxBarParticle;
[SerializeField] private GameObject _player;
private float[] _spectrumData; /// An array for our audio spectrum data;
private float _previousScale = 0f; /// Used to compare current value to previous value;
private float _ringDistance = 3.9f; /// Distance between ring screens and map centre.
private float _screenHeight = .12f; /// Height of the ring screens.
void Start()
{
// Set the initial colours of the bars.
SetBarColours();
// Set our spectrum data array to our sample size.
_spectrumData = new float[_numberOfSamples];
}
private void SetBarColours()
{
// Loop through our array of bars and set them to different colours of the rainbow and position them in an arc around the map centre.
for (int i = 0; i < _audioVisualiserBars.Length; i++)
{
// Set rainbow colours.
Color _colour = Color.HSVToRGB(i * .875f / _audioVisualiserBars.Length, 1, 1);
// Set alpha.
_colour.a = 1f;
// Set colour (if using standard type shaders);
_audioVisualiserBars[i].GetComponent<Renderer>().material.color = _colour;
// Set tint colour (if using FX type shaders);
_audioVisualiserBars[i].GetComponent<Renderer>().material.SetColor("_TintColor", _colour);
// Repeat for the shadows.
_colour.a = .25f;
_audioVisualiserShadow[i].GetComponent<Renderer>().material.color = _colour;
_audioVisualiserShadow[i].GetComponent<Renderer>().material.SetColor("_TintColor", _colour);
//// Move the bars to the edge of the ring.
//_audioVisualiserBars[i].position += _audioVisualiserBars[i].up * (Vector3.Distance(_audioVisualiserBars[i].position, Vector3.zero) - _ringDistance);
//// Make the bars face the centre.
//_audioVisualiserBars[i].LookAt(Vector3.zero);
//// Flip the bars back up because we actually need their 'up' vectors facing the centre to see them.
//_audioVisualiserBars[i].Rotate(90f * Vector3.right);
//// Reapeat for the shadows.
//_audioVisualiserShadow[i].position += _audioVisualiserShadow[i].up * (Vector3.Distance(_audioVisualiserShadow[i].position, Vector3.zero) - _ringDistance);
//_audioVisualiserShadow[i].LookAt(Vector3.zero);
//_audioVisualiserShadow[i].Rotate(90f * Vector3.right);
}
}
void Update()
{
// Set the size of the bars.
SetBarSize();
}
private void SetBarSize()
{
// Put our spectrum data into our spectrum array accross all channels and using the window type we have selected in the inspector.
_player.GetComponent<AudioSource>().GetSpectrumData(_spectrumData, 0, _fftWindow);
// Loop through our audio visualiser bars and update their size.
for (int i = 0; i < _audioVisualiserBars.Length; i++)
{
// Linearly interpolate from the current size to the detected input size by our step size.
float lerpZ = Mathf.Lerp(_audioVisualiserBars[i].localScale.z, _spectrumData[i + 6] * _sizeMultiplier, _stepSize); /// The first 6 frequency bands have been omitted as they are largely affected by background noise.
float lerpZShadow = Mathf.Lerp(_audioVisualiserShadow[i].localScale.z, _spectrumData[i + 6] * _sizeMultiplier, _stepSize / 5);
// Update the size of each bar (only the z-scale is changing).
_audioVisualiserBars[i].localScale = new Vector3(_audioVisualiserBars[i].localScale.x, _audioVisualiserBars[i].localScale.y, Mathf.Clamp(lerpZ, 0, _screenHeight));
_audioVisualiserShadow[i].localScale = new Vector3(_audioVisualiserShadow[i].localScale.x,
_audioVisualiserShadow[i].localScale.y,
_audioVisualiserBars[i].localScale.z > _previousScale && _audioVisualiserBars[i].localScale.z >= _audioVisualiserShadow[i].localScale.z ? _audioVisualiserBars[i].localScale.z : Mathf.Clamp(lerpZShadow, 0, _screenHeight)); /// Shadow quickly jumps up but slowly moves down.
if (lerpZ >= _screenHeight)
{
GameObject _particle = Instantiate(_maxBarParticle, _audioVisualiserBars[i].position + Vector3.up * .25f, Quaternion.identity);
_particle.GetComponent<Renderer>().material.SetColor("_TintColor", _audioVisualiserBars[i].GetComponent<Renderer>().material.GetColor("_TintColor"));
Destroy(_particle, .2f);
}
// Update the scale tracker.
_previousScale = _audioVisualiserBars[i].localScale.z;
}
}
}
| 63.561404 | 337 | 0.558791 | [
"Apache-2.0"
] | Michael97/ShoutOut | ShoutOutVR/Assets/Scripts/GunVisualiser.cs | 7,248 | C# |
//#define KEEP_ARTIFACTS_FOR_INSPECTION
using System;
using System.Collections;
using System.IO;
using NUnit.Framework;
using Unity.AI.Navigation;
using Unity.AI.Navigation.Editor;
using UnityEditor;
#if !UNITY_2021_2_OR_NEWER
using UnityEditor.Experimental.SceneManagement;
#endif
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.SceneManagement;
using UnityEngine.TestTools;
using Object = UnityEngine.Object;
namespace Unity.AI.Navigation.Editor.Tests
{
[Category("PrefabsWithNavMeshComponents")]
class NavMeshSurfaceInPrefabVariantTests
{
const string k_AutoSaveKey = "AutoSave";
const string k_ParentFolder = "Assets";
const string k_TempFolderName = "TempPrefabVariants";
string m_TempFolder = k_ParentFolder + "/" + k_TempFolderName;
string m_PrefabPath;
string m_PrefabVariantPath;
string m_PreviousScenePath;
string m_TempScenePath;
int m_TestCounter;
const int k_GrayArea = 7;
const int k_BrownArea = 10;
const int k_RedArea = 18;
const int k_OrangeArea = 26;
const int k_YellowArea = 30;
const int k_PrefabDefaultArea = k_YellowArea;
[OneTimeSetUp]
public void OneTimeSetup()
{
AssetDatabase.DeleteAsset(m_TempFolder);
var folderGUID = AssetDatabase.CreateFolder(k_ParentFolder, k_TempFolderName);
m_TempFolder = AssetDatabase.GUIDToAssetPath(folderGUID);
SessionState.SetBool(k_AutoSaveKey, PrefabStageAutoSavingUtil.GetPrefabStageAutoSave());
PrefabStageAutoSavingUtil.SetPrefabStageAutoSave(false);
StageUtility.GoToMainStage();
m_PreviousScenePath = SceneManager.GetActiveScene().path;
m_TempScenePath = Path.Combine(m_TempFolder, "NavMeshSurfacePrefabVariantTestsScene.unity");
var tempScene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);
EditorSceneManager.SaveScene(tempScene, m_TempScenePath);
EditorSceneManager.OpenScene(m_TempScenePath);
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
PrefabStageAutoSavingUtil.SetPrefabStageAutoSave(SessionState.GetBool(k_AutoSaveKey, PrefabStageAutoSavingUtil.GetPrefabStageAutoSave()));
StageUtility.GoToMainStage();
EditorSceneManager.SaveScene(SceneManager.GetActiveScene());
if (string.IsNullOrEmpty(m_PreviousScenePath))
{
EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);
}
#if !KEEP_ARTIFACTS_FOR_INSPECTION
AssetDatabase.DeleteAsset(m_TempFolder);
#endif
}
[UnitySetUp]
public IEnumerator Setup()
{
var plane = GameObject.CreatePrimitive(PrimitiveType.Plane);
plane.name = "NavMeshSurfacePrefab" + (++m_TestCounter);
var surface = plane.AddComponent<NavMeshSurface>();
surface.collectObjects = CollectObjects.Children;
m_PrefabPath = Path.Combine(m_TempFolder, plane.name + ".prefab");
m_PrefabVariantPath = Path.Combine(m_TempFolder, plane.name + "Variant.prefab");
var planePrefab = PrefabUtility.SaveAsPrefabAsset(plane, m_PrefabPath);
Object.DestroyImmediate(plane);
AssetDatabase.OpenAsset(planePrefab);
var theOriginalPrefabStage = PrefabStageUtility.GetCurrentPrefabStage();
var theOriginalPrefabSurface = theOriginalPrefabStage.prefabContentsRoot.GetComponent<NavMeshSurface>();
yield return BakeNavMeshAsync(() => theOriginalPrefabSurface, k_PrefabDefaultArea);
PrefabSavingUtil.SavePrefab(theOriginalPrefabStage);
StageUtility.GoToMainStage();
var instanceForVariant = PrefabUtility.InstantiatePrefab(planePrefab) as GameObject;
PrefabUtility.SaveAsPrefabAsset(instanceForVariant, m_PrefabVariantPath);
#if !KEEP_ARTIFACTS_FOR_INSPECTION
Object.DestroyImmediate(instanceForVariant);
#endif
NavMesh.RemoveAllNavMeshData();
yield return null;
}
[UnityTearDown]
public IEnumerator TearDown()
{
StageUtility.GoToMainStage();
yield return null;
}
[UnityTest]
public IEnumerator NavMeshSurfacePrefabVariant_WhenFreshAndRebaked_ParentAssetUnchanged()
{
var theOriginalPrefab = AssetDatabase.LoadAssetAtPath<GameObject>(m_PrefabPath);
AssetDatabase.OpenAsset(theOriginalPrefab);
var theOriginalPrefabStage = PrefabStageUtility.GetCurrentPrefabStage();
var theOriginalPrefabSurface = theOriginalPrefabStage.prefabContentsRoot.GetComponent<NavMeshSurface>();
var theOriginalPrefabNavMeshData = theOriginalPrefabSurface.navMeshData;
var theOriginalPrefabAssetPath = AssetDatabase.GetAssetPath(theOriginalPrefabSurface.navMeshData);
Assert.IsTrue(theOriginalPrefabNavMeshData != null, "Original prefab must have some NavMeshData.");
Assert.IsTrue(File.Exists(theOriginalPrefabAssetPath), "NavMeshData file must exist for the original prefab. ({0})", theOriginalPrefabAssetPath);
var prefabVariant = AssetDatabase.LoadAssetAtPath<GameObject>(m_PrefabVariantPath);
AssetDatabase.OpenAsset(prefabVariant);
var prefabVariantStage = PrefabStageUtility.GetCurrentPrefabStage();
var prefabVariantSurface = prefabVariantStage.prefabContentsRoot.GetComponent<NavMeshSurface>();
var initialVariantNavMeshData = prefabVariantSurface.navMeshData;
var initialVariantAssetPath = AssetDatabase.GetAssetPath(prefabVariantSurface.navMeshData);
Assert.AreEqual(theOriginalPrefabNavMeshData, initialVariantNavMeshData, "Fresh variant must have the same NavMeshData as the original prefab.");
Assert.IsTrue(initialVariantNavMeshData != null, "Prefab must have some NavMeshData.");
Assert.IsTrue(File.Exists(initialVariantAssetPath), "NavMeshData file must exist. ({0})", initialVariantAssetPath);
yield return BakeNavMeshAsync(() => prefabVariantSurface, k_GrayArea);
Assert.IsTrue(initialVariantNavMeshData != null, "The initial NavMeshData (from original prefab) must still exist immediately after prefab variant re-bake.");
Assert.IsTrue(File.Exists(initialVariantAssetPath), "The initial NavMeshData file (from original prefab) must exist after prefab variant re-bake. ({0})", initialVariantAssetPath);
Assert.IsTrue(prefabVariantSurface.navMeshData != null, "NavMeshSurface must have NavMeshData after baking.");
var unsavedRebakedNavMeshData = prefabVariantSurface.navMeshData;
yield return BakeNavMeshAsync(() => prefabVariantSurface, k_BrownArea);
Assert.IsTrue(unsavedRebakedNavMeshData == null, "An unsaved NavMeshData should not exist after a re-bake.");
Assert.IsTrue(prefabVariantSurface.navMeshData != null, "NavMeshSurface must have NavMeshData after baking.");
PrefabSavingUtil.SavePrefab(prefabVariantStage);
var theNewVariantNavMeshData = prefabVariantSurface.navMeshData;
var theNewVariantAssetPath = AssetDatabase.GetAssetPath(theNewVariantNavMeshData);
Assert.IsTrue(File.Exists(theNewVariantAssetPath), "Variant's own NavMeshData exists in a file after saving. ({0})", theNewVariantAssetPath);
Assert.IsTrue(File.Exists(theOriginalPrefabAssetPath), "NavMeshData file of the original prefab still exists after saving the variant. ({0})", theOriginalPrefabAssetPath);
Assert.IsTrue(theOriginalPrefabNavMeshData != null, "Original prefab must still have NavMeshData.");
StageUtility.GoToMainStage();
yield return null;
}
[UnityTest]
public IEnumerator NavMeshSurfacePrefabVariant_WhenCustomizedAndRebaked_OldAssetDiscardedAndParentAssetUnchanged()
{
var prefabVariant = AssetDatabase.LoadAssetAtPath<GameObject>(m_PrefabVariantPath);
var theOriginalPrefabPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(prefabVariant);
var theOriginalPrefab = AssetDatabase.LoadAssetAtPath<GameObject>(theOriginalPrefabPath);
AssetDatabase.OpenAsset(theOriginalPrefab);
var theOriginalPrefabStage = PrefabStageUtility.GetCurrentPrefabStage();
var theOriginalPrefabSurface = theOriginalPrefabStage.prefabContentsRoot.GetComponent<NavMeshSurface>();
var theOriginalPrefabNavMeshData = theOriginalPrefabSurface.navMeshData;
var theOriginalPrefabAssetPath = AssetDatabase.GetAssetPath(theOriginalPrefabSurface.navMeshData);
Assert.IsTrue(theOriginalPrefabNavMeshData != null, "Original prefab must have some NavMeshData.");
Assert.IsTrue(File.Exists(theOriginalPrefabAssetPath), "NavMeshData file must exist for the original prefab. ({0})", theOriginalPrefabAssetPath);
AssetDatabase.OpenAsset(prefabVariant);
var prefabVariantStage = PrefabStageUtility.GetCurrentPrefabStage();
var prefabVariantSurface = prefabVariantStage.prefabContentsRoot.GetComponent<NavMeshSurface>();
yield return BakeNavMeshAsync(() => prefabVariantSurface, k_GrayArea);
PrefabSavingUtil.SavePrefab(prefabVariantStage);
var modifiedVariantNavMeshData = prefabVariantSurface.navMeshData;
var modifiedVariantAssetPath = AssetDatabase.GetAssetPath(prefabVariantSurface.navMeshData);
Assert.IsTrue(modifiedVariantNavMeshData != null, "Prefab must have some NavMeshData.");
Assert.IsTrue(File.Exists(modifiedVariantAssetPath), "NavMeshData file for modifier variant must exist. ({0})", modifiedVariantAssetPath);
Assert.AreNotEqual(theOriginalPrefabNavMeshData, modifiedVariantNavMeshData, "Modified variant must have a NavMeshData different than that of the original prefab.");
yield return BakeNavMeshAsync(() => prefabVariantSurface, k_OrangeArea);
Assert.IsTrue(modifiedVariantNavMeshData != null, "The initial NavMeshData of a modified variant must still exist immediately after prefab variant re-bake.");
Assert.IsTrue(File.Exists(modifiedVariantAssetPath), "The initial NavMeshData file of a modified variant must exist after prefab variant re-bake. ({0})", modifiedVariantAssetPath);
Assert.IsTrue(prefabVariantSurface.navMeshData != null, "NavMeshSurface must have NavMeshData after baking.");
var unsavedRebakedNavMeshData = prefabVariantSurface.navMeshData;
yield return BakeNavMeshAsync(() => prefabVariantSurface, k_RedArea);
Assert.IsTrue(unsavedRebakedNavMeshData == null, "An unsaved NavMeshData should not exist after a re-bake.");
Assert.IsTrue(prefabVariantSurface.navMeshData != null, "NavMeshSurface must have NavMeshData after baking.");
PrefabSavingUtil.SavePrefab(prefabVariantStage);
var theNewVariantNavMeshData = prefabVariantSurface.navMeshData;
var theNewVariantAssetPath = AssetDatabase.GetAssetPath(theNewVariantNavMeshData);
Assert.IsTrue(modifiedVariantNavMeshData == null, "Initial NavMeshData of the modified variant must no longer exist after saving the variant.");
// ReSharper disable once HeuristicUnreachableCode - modifiedVariantNavMeshData is affected by BakeNavMeshAsync()
Assert.IsFalse(File.Exists(modifiedVariantAssetPath), "Initial NavMeshData file of the modified and saved variant must no longer exist after saving the variant. ({0})", modifiedVariantAssetPath);
Assert.IsTrue(File.Exists(theNewVariantAssetPath), "Variant's own NavMeshData exists in a file after saving. ({0})", theNewVariantAssetPath);
Assert.IsTrue(File.Exists(theOriginalPrefabAssetPath), "NavMeshData file of the original prefab still exists after saving the variant. ({0})", theOriginalPrefabAssetPath);
Assert.AreNotEqual(theOriginalPrefabNavMeshData, theNewVariantNavMeshData, "Re-baked modified variant must have a NavMeshData different than that of the original prefab.");
StageUtility.GoToMainStage();
yield return null;
}
static IEnumerator BakeNavMeshAsync(Func<NavMeshSurface> getSurface, int defaultArea)
{
var surface = getSurface();
surface.defaultArea = defaultArea;
NavMeshAssetManager.instance.StartBakingSurfaces(new Object[] {surface});
yield return new WaitWhile(() => NavMeshAssetManager.instance.IsSurfaceBaking(surface));
}
}
} | 55.277311 | 208 | 0.71169 | [
"MIT"
] | needle-mirror/com.unity.ai.navigation | Tests/Editor/NavMeshSurfaceInPrefabVariantTests.cs | 13,158 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="WhenCreatingAFeatureWithMetaInfo.cs" company="PicklesDoc">
// Copyright 2011 Jeffrey Cameron
// Copyright 2012-present PicklesDoc team and community contributors
//
//
// 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.IO;
using System.IO.Abstractions;
using NFluent;
using NUnit.Framework;
using PicklesDoc.Pickles.DirectoryCrawler;
using PicklesDoc.Pickles.DocumentationBuilders.Json;
using PicklesDoc.Pickles.ObjectModel;
namespace PicklesDoc.Pickles.Test.Formatters.JSON
{
public class WhenCreatingAFeatureWithMetaInfo : BaseFixture
{
private const string RelativePath = @"AcceptanceTest";
private string RootPath { get; }
private const string FeaturePath = @"AdvancedFeature.feature";
private FeatureNode featureDirectoryNode;
private IFileInfo featureFileInfo;
private JsonFeatureWithMetaInfo featureWithMeta;
private Feature testFeature;
public WhenCreatingAFeatureWithMetaInfo()
{
RootPath =FileSystem.Path.Combine(FileSystemPrefix,"AcceptanceTest");
}
public void Setup()
{
this.testFeature = new Feature { Name = "Test" };
this.featureFileInfo = this.FileSystem.FileInfo.FromFileName(FileSystem.Path.Combine(RootPath, FeaturePath));
this.featureDirectoryNode = new FeatureNode(this.featureFileInfo, RelativePath, this.testFeature);
this.featureWithMeta = new JsonFeatureWithMetaInfo(this.featureDirectoryNode, new LanguageServicesRegistry());
}
[Test]
public void ItShouldContainTheFeature()
{
this.Setup();
Check.That(this.featureWithMeta.Feature).IsNotNull();
Check.That(this.featureWithMeta.Feature.Name).IsEqualTo("Test");
}
[Test]
public void ItShouldContainTheRelativePath()
{
this.Setup();
Check.That(this.featureWithMeta.RelativeFolder).IsEqualTo(RelativePath);
}
}
}
| 38.081081 | 122 | 0.64088 | [
"Apache-2.0"
] | CoverGo/pickles | src/Pickles.Test/Formatters/JSON/WhenCreatingAFeatureWithMetaInfo.cs | 2,820 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SuperSocket.ProtoBase;
namespace SuperSocket.SocketBase.Protocol
{
/// <summary>
/// The interface for protocol factory
/// </summary>
/// <typeparam name="TPackageInfo">The type of the package information.</typeparam>
public interface IProtocolFactory<out TPackageInfo> : IReceiveFilterFactory<TPackageInfo>
where TPackageInfo : IPackageInfo
{
}
}
| 25.5 | 93 | 0.733333 | [
"Apache-2.0"
] | cnsuhao/SuperSocket | SocketBase/Protocol/IProtocolFactory.cs | 512 | C# |
namespace NovoProject
{
partial class delete_loja
{
/// <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.listBox1 = new System.Windows.Forms.ListBox();
this.button1 = new System.Windows.Forms.Button();
this.checkBox1 = new System.Windows.Forms.CheckBox();
this.SuspendLayout();
//
// listBox1
//
this.listBox1.FormattingEnabled = true;
this.listBox1.Location = new System.Drawing.Point(22, 12);
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(120, 407);
this.listBox1.TabIndex = 0;
//
// button1
//
this.button1.Location = new System.Drawing.Point(161, 140);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 1;
this.button1.Text = "Deletar";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// checkBox1
//
this.checkBox1.AutoSize = true;
this.checkBox1.Location = new System.Drawing.Point(169, 208);
this.checkBox1.Name = "checkBox1";
this.checkBox1.Size = new System.Drawing.Size(67, 17);
this.checkBox1.TabIndex = 2;
this.checkBox1.Text = "Confirma";
this.checkBox1.UseVisualStyleBackColor = true;
//
// delete_loja
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(426, 447);
this.Controls.Add(this.checkBox1);
this.Controls.Add(this.button1);
this.Controls.Add(this.listBox1);
this.Name = "delete_loja";
this.Text = "delete_loja";
this.Load += new System.EventHandler(this.delete_loja_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ListBox listBox1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.CheckBox checkBox1;
}
} | 37.302326 | 107 | 0.560474 | [
"MIT"
] | PotatoMexicano/Estoque-de-Produtos | NovoProject/delete_loja.Designer.cs | 3,210 | C# |
using System;
using System.Collections.Generic;
namespace Problem0025
{
/// <summary>
/// The Fibonacci sequence is defined by the recurrence relation:
/// Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
/// Hence the first 12 terms will be:
/// F1 = 1
/// F2 = 1
/// F3 = 2
/// F4 = 3
/// F5 = 5
/// F6 = 8
/// F7 = 13
/// F8 = 21
/// F9 = 34
/// F10 = 55
/// F11 = 89
/// F12 = 144
/// The 12th term, F12, is the first term to contain three digits.
/// What is the index of the first term in the Fibonacci sequence to contain 1000 digits?
/// </summary>
class Program
{
static void Main(string[] args)
{
List<int> lst1 = new List<int>();
List<int> lst2 = new List<int>();
lst1.Add(1);
lst2.Add(1);
int i = 2;
bool iseven = false;
while (lst1.Count<1000 && lst2.Count < 1000)
{
if (iseven)
{
int j = 0;
int m = 0;
for (; j < lst1.Count && j<lst2.Count; j++)
{
int k = lst1[j] + lst2[j] + m;
if (k >= 10)
{
lst1[j] = k - 10;
m = 1;
}
else
{
lst1[j] = k;
m = 0;
}
}
while (j<lst1.Count)
{
int k = lst1[j] + m;
if (k >= 10)
{
lst1[j] = k - 10;
m = 1;
}
else
{
lst1[j] = k;
m = 0;
}
j++;
}
while (j < lst2.Count)
{
int k = lst2[j] + m;
if (k >= 10)
{
lst1.Add(k - 10);
m = 1;
}
else
{
lst1.Add(k);
m = 0;
}
j++;
}
if (m > 0)
{
lst1.Add(m);
}
}
else
{
int j = 0;
int m = 0;
for (; j < lst1.Count && j < lst2.Count; j++)
{
int k = lst1[j] + lst2[j] + m;
if (k >= 10)
{
lst2[j] = k - 10;
m = 1;
}
else
{
lst2[j] = k;
m = 0;
}
}
while (j < lst2.Count)
{
int k = lst2[j] + m;
if (k >= 10)
{
lst2[j] = k - 10;
m = 1;
}
else
{
lst2[j] = k;
m = 0;
}
j++;
}
while (j < lst1.Count)
{
int k = lst1[j] + m;
if (k >= 10)
{
lst2.Add(k - 10);
m = 1;
}
else
{
lst2.Add(k);
m = 0;
}
j++;
}
if (m>0)
{
lst2.Add(m);
}
}
iseven = !iseven;
i++;
}
Console.WriteLine(i);
}
}
}
| 29.194805 | 93 | 0.204626 | [
"Apache-2.0"
] | kosmos-zhang/projecteulernet | csharp/Problem0025/Program.cs | 4,502 | C# |
using System;
using KSerialization;
using UnityEngine;
namespace EasyFarming
{
// Token: 0x02000014 RID: 20
[SerializationConfig(1)]
public class WildPlantablePlot : PlantablePlot, ISaveLoadable, IEffectDescriptor, IGameObjectEffectDescriptor
{
// Token: 0x0600001B RID: 27 RVA: 0x000031CC File Offset: 0x000013CC
protected virtual void SyncPriority(PrioritySetting setting)
{
Prioritizable com = base.GetComponent<Prioritizable>();
if (com.GetMasterPriority() != setting)
{
com.SetMasterPriority(setting);
}
if (base.occupyingObject != null)
{
Prioritizable com2 = base.occupyingObject.GetComponent<Prioritizable>();
if (com2 != null && com2.GetMasterPriority() != setting)
{
com2.SetMasterPriority(com.GetMasterPriority());
}
}
}
// Token: 0x0600001C RID: 28 RVA: 0x0000322C File Offset: 0x0000142C
protected override void OnSpawn()
{
KPrefabID temp = base.plant;
base.plant = null;
base.OnSpawn();
if (temp != null)
{
base.plant = temp;
this.SetOccupyInternal(base.plant.gameObject);
}
this.autoReplaceEntity = false;
Components.PlantablePlots.Add(this);
Prioritizable component = base.GetComponent<Prioritizable>();
component.onPriorityChanged = (Action<PrioritySetting>)Delegate.Combine(component.onPriorityChanged, new Action<PrioritySetting>(this.SyncPriority));
}
// Token: 0x0600001D RID: 29 RVA: 0x000032A8 File Offset: 0x000014A8
public override void OrderRemoveOccupant()
{
if (base.Occupant != null)
{
Uprootable com = base.Occupant.GetComponent<Uprootable>();
if (com != null)
{
com.MarkForUproot(true);
}
}
}
// Token: 0x0600001E RID: 30 RVA: 0x000032DC File Offset: 0x000014DC
public override GameObject SpawnOccupyingObject(GameObject go)
{
PlantableSeed ps = go.GetComponent<PlantableSeed>();
if (ps == null)
{
return null;
}
Vector3 poscbc = Grid.CellToPosCBC(Grid.PosToCell(this), this.plantLayer);
GameObject pt = GameUtil.KInstantiate(Assets.GetPrefab(ps.PlantID), poscbc, this.plantLayer, null, 0);
pt.SetActive(true);
base.plant = pt.GetComponent<KPrefabID>();
this.SetOccupyInternal(pt);
UprootedMonitor up = pt.GetComponent<UprootedMonitor>();
if (up)
{
up.canBeUprooted = false;
}
this.autoReplaceEntity = false;
Prioritizable com = base.GetComponent<Prioritizable>();
if (com != null)
{
Prioritizable com2 = pt.GetComponent<Prioritizable>();
if (com2 != null)
{
com2.SetMasterPriority(com.GetMasterPriority());
Prioritizable prioritizable = com2;
prioritizable.onPriorityChanged = (Action<PrioritySetting>)Delegate.Combine(prioritizable.onPriorityChanged, new Action<PrioritySetting>(this.SyncPriority));
}
}
return pt;
}
// Token: 0x0600001F RID: 31 RVA: 0x000033AC File Offset: 0x000015AC
protected virtual void SetOccupyInternal(GameObject go)
{
base.occupyingObject = go;
HarvestDesignatable po = go.GetComponent<HarvestDesignatable>();
if (po != null)
{
po.SetHarvestWhenReady(true);
}
}
// Token: 0x04000012 RID: 18
protected const int OccupyObjHash = -216549700;
}
}
| 30.775701 | 163 | 0.684786 | [
"MIT"
] | ekfvoddl3536/OniMods | decompiled/src/EasyFarming/WildPlantablePlot.cs | 3,295 | C# |
namespace UltimateTrivia.Application.Game.TransitionData
{
public class GameStartedData
{
public int Rounds { get; set; }
public int AnswerDuration { get; set; }
}
} | 24.25 | 57 | 0.659794 | [
"MIT"
] | fabiobaser/Ultimate-Trivia | Server/UltimateTrivia/Application/Game/TransitionData/GameStartedData.cs | 196 | C# |
#pragma checksum "..\..\..\Controls\LargeChatPlayer.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "A281DFC076D7342203533875E4E5D338"
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18444
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms.Integration;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
namespace LegendaryClient.Controls {
/// <summary>
/// LargeChatPlayer
/// </summary>
public partial class LargeChatPlayer : System.Windows.Controls.UserControl, System.Windows.Markup.IComponentConnector {
#line 9 "..\..\..\Controls\LargeChatPlayer.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Image ProfileImage;
#line default
#line hidden
#line 11 "..\..\..\Controls\LargeChatPlayer.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Image UsingLegendary;
#line default
#line hidden
#line 13 "..\..\..\Controls\LargeChatPlayer.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label LevelLabel;
#line default
#line hidden
#line 20 "..\..\..\Controls\LargeChatPlayer.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label PlayerName;
#line default
#line hidden
#line 22 "..\..\..\Controls\LargeChatPlayer.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label PlayerLeague;
#line default
#line hidden
#line 24 "..\..\..\Controls\LargeChatPlayer.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label PlayerWins;
#line default
#line hidden
#line 27 "..\..\..\Controls\LargeChatPlayer.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.TextBlock PlayerStatus;
#line default
#line hidden
#line 30 "..\..\..\Controls\LargeChatPlayer.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.TextBlock Note;
#line default
#line hidden
#line 34 "..\..\..\Controls\LargeChatPlayer.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.TextBlock InGameStatus;
#line default
#line hidden
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Uri resourceLocater = new System.Uri("/LegendaryClient;component/controls/largechatplayer.xaml", System.UriKind.Relative);
#line 1 "..\..\..\Controls\LargeChatPlayer.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
switch (connectionId)
{
case 1:
this.ProfileImage = ((System.Windows.Controls.Image)(target));
return;
case 2:
this.UsingLegendary = ((System.Windows.Controls.Image)(target));
return;
case 3:
this.LevelLabel = ((System.Windows.Controls.Label)(target));
return;
case 4:
this.PlayerName = ((System.Windows.Controls.Label)(target));
return;
case 5:
this.PlayerLeague = ((System.Windows.Controls.Label)(target));
return;
case 6:
this.PlayerWins = ((System.Windows.Controls.Label)(target));
return;
case 7:
this.PlayerStatus = ((System.Windows.Controls.TextBlock)(target));
return;
case 8:
this.Note = ((System.Windows.Controls.TextBlock)(target));
return;
case 9:
this.InGameStatus = ((System.Windows.Controls.TextBlock)(target));
return;
}
this._contentLoaded = true;
}
}
}
| 39.280899 | 141 | 0.634153 | [
"BSD-2-Clause"
] | nongnoobjung/Legendary-Garena | LegendaryClient/obj/Debug/Controls/LargeChatPlayer.g.i.cs | 6,994 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Gov.Jag.Spice.Interfaces
{
using Microsoft.Rest;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Govministryspiceministry operations.
/// </summary>
public partial interface IGovministryspiceministry
{
/// <summary>
/// Get spice_govministry_spice_ministry from spice_govministries
/// </summary>
/// <param name='spiceGovministryid'>
/// key: spice_govministryid of spice_govministry
/// </param>
/// <param name='top'>
/// </param>
/// <param name='skip'>
/// </param>
/// <param name='search'>
/// </param>
/// <param name='filter'>
/// </param>
/// <param name='count'>
/// </param>
/// <param name='orderby'>
/// Order items by property values
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<MicrosoftDynamicsCRMspiceMinistryCollection>> GetWithHttpMessagesAsync(string spiceGovministryid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get spice_govministry_spice_ministry from spice_govministries
/// </summary>
/// <param name='spiceGovministryid'>
/// key: spice_govministryid of spice_govministry
/// </param>
/// <param name='spiceMinistryid'>
/// key: spice_ministryid of spice_ministry
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<MicrosoftDynamicsCRMspiceMinistry>> MinistryByKeyWithHttpMessagesAsync(string spiceGovministryid, string spiceMinistryid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| 44.063158 | 545 | 0.621596 | [
"Apache-2.0"
] | BrendanBeachBC/jag-spd-spice | interfaces/Dynamics-Autorest/IGovministryspiceministry.cs | 4,186 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace DataJuggler.BlazorVideoPlayerDemo
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 26.206897 | 70 | 0.664474 | [
"MIT"
] | DataJuggler/BlazorVideoPlayer | DataJuggler.BlazorVideoPlayerDemo/Program.cs | 760 | C# |
using System;
using Fb2.Document.Models.Base;
namespace Fb2.Document.Exceptions
{
public class UnknownNodeException : Exception
{
public UnknownNodeException(string nodeName) : base($"'{nodeName}' is not known Fb2 node name.") { }
public UnknownNodeException(Fb2Node node) :
base($"'{node.Name}' with type '{node.GetType().Name}' is not known Fb2 node.")
{ }
}
}
| 27.6 | 108 | 0.649758 | [
"MIT"
] | Overrided/Fb2.Document | Fb2.Document/Exceptions/UnknownNodeException.cs | 416 | 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// A barrier allows multiple tasks to cooperatively work on some algorithm in parallel.
// A group of tasks cooperate by moving through a series of phases, where each in the group signals it has arrived at
// the barrier in a given phase and implicitly waits for all others to arrive.
// The same barrier can be used for multiple phases.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Diagnostics;
namespace System.Threading
{
/// <summary>
/// Enables multiple tasks to cooperatively work on an algorithm in parallel through multiple phases.
/// </summary>
/// <remarks>
/// <para>
/// A group of tasks cooperate by moving through a series of phases, where each in the group signals it
/// has arrived at the <see cref="Barrier"/> in a given phase and implicitly waits for all others to
/// arrive. The same <see cref="Barrier"/> can be used for multiple phases.
/// </para>
/// <para>
/// All public and protected members of <see cref="Barrier"/> are thread-safe and may be used
/// concurrently from multiple threads, with the exception of Dispose, which
/// must only be used when all other operations on the <see cref="Barrier"/> have
/// completed.
/// </para>
/// </remarks>
[DebuggerDisplay("Participant Count={ParticipantCount},Participants Remaining={ParticipantsRemaining}")]
public class Barrier : IDisposable
{
//This variable holds the basic barrier variables:
// 1- The current participants count
// 2- The total participants count
// 3- The sense flag (true if the current phase is even, false otherwise)
// The first 15 bits are for the total count which means the maximum participants for the barrier is about 32K
// The 16th bit is dummy
// The next 15th bit for the current
// And the last highest bit is for the sense
private volatile int _currentTotalCount;
// Bitmask to extract the current count
private const int CURRENT_MASK = 0x7FFF0000;
// Bitmask to extract the total count
private const int TOTAL_MASK = 0x00007FFF;
// Bitmask to extract the sense flag
private const int SENSE_MASK = unchecked((int)0x80000000);
// The maximum participants the barrier can operate = 32767 ( 2 power 15 - 1 )
private const int MAX_PARTICIPANTS = TOTAL_MASK;
// The current barrier phase
// We don't need to worry about overflow, the max value is 2^63-1; If it starts from 0 at a
// rate of 4 billion increments per second, it will takes about 64 years to overflow.
//private long _currentPhase;
// rate of 4 million increments per second, it will takes about 18 minutes to overflow.
private volatile int _currentPhase;
// dispose flag
private bool _disposed;
// Odd phases event
private ManualResetEventSlim _oddEvent;
// Even phases event
private ManualResetEventSlim _evenEvent;
// The execution context of the creator thread
//private ExecutionContext _ownerThreadContext;
private SynchronizationContext _ownerSynchronizationContext;
// The EC callback that invokes the post phase action
//private static ContextCallback s_invokePostPhaseAction;
private static SendOrPostCallback s_invokePostPhaseAction;
// Post phase action after each phase
private Action2<Barrier> _postPhaseAction;
// In case the post phase action throws an exception, wraps it in BarrierPostPhaseException
private Exception _exception;
// This is the ManagedThreadID of the postPhaseAction caller thread, this is used to determine if the SignalAndWait, Dispose or Add/RemoveParticipant caller thread is
// the same thread as the postPhaseAction thread which means this method was called from the postPhaseAction which is illegal.
// This value is captured before calling the action and reset back to zero after it.
private int _actionCallerID;
#region Properties
/// <summary>
/// Gets the number of participants in the barrier that haven't yet signaled
/// in the current phase.
/// </summary>
/// <remarks>
/// This could be 0 during a post-phase action delegate execution or if the
/// ParticipantCount is 0.
/// </remarks>
public int ParticipantsRemaining
{
get
{
int currentTotal = _currentTotalCount;
int total = (int)(currentTotal & TOTAL_MASK);
int current = (int)((currentTotal & CURRENT_MASK) >> 16);
return total - current;
}
}
/// <summary>
/// Gets the total number of participants in the barrier.
/// </summary>
public int ParticipantCount
{
get { return (int)(_currentTotalCount & TOTAL_MASK); }
}
/// <summary>
/// Gets the number of the barrier's current phase.
/// </summary>
public long CurrentPhaseNumber
{
// use the new Volatile.Read/Write method because it is cheaper than Interlocked.Read on AMD64 architecture
//get { return Volatile.Read(ref _currentPhase); }
get { return _currentPhase; }
//internal set { Volatile.Write(ref _currentPhase, value); }
}
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="Barrier"/> class.
/// </summary>
/// <param name="participantCount">The number of participating threads.</param>
/// <exception cref="ArgumentOutOfRangeException"> <paramref name="participantCount"/> is less than 0
/// or greater than <see cref="T:System.Int16.MaxValue"/>.</exception>
public Barrier(int participantCount)
: this(participantCount, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Barrier"/> class.
/// </summary>
/// <param name="participantCount">The number of participating threads.</param>
/// <param name="postPhaseAction">The <see cref="T:System.Action`1"/> to be executed after each
/// phase.</param>
/// <exception cref="T:System.ArgumentOutOfRangeException"> <paramref name="participantCount"/> is less than 0
/// or greater than <see cref="T:System.Int32.MaxValue"/>.</exception>
/// <remarks>
/// The <paramref name="postPhaseAction"/> delegate will be executed after
/// all participants have arrived at the barrier in one phase. The participants
/// will not be released to the next phase until the postPhaseAction delegate
/// has completed execution.
/// </remarks>
public Barrier(int participantCount, Action2<Barrier> postPhaseAction)
{
// the count must be non negative value
if (participantCount < 0 || participantCount > MAX_PARTICIPANTS)
{
throw new ArgumentOutOfRangeException2(nameof(participantCount), participantCount, SR.Barrier_ctor_ArgumentOutOfRange);
}
_currentTotalCount = (int)participantCount;
_postPhaseAction = postPhaseAction;
//Lazily initialize the events
_oddEvent = new ManualResetEventSlim(true);
_evenEvent = new ManualResetEventSlim(false);
// Capture the context if the post phase action is not null
if (postPhaseAction != null)
{
//_ownerThreadContext = ExecutionContext.Capture();
_ownerSynchronizationContext = SynchronizationContext.Current ?? new SynchronizationContext();
}
_actionCallerID = 0;
}
/// <summary>
/// Extract the three variables current, total and sense from a given big variable
/// </summary>
/// <param name="currentTotal">The integer variable that contains the other three variables</param>
/// <param name="current">The current participant count</param>
/// <param name="total">The total participants count</param>
/// <param name="sense">The sense flag</param>
private void GetCurrentTotal(int currentTotal, out int current, out int total, out bool sense)
{
total = (int)(currentTotal & TOTAL_MASK);
current = (int)((currentTotal & CURRENT_MASK) >> 16);
sense = (currentTotal & SENSE_MASK) == 0 ? true : false;
}
/// <summary>
/// Write the three variables current. total and the sense to the m_currentTotal
/// </summary>
/// <param name="currentTotal">The old current total to compare</param>
/// <param name="current">The current participant count</param>
/// <param name="total">The total participants count</param>
/// <param name="sense">The sense flag</param>
/// <returns>True if the CAS succeeded, false otherwise</returns>
private bool SetCurrentTotal(int currentTotal, int current, int total, bool sense)
{
int newCurrentTotal = (current << 16) | total;
if (!sense)
{
newCurrentTotal |= SENSE_MASK;
}
#pragma warning disable 0420
return Interlocked.CompareExchange(ref _currentTotalCount, newCurrentTotal, currentTotal) == currentTotal;
#pragma warning restore 0420
}
/// <summary>
/// Notifies the <see cref="Barrier"/> that there will be an additional participant.
/// </summary>
/// <returns>The phase number of the barrier in which the new participants will first
/// participate.</returns>
/// <exception cref="T:System.InvalidOperationException">
/// Adding a participant would cause the barrier's participant count to
/// exceed <see cref="T:System.Int16.MaxValue"/>.
/// </exception>
/// <exception cref="T:System.InvalidOperationException">
/// The method was invoked from within a post-phase action.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
public long AddParticipant()
{
try
{
return AddParticipants(1);
}
catch (ArgumentOutOfRangeException)
{
throw new InvalidOperationException(SR.Barrier_AddParticipants_Overflow_ArgumentOutOfRange);
}
}
/// <summary>
/// Notifies the <see cref="Barrier"/> that there will be additional participants.
/// </summary>
/// <param name="participantCount">The number of additional participants to add to the
/// barrier.</param>
/// <returns>The phase number of the barrier in which the new participants will first
/// participate.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="participantCount"/> is less than
/// 0.</exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">Adding <paramref name="participantCount"/> participants would cause the
/// barrier's participant count to exceed <see cref="T:System.Int16.MaxValue"/>.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The method was invoked from within a post-phase action.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
public long AddParticipants(int participantCount)
{
// check dispose
ThrowIfDisposed();
if (participantCount < 1)
{
throw new ArgumentOutOfRangeException2(nameof(participantCount), participantCount,
SR.Barrier_AddParticipants_NonPositive_ArgumentOutOfRange);
}
else if (participantCount > MAX_PARTICIPANTS) //overflow
{
throw new ArgumentOutOfRangeException(nameof(participantCount),
SR.Barrier_AddParticipants_Overflow_ArgumentOutOfRange);
}
// in case of this is called from the PHA
if (_actionCallerID != 0 && Environment2.CurrentManagedThreadId == _actionCallerID)
{
throw new InvalidOperationException(SR.Barrier_InvalidOperation_CalledFromPHA);
}
SpinWait spinner = new SpinWait();
long newPhase = 0;
while (true)
{
int currentTotal = _currentTotalCount;
int total;
int current;
bool sense;
GetCurrentTotal(currentTotal, out current, out total, out sense);
if (participantCount + total > MAX_PARTICIPANTS) //overflow
{
throw new ArgumentOutOfRangeException(nameof(participantCount),
SR.Barrier_AddParticipants_Overflow_ArgumentOutOfRange);
}
if (SetCurrentTotal(currentTotal, current, total + participantCount, sense))
{
// Calculating the first phase for that participant, if the current phase already finished return the next phase else return the current phase
// To know that the current phase is the sense doesn't match the
// phase odd even, so that means it didn't yet change the phase count, so currentPhase +1 is returned, otherwise currentPhase is returned
long currPhase = CurrentPhaseNumber;
newPhase = (sense != (currPhase % 2 == 0)) ? currPhase + 1 : currPhase;
// If this participant is going to join the next phase, which means the postPhaseAction is being running, this participants must wait until this done
// and its event is reset.
// Without that, if the postPhaseAction takes long time, this means the event that the current participant is going to wait on is still set
// (FinishPhase didn't reset it yet) so it should wait until it reset
if (newPhase != currPhase)
{
// Wait on the opposite event
if (sense)
{
_oddEvent.Wait();
}
else
{
_evenEvent.Wait();
}
}
//This else to fix the racing where the current phase has been finished, m_currentPhase has been updated but the events have not been set/reset yet
// otherwise when this participant calls SignalAndWait it will wait on a set event however all other participants have not arrived yet.
else
{
if (sense && _evenEvent.IsSet)
_evenEvent.Reset();
else if (!sense && _oddEvent.IsSet)
_oddEvent.Reset();
}
break;
}
spinner.SpinOnce();
}
return newPhase;
}
/// <summary>
/// Notifies the <see cref="Barrier"/> that there will be one less participant.
/// </summary>
/// <exception cref="T:System.InvalidOperationException">The barrier already has 0
/// participants.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The method was invoked from within a post-phase action.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
public void RemoveParticipant()
{
RemoveParticipants(1);
}
/// <summary>
/// Notifies the <see cref="Barrier"/> that there will be fewer participants.
/// </summary>
/// <param name="participantCount">The number of additional participants to remove from the barrier.</param>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="participantCount"/> is less than
/// 0.</exception>
/// <exception cref="T:System.InvalidOperationException">The barrier already has 0 participants.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The method was invoked from within a post-phase action.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
public void RemoveParticipants(int participantCount)
{
// check dispose
ThrowIfDisposed();
// Validate input
if (participantCount < 1)
{
throw new ArgumentOutOfRangeException2(nameof(participantCount), participantCount,
SR.Barrier_RemoveParticipants_NonPositive_ArgumentOutOfRange);
}
// in case of this is called from the PHA
if (_actionCallerID != 0 && Environment2.CurrentManagedThreadId == _actionCallerID)
{
throw new InvalidOperationException(SR.Barrier_InvalidOperation_CalledFromPHA);
}
SpinWait spinner = new SpinWait();
while (true)
{
int currentTotal = _currentTotalCount;
int total;
int current;
bool sense;
GetCurrentTotal(currentTotal, out current, out total, out sense);
if (total < participantCount)
{
throw new ArgumentOutOfRangeException(nameof(participantCount),
SR.Barrier_RemoveParticipants_ArgumentOutOfRange);
}
if (total - participantCount < current)
{
throw new InvalidOperationException(SR.Barrier_RemoveParticipants_InvalidOperation);
}
// If the remaining participants = current participants, then finish the current phase
int remaingParticipants = total - participantCount;
if (remaingParticipants > 0 && current == remaingParticipants)
{
if (SetCurrentTotal(currentTotal, 0, total - participantCount, !sense))
{
FinishPhase(sense);
break;
}
}
else
{
if (SetCurrentTotal(currentTotal, current, total - participantCount, sense))
{
break;
}
}
spinner.SpinOnce();
}
}
/// <summary>
/// Signals that a participant has reached the <see cref="Barrier"/> and waits for all other
/// participants to reach the barrier as well.
/// </summary>
/// <exception cref="T:System.InvalidOperationException">
/// The method was invoked from within a post-phase action, the barrier currently has 0 participants,
/// or the barrier is being used by more threads than are registered as participants.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
public void SignalAndWait()
{
SignalAndWait(new CancellationToken());
}
/// <summary>
/// Signals that a participant has reached the <see cref="Barrier"/> and waits for all other
/// participants to reach the barrier, while observing a <see
/// cref="T:System.Threading.CancellationToken"/>.
/// </summary>
/// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to
/// observe.</param>
/// <exception cref="T:System.InvalidOperationException">
/// The method was invoked from within a post-phase action, the barrier currently has 0 participants,
/// or the barrier is being used by more threads than are registered as participants.
/// </exception>
/// <exception cref="T:System.OperationCanceledException"><paramref name="cancellationToken"/> has been
/// canceled.</exception>
/// <exception cref="T:System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
public void SignalAndWait(CancellationToken cancellationToken)
{
#if DEBUG
bool result =
#endif
SignalAndWait(Timeout.Infinite, cancellationToken);
#if DEBUG
Debug.Assert(result);
#endif
}
/// <summary>
/// Signals that a participant has reached the <see cref="Barrier"/> and waits for all other
/// participants to reach the barrier as well, using a
/// <see cref="T:System.TimeSpan"/> to measure the time interval.
/// </summary>
/// <param name="timeout">A <see cref="T:System.TimeSpan"/> that represents the number of
/// milliseconds to wait, or a <see cref="T:System.TimeSpan"/> that represents -1 milliseconds to
/// wait indefinitely.</param>
/// <returns>true if all other participants reached the barrier; otherwise, false.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/>is a negative number
/// other than -1 milliseconds, which represents an infinite time-out, or it is greater than
/// <see cref="T:System.Int32.MaxValue"/>.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The method was invoked from within a post-phase action, the barrier currently has 0 participants,
/// or the barrier is being used by more threads than are registered as participants.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
public Boolean SignalAndWait(TimeSpan timeout)
{
return SignalAndWait(timeout, new CancellationToken());
}
/// <summary>
/// Signals that a participant has reached the <see cref="Barrier"/> and waits for all other
/// participants to reach the barrier as well, using a
/// <see cref="T:System.TimeSpan"/> to measure the time interval, while observing a <see
/// cref="T:System.Threading.CancellationToken"/>.
/// </summary>
/// <param name="timeout">A <see cref="T:System.TimeSpan"/> that represents the number of
/// milliseconds to wait, or a <see cref="T:System.TimeSpan"/> that represents -1 milliseconds to
/// wait indefinitely.</param>
/// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to
/// observe.</param>
/// <returns>true if all other participants reached the barrier; otherwise, false.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/>is a negative number
/// other than -1 milliseconds, which represents an infinite time-out.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The method was invoked from within a post-phase action, the barrier currently has 0 participants,
/// or the barrier is being used by more threads than are registered as participants.
/// </exception>
/// <exception cref="T:System.OperationCanceledException"><paramref name="cancellationToken"/> has been
/// canceled.</exception>
/// <exception cref="T:System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
public Boolean SignalAndWait(TimeSpan timeout, CancellationToken cancellationToken)
{
Int64 totalMilliseconds = (Int64)timeout.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
{
throw new ArgumentOutOfRangeException2(nameof(timeout), timeout,
SR.Barrier_SignalAndWait_ArgumentOutOfRange);
}
return SignalAndWait((int)timeout.TotalMilliseconds, cancellationToken);
}
/// <summary>
/// Signals that a participant has reached the <see cref="Barrier"/> and waits for all other
/// participants to reach the barrier as well, using a
/// 32-bit signed integer to measure the time interval.
/// </summary>
/// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see
/// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param>
/// <returns>true if all other participants reached the barrier; otherwise, false.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a
/// negative number other than -1, which represents an infinite time-out.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The method was invoked from within a post-phase action, the barrier currently has 0 participants,
/// or the barrier is being used by more threads than are registered as participants.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
public bool SignalAndWait(int millisecondsTimeout)
{
return SignalAndWait(millisecondsTimeout, new CancellationToken());
}
/// <summary>
/// Signals that a participant has reached the barrier and waits for all other participants to reach
/// the barrier as well, using a
/// 32-bit signed integer to measure the time interval, while observing a <see
/// cref="T:System.Threading.CancellationToken"/>.
/// </summary>
/// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see
/// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param>
/// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to
/// observe.</param>
/// <returns>true if all other participants reached the barrier; otherwise, false.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a
/// negative number other than -1, which represents an infinite time-out.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The method was invoked from within a post-phase action, the barrier currently has 0 participants,
/// or the barrier is being used by more threads than are registered as participants.
/// </exception>
/// <exception cref="T:System.OperationCanceledException"><paramref name="cancellationToken"/> has been
/// canceled.</exception>
/// <exception cref="T:System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
public bool SignalAndWait(int millisecondsTimeout, CancellationToken cancellationToken)
{
ThrowIfDisposed();
cancellationToken.ThrowIfCancellationRequested();
if (millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException2(nameof(millisecondsTimeout), millisecondsTimeout,
SR.Barrier_SignalAndWait_ArgumentOutOfRange);
}
// in case of this is called from the PHA
if (_actionCallerID != 0 && Environment2.CurrentManagedThreadId == _actionCallerID)
{
throw new InvalidOperationException(SR.Barrier_InvalidOperation_CalledFromPHA);
}
// local variables to extract the basic barrier variable and update them
// The are declared here instead of inside the loop body because the will be used outside the loop
bool sense; // The sense of the barrier *before* the phase associated with this SignalAndWait call completes
int total;
int current;
int currentTotal;
long phase;
SpinWait spinner = new SpinWait();
while (true)
{
currentTotal = _currentTotalCount;
GetCurrentTotal(currentTotal, out current, out total, out sense);
phase = CurrentPhaseNumber;
// throw if zero participants
if (total == 0)
{
throw new InvalidOperationException(SR.Barrier_SignalAndWait_InvalidOperation_ZeroTotal);
}
// Try to detect if the number of threads for this phase exceeded the total number of participants or not
// This can be detected if the current is zero which means all participants for that phase has arrived and the phase number is not changed yet
if (current == 0 && sense != (CurrentPhaseNumber % 2 == 0))
{
throw new InvalidOperationException(SR.Barrier_SignalAndWait_InvalidOperation_ThreadsExceeded);
}
//This is the last thread, finish the phase
if (current + 1 == total)
{
if (SetCurrentTotal(currentTotal, 0, total, !sense))
{
//if (CdsSyncEtwBCLProvider.Log.IsEnabled())
//{
// CdsSyncEtwBCLProvider.Log.Barrier_PhaseFinished(sense, CurrentPhaseNumber);
//}
FinishPhase(sense);
return true;
}
}
else if (SetCurrentTotal(currentTotal, current + 1, total, sense))
{
break;
}
spinner.SpinOnce();
}
// ** Perform the real wait **
// select the correct event to wait on, based on the current sense.
ManualResetEventSlim eventToWaitOn = (sense) ? _evenEvent : _oddEvent;
bool waitWasCanceled = false;
bool waitResult = false;
try
{
waitResult = DiscontinuousWait(eventToWaitOn, millisecondsTimeout, cancellationToken, phase);
}
catch (OperationCanceledException)
{
waitWasCanceled = true;
}
catch (ObjectDisposedException)// in case a race happen where one of the thread returned from SignalAndWait and the current thread calls Wait on a disposed event
{
// make sure the current phase for this thread is already finished, otherwise propagate the exception
if (phase < CurrentPhaseNumber)
waitResult = true;
else
throw;
}
if (!waitResult)
{
//reset the spinLock to prepare it for the next loop
spinner.Reset();
//If the wait timeout expired and all other thread didn't reach the barrier yet, update the current count back
while (true)
{
bool newSense;
currentTotal = _currentTotalCount;
GetCurrentTotal(currentTotal, out current, out total, out newSense);
// If the timeout expired and the phase has just finished, return true and this is considered as succeeded SignalAndWait
//otherwise the timeout expired and the current phase has not been finished yet, return false
//The phase is finished if the phase member variable is changed (incremented) or the sense has been changed
// we have to use the statements in the comparison below for two cases:
// 1- The sense is changed but the last thread didn't update the phase yet
// 2- The phase is already incremented but the sense flipped twice due to the termination of the next phase
if (phase < CurrentPhaseNumber || sense != newSense)
{
// The current phase has been finished, but we shouldn't return before the events are set/reset otherwise this thread could start
// next phase and the appropriate event has not reset yet which could make it return immediately from the next phase SignalAndWait
// before waiting other threads
WaitCurrentPhase(eventToWaitOn, phase);
Debug.Assert(phase < CurrentPhaseNumber);
break;
}
//The phase has not been finished yet, try to update the current count.
if (SetCurrentTotal(currentTotal, current - 1, total, sense))
{
//if here, then the attempt to back out was successful.
//throw (a fresh) OCE if cancellation woke the wait
//or return false if it was the timeout that woke the wait.
//
if (waitWasCanceled)
throw new OperationCanceledException(SR.Common_OperationCanceled, cancellationToken);
else
return false;
}
spinner.SpinOnce();
}
}
if (_exception != null)
throw new BarrierPostPhaseException(_exception);
return true;
}
/// <summary>
/// Finish the phase by invoking the post phase action, and setting the event, this must be called by the
/// last arrival thread
/// </summary>
/// <param name="observedSense">The current phase sense</param>
private void FinishPhase(bool observedSense)
{
// Execute the PHA in try/finally block to reset the variables back in case of it threw an exception
if (_postPhaseAction != null)
{
try
{
// Capture the caller thread ID to check if the Add/RemoveParticipant(s) is called from the PHA
_actionCallerID = Environment2.CurrentManagedThreadId;
//if (_ownerThreadContext != null)
if (_ownerSynchronizationContext != null)
{
//var currentContext = _ownerThreadContext;
var currentContext = _ownerSynchronizationContext;
//ContextCallback handler = s_invokePostPhaseAction;
var handler = s_invokePostPhaseAction;
if (handler == null)
{
s_invokePostPhaseAction = handler = InvokePostPhaseAction;
}
//ExecutionContext.Run(_ownerThreadContext, handler, this);
_ownerSynchronizationContext.Send(handler, this);
}
else
{
_postPhaseAction(this);
}
_exception = null; // reset the exception if it was set previously
}
catch (Exception ex)
{
_exception = ex;
}
finally
{
_actionCallerID = 0;
SetResetEvents(observedSense);
if (_exception != null)
throw new BarrierPostPhaseException(_exception);
}
}
else
{
SetResetEvents(observedSense);
}
}
/// <summary>
/// Helper method to call the post phase action
/// </summary>
/// <param name="obj"></param>
private static void InvokePostPhaseAction(object obj)
{
var thisBarrier = (Barrier)obj;
thisBarrier._postPhaseAction(thisBarrier);
}
/// <summary>
/// Sets the current phase event and reset the next phase event
/// </summary>
/// <param name="observedSense">The current phase sense</param>
private void SetResetEvents(bool observedSense)
{
// Increment the phase count using Volatile class because m_currentPhase is 64 bit long type, that could cause torn write on 32 bit machines
//CurrentPhaseNumber = CurrentPhaseNumber + 1;
Interlocked.Increment(ref _currentPhase);
if (observedSense)
{
_oddEvent.Reset();
_evenEvent.Set();
}
else
{
_evenEvent.Reset();
_oddEvent.Set();
}
}
/// <summary>
/// Wait until the current phase finishes completely by spinning until either the event is set,
/// or the phase count is incremented more than one time
/// </summary>
/// <param name="currentPhaseEvent">The current phase event</param>
/// <param name="observedPhase">The current phase for that thread</param>
private void WaitCurrentPhase(ManualResetEventSlim currentPhaseEvent, long observedPhase)
{
//spin until either of these two conditions succeeds
//1- The event is set
//2- the phase count is incremented more than one time, this means the next phase is finished as well,
//but the event will be reset again, so we check the phase count instead
SpinWait spinner = new SpinWait();
while (!currentPhaseEvent.IsSet && CurrentPhaseNumber - observedPhase <= 1)
{
spinner.SpinOnce();
}
}
/// <summary>
/// The reason of discontinuous waiting instead of direct waiting on the event is to avoid the race where the sense is
/// changed twice because the next phase is finished (due to either RemoveParticipant is called or another thread joined
/// the next phase instead of the current thread) so the current thread will be stuck on the event because it is reset back
/// The maxWait and the shift numbers are arbitrarily chosen, there were no references picking them
/// </summary>
/// <param name="currentPhaseEvent">The current phase event</param>
/// <param name="totalTimeout">wait timeout in milliseconds</param>
/// <param name="token">cancellation token passed to SignalAndWait</param>
/// <param name="observedPhase">The current phase number for this thread</param>
/// <returns>True if the event is set or the phase number changed, false if the timeout expired</returns>
private bool DiscontinuousWait(ManualResetEventSlim currentPhaseEvent, int totalTimeout, CancellationToken token, long observedPhase)
{
int maxWait = 100; // 100 ms
int waitTimeCeiling = 10000; // 10 seconds
while (observedPhase == CurrentPhaseNumber)
{
// the next wait time, the min of the maxWait and the totalTimeout
int waitTime = totalTimeout == Timeout.Infinite ? maxWait : Math.Min(maxWait, totalTimeout);
if (currentPhaseEvent.Wait(waitTime, token))
return true;
//update the total wait time
if (totalTimeout != Timeout.Infinite)
{
totalTimeout -= waitTime;
if (totalTimeout <= 0)
return false;
}
//if the maxwait exceeded 10 seconds then we will stop increasing the maxWait time and keep it 10 seconds, otherwise keep doubling it
maxWait = maxWait >= waitTimeCeiling ? waitTimeCeiling : Math.Min(maxWait << 1, waitTimeCeiling);
}
//if we exited the loop because the observed phase doesn't match the current phase, then we have to spin to make sure
//the event is set or the next phase is finished
WaitCurrentPhase(currentPhaseEvent, observedPhase);
return true;
}
/// <summary>
/// Releases all resources used by the current instance of <see cref="Barrier"/>.
/// </summary>
/// <exception cref="T:System.InvalidOperationException">
/// The method was invoked from within a post-phase action.
/// </exception>
/// <remarks>
/// Unlike most of the members of <see cref="Barrier"/>, Dispose is not thread-safe and may not be
/// used concurrently with other members of this instance.
/// </remarks>
public void Dispose()
{
// in case of this is called from the PHA
if (_actionCallerID != 0 && Environment2.CurrentManagedThreadId == _actionCallerID)
{
throw new InvalidOperationException(SR.Barrier_InvalidOperation_CalledFromPHA);
}
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// When overridden in a derived class, releases the unmanaged resources used by the
/// <see cref="Barrier"/>, and optionally releases the managed resources.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources; false to release
/// only unmanaged resources.</param>
/// <remarks>
/// Unlike most of the members of <see cref="Barrier"/>, Dispose is not thread-safe and may not be
/// used concurrently with other members of this instance.
/// </remarks>
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
_oddEvent.Dispose();
_evenEvent.Dispose();
}
_disposed = true;
}
}
/// <summary>
/// Throw ObjectDisposedException if the barrier is disposed
/// </summary>
private void ThrowIfDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException("Barrier", SR.Barrier_Dispose);
}
}
}
} | 48.217054 | 174 | 0.590928 | [
"Apache-2.0"
] | WindowsCE/NETStandard.WindowsCE | src/NETStandard.WindowsCE/Threading/Barrier.cs | 43,542 | C# |
namespace Steamworks
{
public enum EDurationControlProgress
{
k_EDurationControlProgress_Full,
k_EDurationControlProgress_Half,
k_EDurationControlProgress_None,
k_EDurationControl_ExitSoon_3h,
k_EDurationControl_ExitSoon_5h,
k_EDurationControl_ExitSoon_Night
}
}
| 21.384615 | 37 | 0.859712 | [
"MIT"
] | undancer/oni-data | Managed/firstpass/Steamworks/EDurationControlProgress.cs | 278 | C# |
// **********************************************************************************************\
// Module Name: AsyncSemaphore.cs
// Project: ElementLab.Drugscreening.Client
//
// Copyright (c) Element Lab LLC
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// **********************************************************************************************/
//
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace ElementLab.Drugscreening.Client
{
// http://blogs.msdn.com/b/pfxteam/archive/2012/02/12/10266983.aspx
class AsyncSemaphore
{
static readonly Task _completed = Task.FromResult(true);
readonly Queue<TaskCompletionSource<bool>> _waiters = new Queue<TaskCompletionSource<bool>>();
int _currentCount;
public AsyncSemaphore(int initialCount)
{
if (initialCount < 0) throw new ArgumentOutOfRangeException(nameof(initialCount));
_currentCount = initialCount;
}
public Task WaitAsync()
{
lock (_waiters)
{
if (_currentCount > 0)
{
--_currentCount;
return _completed;
}
var waiter = new TaskCompletionSource<bool>();
_waiters.Enqueue(waiter);
return waiter.Task;
}
}
public void Release()
{
TaskCompletionSource<bool> toRelease = null;
lock (_waiters)
{
if (_waiters.Count > 0)
toRelease = _waiters.Dequeue();
else
++_currentCount;
}
toRelease?.SetResult(true);
}
}
} | 31.435484 | 102 | 0.511544 | [
"MIT"
] | elementlab-llc/sln-net | DrugscreeningApiClient/ElementLab.Drugscreening.Client/Drugscreening/Client/AsyncSemaphore.cs | 1,951 | C# |
using Autofac;
using PlainCQRS.Core.Events;
namespace PlainCQRS.Autofac.Tests.Events
{
public class EventsModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.Register(c =>
{
var threadSpecificContext = c.Resolve<IComponentContext>();
return new EventDispatcher(threadSpecificContext);
})
.As<IEventPublisher>()
.InstancePerDependency();
builder.Register(c =>
{
var threadSpecificContext = c.Resolve<IComponentContext>();
return new EventDispatcherAsync(threadSpecificContext);
})
.As<IEventPublisherAsync>()
.InstancePerDependency();
builder.RegisterType<TestEventHandler>().As<IEventHandler<TestEvent>>().InstancePerDependency();
builder.RegisterType<TestEventHandlerAsync>().As<IEventHandlerAsync<TestEvent>>().InstancePerDependency();
}
}
} | 34.066667 | 118 | 0.611546 | [
"Apache-2.0"
] | marekzet/plain-cqr | PlainCQRS.Autofac.Tests/Events/EventsModule.cs | 1,024 | C# |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Neo.Lua")]
[assembly: AssemblyDescription("Lua Language for DLR")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("8278b1f1-cfc2-41e2-94c1-5167abbce780")]
[assembly: NeutralResourcesLanguageAttribute("en-US")]
[assembly: InternalsVisibleTo("Neo.Lua.Desktop, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f94d9d7c92e0848eab4f6ef97934d020c24bbc122b915b00789af183f3e3084dc4a0811754a5308c803d25cd14dd42eee792a84295432dd781995fb270bd29ae90b431e8f74d56ea32bc80955ae81a52e5cacf6834da0ae4f9c805b436f3b562e415326da8b3a4df94e67b4e737b269d4277a03fe45a8f54cf8bc889f60848ea")]
[assembly: InternalsVisibleTo("LuaDLR.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f94d9d7c92e0848eab4f6ef97934d020c24bbc122b915b00789af183f3e3084dc4a0811754a5308c803d25cd14dd42eee792a84295432dd781995fb270bd29ae90b431e8f74d56ea32bc80955ae81a52e5cacf6834da0ae4f9c805b436f3b562e415326da8b3a4df94e67b4e737b269d4277a03fe45a8f54cf8bc889f60848ea")]
[assembly: InternalsVisibleTo("lua.dynamic, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f94d9d7c92e0848eab4f6ef97934d020c24bbc122b915b00789af183f3e3084dc4a0811754a5308c803d25cd14dd42eee792a84295432dd781995fb270bd29ae90b431e8f74d56ea32bc80955ae81a52e5cacf6834da0ae4f9c805b436f3b562e415326da8b3a4df94e67b4e737b269d4277a03fe45a8f54cf8bc889f60848ea")]
| 86.277778 | 382 | 0.909208 | [
"Apache-2.0"
] | oohicksyoo/neolua | NeoLua/Properties/AssemblyInfo.cs | 1,555 | 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 ivs-2020-07-14.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.IVS.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.IVS.Model.Internal.MarshallTransformations
{
/// <summary>
/// ListTagsForResource Request Marshaller
/// </summary>
public class ListTagsForResourceRequestMarshaller : IMarshaller<IRequest, ListTagsForResourceRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((ListTagsForResourceRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(ListTagsForResourceRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.IVS");
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2020-07-14";
request.HttpMethod = "GET";
if (!publicRequest.IsSetResourceArn())
throw new AmazonIVSException("Request object does not have required field ResourceArn set");
request.AddPathResource("{resourceArn}", StringUtils.FromString(publicRequest.ResourceArn));
request.ResourcePath = "/tags/{resourceArn}";
request.MarshallerVersion = 2;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetMaxResults())
{
context.Writer.WritePropertyName("maxResults");
context.Writer.Write(publicRequest.MaxResults);
}
if(publicRequest.IsSetNextToken())
{
context.Writer.WritePropertyName("nextToken");
context.Writer.Write(publicRequest.NextToken);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static ListTagsForResourceRequestMarshaller _instance = new ListTagsForResourceRequestMarshaller();
internal static ListTagsForResourceRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static ListTagsForResourceRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 36.225225 | 153 | 0.629943 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/IVS/Generated/Model/Internal/MarshallTransformations/ListTagsForResourceRequestMarshaller.cs | 4,021 | C# |
using System.Collections.Generic;
using Assets.Scripts.CSharpUtilities;
using Assets.Scripts.GameLogic.ActionLoop.ActionEffects;
using Assets.Scripts.GameLogic.ActionLoop.Actions;
using Assets.Scripts.GameLogic.GameCore;
using UnityEngine;
using UnityEngine.Tilemaps;
namespace Assets.Scripts.GameLogic.ActionLoop
{
public class OpenDoorAction : GameAction
{
private readonly Vector2Int _targetPosition;
private readonly bool _isHorizontal;
private readonly bool _isHeavyDoor;
private readonly IGameContext _gameContext;
public OpenDoorAction(ActorData actorData, Vector2Int targetPosition, bool isHorizontal, bool isHeavyDoor,
float energyCost, IActionEffectFactory actionEffectFactory, IGameContext gameContext)
: base(actorData, energyCost, actionEffectFactory)
{
_targetPosition = targetPosition;
_isHorizontal = isHorizontal;
_isHeavyDoor = isHeavyDoor;
_gameContext = gameContext;
}
public override IEnumerable<IActionEffect> Execute()
{
_gameContext.WallsTilemap.SetTile(_targetPosition.ToVector3Int(), null);
if (_isHeavyDoor)
{
TileBase openDoorTile = _isHorizontal
? Resources.Load<TileBase>("Tiles/Environment/doors_HEAVY_1")
: Resources.Load<TileBase>("Tiles/Environment/doors_HEAVY_3");
_gameContext.EnvironmentTilemap.SetTile(_targetPosition.ToVector3Int(), openDoorTile);
}
else
{
TileBase openDoorTile = _isHorizontal ? Resources.Load<TileBase>("Tiles/Environment/doors_H_open")
: Resources.Load<TileBase>("Tiles/Environment/doors_V_open");
_gameContext.EnvironmentTilemap.SetTile(_targetPosition.ToVector3Int(), openDoorTile);
}
yield break;
}
}
} | 33.38 | 109 | 0.786099 | [
"MIT"
] | azsdaja/7drl-2018 | Assets/Scripts/GameLogic/ActionLoop/OpenDoorAction.cs | 1,671 | C# |
using CourseLibrary.API.DbContexts;
using CourseLibrary.API.Entities;
using CourseLibrary.API.Helpers;
using CourseLibrary.API.ResourceParameters;
using System;
using System.Collections.Generic;
using System.Linq;
namespace CourseLibrary.API.Services
{
public class CourseLibraryRepository : ICourseLibraryRepository, IDisposable
{
private readonly CourseLibraryContext _context;
public readonly IPropertyMappingService _propertyMappingService;
public CourseLibraryRepository(CourseLibraryContext context,
IPropertyMappingService propertyMappingService)
{
_propertyMappingService = propertyMappingService?? throw new ArgumentNullException(nameof(propertyMappingService));
_context = context ?? throw new ArgumentNullException(nameof(context));
}
public void AddCourse(Guid authorId, Course course)
{
if (authorId == Guid.Empty)
throw new ArgumentNullException(nameof(authorId));
if (course == null)
throw new ArgumentNullException(nameof(course));
// always set the AuthorId to the passed-in authorId
course.AuthorId = authorId;
_context.Courses.Add(course);
}
public void DeleteCourse(Course course)
{
_context.Courses.Remove(course);
}
public Course GetCourse(Guid authorId, Guid courseId)
{
if (authorId == Guid.Empty)
throw new ArgumentNullException(nameof(authorId));
if (courseId == Guid.Empty)
throw new ArgumentNullException(nameof(courseId));
return _context.Courses
.Where(c => c.AuthorId == authorId && c.Id == courseId).FirstOrDefault();
}
public IEnumerable<Course> GetCourses(Guid authorId)
{
if (authorId == Guid.Empty)
throw new ArgumentNullException(nameof(authorId));
return _context.Courses
.Where(c => c.AuthorId == authorId)
.OrderBy(c => c.Title).ToList();
}
public void UpdateCourse(Course course)
{
// no code in this implementation
}
public void AddAuthor(Author author)
{
if (author == null)
throw new ArgumentNullException(nameof(author));
// the repository fills the id (instead of using identity columns)
author.Id = Guid.NewGuid();
foreach (var course in author.Courses)
{
course.Id = Guid.NewGuid();
}
_context.Authors.Add(author);
}
public bool AuthorExists(Guid authorId)
{
if (authorId == Guid.Empty)
throw new ArgumentNullException(nameof(authorId));
return _context.Authors.Any(a => a.Id == authorId);
}
public void DeleteAuthor(Author author)
{
if (author == null)
throw new ArgumentNullException(nameof(author));
_context.Authors.Remove(author);
}
public Author GetAuthor(Guid authorId)
{
if (authorId == Guid.Empty)
throw new ArgumentNullException(nameof(authorId));
return _context.Authors.FirstOrDefault(a => a.Id == authorId);
}
public IEnumerable<Author> GetAuthors()
{
return _context.Authors.ToList<Author>();
}
public PagedList<Author> GetAuthors(AuthorsResourceParameters authorsResourceParameters)
{
/* if (string.IsNullOrWhiteSpace(authorsResourceParameters.MainCategory)
&& string.IsNullOrWhiteSpace(authorsResourceParameters.SearchQuery))
return GetAuthors(); */
var collection = _context.Authors as IQueryable<Author>;
if (!string.IsNullOrWhiteSpace(authorsResourceParameters.MainCategory))
{
var mainCategory = authorsResourceParameters.MainCategory.Trim();
collection = _context.Authors.Where(a => a.MainCategory == mainCategory);
}
if (!string.IsNullOrWhiteSpace(authorsResourceParameters.SearchQuery))
{
var searchQuery = authorsResourceParameters.SearchQuery.Trim();
collection = collection.Where(a => a.MainCategory.Contains(searchQuery)
|| a.FirstName.Contains(searchQuery)
|| a.LastName.Contains(searchQuery));
}
if (!string.IsNullOrWhiteSpace(authorsResourceParameters.OrderBy))
{
/* if (authorsResourceParameters.OrderBy.ToLowerInvariant() == "name")
collection = collection.OrderBy(a => a.FirstName).ThenBy(a => a.LastName); */
var authorPropertyMappingDictionnary = _propertyMappingService.GetPropertyMapping<Models.AuthorDto, Author>();
collection = collection.ApplySort(authorsResourceParameters.OrderBy, authorPropertyMappingDictionnary);
}
/* return collection.Skip(authorsResourceParameters.PageSize * (authorsResourceParameters.PageNumber - 1))
.Take(authorsResourceParameters.PageSize).ToList();*/
return PagedList<Author>.Create(collection, authorsResourceParameters.PageNumber, authorsResourceParameters.PageSize);
}
public IEnumerable<Author> GetAuthors(IEnumerable<Guid> authorIds)
{
if (authorIds == null)
throw new ArgumentNullException(nameof(authorIds));
return _context.Authors.Where(a => authorIds.Contains(a.Id))
.OrderBy(a => a.FirstName)
.OrderBy(a => a.LastName)
.ToList();
}
public void UpdateAuthor(Author author)
{
// no code in this implementation
}
public bool Save()
{
return (_context.SaveChanges() >= 0);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// dispose resources when needed
}
}
}
}
| 35.766304 | 131 | 0.577572 | [
"MIT"
] | nhalflants/Courses-Library-API | Services/CourseLibraryRepository.cs | 6,583 | C# |
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace SMOWMS.DTOs.InputDTO
{
/// <summary>
/// 资产入库相关信息
/// </summary>
public class AssInStorageInputDto:IEntity
{
/// <summary>
/// 采购单编号
/// </summary>
[Required]
[DisplayName("采购单编号")]
public string POID { get; set; }
/// <summary>
/// 资产模板编号
/// </summary>
[Required]
[DisplayName("资产模板编号")]
public string TEMPLATEID { get; set; }
/// <summary>
/// 仓库编号
/// </summary>
[Required]
[DisplayName("仓库编号")]
public string WAREID { get; set; }
/// <summary>
/// 存储类型编号
/// </summary>
[Required]
[DisplayName("存储类型编号")]
public string STID { get; set; }
/// <summary>
/// 库位编号
/// </summary>
[Required]
[DisplayName("库位编号")]
public string SLID { get; set; }
/// <summary>
/// 用户编号
/// </summary>
public string UserId { get; set; }
/// <summary>
/// 序列号
/// </summary>
public List<string> SnList { get; set; }
}
} | 22.017544 | 48 | 0.478884 | [
"MIT"
] | comsmobiler/SmoWMS | Source/SMOWMS.DTOs/InputDTO/AssInStorageInputDto.cs | 1,387 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Logic.Models
{
using System;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Microsoft.Rest.Azure;
public partial class WorkflowTriggerHistoryFilter
{
/// <summary>
/// Initializes a new instance of the WorkflowTriggerHistoryFilter
/// class.
/// </summary>
public WorkflowTriggerHistoryFilter() { }
/// <summary>
/// Initializes a new instance of the WorkflowTriggerHistoryFilter
/// class.
/// </summary>
public WorkflowTriggerHistoryFilter(WorkflowStatus? status = default(WorkflowStatus?))
{
Status = status;
}
/// <summary>
/// Gets or sets gets or sets the status of workflow trigger history.
/// Possible values include: 'NotSpecified', 'Paused', 'Running',
/// 'Waiting', 'Succeeded', 'Skipped', 'Suspended', 'Cancelled',
/// 'Failed', 'Faulted', 'TimedOut', 'Aborted', 'Ignored'
/// </summary>
[JsonProperty(PropertyName = "status")]
public WorkflowStatus? Status { get; set; }
}
}
| 33.12766 | 94 | 0.641618 | [
"MIT"
] | samtoubia/azure-sdk-for-net | src/ResourceManagement/Logic/Microsoft.Azure.Management.Logic/Generated/Models/WorkflowTriggerHistoryFilter.cs | 1,557 | C# |
using Nest;
using Tests.Core.ManagedElasticsearch.Clusters;
using Tests.Domain;
using Tests.Framework.Integration;
using Tests.Framework.ManagedElasticsearch.Clusters;
namespace Tests.QueryDsl.Span.FieldMasking
{
public class SpanFieldMaskingUsageTests : QueryDslUsageTestsBase
{
public SpanFieldMaskingUsageTests(ReadOnlyCluster i, EndpointUsage usage) : base(i, usage) { }
protected override object QueryJson => new
{
field_masking_span = new
{
_name = "named_query",
boost = 1.1,
field = "name",
query = new
{
span_term = new { description = new { value = "dolorem" } }
}
}
};
protected override QueryContainer QueryInitializer => new SpanFieldMaskingQuery
{
Name = "named_query",
Boost = 1.1,
Field = Infer.Field<Project>(p => p.Name),
Query = new SpanQuery
{
SpanTerm = new SpanTermQuery
{
Field = Infer.Field<Project>(p => p.Description),
Value = "dolorem"
}
}
};
protected override QueryContainer QueryFluent(QueryContainerDescriptor<Project> q) => q
.SpanFieldMasking(c => c
.Name("named_query")
.Boost(1.1)
.Field(p => p.Name)
.Query(sq=>sq
.SpanTerm(st=>st.Field(p=>p.Description).Value("dolorem"))
)
);
protected override ConditionlessWhen ConditionlessWhen => new ConditionlessWhen<ISpanFieldMaskingQuery>(a => a.SpanFieldMasking)
{
q => q.Query = null,
q => q.Field = null ,
};
}
}
| 24.423729 | 130 | 0.673144 | [
"Apache-2.0"
] | msarilar/elasticsearch-net | src/Tests/Tests/QueryDsl/Span/FieldMasking/SpanFieldMaskingUsageTests.cs | 1,443 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
using Microsoft.Graph;
using System;
namespace Hosts.SecurityGroup
{
public class SubsequentUsersReaderRequest
{
public Guid RunId { get; set; }
public string NextPageUrl { get; set; }
public IGroupTransitiveMembersCollectionWithReferencesPage GroupMembersPage { get; set; }
}
} | 27.857143 | 97 | 0.720513 | [
"MIT"
] | microsoftgraph/group-membership-management | Service/GroupMembershipManagement/Hosts/SecurityGroup/Function/Activity/SubsequentUsersReader/SubsequentUsersReaderRequest.cs | 390 | C# |
using System.Collections.Generic;
namespace CustomerServiceLib
{
public class CustomerService
{
private readonly ICustomerRepository _repository;
private readonly INameBuilder _nameBuilder;
public CustomerService(ICustomerRepository repository, INameBuilder nameBuilder = null)
{
_repository = repository;
_nameBuilder = nameBuilder;
}
public void Create(IEnumerable<CustomerDTO> customers)
{
foreach (var customer in customers)
{
_repository.Save(new Customer(customer.FirstName, customer.LastName));
}
}
public void Create(CustomerDTO customerDto)
{
string fullName = _nameBuilder.From(customerDto.FirstName, customerDto.LastName);
_repository.Save(new Customer(fullName));
}
}
} | 29.533333 | 95 | 0.63544 | [
"MIT"
] | VanHakobyan/TestingPractise | MoqFramework/CustomerServiceLib/CustomerService.cs | 888 | C# |
/* Generated by QSI
Date: 2020-08-12
Span: 1786:9 - 1786:34
File: src/postgres/include/nodes/execnodes.h
*/
namespace Qsi.PostgreSql.Internal.PG10.Types
{
internal class AggStatePerAggData
{
}
}
| 14.2 | 45 | 0.694836 | [
"MIT"
] | ScriptBox99/chequer-qsi | Qsi.PostgreSql/Internal/PG10/Types/AggStatePerAggData.cs | 213 | C# |
namespace AspNetCoreAnalyzers.Tests.Helpers
{
using System;
using System.Linq;
using Gu.Roslyn.Asserts;
using Microsoft.CodeAnalysis.CSharp;
using NUnit.Framework;
public static class UrlTemplateTests
{
[TestCase("foo", new[] { "foo" })]
[TestCase("/foo", new[] { "foo" })]
[TestCase("~/foo", new[] { "foo" })]
[TestCase("foo/bar", new[] { "foo", "bar" })]
public static void TryParse(string text, string[] expected)
{
var syntaxTree = CSharpSyntaxTree.ParseText(@"
namespace AspBox
{
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
[ApiController]
public class OrdersController : Controller
{
[HttpGet(""api/orders/{id}"")]
public async Task<IActionResult> GetOrder([FromRoute]int id)
{
}
}
}".AssertReplace("api/orders/{id}", text));
var literal = syntaxTree.FindLiteralExpression(text);
Assert.AreEqual(true, UrlTemplate.TryParse(literal, out var template));
CollectionAssert.AreEqual(expected, template.Path.Select(x => x.Span.ToString()));
Assert.IsTrue(template.Path.All(x => x.Parameter == null));
}
[TestCase("{id}", new[] { "{id}" })]
[TestCase("{*id}", new[] { "{*id}" })]
[TestCase("{**id}", new[] { "{**id}" })]
[TestCase("{id=1}", new[] { "{id=1}" })]
[TestCase("{id}/info", new[] { "{id}", "info" })]
[TestCase("{id?}/info", new[] { "{id?}", "info" })]
[TestCase("{id:int}/info", new[] { "{id:int}", "info" })]
[TestCase("{id:required}/info", new[] { "{id:required}", "info" })]
[TestCase("api/orders/{id}", new[] { "api", "orders", "{id}" })]
[TestCase("api/orders/{id}/info", new[] { "api", "orders", "{id}", "info" })]
public static void TryParseWithParameter(string text, string[] expected)
{
var syntaxTree = CSharpSyntaxTree.ParseText(@"
namespace AspBox
{
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
[ApiController]
public class OrdersController : Controller
{
[HttpGet(""api/orders/{id}"")]
public async Task<IActionResult> GetOrder([FromRoute]int id)
{
}
}
}".AssertReplace("api/orders/{id}", text));
var literal = syntaxTree.FindLiteralExpression(text);
Assert.AreEqual(true, UrlTemplate.TryParse(literal, out var template));
CollectionAssert.AreEqual(expected, template.Path.Select(x => x.Span.ToString()));
// ReSharper disable once PossibleInvalidOperationException
var segment = template.Path.Single(x => x.Parameter.HasValue);
Assert.AreEqual(expected.Single(x => x.StartsWith("{", StringComparison.Ordinal)), segment.Span.ToString());
Assert.AreEqual("id", segment.Parameter?.Name.ToString());
}
[TestCase("\"orders/{id}\"", new[] { "orders", "{id}" }, new string[0])]
[TestCase("@\"orders/{id}\"", new[] { "orders", "{id}" }, new string[0])]
[TestCase("\"orders/{id?}\"", new[] { "orders", "{id?}" }, new[] { "?" })]
[TestCase("\"orders/{id:min(1)}\"", new[] { "orders", "{id:min(1)}" }, new[] { "min(1)" })]
[TestCase("\"orders/{id:int:min(1):max(2)}\"", new[] { "orders", "{id:int:min(1):max(2)}" }, new[] { "int", "min(1)", "max(2)" })]
[TestCase("\"orders/{id:max(2)}\"", new[] { "orders", "{id:max(2)}" }, new[] { "max(2)" })]
[TestCase("\"orders/{id:int:max(2)}\"", new[] { "orders", "{id:int:max(2)}" }, new[] { "int", "max(2)" })]
[TestCase("\"orders/{id:range(1,23)}\"", new[] { "orders", "{id:range(1,23)}" }, new[] { "range(1,23)" })]
public static void TryParseWhenIntParameter(string text, string[] segments, string[] constraints)
{
var syntaxTree = CSharpSyntaxTree.ParseText(@"
namespace AspBox
{
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
[ApiController]
public class OrdersController : Controller
{
[HttpGet(""orders/{id}"")]
public async Task<IActionResult> GetOrder([FromRoute]int id)
{
}
}
}".AssertReplace("\"orders/{id}\"", text));
var literal = syntaxTree.FindLiteralExpression(text);
Assert.AreEqual(true, UrlTemplate.TryParse(literal, out var template));
CollectionAssert.AreEqual(segments, template.Path.Select(x => x.Span.ToString()));
// ReSharper disable once PossibleInvalidOperationException
var parameter = template.Path.Single(x => x.Parameter.HasValue)
.Parameter.Value;
Assert.AreEqual("id", parameter.Name.ToString());
CollectionAssert.AreEqual(constraints, parameter.Constraints.Select(x => x.Span.ToString()));
}
[TestCase("\"orders/{id}\"", new[] { "orders", "{id}" }, new string[0])]
[TestCase("\"orders/{id?}\"", new[] { "orders", "{id?}" }, new[] { "?" })]
[TestCase("\"orders/{id:alpha}\"", new[] { "orders", "{id:alpha}" }, new[] { "alpha" })]
[TestCase("\"orders/{id:ALPHA}\"", new[] { "orders", "{id:ALPHA}" }, new[] { "ALPHA" })]
[TestCase("\"orders/{id:alpha:minlength(1)}\"", new[] { "orders", "{id:alpha:minlength(1)}" }, new[] { "alpha", "minlength(1)" })]
[TestCase("\"orders/{id:minlength(1)}\"", new[] { "orders", "{id:minlength(1)}" }, new[] { "minlength(1)" })]
[TestCase("\"orders/{id:maxlength(1)}\"", new[] { "orders", "{id:maxlength(1)}" }, new[] { "maxlength(1)" })]
[TestCase("\"orders/{id:length(1)}\"", new[] { "orders", "{id:length(1)}" }, new[] { "length(1)" })]
[TestCase("\"orders/{id:length(1,2)}\"", new[] { "orders", "{id:length(1,2)}" }, new[] { "length(1,2)" })]
[TestCase("\"orders/{id:regex(^\\\\d$)}\"", new[] { "orders", "{id:regex(^\\d$)}" }, new[] { "regex(^\\d$)" })]
[TestCase("@\"orders/{id:regex(^\\d$)}\"", new[] { "orders", "{id:regex(^\\d$)}" }, new[] { "regex(^\\d$)" })]
[TestCase("\"orders/{id:regex(^\\\\d{{3}}-\\\\d{{2}}-\\\\d{4}$)}\"", new[] { "orders", "{id:regex(^\\d{{3}}-\\d{{2}}-\\d{4}$)}" }, new[] { "regex(^\\d{{3}}-\\d{{2}}-\\d{4}$)" })]
[TestCase("\"orders/{id:regex(a/b)}\"", new[] { "orders", "{id:regex(a/b)}" }, new[] { "regex(a/b)" })]
[TestCase("\"orders/{id:regex(a{{0,1}})}\"", new[] { "orders", "{id:regex(a{{0,1}})}" }, new[] { "regex(a{{0,1}})" })]
[TestCase("\"orders/{id:minlength(1):regex(a{{0,1}})}\"", new[] { "orders", "{id:minlength(1):regex(a{{0,1}})}" }, new[] { "minlength(1)", "regex(a{{0,1}})" })]
[TestCase("\"orders/{id:regex(a{{0,1}}):minlength(1)}\"", new[] { "orders", "{id:regex(a{{0,1}}):minlength(1)}" }, new[] { "regex(a{{0,1}})", "minlength(1)" })]
public static void TryParseWhenStringParameter(string text, string[] segments, string[] constraints)
{
var syntaxTree = CSharpSyntaxTree.ParseText(@"
namespace AspBox
{
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
[ApiController]
public class OrdersController : Controller
{
[HttpGet(""orders/{id}"")]
public async Task<IActionResult> GetOrder(string id)
{
}
}
}".AssertReplace("\"orders/{id}\"", text));
var literal = syntaxTree.FindLiteralExpression(text);
Assert.AreEqual(true, UrlTemplate.TryParse(literal, out var template));
CollectionAssert.AreEqual(segments, template.Path.Select(x => x.Span.ToString()));
// ReSharper disable once PossibleInvalidOperationException
var parameter = template.Path.Single(x => x.Parameter.HasValue)
.Parameter.Value;
Assert.AreEqual("id", parameter.Name.ToString());
CollectionAssert.AreEqual(constraints, parameter.Constraints.Select(x => x.Span.ToString()));
}
[TestCase("{?id}", new[] { "{?id}" }, "?id")]
[TestCase("{id*}", new[] { "{id*}" }, "id*")]
[TestCase("{i*d*}", new[] { "{i*d*}" }, "i*d*")]
[TestCase("orders/{id*}", new[] { "orders", "{id*}" }, "id*")]
[TestCase("{id/}", new[] { "{id/}" }, "id/")]
[TestCase("{i/d}", new[] { "{i/d}" }, "i/d")]
[TestCase("{i/d/}", new[] { "{i/d/}" }, "i/d/")]
[TestCase("{/i/d/}", new[] { "{/i/d/}" }, "/i/d/")]
[TestCase("orders/{id/}", new[] { "orders", "{id/}" }, "id/")]
[TestCase("orders/{/i/d/}", new[] { "orders", "{/i/d/}" }, "/i/d/")]
public static void TryParseWhenSyntaxErrorParameter(string text, string[] segments, string name)
{
var syntaxTree = CSharpSyntaxTree.ParseText(@"
namespace AspBox
{
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
[ApiController]
public class OrdersController : Controller
{
[HttpGet(""{id}"")]
public async Task<IActionResult> GetOrder([FromRoute]int id)
{
}
}
}".AssertReplace("{id}", text));
var literal = syntaxTree.FindLiteralExpression(text);
Assert.AreEqual(true, UrlTemplate.TryParse(literal, out var template));
CollectionAssert.AreEqual(segments, template.Path.Select(x => x.Span.ToString()));
// ReSharper disable once PossibleInvalidOperationException
var parameter = template.Path.Single(x => x.Parameter.HasValue)
.Parameter.Value;
Assert.AreEqual(name, parameter.Name.ToString());
}
[TestCase("orders/{id:}", new[] { "orders", "{id:}" }, new[] { "" })]
[TestCase("orders/{id:min(1}", new[] { "orders", "{id:min(1}" }, new[] { "min(1" })]
[TestCase("orders/{id:min1)}", new[] { "orders", "{id:min1)}" }, new[] { "min1)" })]
public static void TryParseWhenSyntaxErrorConstraint(string text, string[] segments, string[] constraints)
{
var syntaxTree = CSharpSyntaxTree.ParseText(@"
namespace AspBox
{
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
[ApiController]
public class OrdersController : Controller
{
[HttpGet(""orders/{id}"")]
public async Task<IActionResult> GetOrder([FromRoute]int id)
{
}
}
}".AssertReplace("orders/{id}", text));
var literal = syntaxTree.FindLiteralExpression(text);
Assert.AreEqual(true, UrlTemplate.TryParse(literal, out var template));
CollectionAssert.AreEqual(segments, template.Path.Select(x => x.Span.ToString()));
// ReSharper disable once PossibleInvalidOperationException
var parameter = template.Path.Single(x => x.Parameter.HasValue)
.Parameter.Value;
Assert.AreEqual("id", parameter.Name.ToString());
CollectionAssert.AreEqual(constraints, parameter.Constraints.Select(x => x.Span.ToString()));
}
}
}
| 54.36 | 186 | 0.496934 | [
"MIT"
] | JTOne123/AspNetCoreAnalyzers | AspNetCoreAnalyzers.Tests/Helpers/UrlTemplateTests.cs | 12,231 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using RecipesSearch.Data.Models;
using RecipesSearch.DAL.Cache.Adapters;
using RecipesSearch.SearchEngine.Clusters.Base;
namespace RecipesSearch.SearchEngine.Clusters
{
public class SpanningTreeBuilder : BaseClustersBuilder
{
private int[] _parents;
private int[] _ranks;
protected static SpanningTreeBuilder _instance;
private SpanningTreeBuilder()
{
}
public static SpanningTreeBuilder GetInstance()
{
if (_instance == null)
{
_instance = new SpanningTreeBuilder();
}
return _instance;
}
protected override void ComputeClusters(List<NearestResult> results, TfIdfConfig config)
{
var threshold = GetSetting<int>(config, "threshold") ?? 0;
var graphInfo = BuildGraphInfo(results);
int[] edgesCount = new int[graphInfo.RecipesCount];
Array.Sort(graphInfo.Edges, (IComparer)null);
_parents = new int[graphInfo.RecipesCount];
_ranks = new int[graphInfo.RecipesCount];
for (int i = 0; i < graphInfo.RecipesCount; ++i)
{
MakeSet(i);
}
List<Edge> minTreeEdges = new List<Edge>();
for (int i = 0; i < graphInfo.Edges.Length; ++i)
{
int a = graphInfo.Edges[i].FromSurrogateId;
int b = graphInfo.Edges[i].ToSurrogateId;
if (FindSet(a) != FindSet(b))
{
minTreeEdges.Add(graphInfo.Edges[i]);
UnionSets(a, b);
}
}
for (int i = 0; i < minTreeEdges.Count; ++i)
{
int from = minTreeEdges[i].FromSurrogateId;
int to = minTreeEdges[i].ToSurrogateId;
double weight = minTreeEdges[i].Weight;
if(minTreeEdges[i].Weight <= threshold)
{
graphInfo.Graph[from].Add(new Tuple<int, double>(to, weight));
graphInfo.Graph[to].Add(new Tuple<int, double>(from, weight));
}
}
int clusterId = 1;
for (int i = 0; i < graphInfo.RecipesCount; ++i)
{
Dfs(i, graphInfo.Graph, graphInfo.Clusters, clusterId++);
}
SaveResults(graphInfo);
}
private void MakeSet(int v)
{
_parents[v] = v;
_ranks[v] = 0;
}
private int FindSet(int v)
{
if (v == _parents[v])
return v;
return _parents[v] = FindSet(_parents[v]);
}
private void UnionSets(int a, int b)
{
a = FindSet(a);
b = FindSet(b);
if (a != b)
{
if (_ranks[a] < _ranks[b])
{
a = a ^ b;
b = a ^ b;
a = a ^ b;
}
_parents[b] = a;
if (_ranks[a] == _ranks[b])
{
++_ranks[a];
}
}
}
private void Dfs(int v, List<Tuple<int, double>>[] graph, List<int>[] clusters, int clusterId)
{
if (clusters[v].Any())
{
return;
}
clusters[v].Add(clusterId);
for (int i = 0; i < graph[v].Count; ++i)
{
int to = graph[v][i].Item1;
Dfs(to, graph, clusters, clusterId);
}
}
}
}
| 27.284672 | 102 | 0.466827 | [
"MIT"
] | intersystems-ru/recipesearch | recipessearch/recipessearch.searchengine/Clusters/SpanningTreeBuilder.cs | 3,740 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Este código fue generado por una herramienta.
// Versión de runtime:4.0.30319.42000
//
// Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si
// se vuelve a generar el código.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("TestingConsola")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("TestingConsola")]
[assembly: System.Reflection.AssemblyTitleAttribute("TestingConsola")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generado por la clase WriteCodeFragment de MSBuild.
| 44 | 96 | 0.645833 | [
"MIT"
] | hangardonelli/FC-Cba-services | TestingConsola/obj/Debug/net6.0/TestingConsola.AssemblyInfo.cs | 1,061 | C# |
namespace CleanDDDArchitecture.Domains.Todo.SubDomains.TodoItem.Application.UseCases.Delete
{
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Aviant.DDD.Application.Orchestration;
using Aviant.DDD.Application.UseCases;
using Todo.Application.Persistence;
public sealed class TodoItemDeleteUseCase
: UseCase<TodoItemDeleteInput, ITodoItemDeleteOutput, ITodoDbContextWrite>
{
public override async Task ExecuteAsync(
TodoItemDeleteInput input,
CancellationToken cancellationToken = default)
{
OrchestratorResponse requestResult = await Orchestrator.SendCommandAsync(
new DeleteTodoItemCommand(input.Id),
cancellationToken)
.ConfigureAwait(false);
if (!requestResult.Succeeded)
Output.Invalid(requestResult.Messages.First());
}
}
}
| 35.222222 | 91 | 0.678233 | [
"MIT"
] | panosru/CleanDDDArchitecture | Domains/Todo/SubDomains/TodoItem/Application/UseCases/Delete/TodoItemDeleteUseCase.cs | 951 | C# |
using System;
using System.Drawing;
namespace RecoHuman.Sources
{
[Flags]
public enum ImageSourceType
{
None = 0x00,
Camera = 0x01,
ImageServer = 0x02,
File = 0x04,
Pipe = 0x08,
All = ImageSourceType.Camera | ImageSourceType.ImageServer | ImageSourceType.Pipe | ImageSourceType.File
};
/// <summary>
/// Represents the method that will handle the ElementAdded and ElementRemoved of a ImageSourceCollection object
/// </summary>
/// <param name="source">The ImageSourceCollection which rises the event</param>
/// <param name="element">The element which has been added or remoed from the collection</param>
public delegate void ImageSourceCollectionChanged(ImageSourceCollection source, IImageSource element);
/// <summary>
/// Represents the method that will handle the ImageProduced event of a IImageSource object
/// </summary>
/// <param name="source">The source object on which the image was produced</param>
public delegate void ImageProducedEventHandler(IImageSource source);
/// <summary>
/// Represents the method that will handle the CameraCollectionChanged event of the VeriLookWebCamAdapter class
/// </summary>
/// <param name="sender">The VeriLookWebCamAdapter object which rises the event</param>
public delegate void VeriLookWebCamAdapterEventHandler(VeriLookWebCamAdapter sender);
/// <summary>
/// Represents the method that will handle the ImageCaptured event of the WIACameraAdapter class
/// </summary>
/// <param name="sender">The WIACameraAdapter object which rises the event</param>
/// <param name="capturedImage">The captured image</param>
public delegate void WIACameraAdapterImageCapturedEventHandler(WIACameraAdapter sender, Bitmap capturedImage);
/// <summary>
/// Represents the method that will handle the CameraCollectionChanged event of the WIACameraAdapter class
/// </summary>
/// <param name="sender">The WIACameraAdapter object which rises the event</param>
public delegate void WIACameraAdapterEventHandler(WIACameraAdapter sender);
/// <summary>
/// Represents the method that will handle the ImageCaptured event of the CameraAdapter class
/// </summary>
/// <param name="sender">The WIACameraAdapter object which rises the event</param>
/// <param name="capturedImage">The captured image</param>
public delegate void ImageCapturedEventHandler(CameraAdapter sender, Bitmap capturedImage);
/// <summary>
/// Represents the method that will handle the CameraCollectionChanged event of the CameraAdapter class
/// </summary>
/// <param name="sender">The WIACameraAdapter object which rises the event</param>
public delegate void CameraAdapterEventHandler(CameraAdapter sender);
}
| 41.90625 | 113 | 0.768829 | [
"MIT"
] | BioRoboticsUNAM/PRS-FND | RecoHuman2/Sources/Sources.cs | 2,684 | C# |
using Karambit.Logging;
using Karambit.Net;
using System;
using System.Collections.Generic;
namespace Karambit
{
/// <summary>
/// Started event handler.
/// </summary>
public delegate void StartedEventHandler(object sender, EventArgs e);
/// <summary>
/// Errror event handler.
/// </summary>
public delegate void ErrorEventHandler(object sender, UnhandledExceptionEventArgs e);
/// <summary>
/// Stopped event handler.
/// </summary>
public delegate void StoppedEventHandler(object sender, EventArgs e);
/// <summary>
/// An abstract class which represents the Karambit application framework.
/// </summary>
public abstract class Application : IApplication
{
#region Fields
private Deployment deployment = Deployment.Release;
private bool running = false;
protected string name = "untitledapp";
protected List<IServer> servers = new List<IServer>();
private static Logger logger;
private static IApplication currentApp;
#endregion
#region Properties
/// <summary>
/// Gets the current logger.
/// </summary>
/// <value>The logger.</value>
public static Logger Logger {
get {
if (logger == null)
logger = new Logger();
return logger;
}
}
/// <summary>
/// Gets the deployment type.
/// </summary>
/// <value>The deployment.</value>
public virtual Deployment Deployment {
get {
return deployment;
}
set {
deployment = value;
}
}
/// <summary>
/// Gets a value indicating whether this <see cref="Application"/> is running.
/// </summary>
/// <value>
/// <c>true</c> if running; otherwise, <c>false</c>.
/// </value>
public bool Running {
get {
return running;
}
}
/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>The name.</value>
public string Name {
get {
return name;
}
set {
this.name = value;
}
}
/// <summary>
/// Gets the currently executing application (if any).
/// </summary>
/// <value>The current app.</value>
public static IApplication Current {
get {
return currentApp;
}
}
/// <summary>
/// Gets or sets the current deployment.
/// When attempting to set the deployment when no application is running,
/// this property will do nothing. Getting the deployment value will return
/// release if no application is running.
/// </summary>
/// <value>The current deployment.</value>
public static Deployment CurrentDeployment {
get {
if (currentApp == null)
return Deployment.Release;
return currentApp.Deployment;
} set {
if (currentApp == null)
return;
currentApp.Deployment = value;
}
}
#endregion
#region Events
/// <summary>
/// Occurs when the application has started.
/// </summary>
public event StartedEventHandler Started;
/// <summary>
/// Occurs when the application has stopped.
/// </summary>
public event StoppedEventHandler Stopped;
/// <summary>
/// Occurs when the application encounters a generic error.
/// </summary>
public event ErrorEventHandler Error;
/// <summary>
/// Called when the application starts.
/// </summary>
protected virtual void OnStarted() {
if (Started != null)
Started(this, new EventArgs());
}
/// <summary>
/// Called when the application stops.
/// </summary>
protected virtual void OnStopped() {
if (Stopped != null)
Stopped(this, new EventArgs());
}
/// <summary>
/// Called when the application encounters a generic error.
/// </summary>
/// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
protected virtual void OnError(UnhandledExceptionEventArgs e) {
if (Error != null)
Error(this, e);
}
#endregion
#region Methods
/// <summary>
/// Starts this application.
/// </summary>
public virtual void Start() {
if (running)
return;
running = true;
// invoke event
OnStarted();
// start servers
foreach (IServer server in servers)
server.Start();
}
/// <summary>
/// Stops this application.
/// </summary>
public virtual void Stop() {
if (!running)
return;
running = false;
// invoke event
OnStopped();
// stop servers
foreach (IServer server in servers)
server.Stop();
}
/// <summary>
/// Logs a message to the application channel.
/// </summary>
/// <param name="level">The level.</param>
/// <param name="msg">The message.</param>
public virtual void Log(LogLevel level, string msg) {
Logger.Log(level, name.ToLower(), msg);
}
/// <summary>
/// Attaches the specified server to the application.
/// </summary>
/// <param name="server">The server.</param>
public virtual void Attach(IServer server) {
servers.Add(server);
}
/// <summary>
/// Detaches the specified server from the application.
/// </summary>
/// <param name="server">The server.</param>
public virtual void Detach(IServer server) {
servers.Remove(server);
}
/// <summary>
/// Runs the specified application.
/// </summary>
/// <param name="app">The application.</param>
/// <param name="args">The arguments.</param>
public static void Run(IApplication app, string[] args) {
// deployment
app.Deployment = (System.Diagnostics.Debugger.IsAttached) ? Deployment.Production : Deployment.Release;
// start
app.Start();
// set current
currentApp = app;
// stop on process exit
AppDomain.CurrentDomain.ProcessExit += delegate(object sender, EventArgs e) {
if (app.Running)
app.Stop();
};
// loop
while (true) {
string command = Console.ReadLine();
if (command == "quit" || command == "exit")
return;
else if (command == "clear")
Console.Clear();
}
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Application"/> class.
/// </summary>
protected Application() {
}
/// <summary>
/// Initializes a new instance of the <see cref="Application"/> class.
/// </summary>
/// <param name="name">The name.</param>
protected Application(string name)
: this() {
this.name = name;
}
#endregion
}
} | 28.564103 | 117 | 0.508592 | [
"MIT"
] | Karambyte/karambit | Karambit/Application.cs | 7,800 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication2
{
public partial class SiteMaster : MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
} | 19.352941 | 61 | 0.662614 | [
"MIT"
] | brentmorgan43/MVCStyleBehaviorInClassicASPNET | After MVC WebApplication2/WebApplication2/Site.Master.cs | 331 | C# |
using Business.PlateRecognizer;
using Microsoft.Extensions.DependencyInjection;
namespace Business
{
public static class BusinessDependencyInjection
{
public static void InjectBusiness(this IServiceCollection services)
{
services.AddTransient<IUserBusiness, UserBusiness>();
services.AddTransient<IVehicleBusiness, VehicleBusiness>();
services.AddTransient<IAccessBusiness, AccessBusiness>();
services.AddTransient<IPlateRecognizer, PlateRecognizerBusiness>();
services.AddTransient<IGateControl, GateControl>();
}
}
} | 36.176471 | 79 | 0.713821 | [
"MIT"
] | CristianoRC/Gatel | src/api/Business/BusinessDependencyInjection.cs | 615 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Loteria.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Loteria Mega-Sena";
return View();
}
}
}
| 17.526316 | 48 | 0.624625 | [
"MIT"
] | leomaturano/loteria | Loteria/Controllers/HomeController.cs | 335 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.vod.Model.V20170321;
namespace Aliyun.Acs.vod.Transform.V20170321
{
public class DescribePlayUserTotalResponseUnmarshaller
{
public static DescribePlayUserTotalResponse Unmarshall(UnmarshallerContext _ctx)
{
DescribePlayUserTotalResponse describePlayUserTotalResponse = new DescribePlayUserTotalResponse();
describePlayUserTotalResponse.HttpResponse = _ctx.HttpResponse;
describePlayUserTotalResponse.RequestId = _ctx.StringValue("DescribePlayUserTotal.RequestId");
List<DescribePlayUserTotalResponse.DescribePlayUserTotal_UserPlayStatisTotal> describePlayUserTotalResponse_userPlayStatisTotals = new List<DescribePlayUserTotalResponse.DescribePlayUserTotal_UserPlayStatisTotal>();
for (int i = 0; i < _ctx.Length("DescribePlayUserTotal.UserPlayStatisTotals.Length"); i++) {
DescribePlayUserTotalResponse.DescribePlayUserTotal_UserPlayStatisTotal userPlayStatisTotal = new DescribePlayUserTotalResponse.DescribePlayUserTotal_UserPlayStatisTotal();
userPlayStatisTotal.Date = _ctx.StringValue("DescribePlayUserTotal.UserPlayStatisTotals["+ i +"].Date");
userPlayStatisTotal.PlayDuration = _ctx.StringValue("DescribePlayUserTotal.UserPlayStatisTotals["+ i +"].PlayDuration");
userPlayStatisTotal.PlayRange = _ctx.StringValue("DescribePlayUserTotal.UserPlayStatisTotals["+ i +"].PlayRange");
DescribePlayUserTotalResponse.DescribePlayUserTotal_UserPlayStatisTotal.DescribePlayUserTotal_VV vV = new DescribePlayUserTotalResponse.DescribePlayUserTotal_UserPlayStatisTotal.DescribePlayUserTotal_VV();
vV.Android = _ctx.StringValue("DescribePlayUserTotal.UserPlayStatisTotals["+ i +"].VV.Android");
vV.IOS = _ctx.StringValue("DescribePlayUserTotal.UserPlayStatisTotals["+ i +"].VV.iOS");
vV.Flash = _ctx.StringValue("DescribePlayUserTotal.UserPlayStatisTotals["+ i +"].VV.Flash");
vV.HTML5 = _ctx.StringValue("DescribePlayUserTotal.UserPlayStatisTotals["+ i +"].VV.HTML5");
userPlayStatisTotal.VV = vV;
DescribePlayUserTotalResponse.DescribePlayUserTotal_UserPlayStatisTotal.DescribePlayUserTotal_UV uV = new DescribePlayUserTotalResponse.DescribePlayUserTotal_UserPlayStatisTotal.DescribePlayUserTotal_UV();
uV.Android = _ctx.StringValue("DescribePlayUserTotal.UserPlayStatisTotals["+ i +"].UV.Android");
uV.IOS = _ctx.StringValue("DescribePlayUserTotal.UserPlayStatisTotals["+ i +"].UV.iOS");
uV.Flash = _ctx.StringValue("DescribePlayUserTotal.UserPlayStatisTotals["+ i +"].UV.Flash");
uV.HTML5 = _ctx.StringValue("DescribePlayUserTotal.UserPlayStatisTotals["+ i +"].UV.HTML5");
userPlayStatisTotal.UV = uV;
describePlayUserTotalResponse_userPlayStatisTotals.Add(userPlayStatisTotal);
}
describePlayUserTotalResponse.UserPlayStatisTotals = describePlayUserTotalResponse_userPlayStatisTotals;
return describePlayUserTotalResponse;
}
}
}
| 58.646154 | 219 | 0.790661 | [
"Apache-2.0"
] | pengweiqhca/aliyun-openapi-net-sdk | aliyun-net-sdk-vod/Vod/Transform/V20170321/DescribePlayUserTotalResponseUnmarshaller.cs | 3,812 | C# |
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MyOnlineShop.Common.Constants;
using MyOnlineShop.Common.Services;
using MyOnlineShop.Common.ViewModels.Addresses;
using MyOnlineShop.Common.ViewModels.Products;
using MyOnlineShop.Common.ViewModels.ShoppingCarts;
using MyOnlineShop.WebMVC.Services.Catalog;
using MyOnlineShop.WebMVC.Services.Ordering;
using MyOnlineShop.WebMVC.Services.ShoppingCart;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace MyOnlineShop.WebMVC.Controllers
{
[Authorize]
public class ShoppingCartsController : Controller
{
private readonly IMapper mapper;
private readonly IShoppingCartService shoppingCartService;
private readonly ICatalogService catalogService;
private readonly IOrderingService orderingService;
private readonly ICurrentUserService currentUserService;
private readonly IShoppingCartGatewayService shoppingCartGatewayService;
public ShoppingCartsController(
IMapper mapper,
IShoppingCartService shoppingCartService,
ICatalogService catalogService,
IOrderingService orderingService,
ICurrentUserService currentUserService,
IShoppingCartGatewayService shoppingCartGatewayService)
{
this.mapper = mapper;
this.shoppingCartService = shoppingCartService;
this.catalogService = catalogService;
this.orderingService = orderingService;
this.currentUserService = currentUserService;
this.shoppingCartGatewayService = shoppingCartGatewayService;
}
public async Task<IActionResult> Index()
{
try
{
var shoppingCartViewModel = await this.shoppingCartService.GetShoppingCart(this.currentUserService.UserId);
return this.View(shoppingCartViewModel);
}
catch (Refit.ApiException apiEx)
{
if (apiEx.HasContent)
{
JsonConvert
.DeserializeObject<List<string>>(apiEx.Content)
.ForEach(error => this.ModelState.AddModelError(string.Empty, error));
}
else
{
this.ModelState.AddModelError(string.Empty, ErrorConstants.InternalServerErrorMessage);
}
this.HandleException(apiEx);
}
return this.View();
}
[HttpPost]
public async Task<IActionResult> AddProduct(int productId, int? fromPage = 1)
{
try
{
var productDetailsViewModel = await this.catalogService.GetProductDetails(productId, fromPage);
var cartItemViewModel = this.mapper.Map<ProductDetailsViewModel, CartItemViewModel>(productDetailsViewModel);
await this.shoppingCartService.AddToCart(this.currentUserService.UserId, cartItemViewModel);
return this.Redirect($"/Products/Index/?currentPage={fromPage}");
}
catch (Refit.ApiException apiEx)
{
if (apiEx.HasContent)
{
JsonConvert
.DeserializeObject<List<string>>(apiEx.Content)
.ForEach(error => this.ModelState.AddModelError(string.Empty, error));
}
else
{
this.ModelState.AddModelError(string.Empty, ErrorConstants.InternalServerErrorMessage);
}
this.HandleException(apiEx);
return this.Redirect($"/Products/Index/?currentPage={fromPage}");
}
}
[HttpPost]
public async Task<IActionResult> Clear()
{
try
{
await this.shoppingCartService.Clear(this.currentUserService.UserId);
return this.Redirect(nameof(Index));
}
catch (Refit.ApiException apiEx)
{
if (apiEx.HasContent)
{
JsonConvert
.DeserializeObject<List<string>>(apiEx.Content)
.ForEach(error => this.ModelState.AddModelError(string.Empty, error));
}
else
{
this.ModelState.AddModelError(string.Empty, ErrorConstants.InternalServerErrorMessage);
}
this.HandleException(apiEx);
}
return this.Redirect(nameof(Index));
}
[HttpPost]
public async Task<IActionResult> RemoveItem(int productId)
{
try
{
await this.shoppingCartService.RemoveItem(productId, this.currentUserService.UserId);
return this.Redirect(nameof(Index));
}
catch (Refit.ApiException apiEx)
{
if (apiEx.HasContent)
{
JsonConvert
.DeserializeObject<List<string>>(apiEx.Content)
.ForEach(error => this.ModelState.AddModelError(string.Empty, error));
}
else
{
this.ModelState.AddModelError(string.Empty, ErrorConstants.InternalServerErrorMessage);
}
this.HandleException(apiEx);
}
return this.Redirect(nameof(Index));
}
public async Task<IActionResult> Checkout()
{
try
{
var shoppingCartOrderWrapperViewModel = await this.shoppingCartGatewayService.GetCheckout();
return this.View(shoppingCartOrderWrapperViewModel);
}
catch (Refit.ApiException apiEx)
{
if (apiEx.HasContent)
{
JsonConvert
.DeserializeObject<List<string>>(apiEx.Content)
.ForEach(error => this.ModelState.AddModelError(string.Empty, error));
}
else
{
this.ModelState.AddModelError(string.Empty, ErrorConstants.InternalServerErrorMessage);
}
this.HandleException(apiEx);
}
return this.View();
}
[HttpPost]
public async Task<IActionResult> Checkout(OrderAddressViewModel orderAddressViewModel)
{
try
{
await this.shoppingCartGatewayService.Checkout(orderAddressViewModel);
return this.RedirectToAction(nameof(Success));
}
catch (Refit.ApiException apiEx)
{
if (apiEx.HasContent)
{
JsonConvert
.DeserializeObject<List<string>>(apiEx.Content)
.ForEach(error => this.ModelState.AddModelError(string.Empty, error));
}
else
{
this.ModelState.AddModelError(string.Empty, ErrorConstants.InternalServerErrorMessage);
}
this.HandleException(apiEx);
}
return this.View();
}
public IActionResult Success()
{
return this.View("Success", ShoppingCartConstants.SuccessMessage);
}
private void HandleException(Exception ex)
{
ViewBag.ShoppingCartInoperativeMsg = $"Shopping Cart Service is inoperative {ex.GetType().Name} - {ex.Message}";
}
}
}
| 34.495575 | 125 | 0.564905 | [
"MIT"
] | DimchoLakov/Architecture-Of-ASP-NET-Core-Microservices-Apps | MyOnlineShop/MyOnlineShop.WebMVC/Controllers/ShoppingCartsController.cs | 7,798 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace k8s.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <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>
public partial class V1ControllerRevision
{
/// <summary>
/// Initializes a new instance of the V1ControllerRevision class.
/// </summary>
public V1ControllerRevision()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the V1ControllerRevision class.
/// </summary>
/// <param name="revision">Revision indicates the revision of the state
/// represented by Data.</param>
/// <param name="apiVersion">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</param>
/// <param name="data">Data is the serialized representation of the
/// state.</param>
/// <param name="kind">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</param>
/// <param name="metadata">Standard object's metadata. More info:
/// https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata</param>
public V1ControllerRevision(long revision, string apiVersion = default(string), object data = default(object), string kind = default(string), V1ObjectMeta metadata = default(V1ObjectMeta))
{
ApiVersion = apiVersion;
Data = data;
Kind = kind;
Metadata = metadata;
Revision = revision;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets 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>
[JsonProperty(PropertyName = "apiVersion")]
public string ApiVersion { get; set; }
/// <summary>
/// Gets or sets data is the serialized representation of the state.
/// </summary>
[JsonProperty(PropertyName = "data")]
public object Data { get; set; }
/// <summary>
/// Gets or sets 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>
[JsonProperty(PropertyName = "kind")]
public string Kind { get; set; }
/// <summary>
/// Gets or sets standard object's metadata. More info:
/// https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
/// </summary>
[JsonProperty(PropertyName = "metadata")]
public V1ObjectMeta Metadata { get; set; }
/// <summary>
/// Gets or sets revision indicates the revision of the state
/// represented by Data.
/// </summary>
[JsonProperty(PropertyName = "revision")]
public long Revision { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
}
}
}
| 44.683333 | 197 | 0.621783 | [
"Apache-2.0"
] | AshenW0lf/csharp | src/KubernetesClient/generated/Models/V1ControllerRevision.cs | 5,362 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void MultiplyRoundedDoublingAndAddSaturateHigh_Vector128_Int32()
{
var test = new SimpleTernaryOpTest__MultiplyRoundedDoublingAndAddSaturateHigh_Vector128_Int32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleTernaryOpTest__MultiplyRoundedDoublingAndAddSaturateHigh_Vector128_Int32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] inArray3;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle inHandle3;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] inArray3, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inArray3 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Int32, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
inHandle3.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int32> _fld1;
public Vector128<Int32> _fld2;
public Vector128<Int32> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__MultiplyRoundedDoublingAndAddSaturateHigh_Vector128_Int32 testClass)
{
var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh(_fld1, _fld2, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplyRoundedDoublingAndAddSaturateHigh_Vector128_Int32 testClass)
{
fixed (Vector128<Int32>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
fixed (Vector128<Int32>* pFld3 = &_fld3)
{
var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh(
AdvSimd.LoadVector128((Int32*)(pFld1)),
AdvSimd.LoadVector128((Int32*)(pFld2)),
AdvSimd.LoadVector128((Int32*)(pFld3))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Int32[] _data3 = new Int32[Op3ElementCount];
private static Vector128<Int32> _clsVar1;
private static Vector128<Int32> _clsVar2;
private static Vector128<Int32> _clsVar3;
private Vector128<Int32> _fld1;
private Vector128<Int32> _fld2;
private Vector128<Int32> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__MultiplyRoundedDoublingAndAddSaturateHigh_Vector128_Int32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public SimpleTernaryOpTest__MultiplyRoundedDoublingAndAddSaturateHigh_Vector128_Int32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, _data3, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Rdm.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh(
AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector128((Int32*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Rdm).GetMethod(nameof(Rdm.MultiplyRoundedDoublingAndAddSaturateHigh), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Rdm).GetMethod(nameof(Rdm.MultiplyRoundedDoublingAndAddSaturateHigh), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector128((Int32*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int32>* pClsVar1 = &_clsVar1)
fixed (Vector128<Int32>* pClsVar2 = &_clsVar2)
fixed (Vector128<Int32>* pClsVar3 = &_clsVar3)
{
var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh(
AdvSimd.LoadVector128((Int32*)(pClsVar1)),
AdvSimd.LoadVector128((Int32*)(pClsVar2)),
AdvSimd.LoadVector128((Int32*)(pClsVar3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr);
var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr));
var op3 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray3Ptr));
var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleTernaryOpTest__MultiplyRoundedDoublingAndAddSaturateHigh_Vector128_Int32();
var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleTernaryOpTest__MultiplyRoundedDoublingAndAddSaturateHigh_Vector128_Int32();
fixed (Vector128<Int32>* pFld1 = &test._fld1)
fixed (Vector128<Int32>* pFld2 = &test._fld2)
fixed (Vector128<Int32>* pFld3 = &test._fld3)
{
var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh(
AdvSimd.LoadVector128((Int32*)(pFld1)),
AdvSimd.LoadVector128((Int32*)(pFld2)),
AdvSimd.LoadVector128((Int32*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int32>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
fixed (Vector128<Int32>* pFld3 = &_fld3)
{
var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh(
AdvSimd.LoadVector128((Int32*)(pFld1)),
AdvSimd.LoadVector128((Int32*)(pFld2)),
AdvSimd.LoadVector128((Int32*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh(
AdvSimd.LoadVector128((Int32*)(&test._fld1)),
AdvSimd.LoadVector128((Int32*)(&test._fld2)),
AdvSimd.LoadVector128((Int32*)(&test._fld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int32> op1, Vector128<Int32> op2, Vector128<Int32> op3, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] inArray3 = new Int32[Op3ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] inArray3 = new Int32[Op3ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(Int32[] firstOp, Int32[] secondOp, Int32[] thirdOp, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.MultiplyRoundedDoublingAndAddSaturateHigh(firstOp[i], secondOp[i], thirdOp[i]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Rdm)}.{nameof(Rdm.MultiplyRoundedDoublingAndAddSaturateHigh)}<Int32>(Vector128<Int32>, Vector128<Int32>, Vector128<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| 47.08056 | 210 | 0.603169 | [
"MIT"
] | 2m0nd/runtime | src/tests/JIT/HardwareIntrinsics/Arm/Rdm/MultiplyRoundedDoublingAndAddSaturateHigh.Vector128.Int32.cs | 26,883 | C# |
/*
Copyright (C) 2018-2019 de4dot@gmail.com
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.Linq;
namespace Generator.Enums {
enum CodeSize {
[Comment("Unknown size")]
Unknown,
[Comment("16-bit code")]
Code16,
[Comment("32-bit code")]
Code32,
[Comment("64-bit code")]
Code64,
}
static class CodeSizeEnum {
const string documentation = "The code size (16/32/64) that was used when an instruction was decoded";
static EnumValue[] GetValues() =>
typeof(CodeSize).GetFields().Where(a => a.IsLiteral).Select(a => new EnumValue((uint)(CodeSize)a.GetValue(null)!, a.Name, CommentAttribute.GetDocumentation(a))).ToArray();
public static readonly EnumType Instance = new EnumType(TypeIds.CodeSize, documentation, GetValues(), EnumTypeFlags.Public);
}
}
| 37.659574 | 174 | 0.766102 | [
"MIT"
] | NIKJOO/iced | src/csharp/Intel/Generator/Enums/CodeSizeEnum.cs | 1,770 | C# |
using Spectre.Cli;
using System.ComponentModel;
namespace Omnia.CLI.Commands.Management.Tenants
{
public sealed class AddCommandSettings : CommandSettings
{
[CommandOption("-s|--subscription <VALUE>")]
[Description("Name of the configured subscription.")]
public string Subscription { get; set; }
[CommandOption("-c|--code <VALUE>")]
[Description("Code of the Tenant to create.")]
public string Code { get; set; }
[CommandOption("-n|--name <VALUE>")]
[Description("Name of the Tenant to create.")]
public string Name { get; set; }
}
} | 31.1 | 61 | 0.631833 | [
"MIT"
] | davidcaldas/omnia-cli | src/Console/Commands/Management/Tenants/AddCommandSettings.cs | 624 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.DocumentDB.V20200301.Outputs
{
[OutputType]
public sealed class FailoverPolicyResponse
{
/// <summary>
/// The failover priority of the region. A failover priority of 0 indicates a write region. The maximum value for a failover priority = (total number of regions - 1). Failover priority values must be unique for each of the regions in which the database account exists.
/// </summary>
public readonly int? FailoverPriority;
/// <summary>
/// The unique identifier of the region in which the database account replicates to. Example: &lt;accountName&gt;-&lt;locationName&gt;.
/// </summary>
public readonly string Id;
/// <summary>
/// The name of the region in which the database account exists.
/// </summary>
public readonly string? LocationName;
[OutputConstructor]
private FailoverPolicyResponse(
int? failoverPriority,
string id,
string? locationName)
{
FailoverPriority = failoverPriority;
Id = id;
LocationName = locationName;
}
}
}
| 35 | 276 | 0.653156 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/DocumentDB/V20200301/Outputs/FailoverPolicyResponse.cs | 1,505 | C# |
using Fpl.Client.Models;
using Fpl.EventPublishers.Models.Mappers;
namespace FplBot.Tests;
public class PriceMonitorTests
{
private readonly ITestOutputHelper _helper;
public PriceMonitorTests(ITestOutputHelper helper)
{
_helper = helper;
}
[Fact]
public void GetChangedPlayers_WhenNoPlayers_ReturnsNoChanges()
{
var before = new List<Player>{ };
var after = new List<Player>{ };
var priceChanges = PlayerChangesEventsExtractor.GetPriceChanges(after,before, new List<Team>());
Assert.Empty(priceChanges);
}
[Fact]
public void GetChangedPlayers_WhenSamePlayersWithPriceChange_ReturnsNoChanges()
{
var before = new List<Player>{ TestBuilder.Player().WithCostChangeEvent(1) };
var after = new List<Player>{ TestBuilder.Player().WithCostChangeEvent(1) };
var priceChanges = PlayerChangesEventsExtractor.GetPriceChanges(after,before, new List<Team>());
Assert.Empty(priceChanges);
}
[Fact]
public void GetChangedPlayers_WhenSamePlayersWithChangeInPriceChange_ReturnsChanges()
{
var before = new List<Player>{ TestBuilder.Player().WithCostChangeEvent(0) };
var after = new List<Player>{ TestBuilder.Player().WithCostChangeEvent(1) };
var priceChanges = PlayerChangesEventsExtractor.GetPriceChanges(after,before, new List<Team> { TestBuilder.HomeTeam(), TestBuilder.AwayTeam()});
Assert.Single(priceChanges);
Assert.Equal(TestBuilder.Player().WebName, priceChanges.First().WebName);
}
[Fact]
public void GetChangedPlayers_WhenSamePlayersDuplicateWithChangeInPriceChange_ReturnsSingleChanges()
{
var before = new List<Player>{ TestBuilder.Player().WithCostChangeEvent(0) };
var after = new List<Player>{ TestBuilder.Player().WithCostChangeEvent(1), TestBuilder.Player().WithCostChangeEvent(1) };
var priceChanges = PlayerChangesEventsExtractor.GetPriceChanges(after,before, new List<Team> { TestBuilder.HomeTeam(), TestBuilder.AwayTeam()});
Assert.Single(priceChanges);
Assert.Equal(TestBuilder.Player().WebName, priceChanges.First().WebName);
var before2 = new List<Player>{ TestBuilder.Player().WithCostChangeEvent(0), TestBuilder.Player().WithCostChangeEvent(0) };
var after2 = new List<Player>{ TestBuilder.Player().WithCostChangeEvent(1), TestBuilder.Player().WithCostChangeEvent(1) };
var priceChanges2 = PlayerChangesEventsExtractor.GetPriceChanges(after2,before2, new List<Team> { TestBuilder.HomeTeam(), TestBuilder.AwayTeam()});
Assert.Single(priceChanges2);
Assert.Equal(TestBuilder.Player().WebName, priceChanges2.First().WebName);
var before3 = new List<Player>{ TestBuilder.Player().WithCostChangeEvent(0), TestBuilder.Player().WithCostChangeEvent(0) };
var after3 = new List<Player>{ TestBuilder.Player().WithCostChangeEvent(1) };
var priceChanges3 = PlayerChangesEventsExtractor.GetPriceChanges(after3,before3, new List<Team> { TestBuilder.HomeTeam(), TestBuilder.AwayTeam()});
Assert.Single(priceChanges3);
Assert.Equal(TestBuilder.Player().WebName, priceChanges3.First().WebName);
}
[Fact]
public void GetChangedPlayers_WhenSamePlayersWithChangeInPriceRemoved_ReturnsNoChanges()
{
var before = new List<Player>{ TestBuilder.Player().WithCostChangeEvent(1) };
var after = new List<Player>{ TestBuilder.Player().WithCostChangeEvent(0) };
var priceChanges = PlayerChangesEventsExtractor.GetPriceChanges(after,before, new List<Team> { TestBuilder.HomeTeam(), TestBuilder.AwayTeam()});
Assert.Single(priceChanges);
}
[Fact]
public void GetChangedPlayers_OneNewPlayerWithCostChange_ReturnsNewPlayer()
{
var before = new List<Player>{ TestBuilder.Player().WithCostChangeEvent(1) };
var after = new List<Player>
{
TestBuilder.Player().WithCostChangeEvent(1),
TestBuilder.OtherPlayer().WithCostChangeEvent(1)
};
var priceChanges = PlayerChangesEventsExtractor.GetPriceChanges(after, before, new List<Team> { TestBuilder.HomeTeam(), TestBuilder.AwayTeam()});
Assert.Empty(priceChanges);
}
[Fact]
public void GetChangedPlayers_OnePlayerRemoved_ReturnsNoChanges()
{
var before = new List<Player>
{
TestBuilder.Player().WithCostChangeEvent(1),
TestBuilder.OtherPlayer().WithCostChangeEvent(1)
};
var after = new List<Player>
{
TestBuilder.Player().WithCostChangeEvent(1)
};
var priceChanges = PlayerChangesEventsExtractor.GetPriceChanges(after, before, new List<Team>());
Assert.Empty(priceChanges);
}
}
| 39.311475 | 155 | 0.704128 | [
"MIT"
] | Eszra92/fplbot | src/FplBot.Tests/PriceMonitorTests.cs | 4,796 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Azure;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace LineCounter
{
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.AddMvc();
services.AddAzureClients(
builder => {
builder.ConfigureDefaults(Configuration.GetSection("Defaults"));
builder.AddBlobServiceClient(Configuration.GetSection("Blob"));
builder.AddEventHubProducerClient(Configuration.GetSection("Uploads")).WithName("Uploads");
builder.AddEventHubProducerClient(Configuration.GetSection("Results")).WithName("Results");
});
services.AddApplicationInsightsTelemetry();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
| 31.490909 | 111 | 0.622979 | [
"MIT"
] | AWESOME-S-MINDSET/azure-sdk-for-net | samples/linecounter/Startup.cs | 1,732 | C# |
using System;
using System.Runtime.InteropServices;
namespace hds
{
public class AttributeClass1653 :GameObject
{
public Attribute Orientation = new Attribute(16, "Orientation");
public Attribute Position = new Attribute(24, "Position");
public Attribute HalfExtents = new Attribute(12, "HalfExtents");
public AttributeClass1653(string name,UInt16 _goid)
: base(3, 0, name, _goid, 0xFFFFFFFF)
{
AddAttribute(ref Orientation, 0, -1);
AddAttribute(ref Position, 1, -1);
AddAttribute(ref HalfExtents, 2, -1);
}
}
} | 24.166667 | 68 | 0.677586 | [
"MIT"
] | hdneo/mxo-hd | hds/resources/gameobjects/definitions/AttributeClasses/AttributeClass1653.cs | 580 | C# |
//___________________________________________________________________________________
//
// Copyright (C) 2021, Mariusz Postol LODZ POLAND.
//
// To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI
//___________________________________________________________________________________
using CAS.UA.Model.Designer.ExportingTools;
using CAS.UA.Model.Designer.Properties;
using CAS.UA.Model.Designer.StateMachineEditor;
using CAS.UA.Model.Designer.Wrappers;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using UAOOI.SemanticData.BuildingErrorsHandling;
using UAOOI.Windows.Forms;
using UAOOI.Windows.Forms.ControlExtenders;
namespace CAS.UA.Model.Designer
{
public partial class MainForm : Form
{
#region constructors
public MainForm(string SolutionFileName)
: this(false)
{
m_StartupFileName = SolutionFileName;
}
public MainForm(bool setAfterInstallationFlag)
{
SetAfterInstallationFlag = setAfterInstallationFlag;
InitializeComponent();
ProcessInitialization();
}
#endregion constructors
#region private
#region private members and helper functions
//vars
private ToolStripContainerHelper toolStripContainerHelper;
private PropertyGrid myGrid;
private MessageBoxSentEmail messageBoxSentEmail = new MessageBoxSentEmail(Resources.FeatureRequest_EmailAddress, Resources.FeatureRequest_Email_Subject, Resources.FeatureRequest_MessageBox_Caption);
private bool SetAfterInstallationFlag { set; get; }
//methods
private void ProcessInitialization()
{
if (Settings.Default.FontSize < 6)
{
Settings.Default.FontSize = 6;
this.Font = new Font(Form.DefaultFont.FontFamily, 6);
}
else if (Settings.Default.FontSize > 18)
{
Settings.Default.FontSize = 18;
this.Font = new Font(Form.DefaultFont.FontFamily, 18);
}
else
this.Font = new Font(Form.DefaultFont.FontFamily, Settings.Default.FontSize);
#region docking and debug panel
// declare dockExtender as a member of the form
DockExtender dockExtender;
dockExtender = new DockExtender(toolStripContainer1); // 'this' is Form1
// on for the 'dockHost'
this.debugDockPanelUserControl1.AttachToDockExtender(dockExtender, splitter_main);
this.debugDockPanelUserControl1.Floaty.Docking += new EventHandler(Floaty_Docking);
this.windowsToolStripMenuItem.DropDownItems.AddRange(dockExtender.GetListOfToolStripMenuItem());
foreach (ToolStripMenuItem _menuItem in this.windowsToolStripMenuItem.DropDownItems)
_menuItem.ToolTipText = "Show/hide " + _menuItem.Text;
#endregion docking and debug panel
#region toolstrip (toolbars) show/hide context menus
// Show and hide toolstrip menus
this.toolStripContainerHelper = new ToolStripContainerHelper(toolStripContainer1);
this.toolbarsToolStripMenuItem.DropDownItems.AddRange(toolStripContainerHelper.GetListOfToolStripMenuItem());
foreach (ToolStripMenuItem tsmi in this.toolbarsToolStripMenuItem.DropDownItems)
tsmi.ToolTipText = "Show/hide " + tsmi.Text + " tool-bar";
if (toolStripContainer1.TopToolStripPanel.ContextMenuStrip == null)
toolStripContainer1.TopToolStripPanel.ContextMenuStrip = new ContextMenuStrip();
toolStripContainer1.TopToolStripPanel.ContextMenuStrip.Items.AddRange(toolStripContainerHelper.GetListOfToolStripMenuItem());
if (toolStripContainer1.BottomToolStripPanel.ContextMenuStrip == null)
toolStripContainer1.BottomToolStripPanel.ContextMenuStrip = new ContextMenuStrip();
toolStripContainer1.BottomToolStripPanel.ContextMenuStrip.Items.AddRange(toolStripContainerHelper.GetListOfToolStripMenuItem());
if (toolStripContainer1.LeftToolStripPanel.ContextMenuStrip == null)
toolStripContainer1.LeftToolStripPanel.ContextMenuStrip = new ContextMenuStrip();
toolStripContainer1.LeftToolStripPanel.ContextMenuStrip.Items.AddRange(toolStripContainerHelper.GetListOfToolStripMenuItem());
if (toolStripContainer1.RightToolStripPanel.ContextMenuStrip == null)
toolStripContainer1.RightToolStripPanel.ContextMenuStrip = new ContextMenuStrip();
toolStripContainer1.RightToolStripPanel.ContextMenuStrip.Items.AddRange(toolStripContainerHelper.GetListOfToolStripMenuItem());
#endregion toolstrip (toolbars) show/hide context menus
goToToolStripMenuItem.DropDownOpening += new EventHandler(goToToolStripMenuItem_DropDownOpening);
m_EditToolStripMenuItem.DropDownOpening += new EventHandler(editToolStripMenuItem_DropDownOpening);
if (SetAfterInstallationFlag)
{
helpUserControl.SetUrl(Resources.MainForm_ReadmePage_mainframe);
tabControl_Main.SelectedIndex = tabControl_Main.Controls.IndexOf(tabPage_help);
debugDockPanelUserControl1.Hide();
this.WindowState = FormWindowState.Maximized;
}
else
this.WindowState = FormWindowState.Normal;
}
private void FeatureRequest(ToolStripMenuItem menuItem)
{
string featureName = "not set";
string featureDescription = "unavailable";
if (menuItem != null)
{
featureName = menuItem.Text;
ToolStripItem owneritem = menuItem.OwnerItem;
while (owneritem != null)
{
featureName = owneritem.Text + "\\" + featureName;
owneritem = owneritem.OwnerItem;
}
featureDescription = menuItem.ToolTipText;
}
messageBoxSentEmail.ShowMessageAndSendEmailIfOK(string.Format(Resources.FeatureRequest_MessageBox_Body, featureName, featureDescription),
string.Format(Resources.FeatureRequest_Email_Body, featureName));
}
private void UpdateWindowTitle()
{
this.Text = $"{Resources.MainWindowName}:{m_MainContol.SolutionDisplayName}";
}
#endregion private members and helper functions
#region private event handlers
private void Floaty_Docking(object sender, EventArgs e)
{
this.tabControl_Main.BringToFront();
this.debugDockPanelUserControl1.SendToBack();
this.BringToFront();
}
#region Menu
#region File
private void MHExitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void MHNewToolStripMenuItem_Click(object sender, EventArgs e)
{
m_MainContol.NewSolution();
}
private void MHOpenToolStripMenuItem_Click(object sender, EventArgs e)
{
m_MainContol.OpenSolution(null);
}
private void MHSaveToolStripMenuItem_Click(object sender, EventArgs e)
{
m_MainContol.Save(false);
}
private void MHSaveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
m_MainContol.Save(true);
}
#region import
private void MHFileImport_DropDownOpening(object sender, EventArgs e)
{
ToolStripMenuItem _mm = sender as ToolStripMenuItem;
_mm.DropDownItems.Clear();
m_MainContol.GetImportMenu(_mm.DropDownItems);
if (_mm.DropDownItems.Count > 0)
_mm.DropDownItems.Add(new ToolStripSeparator());
_mm.DropDownItems.Add(MenuFactory.ImportNodeSetMenuItem((x, y) => m_MainContol.ImportNodeSet()));
_mm.DropDownItems.Add(m_FromUMLDiagramToolStripMenuItem);
_mm.DropDownItems.Add(m_FromXMLSchemaToolStripMenuItem);
_mm.DropDownItems.Add(m_FromVisioToolStripMenuItem);
_mm.DropDownItems.Add(m_FromEnterpriceArchitectToolStripMenuItem);
_mm.DropDownItems.Add(m_FileImportFromTSMI);
}
private void MHFromFileImportTSMI_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void MHFromVisioToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void MHFromEnterpriceArchitectToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void MHFromUMLDiagramToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void MHFromXMLSchemaToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void m_FromUANodeSetToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
#endregion import
#region export
private void MHExport2Word_Click(object sender, EventArgs e)
{
ExportTool.ExportToDocument(m_MainContol.SelectedIModelNodeAdvanced, ExportTool.TypeOfTheDocument.Docx);
}
private void MHExport2Excel_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void MHExport2MAML_Click(object sender, EventArgs e)
{
ExportTool.ExportToDocument(m_MainContol.SelectedIModelNodeAdvanced, ExportTool.TypeOfTheDocument.Maml);
}
private void MHExport2Graphic_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void MHExport2Eny_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void MHExport2XMLSchema_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void MHExport2UML_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void MHExport2EnterpriceArchitect_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void MHExport2Visio_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
#endregion export
#endregion File
#region Edit
private void editToolStripMenuItem_DropDownOpening(object sender, EventArgs e)
{
cutToolStripMenuItem.Enabled = false;
copyToolStripMenuItem.Enabled = false;
pasteToolStripMenuItem.Enabled = false;
if (m_MainContol.ModelTreeViewIsFocused && m_MainContol.SelectedIModelNodeAdvanced != null)
{
pasteToolStripMenuItem.Enabled = m_MainContol.SelectedIModelNodeAdvanced.ShouldPasteMenuBeEnabled();
cutToolStripMenuItem.Enabled = true;
copyToolStripMenuItem.Enabled = true;
}
}
private void goToToolStripMenuItem_DropDownOpening(object sender, EventArgs e)
{
goToToolStripMenuItem.DropDownItems.Clear();
System.Collections.Generic.List<ToolStripMenuItem> menulist = m_MainContol.GoToMenuItemList;
if (m_MainContol.ModelTreeViewIsFocused && menulist != null)
{
goToToolStripMenuItem.DropDownItems.AddRange(menulist.ToArray());
}
}
#endregion Edit
private void HelpAboutUaModelDesignerToolStripMenuItem_Click(object sender, EventArgs e)
{
using (AboutForm dial = new AboutForm(Resources.ASMDbanner, Assembly.GetEntryAssembly()))
dial.ShowDialog(this);
}
private void HelpAboutOpcUaModelCompilerToolStripMenuItem_Click(object sender, EventArgs e)
{
new AboutOpcUaModelCompilerWindow().ShowDialog(this);
}
private void contentsToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
Process.Start(Resources.AsmdHelp);
}
catch (Win32Exception ex)
{
MessageBox.Show(string.Format(Resources.MainForm_DefaultAppMissing, Resources.AsmdHelp, ex.Message));
}
}
private void HelpConfigurationToolStripMenuItem_Click(object sender, EventArgs e)
{
myGrid = new PropertyGrid
{
SelectedObject = Properties.Settings.Default
};
myGrid.SelectedGridItemChanged += new SelectedGridItemChangedEventHandler(myGrid_SelectedGridItemChanged);
myGrid.SizeChanged += new EventHandler(myGrid_SizeChanged);
myGrid.Anchor = AnchorStyles.Bottom | AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
int windowHight;
int windowWidth;
OKCancelForm myConfigurationForm = new OKCancelForm(Resources.ConfigurationFormName);
using (myConfigurationForm)
{
myConfigurationForm.AddButton("Reset", System.Windows.Forms.DialogResult.Ignore);
UserControl myControl = new UserControl();
myControl.Controls.Add(myGrid);
myConfigurationForm.SetUserControl = myControl;
myConfigurationForm.CanBeAccepted(true);
myConfigurationForm.AutoSize = false;
myConfigurationForm.Height = 580;
myConfigurationForm.Width = 620;
System.Windows.Forms.DialogResult dr = myConfigurationForm.ShowDialog(this);
while (dr == System.Windows.Forms.DialogResult.Ignore)
{
windowHight = myConfigurationForm.Height;
windowWidth = myConfigurationForm.Width;
myConfigurationForm.StartPosition = FormStartPosition.Manual;
myGrid.SelectedObject = Properties.Settings.Default;
myControl.Controls.Clear();
myControl.Controls.Add(myGrid);
myConfigurationForm.SetUserControl = myControl;
myConfigurationForm.Controls[0].Refresh();
myConfigurationForm.Height = windowHight;
myConfigurationForm.Width = windowWidth;
OnReset();
dr = myConfigurationForm.ShowDialog(this);
if (dr == System.Windows.Forms.DialogResult.OK)
OnOk();
else if (dr == System.Windows.Forms.DialogResult.Cancel)
OnCancel();
}
}
}
private void myGrid_SizeChanged(object sender, EventArgs e)
{
ChangeDescription(((PropertyGrid)sender).SelectedGridItem.Label);
}
private void myGrid_SelectedGridItemChanged(object sender, SelectedGridItemChangedEventArgs e)
{
ChangeDescription(e.NewSelection.Label);
}
/// <summary>
/// Changes the description of the item in Property Grid.
/// </summary>
/// <param name="propertyGridItemLabel">The property grid item label.</param>
private void ChangeDescription(string propertyGridItemLabel)
{
try
{
object oDocComment = myGrid.GetType().InvokeMember("doccomment", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance, null, myGrid, null);
Label oDocCommentDescription = (Label)oDocComment.GetType().InvokeMember("m_labelDesc", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance, null, oDocComment, null);
oDocCommentDescription.Text = (string)Resources.ResourceManager.GetString("OptionDescription_" + propertyGridItemLabel);
}
catch (Exception ex)
{
AssemblyTraceEvent.Tracer.TraceEvent(TraceEventType.Warning, 379, Resources.ProblemWithDescriptionForOption + ex.Message);
}
}
private void OnCancel()
{
Properties.Settings.Default.Reload();
}
private void OnReset()
{
Properties.Settings.Default.TargetNamespace = @"http://cas.eu/UA/CommServer/";
Properties.Settings.Default.TargetXmlNamespace = @"http://cas.eu/UA/CommServer/";
Properties.Settings.Default.DefaultSolutionFileName = "UAModelDesignerSolution";
Properties.Settings.Default.FontSize = 8;
Properties.Settings.Default.CoupledNodesAreEnabled = true;
Properties.Settings.Default.HelpSynchronizationIsEnabled = true;
Properties.Settings.Default.XmlUATypesNamespace = @"http://opcfoundation.org/UA/2008/02/Types.xsd";
Properties.Settings.Default.XmlUATypesPrefix = "ua";
Properties.Settings.Default.Build_ProjectCompilationString = "-d2 \"{0}\" -cg \"{1}\" -o \"{2}\" -console";
Properties.Settings.Default.ProjectCompilationExecutable = @"exe\CAS.CommServer.UA.ModelCompiler.Command.exe";
Properties.Settings.Default.TargetNamespaceXmlPrefix = "cas";
Properties.Settings.Default.XmlOPCTypesNamespace = @"http://opcfoundation.org/UA/2008/02/Types.xsd";
Properties.Settings.Default.XmlOPCTypesPrefix = "uax";
Properties.Settings.Default.XmlSchemaNamespace = @"http://www.w3.org/2001/XMLSchema";
Properties.Settings.Default.XmlSchemaPrefix = "xsd";
Properties.Settings.Default.XmlSchemaInstanceNamespace = @"http://www.w3.org/2001/XMLSchema-instance";
Properties.Settings.Default.XmlSchemaInstancePrefix = "xsi";
}
private void OnOk()
{
Properties.Settings.Default.Save();
MessageBox.Show(Resources.ConfigurationForm_MessageAfterChange);
}
private void buildToolStripMenuItem_Click(object sender, EventArgs e)
{
m_MainContol.Build(x => AssemblyTraceEvent.Log.TraceMessage(TraceMessage.DiagnosticTraceMessage(x), nameof(m_MainContol.Build), 851392402));
}
private void stateMachineEditorToolStripMenuItem_Click(object sender, EventArgs e)
{
IModelNodeAdvance imna = m_MainContol.SelectedIModelNodeAdvanced;
if ((imna != null) && (imna.NodeClass == NodeClassesEnum.ObjectType))
{
StateMachineEditorMain.AnalizeStateMachine(imna);
return;
}
MessageBox.Show(Resources.ProblemWithStateMachine_Header, Resources.ProblemWithStateMachine_Info, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
}
private void coupledNodesToolStripMenuItem_Click(object sender, EventArgs e)
{
m_MainContol.ModelCoupledNodesAreEnabled = coupledNodesToolStripMenuItem.Checked;
Settings.Default.CoupledNodesAreEnabled = coupledNodesToolStripMenuItem.Checked;
}
private void automaticHelpSynchronisationToolStripMenuItem_Click(object sender, EventArgs e)
{
Settings.Default.HelpSynchronizationIsEnabled = automaticHelpSynchonisationToolStripMenuItem.Checked;
}
private void pageSetupToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void printToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void recentSolutionsToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void undoToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void redoToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void findToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void replaceToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void allReferencesToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void findUnusedNodesToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void addToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void removeToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void toggleBookmarkToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void disableEnableAllBookmarksToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void disableEnableBookmarkToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void previousBookmarkToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void nextBookmarkToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void clearAllBookmarksToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void objectToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void childrenToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void referenceToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void nodeClassToolStripMenuItem_Click(object sender, EventArgs e)
{
this.m_MainContol.PerformNodeClassFiltering();
}
private void nAmeToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void allReferencesToolStripMenuItem1_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void othersToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void synchronizeTreeToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void collapsAllNodesToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void buildProjectToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void verifySolutionToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void verifyProjectToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void customizeToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void technicalSupportToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start(Resources.MainForm_TechnicalSupportPage);
}
private void HelpSendUsCommentToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBoxSentEmail.OpenEmailClient(Resources.FeatureRequest_EmailAddress,
Resources.FeatureRequest_Email_Subject_Comments, Resources.FeatureRequest_Email_Body_Comments);
}
private void HelpReadmeToolStripMenuItem_Click(object sender, EventArgs e)
{
Process.Start(Resources.MainForm_ReadmePage);
}
private void navigateForwardToolStripMenuItem_Click(object sender, EventArgs e)
{
m_MainContol.NavigateViewForward();
}
private void navigateBackwardToolStripMenuItem_Click(object sender, EventArgs e)
{
m_MainContol.NavigateViewBackward();
}
private void nodeClassToolStripMenuItem1_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void alphabeticallyToolStripMenuItem_Click(object sender, EventArgs e)
{
FeatureRequest(sender as ToolStripMenuItem);
}
private void cutToolStripMenuItem_Click(object sender, EventArgs e)
{
if (m_MainContol.ModelTreeViewIsFocused)
{
if (m_MainContol.SelectedIModelNodeAdvanced != null)
{
m_MainContol.SelectedIModelNodeAdvanced.MenuItemCut_Action();
}
}
else
MessageBox.Show(Resources.MianWindow_FunctionalityAvailiableOnlyInModelView);
}
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
if (m_MainContol.ModelTreeViewIsFocused)
{
if (m_MainContol.SelectedIModelNodeAdvanced != null)
{
m_MainContol.SelectedIModelNodeAdvanced.MenuItemCopy_Action();
}
}
else
MessageBox.Show(Resources.MianWindow_FunctionalityAvailiableOnlyInModelView);
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
if (m_MainContol.ModelTreeViewIsFocused)
{
if (m_MainContol.SelectedIModelNodeAdvanced != null)
{
m_MainContol.SelectedIModelNodeAdvanced.MenuItemPaste_Action();
}
}
else
MessageBox.Show(Resources.MianWindow_FunctionalityAvailiableOnlyInModelView);
}
//TODO Remove dependency on CodeProtect - consolidated #211
private void oPCViewerToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
Lib.OPCClientControlsLib.MainFormV2008 _mainForm = new Lib.OPCClientControlsLib.MainFormV2008();
_mainForm.Show();
}
catch (Exception ex)
{
AssemblyTraceEvent.Tracer.TraceEvent(TraceEventType.Warning, 700, $"OPC Viewer has thrown the exception {ex.Message}");
}
}
private void visualisationToolStripMenuItem_DropDownOpening(object sender, EventArgs e)
{
visualisationToolStripMenuItem.DropDownItems.Clear();
visualisationToolStripMenuItem.DropDownItems.AddRange(m_MainContol.TabControlManager.GetToolStripItemCollection());
}
#region Server UA
private void m_MenuServerUA_DropDownOpening(object sender, EventArgs e)
{
ToolStripMenuItem _sender = sender as ToolStripMenuItem;
_sender.DropDownItems.Clear();
m_MainContol.GetServerUAMenu(_sender.DropDownItems);
}
#endregion Server UA
#endregion Menu
private void m_LogsContainingFolderToolStripMenuItem_Click(object sender, EventArgs e)
{
string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), Settings.Default.LogFolder);
try
{
using (Process process = Process.Start(@path)) { }
}
catch (Win32Exception)
{
MessageBox.Show("No Log folder exists under this link: " + path + " You can create this folder yourself.", "No Log folder !", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
return;
}
catch (Exception)
{
MessageBox.Show("An error during opening a log folder occurs and the log folder cannot be open", "Problem with log folder !", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
return;
}
}
#region Main
private string m_StartupFileName = string.Empty;
private void MainForm_Load(object sender, EventArgs e)
{
AssemblyTraceEvent.Listeners += (x, y) => debugDockPanelUserControl1.TextWriterStream.WriteLine(y);
AssemblyTraceEvent.Tracer.TraceEvent(TraceEventType.Verbose, 1334099901, "Starting application");
string _solutionFileName = m_StartupFileName;
if (_solutionFileName.StartsWith("file://"))
{
_solutionFileName = (new System.Uri(_solutionFileName)).AbsolutePath;
_solutionFileName = _solutionFileName.Replace("%20", " ");
_solutionFileName = _solutionFileName.Replace("/", "\\");
}
m_MainContol.PropertyChanged += M_MainContol_PropertyChanged;
m_MainContol.OpenSolution(_solutionFileName);
}
private void M_MainContol_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(Main.SolutionDisplayName))
this.UpdateWindowTitle();
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (!m_MainContol.TestIfChangesArePresentDisplayWindowAndReturnTrueIfShouldBeContinued())
e.Cancel = true;
}
private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
{
AssemblyTraceEvent.Tracer.TraceEvent(TraceEventType.Verbose, 763, "Application is closing");
AssemblyTraceEvent.Tracer.Flush();
AssemblyTraceEvent.Tracer.Close();
}
#endregion Main
#endregion private event handlers
#endregion private
}
} | 36.670051 | 221 | 0.710548 | [
"MIT"
] | mpostol/ASMD | ModelDesigner.DesignStudio/MainForm.cs | 28,898 | C# |
// Copyright (c) Avanade. Licensed under the MIT License. See https://github.com/Avanade/Beef
using Beef.Entities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Mime;
using System.Threading.Tasks;
namespace Beef.WebApi
{
/// <summary>
/// Provides the base capabilites to <b>invoke</b> Web API agent operations.
/// </summary>
public abstract class WebApiAgentBase : IWebApiAgent
{
/// <summary>
/// Sets the accept header for the <paramref name="httpClient"/> to <see cref="MediaTypeNames.Application.Json"/>.
/// </summary>
/// <param name="httpClient">The <see cref="System.Net.Http.HttpClient"/>.</param>
public static void SetAcceptApplicationJson(HttpClient httpClient)
{
if (httpClient == null)
throw new ArgumentNullException(nameof(httpClient));
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypeNames.Application.Json));
}
/// <summary>
/// Initializes a new instance of the <see cref="WebApiAgentBase"/> class.
/// </summary>
/// <param name="args">The <see cref="IWebApiAgentArgs"/>.</param>
protected WebApiAgentBase(IWebApiAgentArgs args) => Args = args ?? throw new ArgumentNullException(nameof(args));
/// <summary>
/// Gets the <see cref="IWebApiAgentArgs"/>.
/// </summary>
public IWebApiAgentArgs Args { get; private set; }
/// <summary>
/// Creates the <see cref="HttpRequestMessage"/> and invokes the <see cref="IWebApiAgentArgs.BeforeRequest"/>.
/// </summary>
private async Task<HttpRequestMessage> CreateRequestMessageAsync(HttpMethod method, Uri uri, StringContent? content = null, WebApiRequestOptions? requestOptions = null)
{
var req = new HttpRequestMessage(method, uri);
if (content != null)
req.Content = content;
if (ExecutionContext.HasCurrent && !string.IsNullOrEmpty(ExecutionContext.Current.CorrelationId))
req.Headers.Add(WebApiConsts.CorrelationIdHeaderName, ExecutionContext.Current.CorrelationId);
ApplyWebApiOptions(req, requestOptions);
Args.BeforeRequest?.Invoke(req);
await (Args.BeforeRequestAsync?.Invoke(req) ?? Task.CompletedTask).ConfigureAwait(false);
return req;
}
/// <summary>
/// Applys the <see cref="WebApiRequestOptions"/> to the<see cref="HttpRequestMessage"/>.
/// </summary>
private static void ApplyWebApiOptions(HttpRequestMessage request, WebApiRequestOptions? requestOptions = null)
{
if (requestOptions == null || string.IsNullOrEmpty(requestOptions.ETag))
return;
var etag = requestOptions.ETag.StartsWith("\"", StringComparison.InvariantCultureIgnoreCase) && requestOptions.ETag.EndsWith("\"", StringComparison.InvariantCultureIgnoreCase) ? requestOptions.ETag : "\"" + requestOptions.ETag + "\"";
if (request.Method == HttpMethod.Get)
request.Headers.IfNoneMatch.Add(new EntityTagHeaderValue(etag));
else
request.Headers.IfMatch.Add(new EntityTagHeaderValue(etag));
}
#region Get/Put/Post/Delete Async
/// <summary>
/// Send a <see cref="HttpMethod.Get"/> request as an asynchronous operation.
/// </summary>
/// <param name="urlSuffix">The url suffix for the operation.</param>
/// <param name="requestOptions">The optional <see cref="WebApiRequestOptions"/>.</param>
/// <param name="args">The operation arguments to be substituted within the <paramref name="urlSuffix"/>.</param>
/// <returns>The <see cref="WebApiAgentResult"/>.</returns>
public async Task<WebApiAgentResult> GetAsync(string? urlSuffix, WebApiRequestOptions? requestOptions = null, WebApiArg[]? args = null)
{
var uri = CreateFullUri(urlSuffix, args, requestOptions);
return await WebApiAgentInvoker.Current.InvokeAsync(this, async () =>
{
var value = args?.Where(x => x.ArgType == WebApiArgType.FromBody).SingleOrDefault()?.GetValue();
var result = new WebApiAgentResult(await Args.HttpClient.SendAsync(await CreateRequestMessageAsync(HttpMethod.Get, uri, CreateJsonContentFromValue(value), requestOptions).ConfigureAwait(false)).ConfigureAwait(false));
result.Content = await result.Response.Content.ReadAsStringAsync().ConfigureAwait(false);
return VerifyResult(result);
}, null!).ConfigureAwait(false);
}
/// <summary>
/// Send a <see cref="HttpMethod.Get"/> request as an asynchronous operation with an expected response.
/// </summary>
/// <typeparam name="TResult">The result <see cref="Type"/>.</typeparam>
/// <param name="urlSuffix">The url suffix for the operation.</param>
/// <param name="requestOptions">The optional <see cref="WebApiRequestOptions"/>.</param>
/// <param name="args">The operation arguments to be substituted within the <paramref name="urlSuffix"/>.</param>
/// <returns>The <see cref="WebApiAgentResult{TResult}"/>.</returns>
public async Task<WebApiAgentResult<TResult>> GetAsync<TResult>(string? urlSuffix, WebApiRequestOptions? requestOptions = null, WebApiArg[]? args = null)
{
var uri = CreateFullUri(urlSuffix, args, requestOptions);
return await WebApiAgentInvoker.Current.InvokeAsync(this, async () =>
{
var value = args?.Where(x => x.ArgType == WebApiArgType.FromBody).SingleOrDefault()?.GetValue();
var result = new WebApiAgentResult(await Args.HttpClient.SendAsync(await CreateRequestMessageAsync(HttpMethod.Get, uri, CreateJsonContentFromValue(value), requestOptions).ConfigureAwait(false)).ConfigureAwait(false));
result.Content = await result.Response.Content.ReadAsStringAsync().ConfigureAwait(false);
return new WebApiAgentResult<TResult>(VerifyResult(result));
}, null!).ConfigureAwait(false);
}
/// <summary>
/// Send a <see cref="HttpMethod.Get"/> request as an asynchronous operation converting the expected collection response to a <see cref="EntityCollectionResult{TColl, TEntity}"/>.
/// </summary>
/// <typeparam name="TResult">The result <see cref="Type"/>.</typeparam>
/// <typeparam name="TColl">The collection <see cref="Type"/>.</typeparam>
/// <typeparam name="TEntity">The entity <see cref="Type"/>.</typeparam>
/// <param name="urlSuffix">The url suffix for the operation.</param>
/// <param name="requestOptions">The optional <see cref="WebApiRequestOptions"/>.</param>
/// <param name="args">The operation arguments to be substituted within the <paramref name="urlSuffix"/>.</param>
/// <returns>The <see cref="WebApiAgentResult{TResult}"/>.</returns>
public async Task<WebApiAgentResult<TResult>> GetCollectionResultAsync<TResult, TColl, TEntity>(string? urlSuffix, WebApiRequestOptions? requestOptions = null, WebApiArg[]? args = null)
where TResult : IEntityCollectionResult<TColl, TEntity>, new()
where TColl : IEnumerable<TEntity>, new()
where TEntity : class
{
var result = await GetAsync<TColl>(urlSuffix, requestOptions, args).ConfigureAwait(false);
if (!result.Response.IsSuccessStatusCode)
return new WebApiAgentResult<TResult>(result);
var collResult = new TResult()
{
Result = result.Value
};
var skip = GetHeaderValueLong(result, WebApiConsts.PagingSkipHeaderName);
var page = skip.HasValue ? null : GetHeaderValueLong(result, WebApiConsts.PagingPageNumberHeaderName);
if (skip.HasValue)
collResult.Paging = new PagingResult(PagingResult.CreateSkipAndTake(skip.Value, GetHeaderValueLong(result, WebApiConsts.PagingTakeHeaderName)));
else if (page.HasValue && result.Response.Headers.Contains(WebApiConsts.PagingPageNumberHeaderName))
collResult.Paging = new PagingResult(PagingResult.CreatePageAndSize(page.Value, GetHeaderValueLong(result, WebApiConsts.PagingPageSizeHeaderName)));
if (collResult.Paging != null)
collResult.Paging.TotalCount = GetHeaderValueLong(result, WebApiConsts.PagingTotalCountHeaderName);
return new WebApiAgentResult<TResult>(result, collResult);
}
/// <summary>
/// Send a <see cref="HttpMethod.Put"/> <paramref name="value"/> request as an asynchronous operation.
/// </summary>
/// <param name="urlSuffix">The url suffix for the operation.</param>
/// <param name="value">The content value.</param>
/// <param name="requestOptions">The optional <see cref="WebApiRequestOptions"/>.</param>
/// <param name="args">The operation arguments to be substituted within the <paramref name="urlSuffix"/>.</param>
/// <returns>The <see cref="WebApiAgentResult"/>.</returns>
public async Task<WebApiAgentResult> PutAsync(string? urlSuffix, object value, WebApiRequestOptions? requestOptions = null, WebApiArg[]? args = null)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var uri = CreateFullUri(urlSuffix, args, requestOptions);
if (args != null && args.Any(x => x.ArgType == WebApiArgType.FromBody))
throw new ArgumentException("No arguments can be marked as IsFromBody where a content value is used.", nameof(args));
return await WebApiAgentInvoker.Current.InvokeAsync(this, async () =>
{
var result = new WebApiAgentResult(await Args.HttpClient.SendAsync(await CreateRequestMessageAsync(HttpMethod.Put, uri, CreateJsonContentFromValue(value), requestOptions).ConfigureAwait(false)).ConfigureAwait(false));
result.Content = await result.Response.Content.ReadAsStringAsync().ConfigureAwait(false);
return VerifyResult(result);
}, value).ConfigureAwait(false);
}
/// <summary>
/// Send a <see cref="HttpMethod.Put"/> <paramref name="value"/> request as an asynchronous operation with an expected response.
/// </summary>
/// <typeparam name="TResult">The result <see cref="Type"/>.</typeparam>
/// <param name="urlSuffix">The url suffix for the operation.</param>
/// <param name="value">The content value.</param>
/// <param name="requestOptions">The optional <see cref="WebApiRequestOptions"/>.</param>
/// <param name="args">The operation arguments to be substituted within the <paramref name="urlSuffix"/>.</param>
/// <returns>The <see cref="WebApiAgentResult{TResult}"/>.</returns>
public async Task<WebApiAgentResult<TResult>> PutAsync<TResult>(string? urlSuffix, object value, WebApiRequestOptions? requestOptions = null, WebApiArg[]? args = null)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var uri = CreateFullUri(urlSuffix, args, requestOptions);
if (args != null && args.Any(x => x.ArgType == WebApiArgType.FromBody))
throw new ArgumentException("No arguments can be marked as IsFromBody where a content value is used.", nameof(args));
return await WebApiAgentInvoker.Current.InvokeAsync(this, async () =>
{
var result = new WebApiAgentResult(await Args.HttpClient.SendAsync(await CreateRequestMessageAsync(HttpMethod.Put, uri, CreateJsonContentFromValue(value), requestOptions).ConfigureAwait(false)).ConfigureAwait(false));
result.Content = await result.Response.Content.ReadAsStringAsync().ConfigureAwait(false);
return new WebApiAgentResult<TResult>(VerifyResult(result));
}, value).ConfigureAwait(false);
}
/// <summary>
/// Send a <see cref="HttpMethod.Put"/> request as an asynchronous operation.
/// </summary>
/// <param name="urlSuffix">The url suffix for the operation.</param>
/// <param name="requestOptions">The optional <see cref="WebApiRequestOptions"/>.</param>
/// <param name="args">The operation arguments to be substituted within the <paramref name="urlSuffix"/>.</param>
/// <returns>The <see cref="WebApiAgentResult"/>.</returns>
public async Task<WebApiAgentResult> PutAsync(string? urlSuffix, WebApiRequestOptions? requestOptions = null, WebApiArg[]? args = null)
{
var uri = CreateFullUri(urlSuffix, args, requestOptions);
return await WebApiAgentInvoker.Current.InvokeAsync(this, async () =>
{
var value = args?.Where(x => x.ArgType == WebApiArgType.FromBody).SingleOrDefault()?.GetValue();
var result = new WebApiAgentResult(await Args.HttpClient.SendAsync(await CreateRequestMessageAsync(HttpMethod.Put, uri, CreateJsonContentFromValue(value), requestOptions).ConfigureAwait(false)).ConfigureAwait(false));
result.Content = await result.Response.Content.ReadAsStringAsync().ConfigureAwait(false);
return VerifyResult(result);
}, null!).ConfigureAwait(false);
}
/// <summary>
/// Send a <see cref="HttpMethod.Put"/> request as an asynchronous operation with an expected response.
/// </summary>
/// <typeparam name="TResult">The result <see cref="Type"/>.</typeparam>
/// <param name="urlSuffix">The url suffix for the operation.</param>
/// <param name="requestOptions">The optional <see cref="WebApiRequestOptions"/>.</param>
/// <param name="args">The operation arguments to be substituted within the <paramref name="urlSuffix"/>.</param>
/// <returns>The <see cref="WebApiAgentResult{TResult}"/>.</returns>
public async Task<WebApiAgentResult<TResult>> PutAsync<TResult>(string? urlSuffix, WebApiRequestOptions? requestOptions = null, WebApiArg[]? args = null)
{
var uri = CreateFullUri(urlSuffix, args, requestOptions);
return await WebApiAgentInvoker.Current.InvokeAsync(this, async () =>
{
var value = args?.Where(x => x.ArgType == WebApiArgType.FromBody).SingleOrDefault()?.GetValue();
var result = new WebApiAgentResult(await Args.HttpClient.SendAsync(await CreateRequestMessageAsync(HttpMethod.Put, uri, CreateJsonContentFromValue(value), requestOptions).ConfigureAwait(false)).ConfigureAwait(false));
result.Content = await result.Response.Content.ReadAsStringAsync().ConfigureAwait(false);
return new WebApiAgentResult<TResult>(VerifyResult(result));
}, null!).ConfigureAwait(false);
}
/// <summary>
/// Send a <see cref="HttpMethod.Post"/> <paramref name="value"/> request as an asynchronous operation.
/// </summary>
/// <param name="urlSuffix">The url suffix for the operation.</param>
/// <param name="value">The content value.</param>
/// <param name="requestOptions">The optional <see cref="WebApiRequestOptions"/>.</param>
/// <param name="args">The operation arguments to be substituted within the <paramref name="urlSuffix"/>.</param>
/// <returns>The <see cref="WebApiAgentResult"/>.</returns>
public async Task<WebApiAgentResult> PostAsync(string? urlSuffix, object value, WebApiRequestOptions? requestOptions = null, WebApiArg[]? args = null)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var uri = CreateFullUri(urlSuffix, args, requestOptions);
if (args != null && args.Any(x => x.ArgType == WebApiArgType.FromBody))
throw new ArgumentException("No arguments can be marked as IsFromBody where a content value is used.", nameof(args));
return await WebApiAgentInvoker.Current.InvokeAsync(this, async () =>
{
var result = new WebApiAgentResult(await Args.HttpClient.SendAsync(await CreateRequestMessageAsync(HttpMethod.Post, uri, CreateJsonContentFromValue(value), requestOptions).ConfigureAwait(false)).ConfigureAwait(false));
result.Content = await result.Response.Content.ReadAsStringAsync().ConfigureAwait(false);
return VerifyResult(result);
}, value).ConfigureAwait(false);
}
/// <summary>
/// Send a <see cref="HttpMethod.Post"/> <paramref name="value"/> request as an asynchronous operation with an expected response.
/// </summary>
/// <typeparam name="TResult">The result <see cref="Type"/>.</typeparam>
/// <param name="urlSuffix">The url suffix for the operation.</param>
/// <param name="value">The content value.</param>
/// <param name="requestOptions">The optional <see cref="WebApiRequestOptions"/>.</param>
/// <param name="args">The operation arguments to be substituted within the <paramref name="urlSuffix"/>.</param>
/// <returns>The <see cref="WebApiAgentResult{TResult}"/>.</returns>
public async Task<WebApiAgentResult<TResult>> PostAsync<TResult>(string? urlSuffix, object value, WebApiRequestOptions? requestOptions = null, WebApiArg[]? args = null)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var uri = CreateFullUri(urlSuffix, args, requestOptions);
if (args != null && args.Any(x => x.ArgType == WebApiArgType.FromBody))
throw new ArgumentException("No arguments can be marked as IsFromBody where a content value is used.", nameof(args));
return await WebApiAgentInvoker.Current.InvokeAsync(this, async () =>
{
var result = new WebApiAgentResult(await Args.HttpClient.SendAsync(await CreateRequestMessageAsync(HttpMethod.Post, uri, CreateJsonContentFromValue(value), requestOptions).ConfigureAwait(false)).ConfigureAwait(false));
result.Content = await result.Response.Content.ReadAsStringAsync().ConfigureAwait(false);
return new WebApiAgentResult<TResult>(VerifyResult(result));
}, value).ConfigureAwait(false);
}
/// <summary>
/// Send a <see cref="HttpMethod.Post"/> request as an asynchronous operation.
/// </summary>
/// <param name="urlSuffix">The url suffix for the operation.</param>
/// <param name="requestOptions">The optional <see cref="WebApiRequestOptions"/>.</param>
/// <param name="args">The operation arguments to be substituted within the <paramref name="urlSuffix"/>.</param>
/// <returns>The <see cref="WebApiAgentResult"/>.</returns>
public async Task<WebApiAgentResult> PostAsync(string? urlSuffix, WebApiRequestOptions? requestOptions = null, WebApiArg[]? args = null)
{
var uri = CreateFullUri(urlSuffix, args, requestOptions);
return await WebApiAgentInvoker.Current.InvokeAsync(this, async () =>
{
var value = args?.Where(x => x.ArgType == WebApiArgType.FromBody).SingleOrDefault()?.GetValue();
var result = new WebApiAgentResult(await Args.HttpClient.SendAsync(await CreateRequestMessageAsync(HttpMethod.Post, uri, CreateJsonContentFromValue(value), requestOptions).ConfigureAwait(false)).ConfigureAwait(false));
result.Content = await result.Response.Content.ReadAsStringAsync().ConfigureAwait(false);
return VerifyResult(result);
}, null!).ConfigureAwait(false);
}
/// <summary>
/// Send a <see cref="HttpMethod.Post"/> request as an asynchronous operation with an expected response.
/// </summary>
/// <typeparam name="TResult">The result <see cref="Type"/>.</typeparam>
/// <param name="urlSuffix">The url suffix for the operation.</param>
/// <param name="requestOptions">The optional <see cref="WebApiRequestOptions"/>.</param>
/// <param name="args">The operation arguments to be substituted within the <paramref name="urlSuffix"/>.</param>
/// <returns>The <see cref="WebApiAgentResult{TResult}"/>.</returns>
public async Task<WebApiAgentResult<TResult>> PostAsync<TResult>(string? urlSuffix, WebApiRequestOptions? requestOptions = null, WebApiArg[]? args = null)
{
var uri = CreateFullUri(urlSuffix, args, requestOptions);
return await WebApiAgentInvoker.Current.InvokeAsync(this, async () =>
{
var value = args?.Where(x => x.ArgType == WebApiArgType.FromBody).SingleOrDefault()?.GetValue();
var result = new WebApiAgentResult(await Args.HttpClient.SendAsync(await CreateRequestMessageAsync(HttpMethod.Post, uri, CreateJsonContentFromValue(value), requestOptions).ConfigureAwait(false)).ConfigureAwait(false));
result.Content = await result.Response.Content.ReadAsStringAsync().ConfigureAwait(false);
return new WebApiAgentResult<TResult>(VerifyResult(result));
}, null!).ConfigureAwait(false);
}
/// <summary>
/// Send a <see cref="HttpMethod.Delete"/> request as an asynchronous operation.
/// </summary>
/// <param name="urlSuffix">The url suffix for the operation.</param>
/// <param name="requestOptions">The optional <see cref="WebApiRequestOptions"/>.</param>
/// <param name="args">The operation arguments to be substituted within the <paramref name="urlSuffix"/>.</param>
/// <returns>The <see cref="WebApiAgentResult{T}"/>.</returns>
public async Task<WebApiAgentResult> DeleteAsync(string? urlSuffix, WebApiRequestOptions? requestOptions = null, WebApiArg[]? args = null)
{
var uri = CreateFullUri(urlSuffix, args, requestOptions);
return await WebApiAgentInvoker.Current.InvokeAsync(this, async () =>
{
var result = new WebApiAgentResult(await Args.HttpClient.SendAsync(await CreateRequestMessageAsync(HttpMethod.Delete, uri, requestOptions: requestOptions).ConfigureAwait(false)).ConfigureAwait(false));
result.Content = await result.Response.Content.ReadAsStringAsync().ConfigureAwait(false);
return VerifyResult(result);
}, null!).ConfigureAwait(false);
}
/// <summary>
/// Send a <see cref="HttpMethod"/> <b>PATCH</b> <paramref name="json"/> request as an asynchronous operation.
/// </summary>
/// <param name="urlSuffix">The url suffix for the operation.</param>
/// <param name="patchOption">The <see cref="WebApiPatchOption"/>.</param>
/// <param name="json">The json value.</param>
/// <param name="requestOptions">The optional <see cref="WebApiRequestOptions"/>.</param>
/// <param name="args">The operation arguments to be substituted within the <paramref name="urlSuffix"/>.</param>
/// <returns>The <see cref="WebApiAgentResult{TResult}"/>.</returns>
public async Task<WebApiAgentResult> PatchAsync(string? urlSuffix, WebApiPatchOption patchOption, JToken json, WebApiRequestOptions? requestOptions = null, WebApiArg[]? args = null)
{
if (json == null)
throw new ArgumentNullException(nameof(json));
if (patchOption == WebApiPatchOption.NotSpecified)
throw new ArgumentException("A valid patch option must be specified.", nameof(patchOption));
var uri = CreateFullUri(urlSuffix, args, requestOptions);
if (args != null && args.Any(x => x.ArgType == WebApiArgType.FromBody))
throw new ArgumentException("No arguments can be marked as IsFromBody for a PATCH.", nameof(args));
return await WebApiAgentInvoker.Current.InvokeAsync(this, async () =>
{
var content = new StringContent(json.ToString());
content.Headers.ContentType = MediaTypeHeaderValue.Parse(patchOption == WebApiPatchOption.JsonPatch ? "application/json-patch+json" : "application/merge-patch+json");
var result = new WebApiAgentResult(await Args.HttpClient.SendAsync(await CreateRequestMessageAsync(new HttpMethod("PATCH"), uri, content, requestOptions).ConfigureAwait(false)).ConfigureAwait(false));
result.Content = await result.Response.Content.ReadAsStringAsync().ConfigureAwait(false);
return VerifyResult(result);
}, json).ConfigureAwait(false);
}
/// <summary>
/// Send a <see cref="HttpMethod"/> <b>PATCH</b> <paramref name="json"/> request as an asynchronous operation with an expected response.
/// </summary>
/// <typeparam name="TResult">The result <see cref="Type"/>.</typeparam>
/// <param name="urlSuffix">The url suffix for the operation.</param>
/// <param name="patchOption">The <see cref="WebApiPatchOption"/>.</param>
/// <param name="json">The json value.</param>
/// <param name="requestOptions">The optional <see cref="WebApiRequestOptions"/>.</param>
/// <param name="args">The operation arguments to be substituted within the <paramref name="urlSuffix"/>.</param>
/// <returns>The <see cref="WebApiAgentResult{TResult}"/>.</returns>
public async Task<WebApiAgentResult<TResult>> PatchAsync<TResult>(string? urlSuffix, WebApiPatchOption patchOption, JToken json, WebApiRequestOptions? requestOptions = null, WebApiArg[]? args = null)
{
if (json == null)
throw new ArgumentNullException(nameof(json));
var uri = CreateFullUri(urlSuffix, args, requestOptions);
if (args != null && args.Any(x => x.ArgType == WebApiArgType.FromBody))
throw new ArgumentException("No arguments can be marked as IsFromBody for a PATCH.", nameof(args));
return await WebApiAgentInvoker.Current.InvokeAsync(this, async () =>
{
var content = new StringContent(json.ToString());
content.Headers.ContentType = MediaTypeHeaderValue.Parse(patchOption == WebApiPatchOption.JsonPatch ? "application/json-patch+json" : "application/merge-patch+json");
var result = new WebApiAgentResult(await Args.HttpClient.SendAsync(await CreateRequestMessageAsync(new HttpMethod("PATCH"), uri, content, requestOptions).ConfigureAwait(false)).ConfigureAwait(false));
result.Content = await result.Response.Content.ReadAsStringAsync().ConfigureAwait(false);
return new WebApiAgentResult<TResult>(VerifyResult(result));
}, json).ConfigureAwait(false);
}
#endregion
/// <summary>
/// Creates the full <see cref="Uri"/> from concatenating the <see cref="HttpClient.BaseAddress"/> and <paramref name="urlSuffix"/>.
/// </summary>
/// <param name="urlSuffix">The specific url suffix for the operation.</param>
/// <param name="args">The operation arguments to be substituted within the <paramref name="urlSuffix"/>.</param>
/// <param name="requestOptions">The optional <see cref="WebApiRequestOptions"/>.</param>
protected Uri CreateFullUri(string? urlSuffix = null, WebApiArg[]? args = null, WebApiRequestOptions? requestOptions = null)
{
// Concatenate the base and specific url strings to form the full Url.
var fullUrl = Args.HttpClient.BaseAddress.AbsoluteUri;
if (!string.IsNullOrEmpty(urlSuffix))
{
if (fullUrl[^1] != '/')
fullUrl += "/";
fullUrl += ((urlSuffix[0] == '/') ? urlSuffix[1..] : urlSuffix);
}
// Replace known url tokens with passed argument values.
if (args != null)
{
if (args.Count(x => x.ArgType == WebApiArgType.FromBody) > 1)
throw new ArgumentException("Only a single argument can have an ArgType of FromBody.", nameof(args));
foreach (var arg in args.Where(x => x.ArgType != WebApiArgType.FromBody))
{
var argUrl = "{" + arg.Name + "}";
if (fullUrl.Contains(argUrl, StringComparison.InvariantCulture))
{
fullUrl = fullUrl.Replace(argUrl, arg.ToString(), StringComparison.InvariantCulture);
arg.IsUsed = true;
}
}
bool firstTime = !fullUrl.Contains("?", StringComparison.InvariantCulture);
foreach (var arg in args.Where(x => !x.IsDefault && x.ArgType != WebApiArgType.FromBody && !x.IsUsed))
{
var argUrl = arg.ToUrlQueryString();
if (!string.IsNullOrEmpty(argUrl))
{
fullUrl = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}{1}{2}", fullUrl, firstTime ? "?" : "&", arg.ToUrlQueryString());
firstTime = false;
}
}
}
// Add any optional query string arguments.
if (requestOptions != null)
{
if (requestOptions.IncludeFields.Any())
fullUrl = fullUrl + (fullUrl.Contains("?", StringComparison.InvariantCulture) ? "&" : "?") + WebApiRequestOptions.IncludeFieldsQueryStringName + "=" + Uri.EscapeDataString(string.Join(",", requestOptions.IncludeFields.Where(x => !string.IsNullOrEmpty(x))));
if (requestOptions.ExcludeFields.Any())
fullUrl = fullUrl + (fullUrl.Contains("?", StringComparison.InvariantCulture) ? "&" : "?") + WebApiRequestOptions.ExcludeFieldsQueryStringName + "=" + Uri.EscapeDataString(string.Join(",", requestOptions.ExcludeFields.Where(x => !string.IsNullOrEmpty(x))));
if (requestOptions.IncludeRefDataText)
fullUrl = fullUrl + (fullUrl.Contains("?", StringComparison.InvariantCulture) ? "&" : "?") + WebApiRequestOptions.IncludeRefDataTextQueryStringName + "=true";
if (requestOptions.IncludeInactive)
fullUrl = fullUrl + (fullUrl.Contains("?", StringComparison.InvariantCulture) ? "&" : "?") + WebApiRequestOptions.IncludeInactiveQueryStringName + "=true";
if (!string.IsNullOrEmpty(requestOptions.UrlQueryString))
fullUrl = fullUrl + (fullUrl.Contains("?", StringComparison.InvariantCulture) ? "&" : "?") + (requestOptions.UrlQueryString.StartsWith("?", StringComparison.InvariantCultureIgnoreCase) ? requestOptions.UrlQueryString[1..] : requestOptions.UrlQueryString);
}
return new Uri(fullUrl.Replace(" ", "%20", StringComparison.InvariantCulture));
}
#pragma warning disable CA1822 // Mark members as static; by-design as it can be overridden.
/// <summary>
/// Verify the response status code and handle accordingly.
/// </summary>
/// <param name="result">The <see cref="WebApiAgentResult"/> to verify.</param>
protected WebApiAgentResult VerifyResult(WebApiAgentResult result)
#pragma warning restore CA1822 // Mark members as static
{
Check.NotNull(result, nameof(result));
// Extract any messages sent via the header.
if (result.Response.Headers.TryGetValues(WebApiConsts.MessagesHeaderName, out IEnumerable<string> msgs) && msgs.Any())
result.Messages = JsonConvert.DeserializeObject<MessageItemCollection>(msgs.First());
// Where the status is considered a-OK then get out of here!
if (result.Response.IsSuccessStatusCode)
return result;
// Determine whether the response contains our (beef) headers.
if (result.Response.Headers.TryGetValues(WebApiConsts.ErrorTypeHeaderName, out IEnumerable<string> errorTypes) && errorTypes.Any())
{
// Handle and convert the known errors to their corresponding error types.
if (Enum.TryParse(errorTypes.First(), out ErrorType errortype))
{
result.ErrorType = errortype;
JToken? json = null;
if (result.Response.Content.Headers.ContentLength == 0)
{ }
else if (result.Response.Content.Headers.ContentType.MediaType != MediaTypeNames.Application.Json)
result.ErrorMessage = result.Content;
else
{
json = JToken.Parse(result.Content!);
if (json.Type == JTokenType.String)
result.ErrorMessage = json.Value<string>();
else if (json.Type == JTokenType.Object)
result.ErrorMessage = json["Message"]?.ToObject<string>();
}
if (result.ErrorType == ErrorType.ValidationError)
{
if (json != null && json.Type == JTokenType.Object)
{
foreach (var prop in (json["ModelState"] ?? json).ToObject<Dictionary<string, ICollection<string>>>() ?? new Dictionary<string, ICollection<string>>())
{
foreach (var text in prop.Value)
{
if (result.Messages == null)
result.Messages = new MessageItemCollection();
result.Messages.Add(prop.Key, MessageType.Error, text);
}
}
}
}
}
}
return result;
}
/// <summary>
/// Create the content by JSON serializing the request value.
/// </summary>
private static StringContent? CreateJsonContentFromValue(object? value)
{
if (value == null)
return null;
var content = new StringContent(JsonConvert.SerializeObject(value));
content.Headers.ContentType = MediaTypeHeaderValue.Parse(MediaTypeNames.Application.Json);
return content;
}
/// <summary>
/// Gets the named header value as a nullable long.
/// </summary>
private static long? GetHeaderValueLong(WebApiAgentResult result, string name)
{
if (!result.Response.Headers.TryGetValues(name, out IEnumerable<string> values) || !values.Any())
return null;
if (!long.TryParse(values.First(), out long val))
return null;
return val;
}
}
} | 61.525952 | 277 | 0.633541 | [
"MIT"
] | ciaranodonnell/Beef | src/Beef.Abstractions/WebApi/WebApiAgentBase.cs | 35,564 | C# |
using System.Web.Mvc;
using Core.Framework.Permissions.Helpers;
using Core.Framework.Permissions.Models;
using Core.Web.NHibernate.Contracts;
using Core.Web.NHibernate.Models;
using Framework.Mvc.Controllers;
using Microsoft.Practices.ServiceLocation;
namespace Core.Web.Areas.Admin.Controllers
{
[Permissions((int)BaseEntityOperations.Manage, typeof(SiteSettings))]
public partial class SiteSettingsController : FrameworkController
{
#region Fields
private readonly ISiteSettingsService siteSettingsService;
#endregion
#region Constructor
public SiteSettingsController()
{
siteSettingsService = ServiceLocator.Current.GetInstance<ISiteSettingsService>();
}
#endregion
#region Actions
public virtual ActionResult Show()
{
return View("ViewSettings", siteSettingsService.GetSettings());
}
[HttpPost]
public virtual ActionResult Edit(SiteSettings model)
{
if (ModelState.IsValid)
{
if (siteSettingsService.Save(model))
Success(Translate("Messages.SiteSettingsApplied"));
else Error(Translate("Messages.Error"));
}
else
{
Error(Translate("Messages.ValidationError"));
}
return View("ViewSettings");
}
#endregion
}
}
| 26.018182 | 92 | 0.635919 | [
"BSD-2-Clause"
] | coreframework/Core-Framework | Source/Core.Web/Areas/Admin/Controllers/SiteSettingsController.cs | 1,433 | C# |
using System;
using System.Text.Json.Serialization;
namespace Switchboard.Controllers.WebSocketized.Contracts
{
internal class MessageWithPayload<T> : Message
{
[Obsolete("For deserialization only")]
public MessageWithPayload() : base(0)
{
}
protected MessageWithPayload(int opCode, T payload) : base(opCode)
{
Payload = payload;
}
[JsonPropertyName("data")] public T Payload { get; set; }
}
} | 24.25 | 74 | 0.62268 | [
"MIT"
] | kirisame-project/switchboard | Switchboard/Controllers/WebSocketized/Contracts/MessageWithPayload.cs | 487 | C# |
/* Copyright 2009 - 2010 Marcus Bratton
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 NUnit.Framework;
using Siege.ServiceLocator.Resolution;
using Siege.ServiceLocator.Native;
using Siege.ServiceLocator.Native.ConstructionStrategies;
namespace Siege.ServiceLocator.UnitTests.Adapters
{
[Category("Siege")]
public class ILSiegeAdapterTests : ServiceLocatorTests
{
protected override IServiceLocatorAdapter GetAdapter()
{
return new Native.SiegeAdapter();
}
private SiegeTypeResolver ilResolver;
public override void SetUp()
{
ilResolver = new SiegeTypeResolver(new SiegeProxyConstructionStrategy());
base.SetUp();
}
protected override void RegisterWithoutSiege<TFrom, TTo>()
{
ilResolver.Register(typeof(TFrom), typeof(TTo));
}
protected override void ResolveWithoutSiege<T>()
{
ilResolver.Get(typeof(T), new ConstructorParameter[] { });
}
[Ignore]
public override void ShouldResolveIfExistsInIoCButNotRegisteredInContainer()
{
base.ShouldResolveIfExistsInIoCButNotRegisteredInContainer();
}
}
} | 32.927273 | 86 | 0.661513 | [
"Apache-2.0"
] | lokalan/Siege | Siege.ServiceLocator/Siege.ServiceLocator.UnitTests/Adapters/ILSiegeAdapterTests.cs | 1,811 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the chime-2018-05-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Chime.Model
{
/// <summary>
/// Container for the parameters to the UpdatePhoneNumberSettings operation.
/// Updates the phone number settings for the administrator's AWS account, such as the
/// default outbound calling name. You can update the default outbound calling name once
/// every seven days. Outbound calling names can take up to 72 hours to update.
/// </summary>
public partial class UpdatePhoneNumberSettingsRequest : AmazonChimeRequest
{
private string _callingName;
/// <summary>
/// Gets and sets the property CallingName.
/// <para>
/// The default outbound calling name for the account.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string CallingName
{
get { return this._callingName; }
set { this._callingName = value; }
}
// Check to see if CallingName property is set
internal bool IsSetCallingName()
{
return this._callingName != null;
}
}
} | 33.344262 | 104 | 0.654376 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/Chime/Generated/Model/UpdatePhoneNumberSettingsRequest.cs | 2,034 | C# |
// <auto-generated />
using System;
using API.Context;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace API.Migrations
{
[DbContext(typeof(MyContext))]
[Migration("20200925073802_updtblEmployee")]
partial class updtblEmployee
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.1.14-servicing-32113")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("API.Models.Division", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTimeOffset>("CreateDate");
b.Property<DateTimeOffset>("DeleteDate");
b.Property<string>("Name");
b.Property<DateTimeOffset>("UpdateDate");
b.Property<bool>("isDelete");
b.HasKey("Id");
b.ToTable("TB_M_Division");
});
modelBuilder.Entity("API.Models.Employee", b =>
{
b.Property<string>("UserId");
b.Property<string>("Address");
b.Property<string>("AssignmentSite");
b.Property<string>("City");
b.Property<DateTimeOffset>("CreateDate");
b.Property<DateTimeOffset>("DeleteDate");
b.Property<string>("DivisionId");
b.Property<string>("NIK");
b.Property<string>("Name");
b.Property<string>("Phone");
b.Property<string>("Province");
b.Property<string>("SubDistrict");
b.Property<DateTimeOffset>("UpdateDate");
b.Property<string>("Village");
b.Property<string>("ZipCode");
b.Property<bool>("isDelete");
b.HasKey("UserId");
b.HasIndex("DivisionId");
b.ToTable("TB_M_Employee");
});
modelBuilder.Entity("API.Models.Log", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTimeOffset>("CreateDate");
b.Property<string>("Email");
b.Property<string>("Response");
b.HasKey("Id");
b.ToTable("TB_T_Log");
});
modelBuilder.Entity("API.Models.Role", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ConcurrencyStamp");
b.Property<DateTimeOffset>("CreateDate");
b.Property<DateTimeOffset>("DeleteDate");
b.Property<string>("Name");
b.Property<string>("NormalizedName");
b.Property<DateTimeOffset>("UpdateDate");
b.Property<bool>("isDelete");
b.HasKey("Id");
b.ToTable("TB_M_Role");
});
modelBuilder.Entity("API.Models.User", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Email");
b.Property<string>("Password");
b.Property<string>("Token");
b.Property<string>("VerifyCode");
b.HasKey("Id");
b.ToTable("TB_M_User");
});
modelBuilder.Entity("API.Models.UserRole", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId");
b.HasIndex("RoleId");
b.ToTable("TB_M_UserRole");
});
modelBuilder.Entity("API.Models.Employee", b =>
{
b.HasOne("API.Models.Division", "Division")
.WithMany()
.HasForeignKey("DivisionId");
b.HasOne("API.Models.User", "User")
.WithOne("Employee")
.HasForeignKey("API.Models.Employee", "UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("API.Models.UserRole", b =>
{
b.HasOne("API.Models.Role", "Role")
.WithMany()
.HasForeignKey("RoleId");
b.HasOne("API.Models.User", "User")
.WithMany("userRoles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}
| 30.228261 | 125 | 0.472312 | [
"MIT"
] | fhmanwar/UserManagement | API/Migrations/20200925073802_updtblEmployee.Designer.cs | 5,564 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Devices.V20190322.Inputs
{
/// <summary>
/// The properties of an IoT hub.
/// </summary>
public sealed class IotHubPropertiesArgs : Pulumi.ResourceArgs
{
[Input("authorizationPolicies")]
private InputList<Inputs.SharedAccessSignatureAuthorizationRuleArgs>? _authorizationPolicies;
/// <summary>
/// The shared access policies you can use to secure a connection to the IoT hub.
/// </summary>
public InputList<Inputs.SharedAccessSignatureAuthorizationRuleArgs> AuthorizationPolicies
{
get => _authorizationPolicies ?? (_authorizationPolicies = new InputList<Inputs.SharedAccessSignatureAuthorizationRuleArgs>());
set => _authorizationPolicies = value;
}
/// <summary>
/// The IoT hub cloud-to-device messaging properties.
/// </summary>
[Input("cloudToDevice")]
public Input<Inputs.CloudToDevicePropertiesArgs>? CloudToDevice { get; set; }
/// <summary>
/// IoT hub comments.
/// </summary>
[Input("comments")]
public Input<string>? Comments { get; set; }
/// <summary>
/// If True, file upload notifications are enabled.
/// </summary>
[Input("enableFileUploadNotifications")]
public Input<bool>? EnableFileUploadNotifications { get; set; }
[Input("eventHubEndpoints")]
private InputMap<Inputs.EventHubPropertiesArgs>? _eventHubEndpoints;
/// <summary>
/// The Event Hub-compatible endpoint properties. The only possible keys to this dictionary is events. This key has to be present in the dictionary while making create or update calls for the IoT hub.
/// </summary>
public InputMap<Inputs.EventHubPropertiesArgs> EventHubEndpoints
{
get => _eventHubEndpoints ?? (_eventHubEndpoints = new InputMap<Inputs.EventHubPropertiesArgs>());
set => _eventHubEndpoints = value;
}
/// <summary>
/// The capabilities and features enabled for the IoT hub.
/// </summary>
[Input("features")]
public InputUnion<string, Pulumi.AzureNative.Devices.V20190322.Capabilities>? Features { get; set; }
[Input("ipFilterRules")]
private InputList<Inputs.IpFilterRuleArgs>? _ipFilterRules;
/// <summary>
/// The IP filter rules.
/// </summary>
public InputList<Inputs.IpFilterRuleArgs> IpFilterRules
{
get => _ipFilterRules ?? (_ipFilterRules = new InputList<Inputs.IpFilterRuleArgs>());
set => _ipFilterRules = value;
}
[Input("messagingEndpoints")]
private InputMap<Inputs.MessagingEndpointPropertiesArgs>? _messagingEndpoints;
/// <summary>
/// The messaging endpoint properties for the file upload notification queue.
/// </summary>
public InputMap<Inputs.MessagingEndpointPropertiesArgs> MessagingEndpoints
{
get => _messagingEndpoints ?? (_messagingEndpoints = new InputMap<Inputs.MessagingEndpointPropertiesArgs>());
set => _messagingEndpoints = value;
}
/// <summary>
/// The routing related properties of the IoT hub. See: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging
/// </summary>
[Input("routing")]
public Input<Inputs.RoutingPropertiesArgs>? Routing { get; set; }
[Input("storageEndpoints")]
private InputMap<Inputs.StorageEndpointPropertiesArgs>? _storageEndpoints;
/// <summary>
/// The list of Azure Storage endpoints where you can upload files. Currently you can configure only one Azure Storage account and that MUST have its key as $default. Specifying more than one storage account causes an error to be thrown. Not specifying a value for this property when the enableFileUploadNotifications property is set to True, causes an error to be thrown.
/// </summary>
public InputMap<Inputs.StorageEndpointPropertiesArgs> StorageEndpoints
{
get => _storageEndpoints ?? (_storageEndpoints = new InputMap<Inputs.StorageEndpointPropertiesArgs>());
set => _storageEndpoints = value;
}
public IotHubPropertiesArgs()
{
}
}
}
| 41.283186 | 380 | 0.656163 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Devices/V20190322/Inputs/IotHubPropertiesArgs.cs | 4,665 | C# |
using QueueIT.KnownUser.V3.AspNetCore.IntegrationConfig;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using Xunit;
namespace QueueIT.KnownUser.V3.AspNetCore.Tests
{
public class KnownUserTest
{
public class MockHttpRequest : IHttpRequest
{
public MockHttpRequest()
{
Headers = new NameValueCollection();
}
public NameValueCollection CookiesValue { get; set; } = new NameValueCollection();
public string UserHostAddress { get; set; }
public NameValueCollection Headers { get; set; }
public string UserAgent { get; set; }
public Uri Url { get; set; }
public string GetCookieValue(string cookieKey)
{
return this.CookiesValue[cookieKey];
}
}
public class MockHttpResponse : IHttpResponse
{
public Dictionary<string, Dictionary<string, object>> CookiesValue { get; set; } =
new Dictionary<string, Dictionary<string, object>>();
public void SetCookie(string cookieName, string cookieValue, string domain, DateTime expiration)
{
CookiesValue.Add(cookieName,
new Dictionary<string, object>() {
{ nameof(cookieName), cookieName},
{ nameof(cookieValue), cookieValue},
{ nameof(domain), domain},
{ nameof(expiration), expiration}}
);
}
}
internal class HttpContextMock : IHttpContextProvider
{
public IHttpRequest HttpRequest { get; set; } = new MockHttpRequest();
public IHttpResponse HttpResponse { get; set; } = new MockHttpResponse();
}
class UserInQueueServiceMock : IUserInQueueService
{
public List<List<string>> validateQueueRequestCalls = new List<List<string>>();
public List<List<string>> extendQueueCookieCalls = new List<List<string>>();
public List<List<string>> cancelRequestCalls = new List<List<string>>();
public List<List<string>> ignoreRequestCalls = new List<List<string>>();
public bool validateQueueRequestRaiseException = false;
public bool validateCancelRequestRaiseException = false;
public RequestValidationResult ValidateQueueRequest(string targetUrl, string queueitToken, QueueEventConfig config, string customerId, string secretKey)
{
List<string> args = new List<string>();
args.Add(targetUrl);
args.Add(queueitToken);
args.Add(config.CookieDomain + ":"
+ config.LayoutName + ":"
+ config.Culture + ":"
+ config.EventId + ":"
+ config.QueueDomain + ":"
+ config.ExtendCookieValidity.ToString().ToLower() + ":"
+ config.CookieValidityMinute + ":"
+ config.Version + ":"
+ config.ActionName);
args.Add(customerId);
args.Add(secretKey);
validateQueueRequestCalls.Add(args);
if (validateQueueRequestRaiseException)
throw new Exception("Exception");
return new RequestValidationResult("Queue");
}
public void ExtendQueueCookie(string eventId, int cookieValidityMinute, string cookieDomain, string secretKey)
{
List<string> args = new List<string>();
args.Add(eventId);
args.Add(cookieValidityMinute.ToString());
args.Add(cookieDomain);
args.Add(secretKey);
extendQueueCookieCalls.Add(args);
}
public RequestValidationResult ValidateCancelRequest(string targetUrl, CancelEventConfig config, string customerId, string secretKey)
{
List<string> args = new List<string>();
args.Add(targetUrl);
args.Add(config.CookieDomain + ":"
+ config.EventId + ":"
+ config.QueueDomain + ":"
+ config.Version + ":"
+ config.ActionName);
args.Add(customerId);
args.Add(secretKey);
cancelRequestCalls.Add(args);
if (validateCancelRequestRaiseException)
throw new Exception("Exception");
return new RequestValidationResult("Cancel");
}
public RequestValidationResult GetIgnoreResult(string actionName)
{
ignoreRequestCalls.Add(new List<string>() { actionName });
return new RequestValidationResult("Ignore");
}
}
private void AssertRequestCookieContent(string[] cookieValues, params string[] expectedValues)
{
Assert.True(cookieValues.Count(v => v.StartsWith("ServerUtcTime=")) == 1);
Assert.True(cookieValues.Count(v => v.StartsWith("RequestIP=")) == 1);
Assert.True(cookieValues.Count(v => v.StartsWith("RequestHttpHeader_Via=")) == 1);
Assert.True(cookieValues.Count(v => v.StartsWith("RequestHttpHeader_Forwarded=")) == 1);
Assert.True(cookieValues.Count(v => v.StartsWith("RequestHttpHeader_XForwardedFor=")) == 1);
Assert.True(cookieValues.Count(v => v.StartsWith("RequestHttpHeader_XForwardedHost=")) == 1);
Assert.True(cookieValues.Count(v => v.StartsWith("RequestHttpHeader_XForwardedProto=")) == 1);
Assert.True(cookieValues.Any(v => v == $"SdkVersion={expectedValues[0]}"));
Assert.True(cookieValues.Any(v => v == $"Runtime={expectedValues[1]}"));
var utcTimeInCookie = cookieValues.FirstOrDefault(v => v.StartsWith("ServerUtcTime")).Split('=')[1];
Assert.True(string.Compare(expectedValues[2], utcTimeInCookie) <= 0);
Assert.True(string.Compare(DateTime.UtcNow.ToString("o"), utcTimeInCookie) >= 0);
Assert.True(cookieValues.Any(v => v == $"RequestIP={expectedValues[3]}"));
Assert.True(cookieValues.Any(v => v == $"RequestHttpHeader_Via={expectedValues[4]}"));
Assert.True(cookieValues.Any(v => v == $"RequestHttpHeader_Forwarded={expectedValues[5]}"));
Assert.True(cookieValues.Any(v => v == $"RequestHttpHeader_XForwardedFor={expectedValues[6]}"));
Assert.True(cookieValues.Any(v => v == $"RequestHttpHeader_XForwardedHost={expectedValues[7]}"));
Assert.True(cookieValues.Any(v => v == $"RequestHttpHeader_XForwardedProto={expectedValues[8]}"));
}
[Fact]
public void CancelRequestByLocalConfig_Test()
{
// Arrange
var httpContextMock = new HttpContextMock() { };
KnownUser._HttpContextProvider = httpContextMock;
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
var cancelEventConfig = new CancelEventConfig() { CookieDomain = "cookiedomain", EventId = "eventid", QueueDomain = "queuedomain", Version = 1, ActionName = "CancelAction" };
// Act
var result = KnownUser.CancelRequestByLocalConfig("url", "queueitToken", cancelEventConfig, "customerid", "secretekey");
// Assert
Assert.Equal("url", mock.cancelRequestCalls[0][0]);
Assert.Equal("cookiedomain:eventid:queuedomain:1:CancelAction", mock.cancelRequestCalls[0][1]);
Assert.Equal("customerid", mock.cancelRequestCalls[0][2]);
Assert.Equal("secretekey", mock.cancelRequestCalls[0][3]);
Assert.False(result.IsAjaxResult);
KnownUser._HttpContextProvider = null;
}
[Fact]
public void CancelRequestByLocalConfig_AjaxCall_Test()
{
// Arrange
var httpContextMock = new HttpContextMock()
{
HttpRequest = new MockHttpRequest()
{ Headers = new NameValueCollection() { { "x-queueit-ajaxpageurl", "http%3A%2F%2Furl" } } }
};
KnownUser._HttpContextProvider = httpContextMock;
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
var cancelEventConfig = new CancelEventConfig() { CookieDomain = "cookiedomain", EventId = "eventid", QueueDomain = "queuedomain", Version = 1, ActionName = "CancelAction" };
// Act
var result = KnownUser.CancelRequestByLocalConfig("url", "queueitToken", cancelEventConfig, "customerid", "secretekey");
// Assert
Assert.Equal("http://url", mock.cancelRequestCalls[0][0]);
Assert.Equal("cookiedomain:eventid:queuedomain:1:CancelAction", mock.cancelRequestCalls[0][1]);
Assert.Equal("customerid", mock.cancelRequestCalls[0][2]);
Assert.Equal("secretekey", mock.cancelRequestCalls[0][3]);
Assert.True(result.IsAjaxResult);
KnownUser._HttpContextProvider = null;
}
[Fact]
public void CancelRequestByLocalConfig_NullQueueDomain_Test()
{
// Arrange
var httpContextMock = new HttpContextMock() { };
KnownUser._HttpContextProvider = httpContextMock;
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
bool exceptionWasThrown = false;
CancelEventConfig eventConfig = new CancelEventConfig();
eventConfig.EventId = "eventid";
eventConfig.CookieDomain = "cookieDomain";
eventConfig.Version = 12;
// Act
try
{
KnownUser.CancelRequestByLocalConfig("targetUrl", "queueitToken", eventConfig, "customerId", "secretKey");
}
catch (ArgumentException ex)
{
exceptionWasThrown = ex.Message == "QueueDomain from cancelEventConfig can not be null or empty.";
}
// Assert
Assert.True(mock.cancelRequestCalls.Count == 0);
Assert.True(exceptionWasThrown);
}
[Fact]
public void CancelRequestByLocalConfig_EventIdNull_Test()
{
// Arrange
var httpContextMock = new HttpContextMock() { };
KnownUser._HttpContextProvider = httpContextMock;
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
bool exceptionWasThrown = false;
CancelEventConfig eventConfig = new CancelEventConfig();
eventConfig.CookieDomain = "domain";
eventConfig.Version = 12;
// Act
try
{
KnownUser.CancelRequestByLocalConfig("targetUrl", "queueitToken", eventConfig, "customerId", "secretKey");
}
catch (ArgumentException ex)
{
exceptionWasThrown = ex.Message == "EventId from cancelEventConfig can not be null or empty.";
}
// Assert
Assert.True(mock.cancelRequestCalls.Count == 0);
Assert.True(exceptionWasThrown);
}
[Fact]
public void CancelRequestByLocalConfig_CancelEventConfigNull_Test()
{
// Arrange
var httpContextMock = new HttpContextMock() { };
KnownUser._HttpContextProvider = httpContextMock;
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
bool exceptionWasThrown = false;
// Act
try
{
KnownUser.CancelRequestByLocalConfig("targetUrl", "queueitToken", null, "customerId", "secretKey");
}
catch (ArgumentException ex)
{
exceptionWasThrown = ex.Message == "cancelEventConfig can not be null.";
}
// Assert
Assert.True(mock.cancelRequestCalls.Count == 0);
Assert.True(exceptionWasThrown);
}
[Fact]
public void CancelRequestByLocalConfig_CustomerIdNull_Test()
{
// Arrange
var httpContextMock = new HttpContextMock() { };
KnownUser._HttpContextProvider = httpContextMock;
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
bool exceptionWasThrown = false;
// Act
try
{
KnownUser.CancelRequestByLocalConfig("targetUrl", "queueitToken", new CancelEventConfig(), null, "secretKey");
}
catch (ArgumentException ex)
{
exceptionWasThrown = ex.Message == "customerId can not be null or empty.";
}
// Assert
Assert.True(mock.cancelRequestCalls.Count == 0);
Assert.True(exceptionWasThrown);
}
[Fact]
public void CancelRequestByLocalConfig_SeceretKeyNull_Test()
{
// Arrange
var httpContextMock = new HttpContextMock() { };
KnownUser._HttpContextProvider = httpContextMock;
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
bool exceptionWasThrown = false;
// Act
try
{
KnownUser.CancelRequestByLocalConfig("targetUrl", "queueitToken", new CancelEventConfig(), "customerid", null);
}
catch (ArgumentException ex)
{
exceptionWasThrown = ex.Message == "secretKey can not be null or empty.";
}
// Assert
Assert.True(mock.cancelRequestCalls.Count == 0);
Assert.True(exceptionWasThrown);
}
[Fact]
public void CancelRequestByLocalConfig_TargetUrl_Test()
{
// Arrange
var httpContextMock = new HttpContextMock() { };
KnownUser._HttpContextProvider = httpContextMock;
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
bool exceptionWasThrown = false;
// Act
try
{
KnownUser.CancelRequestByLocalConfig(null, "queueitToken", new CancelEventConfig(), "customerid", "secretkey");
}
catch (ArgumentException ex)
{
exceptionWasThrown = ex.Message == "targeturl can not be null or empty.";
}
// Assert
Assert.True(mock.cancelRequestCalls.Count == 0);
Assert.True(exceptionWasThrown);
}
[Fact]
public void ExtendQueueCookie_NullEventId_Test()
{
// Arrange
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
bool exceptionWasThrown = false;
// Act
try
{
KnownUser.ExtendQueueCookie(null, 0, null, null);
}
catch (ArgumentException ex)
{
exceptionWasThrown = ex.Message == "eventId can not be null or empty.";
}
// Assert
Assert.True(mock.extendQueueCookieCalls.Count == 0);
Assert.True(exceptionWasThrown);
}
[Fact]
public void ExtendQueueCookie_InvalidCookieValidityMinutes_Test()
{
// Arrange
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
bool exceptionWasThrown = false;
// Act
try
{
KnownUser.ExtendQueueCookie("eventId", 0, "cookiedomain", null);
}
catch (ArgumentException ex)
{
exceptionWasThrown = ex.Message == "cookieValidityMinute should be greater than 0.";
}
// Assert
Assert.True(mock.extendQueueCookieCalls.Count == 0);
Assert.True(exceptionWasThrown);
}
[Fact]
public void ExtendQueueCookie_NullSecretKey_Test()
{
// Arrange
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
bool exceptionWasThrown = false;
// Act
try
{
KnownUser.ExtendQueueCookie("eventId", 20, "cookiedomain", null);
}
catch (ArgumentException ex)
{
exceptionWasThrown = ex.Message == "secretKey can not be null or empty.";
}
// Assert
Assert.True(mock.extendQueueCookieCalls.Count == 0);
Assert.True(exceptionWasThrown);
}
[Fact]
public void ExtendQueueCookie_Test()
{
// Arrange
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
// Act
KnownUser.ExtendQueueCookie("eventId", 20, "cookiedomain", "secretKey");
// Assert
Assert.Equal("eventId", mock.extendQueueCookieCalls[0][0]);
Assert.Equal("20", mock.extendQueueCookieCalls[0][1]);
Assert.Equal("cookiedomain", mock.extendQueueCookieCalls[0][2]);
Assert.Equal("secretKey", mock.extendQueueCookieCalls[0][3]);
}
[Fact]
public void ResolveQueueRequestByLocalConfig_NullCustomerId_Test()
{
// Arrange
var httpContextMock = new HttpContextMock() { };
KnownUser._HttpContextProvider = httpContextMock;
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
bool exceptionWasThrown = false;
// Act
try
{
KnownUser.ResolveQueueRequestByLocalConfig("targetUrl", "queueitToken", null, null, "secretKey");
}
catch (ArgumentException ex)
{
exceptionWasThrown = ex.Message == "customerId can not be null or empty.";
}
// Assert
Assert.True(mock.validateQueueRequestCalls.Count == 0);
Assert.True(exceptionWasThrown);
}
[Fact]
public void ResolveQueueRequestByLocalConfig_NullSecretKey_Test()
{
// Arrange
var httpContextMock = new HttpContextMock() { };
KnownUser._HttpContextProvider = httpContextMock;
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
bool exceptionWasThrown = false;
// Act
try
{
KnownUser.ResolveQueueRequestByLocalConfig("targetUrl", "queueitToken", null, "customerId", null);
}
catch (ArgumentException ex)
{
exceptionWasThrown = ex.Message == "secretKey can not be null or empty.";
}
// Assert
Assert.True(mock.validateQueueRequestCalls.Count == 0);
Assert.True(exceptionWasThrown);
}
[Fact]
public void ResolveQueueRequestByLocalConfig_NullEventConfig_Test()
{
// Arrange
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
bool exceptionWasThrown = false;
// Act
try
{
KnownUser.ResolveQueueRequestByLocalConfig("targetUrl", "queueitToken", null, "customerId", "secretKey");
}
catch (ArgumentException ex)
{
exceptionWasThrown = ex.Message == "eventConfig can not be null.";
}
// Assert
Assert.True(mock.validateQueueRequestCalls.Count == 0);
Assert.True(exceptionWasThrown);
}
[Fact]
public void ResolveRequestByLocalEventConfigNullEventIdTest()
{
// Arrange
var httpContextMock = new HttpContextMock() { };
KnownUser._HttpContextProvider = httpContextMock;
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
bool exceptionWasThrown = false;
QueueEventConfig eventConfig = new QueueEventConfig();
eventConfig.CookieDomain = "cookieDomain";
eventConfig.LayoutName = "layoutName";
eventConfig.Culture = "culture";
//eventConfig.EventId = "eventId";
eventConfig.QueueDomain = "queueDomain";
eventConfig.ExtendCookieValidity = true;
eventConfig.CookieValidityMinute = 10;
eventConfig.Version = 12;
eventConfig.ActionName = "QueueAction";
// Act
try
{
KnownUser.ResolveQueueRequestByLocalConfig("targetUrl", "queueitToken", eventConfig, "customerId", "secretKey");
}
catch (ArgumentException ex)
{
exceptionWasThrown = ex.Message == "EventId from eventConfig can not be null or empty.";
}
// Assert
Assert.True(mock.validateQueueRequestCalls.Count == 0);
Assert.True(exceptionWasThrown);
}
[Fact]
public void ResolveRequestByLocalEventConfig_NullQueueDomain_Test()
{
// Arrange
var httpContextMock = new HttpContextMock() { };
KnownUser._HttpContextProvider = httpContextMock;
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
bool exceptionWasThrown = false;
QueueEventConfig eventConfig = new QueueEventConfig();
eventConfig.CookieDomain = "cookieDomain";
eventConfig.LayoutName = "layoutName";
eventConfig.Culture = "culture";
eventConfig.EventId = "eventId";
//eventConfig.QueueDomain = "queueDomain";
eventConfig.ExtendCookieValidity = true;
eventConfig.CookieValidityMinute = 10;
eventConfig.Version = 12;
eventConfig.ActionName = "QueueAction";
// Act
try
{
KnownUser.ResolveQueueRequestByLocalConfig("targetUrl", "queueitToken", eventConfig, "customerId", "secretKey");
}
catch (ArgumentException ex)
{
exceptionWasThrown = ex.Message == "QueueDomain from eventConfig can not be null or empty.";
}
// Assert
Assert.True(mock.validateQueueRequestCalls.Count == 0);
Assert.True(exceptionWasThrown);
}
[Fact]
public void ResolveQueueRequestByLocalConfig_InvalidCookieValidityMinute_Test()
{
// Arrange
var httpContextMock = new HttpContextMock() { };
KnownUser._HttpContextProvider = httpContextMock;
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
bool exceptionWasThrown = false;
QueueEventConfig eventConfig = new QueueEventConfig();
eventConfig.CookieDomain = "cookieDomain";
eventConfig.LayoutName = "layoutName";
eventConfig.Culture = "culture";
eventConfig.EventId = "eventId";
eventConfig.QueueDomain = "queueDomain";
eventConfig.ExtendCookieValidity = true;
//eventConfig.CookieValidityMinute = 10;
eventConfig.Version = 12;
// Act
try
{
KnownUser.ResolveQueueRequestByLocalConfig("targetUrl", "queueitToken", eventConfig, "customerId", "secretKey");
}
catch (ArgumentException ex)
{
exceptionWasThrown = ex.Message == "CookieValidityMinute from eventConfig should be greater than 0.";
}
// Assert
Assert.True(mock.validateQueueRequestCalls.Count == 0);
Assert.True(exceptionWasThrown);
}
[Fact]
public void ResolveRequestByLocalEventConfig_Test()
{
// Arrange
var httpContextMock = new HttpContextMock() { };
KnownUser._HttpContextProvider = httpContextMock;
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
QueueEventConfig eventConfig = new QueueEventConfig();
eventConfig.CookieDomain = "cookieDomain";
eventConfig.LayoutName = "layoutName";
eventConfig.Culture = "culture";
eventConfig.EventId = "eventId";
eventConfig.QueueDomain = "queueDomain";
eventConfig.ExtendCookieValidity = true;
eventConfig.CookieValidityMinute = 10;
eventConfig.Version = 12;
eventConfig.ActionName = "QueueAction";
// Act
var result = KnownUser.ResolveQueueRequestByLocalConfig("targetUrl", "queueitToken", eventConfig, "customerId", "secretKey");
// Assert
Assert.Equal("targetUrl", mock.validateQueueRequestCalls[0][0]);
Assert.Equal("queueitToken", mock.validateQueueRequestCalls[0][1]);
Assert.Equal("cookieDomain:layoutName:culture:eventId:queueDomain:true:10:12:QueueAction", mock.validateQueueRequestCalls[0][2]);
Assert.Equal("customerId", mock.validateQueueRequestCalls[0][3]);
Assert.Equal("secretKey", mock.validateQueueRequestCalls[0][4]);
Assert.False(result.IsAjaxResult);
}
[Fact]
public void ResolveRequestByLocalEventConfig_AjaxCall_Test()
{
// Arrange
var httpContextMock = new HttpContextMock()
{
HttpRequest = new MockHttpRequest()
{ Headers = new NameValueCollection() { { "x-queueit-ajaxpageurl", "http%3A%2F%2Furl" } } }
};
KnownUser._HttpContextProvider = httpContextMock;
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
QueueEventConfig eventConfig = new QueueEventConfig();
eventConfig.CookieDomain = "cookieDomain";
eventConfig.LayoutName = "layoutName";
eventConfig.Culture = "culture";
eventConfig.EventId = "eventId";
eventConfig.QueueDomain = "queueDomain";
eventConfig.ExtendCookieValidity = true;
eventConfig.CookieValidityMinute = 10;
eventConfig.Version = 12;
eventConfig.ActionName = "QueueAction";
// Act
var result = KnownUser.ResolveQueueRequestByLocalConfig("targetUrl", "queueitToken", eventConfig, "customerId", "secretKey");
// Assert
Assert.Equal("http://url", mock.validateQueueRequestCalls[0][0]);
Assert.Equal("queueitToken", mock.validateQueueRequestCalls[0][1]);
Assert.Equal("cookieDomain:layoutName:culture:eventId:queueDomain:true:10:12:" + eventConfig.ActionName, mock.validateQueueRequestCalls[0][2]);
Assert.Equal("customerId", mock.validateQueueRequestCalls[0][3]);
Assert.Equal("secretKey", mock.validateQueueRequestCalls[0][4]);
Assert.True(result.IsAjaxResult);
}
[Fact]
public void ValidateRequestByIntegrationConfig_EmptyCurrentUrl_Test()
{
var httpContextMock = new HttpContextMock() { };
KnownUser._HttpContextProvider = httpContextMock;
// Arrange
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
bool exceptionWasThrown = false;
// Act
try
{
KnownUser.ValidateRequestByIntegrationConfig("", null, null, null, null);
}
catch (Exception ex)
{
exceptionWasThrown = ex.Message == "currentUrlWithoutQueueITToken can not be null or empty.";
}
// Assert
Assert.True(mock.validateQueueRequestCalls.Count == 0);
Assert.True(exceptionWasThrown);
}
[Fact]
public void ValidateRequestByIntegrationConfig_EmptyIntegrationsConfig_Test()
{
// Arrange
var httpContextMock = new HttpContextMock() { };
KnownUser._HttpContextProvider = httpContextMock;
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
bool exceptionWasThrown = false;
// Act
try
{
KnownUser.ValidateRequestByIntegrationConfig("currentUrl", "queueitToken", null, null, null);
}
catch (Exception ex)
{
exceptionWasThrown = ex.Message == "customerIntegrationInfo can not be null.";
}
// Assert
Assert.True(mock.validateQueueRequestCalls.Count == 0);
Assert.True(exceptionWasThrown);
}
[Fact]
public void ValidateRequestByIntegrationConfig_QueueAction()
{
// Arrange
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
TriggerPart triggerPart1 = new TriggerPart();
triggerPart1.Operator = "Contains";
triggerPart1.ValueToCompare = "event1";
triggerPart1.UrlPart = "PageUrl";
triggerPart1.ValidatorType = "UrlValidator";
triggerPart1.IsNegative = false;
triggerPart1.IsIgnoreCase = true;
TriggerPart triggerPart2 = new TriggerPart();
triggerPart2.Operator = "Contains";
triggerPart2.ValueToCompare = "googlebot";
triggerPart2.ValidatorType = "UserAgentValidator";
triggerPart2.IsNegative = false;
triggerPart2.IsIgnoreCase = false;
TriggerModel trigger = new TriggerModel();
trigger.LogicalOperator = "And";
trigger.TriggerParts = new TriggerPart[] { triggerPart1, triggerPart2 };
IntegrationConfigModel config = new IntegrationConfigModel();
config.Name = "event1action";
//config.ActionType = "Queue";
config.EventId = "event1";
config.CookieDomain = ".test.com";
config.LayoutName = "Christmas Layout by Queue-it";
config.Culture = "da-DK";
config.ExtendCookieValidity = true;
config.CookieValidityMinute = 20;
config.Triggers = new TriggerModel[] { trigger };
config.QueueDomain = "knownusertest.queue-it.net";
config.RedirectLogic = "AllowTParameter";
config.ForcedTargetUrl = "";
config.ActionType = ActionType.QueueAction;
CustomerIntegration customerIntegration = new CustomerIntegration();
customerIntegration.Integrations = new IntegrationConfigModel[] { config };
customerIntegration.Version = 3;
var httpContextMock = new HttpContextMock()
{
HttpRequest =
new MockHttpRequest()
{
UserAgent = "googlebot",
Headers = new NameValueCollection()
}
};
KnownUser._HttpContextProvider = httpContextMock;
// Act
var result = KnownUser.ValidateRequestByIntegrationConfig("http://test.com?event1=true", "queueitToken", customerIntegration, "customerId", "secretKey");
// Assert
Assert.True(mock.validateQueueRequestCalls.Count == 1);
Assert.Equal("http://test.com?event1=true", mock.validateQueueRequestCalls[0][0]);
Assert.Equal("queueitToken", mock.validateQueueRequestCalls[0][1]);
Assert.Equal(".test.com:Christmas Layout by Queue-it:da-DK:event1:knownusertest.queue-it.net:true:20:3:event1action", mock.validateQueueRequestCalls[0][2]);
Assert.Equal("customerId", mock.validateQueueRequestCalls[0][3]);
Assert.Equal("secretKey", mock.validateQueueRequestCalls[0][4]);
Assert.False(result.IsAjaxResult);
KnownUser._HttpContextProvider = null;
}
[Fact]
public void ValidateRequestByIntegrationConfig_AjaxCall_QueueAction()
{
// Arrange
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
TriggerPart triggerPart1 = new TriggerPart();
triggerPart1.Operator = "Contains";
triggerPart1.ValueToCompare = "event1";
triggerPart1.UrlPart = "PageUrl";
triggerPart1.ValidatorType = "UrlValidator";
triggerPart1.IsNegative = false;
triggerPart1.IsIgnoreCase = true;
TriggerPart triggerPart2 = new TriggerPart();
triggerPart2.Operator = "Contains";
triggerPart2.ValueToCompare = "googlebot";
triggerPart2.ValidatorType = "UserAgentValidator";
triggerPart2.IsNegative = false;
triggerPart2.IsIgnoreCase = false;
TriggerModel trigger = new TriggerModel();
trigger.LogicalOperator = "And";
trigger.TriggerParts = new TriggerPart[] { triggerPart1, triggerPart2 };
IntegrationConfigModel config = new IntegrationConfigModel();
config.Name = "event1action";
//config.ActionType = "Queue";
config.EventId = "event1";
config.CookieDomain = ".test.com";
config.LayoutName = "Christmas Layout by Queue-it";
config.Culture = "da-DK";
config.ExtendCookieValidity = true;
config.CookieValidityMinute = 20;
config.Triggers = new TriggerModel[] { trigger };
config.QueueDomain = "knownusertest.queue-it.net";
config.RedirectLogic = "AllowTParameter";
config.ForcedTargetUrl = "";
config.ActionType = ActionType.QueueAction;
CustomerIntegration customerIntegration = new CustomerIntegration();
customerIntegration.Integrations = new IntegrationConfigModel[] { config };
customerIntegration.Version = 3;
var httpContextMock = new HttpContextMock()
{
HttpRequest =
new MockHttpRequest()
{
UserAgent = "googlebot",
Headers = new NameValueCollection() { { "x-queueit-ajaxpageurl", "http%3A%2F%2Furl" } }
}
};
KnownUser._HttpContextProvider = httpContextMock;
// Act
var result = KnownUser.ValidateRequestByIntegrationConfig("http://test.com?event1=true", "queueitToken", customerIntegration, "customerId", "secretKey");
// Assert
Assert.True(mock.validateQueueRequestCalls.Count == 1);
Assert.Equal("http://url", mock.validateQueueRequestCalls[0][0]);
Assert.Equal("queueitToken", mock.validateQueueRequestCalls[0][1]);
Assert.Equal(".test.com:Christmas Layout by Queue-it:da-DK:event1:knownusertest.queue-it.net:true:20:3:event1action", mock.validateQueueRequestCalls[0][2]);
Assert.Equal("customerId", mock.validateQueueRequestCalls[0][3]);
Assert.Equal("secretKey", mock.validateQueueRequestCalls[0][4]);
Assert.True(result.IsAjaxResult);
KnownUser._HttpContextProvider = null;
}
[Fact]
public void ValidateRequestByIntegrationConfig_NotMatch_Test()
{
// Arrange
var httpContextMock = new HttpContextMock() { };
KnownUser._HttpContextProvider = httpContextMock;
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
CustomerIntegration customerIntegration = new CustomerIntegration();
customerIntegration.Integrations = new IntegrationConfigModel[0];
customerIntegration.Version = 3;
// Act
RequestValidationResult result = KnownUser.ValidateRequestByIntegrationConfig("http://test.com?event1=true", "queueitToken", customerIntegration, "customerId", "secretKey");
// Assert
Assert.True(mock.validateQueueRequestCalls.Count == 0);
Assert.False(result.DoRedirect);
}
[Theory]
[InlineData("ForcedTargetUrl", "http://forcedtargeturl.com")]
[InlineData("ForecedTargetUrl", "http://forcedtargeturl.com")]
[InlineData("EventTargetUrl", "")]
public void ValidateRequestByIntegrationConfig_RedirectLogic_Test(string redirectLogic, string forcedTargetUrl)
{
// Arrange
var httpContextMock = new HttpContextMock() { };
KnownUser._HttpContextProvider = httpContextMock;
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
TriggerPart triggerPart = new TriggerPart();
triggerPart.Operator = "Contains";
triggerPart.ValueToCompare = "event1";
triggerPart.UrlPart = "PageUrl";
triggerPart.ValidatorType = "UrlValidator";
triggerPart.IsNegative = false;
triggerPart.IsIgnoreCase = true;
TriggerModel trigger = new TriggerModel();
trigger.LogicalOperator = "And";
trigger.TriggerParts = new TriggerPart[] { triggerPart };
IntegrationConfigModel config = new IntegrationConfigModel();
config.Name = "event1action";
//config.ActionType = "Queue";
config.EventId = "event1";
config.CookieDomain = ".test.com";
config.LayoutName = "Christmas Layout by Queue-it";
config.Culture = "da-DK";
config.ExtendCookieValidity = true;
config.CookieValidityMinute = 20;
config.Triggers = new TriggerModel[] { trigger };
config.QueueDomain = "knownusertest.queue-it.net";
config.RedirectLogic = redirectLogic;
config.ForcedTargetUrl = forcedTargetUrl;
config.ActionType = ActionType.QueueAction;
CustomerIntegration customerIntegration = new CustomerIntegration();
customerIntegration.Integrations = new IntegrationConfigModel[] { config };
customerIntegration.Version = 3;
// Act
KnownUser.ValidateRequestByIntegrationConfig("http://test.com?event1=true", "queueitToken", customerIntegration, "customerId", "secretKey");
// Assert
Assert.True(mock.validateQueueRequestCalls.Count == 1);
Assert.Equal(forcedTargetUrl, mock.validateQueueRequestCalls[0][0]);
}
[Fact]
public void ValidateRequestByIntegrationConfig_IgnoreAction()
{
// Arrange
TriggerPart triggerPart = new TriggerPart();
triggerPart.Operator = "Contains";
triggerPart.ValueToCompare = "event1";
triggerPart.UrlPart = "PageUrl";
triggerPart.ValidatorType = "UrlValidator";
triggerPart.IsNegative = false;
triggerPart.IsIgnoreCase = true;
TriggerModel trigger = new TriggerModel();
trigger.LogicalOperator = "And";
trigger.TriggerParts = new TriggerPart[] { triggerPart };
IntegrationConfigModel config = new IntegrationConfigModel();
config.Name = "event1action";
config.EventId = "eventid";
config.CookieDomain = "cookiedomain";
config.Triggers = new TriggerModel[] { trigger };
config.QueueDomain = "queuedomain";
config.ActionType = ActionType.IgnoreAction;
CustomerIntegration customerIntegration = new CustomerIntegration();
customerIntegration.Integrations = new IntegrationConfigModel[] { config };
customerIntegration.Version = 3;
var httpContextMock = new HttpContextMock() { };
KnownUser._HttpContextProvider = httpContextMock;
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
// Act
var result = KnownUser.ValidateRequestByIntegrationConfig("http://test.com?event1=true", "queueitToken", customerIntegration, "customerid", "secretkey");
// Assert
Assert.True(mock.ignoreRequestCalls.Count() == 1);
Assert.False(result.IsAjaxResult);
Assert.True(mock.ignoreRequestCalls[0][0] == config.Name);
}
[Fact]
public void ValidateRequestByIntegrationConfig_AjaxCall_IgnoreAction()
{
// Arrange
TriggerPart triggerPart = new TriggerPart();
triggerPart.Operator = "Contains";
triggerPart.ValueToCompare = "event1";
triggerPart.UrlPart = "PageUrl";
triggerPart.ValidatorType = "UrlValidator";
triggerPart.IsNegative = false;
triggerPart.IsIgnoreCase = true;
TriggerModel trigger = new TriggerModel();
trigger.LogicalOperator = "And";
trigger.TriggerParts = new TriggerPart[] { triggerPart };
IntegrationConfigModel config = new IntegrationConfigModel();
config.Name = "event1action";
config.EventId = "eventid";
config.CookieDomain = "cookiedomain";
config.Triggers = new TriggerModel[] { trigger };
config.QueueDomain = "queuedomain";
config.ActionType = ActionType.IgnoreAction;
CustomerIntegration customerIntegration = new CustomerIntegration();
customerIntegration.Integrations = new IntegrationConfigModel[] { config };
customerIntegration.Version = 3;
var httpContextMock = new HttpContextMock()
{
HttpRequest = new MockHttpRequest()
{
Headers = new NameValueCollection() { { "x-queueit-ajaxpageurl", "url" } }
}
};
KnownUser._HttpContextProvider = httpContextMock;
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
// Act
var result = KnownUser.ValidateRequestByIntegrationConfig("http://test.com?event1=true", "queueitToken", customerIntegration, "customerid", "secretkey");
// Assert
Assert.True(mock.ignoreRequestCalls.Count() == 1);
Assert.True(result.IsAjaxResult);
Assert.True(mock.ignoreRequestCalls[0][0] == config.Name);
}
[Fact]
public void ValidateRequestByIntegrationConfig_CancelAction()
{
// Arrange
TriggerPart triggerPart = new TriggerPart();
triggerPart.Operator = "Contains";
triggerPart.ValueToCompare = "event1";
triggerPart.UrlPart = "PageUrl";
triggerPart.ValidatorType = "UrlValidator";
triggerPart.IsNegative = false;
triggerPart.IsIgnoreCase = true;
TriggerModel trigger = new TriggerModel();
trigger.LogicalOperator = "And";
trigger.TriggerParts = new TriggerPart[] { triggerPart };
IntegrationConfigModel config = new IntegrationConfigModel();
config.Name = "event1action";
config.EventId = "eventid";
config.CookieDomain = "cookiedomain";
config.Triggers = new TriggerModel[] { trigger };
config.QueueDomain = "queuedomain";
config.ActionType = ActionType.CancelAction;
CustomerIntegration customerIntegration = new CustomerIntegration();
customerIntegration.Integrations = new IntegrationConfigModel[] { config };
customerIntegration.Version = 3;
var httpContextMock = new HttpContextMock() { };
KnownUser._HttpContextProvider = httpContextMock;
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
// Act
var result = KnownUser.ValidateRequestByIntegrationConfig("http://test.com?event1=true", "queueitToken", customerIntegration, "customerid", "secretkey");
// Assert
Assert.Equal("http://test.com?event1=true", mock.cancelRequestCalls[0][0]);
Assert.Equal("cookiedomain:eventid:queuedomain:3:event1action", mock.cancelRequestCalls[0][1]);
Assert.Equal("customerid", mock.cancelRequestCalls[0][2]);
Assert.Equal("secretkey", mock.cancelRequestCalls[0][3]);
Assert.False(result.IsAjaxResult);
}
[Fact]
public void ValidateRequestByIntegrationConfig_AjaxCall_CancelAction()
{
// Arrange
TriggerPart triggerPart = new TriggerPart();
triggerPart.Operator = "Contains";
triggerPart.ValueToCompare = "event1";
triggerPart.UrlPart = "PageUrl";
triggerPart.ValidatorType = "UrlValidator";
triggerPart.IsNegative = false;
triggerPart.IsIgnoreCase = true;
TriggerModel trigger = new TriggerModel();
trigger.LogicalOperator = "And";
trigger.TriggerParts = new TriggerPart[] { triggerPart };
IntegrationConfigModel config = new IntegrationConfigModel();
config.Name = "event1action";
config.EventId = "eventid";
config.CookieDomain = "cookiedomain";
config.Triggers = new TriggerModel[] { trigger };
config.QueueDomain = "queuedomain";
config.ActionType = ActionType.CancelAction;
CustomerIntegration customerIntegration = new CustomerIntegration();
customerIntegration.Integrations = new IntegrationConfigModel[] { config };
customerIntegration.Version = 3;
var httpContextMock = new HttpContextMock()
{
HttpRequest = new MockHttpRequest()
{
Headers = new NameValueCollection() { { "x-queueit-ajaxpageurl", "http%3A%2F%2Furl" } }
}
};
KnownUser._HttpContextProvider = httpContextMock;
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
// Act
var result = KnownUser.ValidateRequestByIntegrationConfig("http://test.com?event1=true", "queueitToken", customerIntegration, "customerid", "secretkey");
// Assert
Assert.Equal(mock.cancelRequestCalls[0][0], "http://url");
Assert.Equal("cookiedomain:eventid:queuedomain:3:event1action", mock.cancelRequestCalls[0][1]);
Assert.Equal("customerid", mock.cancelRequestCalls[0][2]);
Assert.Equal("secretkey", mock.cancelRequestCalls[0][3]);
Assert.True(result.IsAjaxResult);
}
[Fact]
public void ValidateRequestByIntegrationConfig_Debug()
{
// Arrange
string requestIP = "80.35.35.34";
string viaHeader = "1.1 example.com";
string forwardedHeader = "for=192.0.2.60;proto=http;by=203.0.113.43";
string xForwardedForHeader = "129.78.138.66, 129.78.64.103";
string xForwardedHostHeader = "en.wikipedia.org:8080";
string xForwardedProtoHeader = "https";
var mockResponse = new MockHttpResponse();
var httpContextMock = new HttpContextMock()
{
HttpRequest = new MockHttpRequest()
{
Headers = new NameValueCollection() {
{ "Via", viaHeader },
{ "Forwarded", forwardedHeader },
{ "X-Forwarded-For", xForwardedForHeader },
{ "X-Forwarded-Host", xForwardedHostHeader },
{ "X-Forwarded-Proto", xForwardedProtoHeader }
},
UserHostAddress = requestIP,
Url = new Uri("http://test.com/?event1=true&queueittoken=queueittokenvalue"),
},
HttpResponse = mockResponse
};
KnownUser._HttpContextProvider = httpContextMock;
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
TriggerPart triggerPart1 = new TriggerPart();
triggerPart1.Operator = "Contains";
triggerPart1.ValueToCompare = "event1";
triggerPart1.UrlPart = "PageUrl";
triggerPart1.ValidatorType = "UrlValidator";
triggerPart1.IsNegative = false;
triggerPart1.IsIgnoreCase = true;
TriggerModel trigger = new TriggerModel();
trigger.LogicalOperator = "And";
trigger.TriggerParts = new TriggerPart[] { triggerPart1 };
IntegrationConfigModel config = new IntegrationConfigModel();
config.Name = "event1action";
//config.ActionType = "Queue";
config.EventId = "event1";
config.CookieDomain = ".test.com";
config.LayoutName = "Christmas Layout by Queue-it";
config.Culture = "da-DK";
config.ExtendCookieValidity = true;
config.CookieValidityMinute = 20;
config.Triggers = new TriggerModel[] { trigger };
config.QueueDomain = "knownusertest.queue-it.net";
config.RedirectLogic = "AllowTParameter";
config.ForcedTargetUrl = "";
CustomerIntegration customerIntegration = new CustomerIntegration();
customerIntegration.Integrations = new IntegrationConfigModel[] { config };
customerIntegration.Version = 3;
var queueitToken = QueueITTokenGenerator.GenerateToken(
DateTime.UtcNow.AddDays(1), "event1", Guid.NewGuid().ToString(), true, null, "secretKey", out var hash, "debug");
var utcTimeBeforeActionWasPerformed = DateTime.UtcNow.ToString("o");
// Act
RequestValidationResult result = KnownUser.ValidateRequestByIntegrationConfig($"http://test.com?event1=true", queueitToken, customerIntegration, "customerId", "secretKey");
// Assert
var cookieValues = HttpUtility.UrlDecode(mockResponse.CookiesValue["queueitdebug"]["cookieValue"].ToString()).Split('|');
Assert.True(cookieValues.Any(v => v == $"PureUrl=http://test.com?event1=true"));
Assert.True(cookieValues.Any(v => v == $"ConfigVersion=3"));
Assert.True(cookieValues.Any(v => v == $"MatchedConfig=event1action"));
Assert.True(cookieValues.Any(v => v == $"QueueitToken={queueitToken}"));
Assert.True(cookieValues.Any(v => v == $"OriginalUrl=http://test.com/?event1=true&queueittoken=queueittokenvalue"));
Assert.True(cookieValues.Any(v => v == $"TargetUrl=http://test.com?event1=true"));
Assert.True(cookieValues.Any(v => v == $"QueueConfig=EventId:event1&Version:3&QueueDomain:knownusertest.queue-it.net&CookieDomain:.test.com&ExtendCookieValidity:True&CookieValidityMinute:20&LayoutName:Christmas Layout by Queue-it&Culture:da-DK&ActionName:event1action"));
AssertRequestCookieContent(cookieValues,
UserInQueueService.SDK_VERSION, KnownUser.GetRuntime(), utcTimeBeforeActionWasPerformed, requestIP, viaHeader, forwardedHeader, xForwardedForHeader, xForwardedHostHeader, xForwardedProtoHeader);
}
[Fact]
public void ValidateRequestByIntegrationConfig_Debug_WithoutMatch()
{
// Arrange
string requestIP = "80.35.35.34";
string viaHeader = "1.1 example.com";
string forwardedHeader = "for=192.0.2.60;proto=http;by=203.0.113.43";
string xForwardedForHeader = "129.78.138.66, 129.78.64.103";
string xForwardedHostHeader = "en.wikipedia.org:8080";
string xForwardedProtoHeader = "https";
var fakeHttpResponse = new MockHttpResponse();
var httpContextMock = new HttpContextMock()
{
HttpRequest = new MockHttpRequest()
{
Headers = new NameValueCollection() {
{ "Via", viaHeader },
{ "Forwarded", forwardedHeader },
{ "X-Forwarded-For", xForwardedForHeader },
{ "X-Forwarded-Host", xForwardedHostHeader },
{ "X-Forwarded-Proto", xForwardedProtoHeader }
},
UserHostAddress = requestIP,
Url = new Uri("http://test.com/?event1=true&queueittoken=queueittokenvalue")
}
,
HttpResponse = fakeHttpResponse
};
KnownUser._HttpContextProvider = httpContextMock;
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
CustomerIntegration customerIntegration = new CustomerIntegration();
customerIntegration.Integrations = new IntegrationConfigModel[] { };
customerIntegration.Version = 10;
var queueitToken = QueueITTokenGenerator.GenerateToken(
DateTime.UtcNow.AddDays(1), "event1", Guid.NewGuid().ToString(), true, null, "secretKey", out var hash, "debug");
var utcTimeBeforeActionWasPerformed = DateTime.UtcNow.ToString("o");
// Act
RequestValidationResult result = KnownUser
.ValidateRequestByIntegrationConfig("http://test.com?event1=true",
queueitToken, customerIntegration, "customerId", "secretKey");
// Assert
var cookieValues = HttpUtility.UrlDecode(fakeHttpResponse.CookiesValue["queueitdebug"]["cookieValue"].ToString()).Split('|');
Assert.True(cookieValues.Any(v => v == $"PureUrl=http://test.com?event1=true"));
Assert.True(cookieValues.Any(v => v == $"QueueitToken={queueitToken}"));
Assert.True(cookieValues.Any(v => v == $"ConfigVersion=10"));
Assert.True(cookieValues.Any(v => v == $"OriginalUrl=http://test.com/?event1=true&queueittoken=queueittokenvalue"));
Assert.True(cookieValues.Any(v => v == $"MatchedConfig=NULL"));
AssertRequestCookieContent(cookieValues,
UserInQueueService.SDK_VERSION, KnownUser.GetRuntime(), utcTimeBeforeActionWasPerformed, requestIP, viaHeader, forwardedHeader, xForwardedForHeader, xForwardedHostHeader, xForwardedProtoHeader);
}
[Fact]
public void ValidateRequestByIntegrationConfig_Debug_NullConfig()
{
string requestIP = "80.35.35.34";
string viaHeader = "1.1 example.com";
string forwardedHeader = "for=192.0.2.60;proto=http;by=203.0.113.43";
string xForwardedForHeader = "129.78.138.66, 129.78.64.103";
string xForwardedHostHeader = "en.wikipedia.org:8080";
string xForwardedProtoHeader = "https";
var mockResponse = new MockHttpResponse();
KnownUser._HttpContextProvider = new HttpContextMock()
{
HttpRequest = new MockHttpRequest()
{
Headers = new NameValueCollection() {
{ "Via", viaHeader },
{ "Forwarded", forwardedHeader },
{ "X-Forwarded-For", xForwardedForHeader },
{ "X-Forwarded-Host", xForwardedHostHeader },
{ "X-Forwarded-Proto", xForwardedProtoHeader }
},
UserHostAddress = requestIP,
Url = new Uri("http://test.com/?event1=true&queueittoken=queueittokenvalue"),
},
HttpResponse = mockResponse
};
KnownUser._UserInQueueService = new UserInQueueServiceMock();
var queueitToken = QueueITTokenGenerator.GenerateToken(
DateTime.UtcNow.AddDays(1), "event1", Guid.NewGuid().ToString(), true, null, "secretKey", out var _, "debug");
var utcTimeBeforeActionWasPerformed = DateTime.UtcNow.ToString("o");
Assert.Throws<ArgumentException>(() =>
KnownUser.ValidateRequestByIntegrationConfig(
"http://test.com?event1=true", queueitToken, null, "customerId", "secretKey")
);
// Assert
var cookieValues = HttpUtility.UrlDecode(mockResponse.CookiesValue["queueitdebug"]["cookieValue"].ToString()).Split('|');
Assert.True(cookieValues.Any(v => v == $"SdkVersion={UserInQueueService.SDK_VERSION}"));
Assert.True(cookieValues.Any(v => v == $"PureUrl=http://test.com?event1=true"));
Assert.True(cookieValues.Any(v => v == $"ConfigVersion=NULL"));
Assert.True(cookieValues.Any(v => v == $"QueueitToken={queueitToken}"));
Assert.True(cookieValues.Any(v => v == $"OriginalUrl=http://test.com/?event1=true&queueittoken=queueittokenvalue"));
Assert.True(cookieValues.Any(v => v == $"Exception=customerIntegrationInfo can not be null."));
AssertRequestCookieContent(cookieValues,
UserInQueueService.SDK_VERSION, KnownUser.GetRuntime(), utcTimeBeforeActionWasPerformed, requestIP, viaHeader, forwardedHeader, xForwardedForHeader, xForwardedHostHeader, xForwardedProtoHeader);
}
[Fact]
public void ValidateRequestByIntegrationConfig_Debug_Missing_CustomerId()
{
var mockResponse = new MockHttpResponse();
KnownUser._HttpContextProvider = new HttpContextMock() { HttpResponse = mockResponse };
CustomerIntegration customerIntegration = new CustomerIntegration();
var expiredDebugToken = QueueITTokenGenerator.GenerateToken(
DateTime.UtcNow, "event1", Guid.NewGuid().ToString(), true, null, "secretKey", out var _, "debug");
var result = KnownUser.ValidateRequestByIntegrationConfig("http://test.com?event1=true", expiredDebugToken, customerIntegration, null, "secretKey");
Assert.Equal("https://api2.queue-it.net/diagnostics/connector/error/?code=setup", result.RedirectUrl);
Assert.Empty(mockResponse.CookiesValue);
}
[Fact]
public void ValidateRequestByIntegrationConfig_Debug_Missing_Secretkey()
{
var mockResponse = new MockHttpResponse();
KnownUser._HttpContextProvider = new HttpContextMock() { HttpResponse = mockResponse };
CustomerIntegration customerIntegration = new CustomerIntegration();
var expiredDebugToken = QueueITTokenGenerator.GenerateToken(
DateTime.UtcNow, "event1", Guid.NewGuid().ToString(), true, null, "secretKey", out var _, "debug");
var result = KnownUser.ValidateRequestByIntegrationConfig("http://test.com?event1=true", expiredDebugToken, customerIntegration, "customerid", null);
Assert.Equal("https://api2.queue-it.net/diagnostics/connector/error/?code=setup", result.RedirectUrl);
Assert.Empty(mockResponse.CookiesValue);
}
[Fact]
public void ValidateRequestByIntegrationConfig_Debug_ExpiredToken()
{
var mockResponse = new MockHttpResponse();
KnownUser._HttpContextProvider = new HttpContextMock() { HttpResponse = mockResponse };
CustomerIntegration customerIntegration = new CustomerIntegration();
var expiredDebugToken = QueueITTokenGenerator.GenerateToken(
DateTime.UtcNow, "event1", Guid.NewGuid().ToString(), true, null, "secretKey", out var _, "debug");
var result = KnownUser.ValidateRequestByIntegrationConfig("http://test.com?event1=true", expiredDebugToken, customerIntegration, "customerId", "secretKey");
Assert.Equal("https://customerId.api2.queue-it.net/customerId/diagnostics/connector/error/?code=timestamp", result.RedirectUrl);
Assert.Empty(mockResponse.CookiesValue);
}
[Fact]
public void ValidateRequestByIntegrationConfig_Debug_ModifiedToken()
{
var mockResponse = new MockHttpResponse();
KnownUser._HttpContextProvider = new HttpContextMock() { HttpResponse = mockResponse };
CustomerIntegration customerIntegration = new CustomerIntegration();
var invalidDebugToken = QueueITTokenGenerator.GenerateToken(
DateTime.UtcNow, "event1", Guid.NewGuid().ToString(), true, null, "secretKey", out var _, "debug")
+ "invalid-hash";
var result = KnownUser.ValidateRequestByIntegrationConfig("http://test.com?event1=true", invalidDebugToken, customerIntegration, "customerId", "secretKey");
Assert.Equal("https://customerId.api2.queue-it.net/customerId/diagnostics/connector/error/?code=hash", result.RedirectUrl);
Assert.Empty(mockResponse.CookiesValue);
}
[Fact]
public void ResolveQueueRequestByLocalConfig_Debug()
{
// Arrange
var fakeHttpResponse = new MockHttpResponse();
string requestIP = "80.35.35.34";
string viaHeader = "1.1 example.com";
string forwardedHeader = "for=192.0.2.60;proto=http;by=203.0.113.43";
string xForwardedForHeader = "129.78.138.66, 129.78.64.103";
string xForwardedHostHeader = "en.wikipedia.org:8080";
string xForwardedProtoHeader = "https";
var httpContextMock = new HttpContextMock()
{
HttpRequest = new MockHttpRequest()
{
Headers = new NameValueCollection() {
{ "Via", viaHeader },
{ "Forwarded", forwardedHeader },
{ "X-Forwarded-For", xForwardedForHeader },
{ "X-Forwarded-Host", xForwardedHostHeader },
{ "X-Forwarded-Proto", xForwardedProtoHeader }
},
UserHostAddress = requestIP,
Url = new Uri("http://test.com/?event1=true&queueittoken=queueittokenvalue")
}
,
HttpResponse = fakeHttpResponse
};
KnownUser._HttpContextProvider = httpContextMock;
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
QueueEventConfig eventConfig = new QueueEventConfig();
eventConfig.CookieDomain = "cookieDomain";
eventConfig.LayoutName = "layoutName";
eventConfig.Culture = "culture";
eventConfig.EventId = "eventId";
eventConfig.QueueDomain = "queueDomain";
eventConfig.ExtendCookieValidity = true;
eventConfig.CookieValidityMinute = 10;
eventConfig.Version = 12;
eventConfig.ActionName = "QueueAction";
var queueitToken = QueueITTokenGenerator.GenerateToken(
DateTime.UtcNow.AddDays(1), "event1", Guid.NewGuid().ToString(), true, null, "secretKey", out var hash, "debug");
var utcTimeBeforeActionWasPerformed = DateTime.UtcNow.ToString("o");
// Act
RequestValidationResult result = KnownUser.ResolveQueueRequestByLocalConfig("http://test.com?event1=true", queueitToken, eventConfig, "customerId", "secretKey");
// Assert
var cookieValues = HttpUtility.UrlDecode(fakeHttpResponse.CookiesValue["queueitdebug"]["cookieValue"].ToString()).Split('|');
Assert.True(cookieValues.Any(v => v == $"QueueitToken={queueitToken}"));
Assert.True(cookieValues.Any(v => v == $"OriginalUrl=http://test.com/?event1=true&queueittoken=queueittokenvalue"));
Assert.True(cookieValues.Any(v => v == $"TargetUrl=http://test.com?event1=true"));
Assert.True(cookieValues.Any(v => v == $"QueueConfig=EventId:eventId&Version:12&QueueDomain:queueDomain&CookieDomain:cookieDomain&ExtendCookieValidity:True&CookieValidityMinute:10&LayoutName:layoutName&Culture:culture&ActionName:{eventConfig.ActionName}"));
AssertRequestCookieContent(cookieValues,
UserInQueueService.SDK_VERSION, KnownUser.GetRuntime(), utcTimeBeforeActionWasPerformed, requestIP, viaHeader, forwardedHeader, xForwardedForHeader, xForwardedHostHeader, xForwardedProtoHeader);
}
[Fact]
public void ResolveQueueRequestByLocalConfig_Debug_NullConfig()
{
// Arrange
var fakeHttpResponse = new MockHttpResponse();
string requestIP = "80.35.35.34";
string viaHeader = "1.1 example.com";
string forwardedHeader = "for=192.0.2.60;proto=http;by=203.0.113.43";
string xForwardedForHeader = "129.78.138.66, 129.78.64.103";
string xForwardedHostHeader = "en.wikipedia.org:8080";
string xForwardedProtoHeader = "https";
KnownUser._HttpContextProvider = new HttpContextMock()
{
HttpRequest = new MockHttpRequest()
{
Headers = new NameValueCollection() {
{ "Via", viaHeader },
{ "Forwarded", forwardedHeader },
{ "X-Forwarded-For", xForwardedForHeader },
{ "X-Forwarded-Host", xForwardedHostHeader },
{ "X-Forwarded-Proto", xForwardedProtoHeader }
},
UserHostAddress = requestIP,
Url = new Uri("http://test.com/?event1=true&queueittoken=queueittokenvalue")
}
,
HttpResponse = fakeHttpResponse
};
KnownUser._UserInQueueService = new UserInQueueServiceMock();
var queueitToken = QueueITTokenGenerator.GenerateToken(
DateTime.UtcNow.AddDays(1), "event1", Guid.NewGuid().ToString(), true, null, "secretKey", out var hash, "debug");
var utcTimeBeforeActionWasPerformed = DateTime.UtcNow.ToString("o");
Assert.Throws<ArgumentException>(() =>
KnownUser.ResolveQueueRequestByLocalConfig(
"http://test.com?event1=true", queueitToken, null, "customerId", "secretKey")
);
// Assert
var cookieValues = HttpUtility.UrlDecode(fakeHttpResponse.CookiesValue["queueitdebug"]["cookieValue"].ToString()).Split('|');
Assert.True(cookieValues.Any(v => v == $"QueueitToken={queueitToken}"));
Assert.True(cookieValues.Any(v => v == $"OriginalUrl=http://test.com/?event1=true&queueittoken=queueittokenvalue"));
Assert.True(cookieValues.Any(v => v == $"QueueConfig=NULL"));
Assert.True(cookieValues.Any(v => v == $"Exception=eventConfig can not be null."));
AssertRequestCookieContent(cookieValues,
UserInQueueService.SDK_VERSION, KnownUser.GetRuntime(), utcTimeBeforeActionWasPerformed, requestIP, viaHeader, forwardedHeader, xForwardedForHeader, xForwardedHostHeader, xForwardedProtoHeader);
}
[Fact]
public void ResolveQueueRequestByLocalConfig_Debug_Missing_CustomerId()
{
var mockResponse = new MockHttpResponse();
KnownUser._HttpContextProvider = new HttpContextMock() { HttpResponse = mockResponse };
QueueEventConfig eventConfig = new QueueEventConfig();
var expiredDebugToken = QueueITTokenGenerator.GenerateToken(
DateTime.UtcNow, "event1", Guid.NewGuid().ToString(), true, null, "secretKey", out var _, "debug");
var result = KnownUser.ResolveQueueRequestByLocalConfig("http://test.com?event1=true", expiredDebugToken, eventConfig, null, "secretKey");
Assert.Equal("https://api2.queue-it.net/diagnostics/connector/error/?code=setup", result.RedirectUrl);
Assert.Empty(mockResponse.CookiesValue);
}
[Fact]
public void ResolveQueueRequestByLocalConfig_Debug_Missing_SecretKey()
{
var mockResponse = new MockHttpResponse();
KnownUser._HttpContextProvider = new HttpContextMock() { HttpResponse = mockResponse };
QueueEventConfig eventConfig = new QueueEventConfig();
var expiredDebugToken = QueueITTokenGenerator.GenerateToken(
DateTime.UtcNow, "event1", Guid.NewGuid().ToString(), true, null, "secretKey", out var _, "debug");
var result = KnownUser.ResolveQueueRequestByLocalConfig("http://test.com?event1=true", expiredDebugToken, eventConfig, "customerid", null);
Assert.Equal("https://api2.queue-it.net/diagnostics/connector/error/?code=setup", result.RedirectUrl);
Assert.Empty(mockResponse.CookiesValue);
}
[Fact]
public void ResolveQueueRequestByLocalConfig_Debug_ExpiredToken()
{
var mockResponse = new MockHttpResponse();
KnownUser._HttpContextProvider = new HttpContextMock() { HttpResponse = mockResponse };
QueueEventConfig eventConfig = new QueueEventConfig();
var expiredDebugToken = QueueITTokenGenerator.GenerateToken(
DateTime.UtcNow, "event1", Guid.NewGuid().ToString(), true, null, "secretKey", out var _, "debug");
var result = KnownUser.ResolveQueueRequestByLocalConfig("http://test.com?event1=true", expiredDebugToken, eventConfig, "customerId", "secretKey");
Assert.Equal("https://customerId.api2.queue-it.net/customerId/diagnostics/connector/error/?code=timestamp", result.RedirectUrl);
Assert.Empty(mockResponse.CookiesValue);
}
[Fact]
public void ResolveQueueRequestByLocalConfig_Debug_ModifiedToken()
{
var mockResponse = new MockHttpResponse();
KnownUser._HttpContextProvider = new HttpContextMock() { HttpResponse = mockResponse };
QueueEventConfig eventConfig = new QueueEventConfig();
var invalidDebugToken = QueueITTokenGenerator.GenerateToken(
DateTime.UtcNow, "event1", Guid.NewGuid().ToString(), true, null, "secretKey", out var _, "debug")
+ "invalid-hash";
var result = KnownUser.ResolveQueueRequestByLocalConfig("http://test.com?event1=true", invalidDebugToken, eventConfig, "customerId", "secretKey");
Assert.Equal("https://customerId.api2.queue-it.net/customerId/diagnostics/connector/error/?code=hash", result.RedirectUrl);
Assert.Empty(mockResponse.CookiesValue);
}
[Fact]
public void CancelRequestByLocalConfig_Debug()
{
// Arrange
var fakeHttpResponse = new MockHttpResponse();
string requestIP = "80.35.35.34";
string viaHeader = "1.1 example.com";
string forwardedHeader = "for=192.0.2.60;proto=http;by=203.0.113.43";
string xForwardedForHeader = "129.78.138.66, 129.78.64.103";
string xForwardedHostHeader = "en.wikipedia.org:8080";
string xForwardedProtoHeader = "https";
var httpContextMock = new HttpContextMock()
{
HttpRequest = new MockHttpRequest()
{
Headers = new NameValueCollection() {
{ "Via", viaHeader },
{ "Forwarded", forwardedHeader },
{ "X-Forwarded-For", xForwardedForHeader },
{ "X-Forwarded-Host", xForwardedHostHeader },
{ "X-Forwarded-Proto", xForwardedProtoHeader }
},
UserHostAddress = requestIP,
Url = new Uri("http://test.com/?event1=true&queueittoken=queueittokenvalue")
}
,
HttpResponse = fakeHttpResponse
};
KnownUser._HttpContextProvider = httpContextMock;
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
CancelEventConfig eventConfig = new CancelEventConfig();
eventConfig.CookieDomain = "cookieDomain";
eventConfig.EventId = "eventId";
eventConfig.QueueDomain = "queueDomain";
eventConfig.Version = 12;
eventConfig.ActionName = "CancelAction";
var queueitToken = QueueITTokenGenerator.GenerateToken(
DateTime.UtcNow.AddDays(1), "event1", Guid.NewGuid().ToString(), true, null, "secretKey", out var hash, "debug");
var utcTimeBeforeActionWasPerformed = DateTime.UtcNow.ToString("o");
// Act
RequestValidationResult result = KnownUser.CancelRequestByLocalConfig("http://test.com?event1=true", queueitToken, eventConfig, "customerId", "secretKey");
// Assert
var cookieValues = HttpUtility.UrlDecode(fakeHttpResponse.CookiesValue["queueitdebug"]["cookieValue"].ToString()).Split('|');
Assert.True(cookieValues.Any(v => v == $"QueueitToken={queueitToken}"));
Assert.True(cookieValues.Any(v => v == $"OriginalUrl=http://test.com/?event1=true&queueittoken=queueittokenvalue"));
Assert.True(cookieValues.Any(v => v == $"TargetUrl=http://test.com?event1=true"));
Assert.True(cookieValues.Any(v => v == $"CancelConfig=EventId:eventId&Version:12&QueueDomain:queueDomain&CookieDomain:cookieDomain&ActionName:{eventConfig.ActionName}"));
AssertRequestCookieContent(cookieValues,
UserInQueueService.SDK_VERSION, KnownUser.GetRuntime(), utcTimeBeforeActionWasPerformed, requestIP, viaHeader, forwardedHeader, xForwardedForHeader, xForwardedHostHeader, xForwardedProtoHeader);
}
[Fact]
public void CancelRequestByLocalConfig_Debug_NullConfig()
{
// Arrange
var fakeHttpResponse = new MockHttpResponse();
string requestIP = "80.35.35.34";
string viaHeader = "1.1 example.com";
string forwardedHeader = "for=192.0.2.60;proto=http;by=203.0.113.43";
string xForwardedForHeader = "129.78.138.66, 129.78.64.103";
string xForwardedHostHeader = "en.wikipedia.org:8080";
string xForwardedProtoHeader = "https";
KnownUser._HttpContextProvider = new HttpContextMock()
{
HttpRequest = new MockHttpRequest()
{
Headers = new NameValueCollection() {
{ "Via", viaHeader },
{ "Forwarded", forwardedHeader },
{ "X-Forwarded-For", xForwardedForHeader },
{ "X-Forwarded-Host", xForwardedHostHeader },
{ "X-Forwarded-Proto", xForwardedProtoHeader }
},
UserHostAddress = requestIP,
Url = new Uri("http://test.com/?event1=true&queueittoken=queueittokenvalue")
}
,
HttpResponse = fakeHttpResponse
};
KnownUser._UserInQueueService = new UserInQueueServiceMock();
var queueitToken = QueueITTokenGenerator.GenerateToken(
DateTime.UtcNow.AddDays(1), "event1", Guid.NewGuid().ToString(), true, null, "secretKey", out var _, "debug");
var utcTimeBeforeActionWasPerformed = DateTime.UtcNow.ToString("o");
Assert.Throws<ArgumentException>(() =>
KnownUser.CancelRequestByLocalConfig("http://test.com?event1=true", queueitToken, null, "customerId", "secretKey")
);
// Assert
var cookieValues = HttpUtility.UrlDecode(fakeHttpResponse.CookiesValue["queueitdebug"]["cookieValue"].ToString()).Split('|');
Assert.True(cookieValues.Any(v => v == $"QueueitToken={queueitToken}"));
Assert.True(cookieValues.Any(v => v == $"OriginalUrl=http://test.com/?event1=true&queueittoken=queueittokenvalue"));
Assert.True(cookieValues.Any(v => v == $"CancelConfig=NULL"));
Assert.True(cookieValues.Any(v => v == $"Exception=cancelEventConfig can not be null."));
AssertRequestCookieContent(cookieValues,
UserInQueueService.SDK_VERSION, KnownUser.GetRuntime(), utcTimeBeforeActionWasPerformed, requestIP, viaHeader, forwardedHeader, xForwardedForHeader, xForwardedHostHeader, xForwardedProtoHeader);
}
[Fact]
public void CancelRequestByLocalConfig_Debug_Missing_CustomerId()
{
var mockResponse = new MockHttpResponse();
KnownUser._HttpContextProvider = new HttpContextMock() { HttpResponse = mockResponse };
CancelEventConfig eventConfig = new CancelEventConfig();
var token = QueueITTokenGenerator.GenerateToken(
DateTime.UtcNow, "event1", Guid.NewGuid().ToString(), true, null, "secretKey", out var _, "debug");
var result = KnownUser.CancelRequestByLocalConfig("http://test.com?event1=true", token, eventConfig, null, "secretkey");
Assert.Equal("https://api2.queue-it.net/diagnostics/connector/error/?code=setup", result.RedirectUrl);
Assert.Empty(mockResponse.CookiesValue);
}
[Fact]
public void CancelRequestByLocalConfig_Debug_Missing_SecretKey()
{
var mockResponse = new MockHttpResponse();
KnownUser._HttpContextProvider = new HttpContextMock() { HttpResponse = mockResponse };
CancelEventConfig eventConfig = new CancelEventConfig();
var token = QueueITTokenGenerator.GenerateToken(
DateTime.UtcNow, "event1", Guid.NewGuid().ToString(), true, null, "secretKey", out var _, "debug");
var result = KnownUser.CancelRequestByLocalConfig("http://test.com?event1=true", token, eventConfig, "customerid", null);
Assert.Equal("https://api2.queue-it.net/diagnostics/connector/error/?code=setup", result.RedirectUrl);
Assert.Empty(mockResponse.CookiesValue);
}
[Fact]
public void CancelRequestByLocalConfig_Debug_ExpiredToken()
{
var mockResponse = new MockHttpResponse();
KnownUser._HttpContextProvider = new HttpContextMock() { HttpResponse = mockResponse };
CancelEventConfig eventConfig = new CancelEventConfig();
var expiredDebugToken = QueueITTokenGenerator.GenerateToken(
DateTime.UtcNow, "event1", Guid.NewGuid().ToString(), true, null, "secretKey", out var _, "debug");
var result = KnownUser.CancelRequestByLocalConfig("http://test.com?event1=true", expiredDebugToken, eventConfig, "customerId", "secretKey");
Assert.Equal("https://customerId.api2.queue-it.net/customerId/diagnostics/connector/error/?code=timestamp", result.RedirectUrl);
Assert.Empty(mockResponse.CookiesValue);
}
[Fact]
public void CancelRequestByLocalConfig_Debug_ModifiedToken()
{
var mockResponse = new MockHttpResponse();
KnownUser._HttpContextProvider = new HttpContextMock() { HttpResponse = mockResponse };
CancelEventConfig eventConfig = new CancelEventConfig();
var invalidDebugToken = QueueITTokenGenerator.GenerateToken(
DateTime.UtcNow, "event1", Guid.NewGuid().ToString(), true, null, "secretKey", out var _, "debug")
+ "invalid-hash";
var result = KnownUser.CancelRequestByLocalConfig("http://test.com?event1=true", invalidDebugToken, eventConfig, "customerId", "secretKey");
Assert.Equal("https://customerId.api2.queue-it.net/customerId/diagnostics/connector/error/?code=hash", result.RedirectUrl);
Assert.Empty(mockResponse.CookiesValue);
}
[Fact]
public void ValidateRequestByIntegrationConfig__Exception_NoDebugToken_NoDebugCookie_test()
{
// Arrange
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
TriggerPart triggerPart1 = new TriggerPart();
triggerPart1.Operator = "Contains";
triggerPart1.ValueToCompare = "event1";
triggerPart1.UrlPart = "PageUrl";
triggerPart1.ValidatorType = "UrlValidator";
triggerPart1.IsNegative = false;
triggerPart1.IsIgnoreCase = true;
TriggerPart triggerPart2 = new TriggerPart();
triggerPart2.Operator = "Contains";
triggerPart2.ValueToCompare = "googlebot";
triggerPart2.ValidatorType = "UserAgentValidator";
triggerPart2.IsNegative = false;
triggerPart2.IsIgnoreCase = false;
TriggerModel trigger = new TriggerModel();
trigger.LogicalOperator = "And";
trigger.TriggerParts = new TriggerPart[] { triggerPart1, triggerPart2 };
IntegrationConfigModel config = new IntegrationConfigModel();
config.Name = "event1action";
//config.ActionType = "Queue";
config.EventId = "event1";
config.CookieDomain = ".test.com";
config.LayoutName = "Christmas Layout by Queue-it";
config.Culture = "da-DK";
config.ExtendCookieValidity = true;
config.CookieValidityMinute = 20;
config.Triggers = new TriggerModel[] { trigger };
config.QueueDomain = "knownusertest.queue-it.net";
config.RedirectLogic = "AllowTParameter";
config.ForcedTargetUrl = "";
config.ActionType = ActionType.QueueAction;
CustomerIntegration customerIntegration = new CustomerIntegration();
customerIntegration.Integrations = new IntegrationConfigModel[] { config };
customerIntegration.Version = 3;
var mockResponse = new MockHttpResponse();
var httpContextMock = new HttpContextMock()
{
HttpRequest =
new MockHttpRequest()
{
UserAgent = "googlebot",
Headers = new NameValueCollection()
},
HttpResponse = mockResponse
};
KnownUser._HttpContextProvider = httpContextMock;
mock.validateQueueRequestRaiseException = true;
// Act
try
{
var result = KnownUser.ValidateRequestByIntegrationConfig("http://test.com?event1=true", "queueitToken", customerIntegration, "customerId", "secretKey");
}
catch (Exception e)
{
Assert.True(e.Message == "Exception");
}
// Assert
Assert.True(mock.validateQueueRequestCalls.Count > 0);
Assert.True(mockResponse.CookiesValue.Count == 0);
}
[Fact]
public void ResolveRequestByLocalEventConfig__Exception_NoDebugToken_NoDebugCookie_Test()
{
// Arrange
var mockResponse = new MockHttpResponse();
var httpContextMock = new HttpContextMock() { HttpResponse = mockResponse };
KnownUser._HttpContextProvider = httpContextMock;
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
QueueEventConfig eventConfig = new QueueEventConfig();
eventConfig.CookieDomain = "cookieDomain";
eventConfig.LayoutName = "layoutName";
eventConfig.Culture = "culture";
eventConfig.EventId = "eventId";
eventConfig.QueueDomain = "queueDomain";
eventConfig.ExtendCookieValidity = true;
eventConfig.CookieValidityMinute = 10;
eventConfig.Version = 12;
eventConfig.ActionName = "QueueAction";
mock.validateQueueRequestRaiseException = true;
// Act
try
{
var result = KnownUser.ResolveQueueRequestByLocalConfig("targetUrl", "queueitToken", eventConfig, "customerId", "secretKey");
}
catch (Exception e)
{
Assert.True(e.Message == "Exception");
}
// Assert
Assert.True(mock.validateQueueRequestCalls.Count > 0);
Assert.True(mockResponse.CookiesValue.Count == 0);
}
[Fact]
public void CancelRequestByLocalConfig_Exception_NoDebugToken_NoDebugCookie_Test()
{
// Arrange
var mockResponse = new MockHttpResponse();
var httpContextMock = new HttpContextMock() { HttpResponse = mockResponse };
KnownUser._HttpContextProvider = httpContextMock;
UserInQueueServiceMock mock = new UserInQueueServiceMock();
KnownUser._UserInQueueService = (mock);
var cancelEventConfig = new CancelEventConfig() { CookieDomain = "cookiedomain", EventId = "eventid", QueueDomain = "queuedomain", Version = 1, ActionName = "CancelAction" };
// Act
mock.validateCancelRequestRaiseException = true;
try
{
var result = KnownUser.CancelRequestByLocalConfig("url", "queueitToken", cancelEventConfig, "customerid", "secretekey");
}
catch (Exception e)
{
Assert.True(e.Message == "Exception");
}
// Assert
Assert.True(mock.cancelRequestCalls.Count > 0);
Assert.True(mockResponse.CookiesValue.Count == 0);
KnownUser._HttpContextProvider = null;
}
}
public class RequestValidationResultTest
{
[Fact]
public void AjaxRedirectUrl_Test()
{
var testObject = new RequestValidationResult("Queue", isAjaxResult: true, redirectUrl: "http://url/path/?var=hello world");
Assert.Equal("http%3A%2F%2Furl%2Fpath%2F%3Fvar%3Dhello%20world", testObject.AjaxRedirectUrl, ignoreCase: true);
}
}
}
| 46.566437 | 283 | 0.604361 | [
"MIT"
] | queueit/KnownUser.V3.ASPNETCORE | QueueIT.KnownUser.V3.AspNetCore.Tests/KnownUserTest.cs | 87,966 | C# |
using System;
using System.IO;
using System.Linq;
using System.Text;
using UnityEngine;
using UnitySentiment;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
public class SentimentDataTraining : MonoBehaviour
{
public string PathToPositiveDataTrainingFolder;
public string PathToNegativeDataTrainingFolder;
public string PathStopWordsDataTrainingFile;
public string PathContractionWordsDataTrainingFile;
public string PathToSaveTrainedData;
public string NameOfTrainedData;
public bool WriteWeightedFile = false;
public SentimentWeightCommonWords sentimentWeightCommonWords;
private string[] stopWords;
private string[] contractionWords;
private FileInfo currentDataTraining;
private List<string> Words = new List<string>();
private List<int> PositiveTimes = new List<int>();
private List<int> NegativeTimes = new List<int>();
private int totalReview;
private readonly object SyncObject = new object();
void Start()
{
Application.runInBackground = true;
Thread trainingThread = new Thread(StartTraining);
trainingThread.Start();
}
private void StartTraining()
{
lock(SyncObject)
{
Debug.Log("Training Started, please wait!");
stopWords = OpenFile(PathStopWordsDataTrainingFile);
contractionWords = OpenFile(PathContractionWordsDataTrainingFile);
ProcessDataTraining();
Debug.Log("Training Finished");
if (WriteWeightedFile)
{
sentimentWeightCommonWords.SaveTrainedData();
}
}
}
private void ProcessDataTraining()
{
BuildFileOfData(PathToPositiveDataTrainingFolder,true);
BuildFileOfData(PathToNegativeDataTrainingFolder,false);
SaveTheTrainedData(PathToSaveTrainedData + NameOfTrainedData);
}
private void BuildFileOfData(string path, bool isPositive)
{
FileInfo[] filesInPath = GetFilesInDirectory(path);
totalReview += filesInPath.Length;
for (int i = 0; i < filesInPath.Length; i++)
{
string TextOfFile = GetTextFile(filesInPath[i].FullName);
Words.AddRange( SplitsTheParagraphInWords(TextOfFile, isPositive) );
}
}
private void SaveTheTrainedData(string path)
{
try
{
string createText = System.String.Empty;
for (int i = 0; i < Words.Count; i++)
{
// Weighting Logic
// Optimize at will
float positiveWeight = (float)PositiveTimes[i] / (float)( PositiveTimes[i] + NegativeTimes[i] );
float negativeWeight = (float)NegativeTimes[i] / (float)( PositiveTimes[i] + NegativeTimes[i] );
float value = ( positiveWeight > negativeWeight ) ? positiveWeight : negativeWeight;
createText += Words[i] + ":" + value.ToString() + ";";
}
File.WriteAllText(path, createText);
}
catch
{
Debug.Log("Error WritingFile \"SaveTheTrainedData\" Method");
}
}
private List<string> SplitsTheParagraphInWords(string text, bool isPositive)
{
List<string> WordsList = new List<string>();
Stemmer stemmer = new Stemmer();
text = text.Trim().ToLower();
if (text[text.Length - 1 ] != '.') text += ".";
text = text.Replace(',', ' ');
text = text.Replace(';', ' ');
text = text.Replace(':', ' ');
text = text.Replace('\"', ' ');
text = text.Replace('\'', ' ');
text = text.Replace('!', ' ');
text = text.Replace('?', ' ');
text = text.Replace('(', ' ');
text = text.Replace(')', ' ');
text = text.Replace(']', ' ');
text = text.Replace('[', ' ');
text = text.Replace('<', ' ');
text = text.Replace('>', ' ');
text = text.Replace('+', ' ');
text = text.Replace('*', ' ');
text = text.Replace('%', ' ');
text = text.Replace('&', ' ');
text = text.Replace('$', ' ');
text = text.Replace('=', ' ');
text = text.Replace('^', ' ');
text = text.Replace('-', ' ');
text = text.Replace('/', ' ');
text = text.Replace('\\', ' ');
text = text.Replace('\'', ' ');
text = text.Replace('@', ' ');
text = text.Replace('_', ' ');
string[] Sentences = text.Split('.');
for (int i = 0; i < Sentences.Length; i++)
{
if (!string.IsNullOrEmpty(Sentences[i]))
{
string[] Words = Sentences[i].Trim().Split(' ');
for (int j = 0; j < Words.Length; j++)
{
if ( !IsWordContractionOrStop(Words[j]) && !string.IsNullOrEmpty(Words[j]) && Words[j].Length > 3 && Words[j].Length < 13)
{
Words[j] = StemTheWord(Words[j], stemmer);
if (! IsStemmedWordPartOfList(Words[j], isPositive) )
{
if ( !WordsList.Contains(Words[j]) )
{
if (Words[j].Length > 2)
{
WordsList.Add(Words[j]);
if (isPositive)
{
PositiveTimes.Add(1);
NegativeTimes.Add(0);
}
else
{
PositiveTimes.Add(0);
NegativeTimes.Add(1);
}
}
}
else
{
try
{
int indexOfWord = WordsList.IndexOf(Words[j]);
if (isPositive)
{
PositiveTimes[PositiveTimes.Count - WordsList.Count + indexOfWord] ++;
}
else
{
NegativeTimes[NegativeTimes.Count - WordsList.Count + indexOfWord] ++;
}
}
catch
{
Debug.Log("Error Index \"SplitsTheParagraphInWords\" Method");
}
}
}
}
}
}
}
return WordsList;
}
private bool IsWordContractionOrStop(string Word)
{
if (stopWords.Contains(Word) || contractionWords.Contains(Word) ) return true;
return false;
}
private bool IsStemmedWordPartOfList(string stemmedWord, bool isPositive)
{
if (Words.Contains(stemmedWord))
{
int indexOfWord = Words.IndexOf(stemmedWord);
try
{
if (isPositive)
{
PositiveTimes[indexOfWord] ++;
}
else
{
NegativeTimes[indexOfWord] ++;
}
return true;
}
catch
{
Debug.Log("Error Index \"IsStemmedWordPartOfList\" Method");
}
}
return false;
}
private string StemTheWord(string word, Stemmer stemmer)
{
stemmer.SetCharArray(word.ToCharArray(), word.Length);
stemmer.stem();
return stemmer.Tostring();
}
private FileInfo[] GetFilesInDirectory(string path)
{
DirectoryInfo dir = new DirectoryInfo(path);
return dir.GetFiles();
}
private string GetTextFile(string filePath)
{
StreamReader theReader = new StreamReader(filePath, Encoding.Default);
try
{
using (theReader)
{
string textOfFile = theReader.ReadToEnd();
theReader.Close();
return textOfFile;
}
}
catch
{
return System.String.Empty;
}
}
private string[] OpenFile(string filePath)
{
StreamReader theReader = new StreamReader(filePath, Encoding.Default);
try
{
using (theReader)
{
string[] textOfFile = theReader.ReadToEnd().Trim().Split(',');
theReader.Close();
return textOfFile;
}
}
catch
{
return new string[0];
}
}
} | 23 | 127 | 0.629994 | [
"MIT"
] | Reality-Hack-2022/TEAM-16 | AI Witness News/Assets/SentimentAnalysis/Scripts/TrainingData/SentimentDataTraining.cs | 6,810 | C# |
using Microsoft.Extensions.DependencyInjection;
using Prism.DryIoc;
using Shiny;
using Shiny.Prism;
using ShinyPrismSample.Delegates;
using static ShinyPrismSample.Delegates.GpsListener;
namespace ShinyPrismSample
{
public class ShinyAppStartup : PrismStartup
{
public ShinyAppStartup(): base(PrismContainerExtension.Current)
{
}
protected override void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IGpsListener, GpsListener>();
services.UseGps<LocationDelegate>();
}
}
}
| 24.458333 | 78 | 0.708688 | [
"MIT"
] | CrossGeeks/ShinyPrismSample | ShinyPrismSample/ShinyAppStartup.cs | 589 | C# |
using Connect.Core;
using Connect.Core.DomainEvents;
using MediatR;
using Microsoft.AspNetCore.SignalR;
using System.Threading;
using System.Threading.Tasks;
namespace Connect.API.Features.Conversations
{
public class ConversationRequestedHandler : INotificationHandler<ConversationRequested>
{
private readonly IHubContext<IntegrationEventsHub> _hubContext;
public ConversationRequestedHandler(IHubContext<IntegrationEventsHub> hubContext)
=> _hubContext = hubContext;
public async Task Handle(ConversationRequested @event, CancellationToken cancellationToken)
{
await _hubContext.Clients.All.SendAsync("events", @event, cancellationToken);
}
}
}
| 31.608696 | 99 | 0.755158 | [
"MIT"
] | QuinntyneBrown/Connect | src/Connect.API/Features/Conversations/ConversationRequestedHandler.cs | 727 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace PaletteCreator.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("PaletteCreator.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap AppMenuClose {
get {
object obj = ResourceManager.GetObject("AppMenuClose", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap AppMenuDelete {
get {
object obj = ResourceManager.GetObject("AppMenuDelete", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap AppMenuPrint {
get {
object obj = ResourceManager.GetObject("AppMenuPrint", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap AppMenuSave {
get {
object obj = ResourceManager.GetObject("AppMenuSave", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap AppMenuSaveAs {
get {
object obj = ResourceManager.GetObject("AppMenuSaveAs", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap AppMenuSendMessage {
get {
object obj = ResourceManager.GetObject("AppMenuSendMessage", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap color {
get {
object obj = ResourceManager.GetObject("color", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap color_1_ {
get {
object obj = ResourceManager.GetObject("color_1_", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Icon similar to (Icon).
/// </summary>
internal static System.Drawing.Icon color_1_1 {
get {
object obj = ResourceManager.GetObject("color_1_1", resourceCulture);
return ((System.Drawing.Icon)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Icon similar to (Icon).
/// </summary>
internal static System.Drawing.Icon color1 {
get {
object obj = ResourceManager.GetObject("color1", resourceCulture);
return ((System.Drawing.Icon)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Dark_Drive {
get {
object obj = ResourceManager.GetObject("Dark_Drive", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap document_new {
get {
object obj = ResourceManager.GetObject("document_new", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap documentinfo {
get {
object obj = ResourceManager.GetObject("documentinfo", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap environment {
get {
object obj = ResourceManager.GetObject("environment", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap External_Drive_Black {
get {
object obj = ResourceManager.GetObject("External_Drive_Black", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap flag_brazil {
get {
object obj = ResourceManager.GetObject("flag_brazil", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap flag_brazil1 {
get {
object obj = ResourceManager.GetObject("flag_brazil1", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap flag_iceland {
get {
object obj = ResourceManager.GetObject("flag_iceland", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap flag_iceland1 {
get {
object obj = ResourceManager.GetObject("flag_iceland1", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap flag_scotland {
get {
object obj = ResourceManager.GetObject("flag_scotland", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap flag_scotland1 {
get {
object obj = ResourceManager.GetObject("flag_scotland1", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Floppy_Drive {
get {
object obj = ResourceManager.GetObject("Floppy_Drive", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap gnome_mime_application_x_theme {
get {
object obj = ResourceManager.GetObject("gnome_mime_application_x_theme", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Icon similar to (Icon).
/// </summary>
internal static System.Drawing.Icon gnome_mime_application_x_theme1 {
get {
object obj = ResourceManager.GetObject("gnome_mime_application_x_theme1", resourceCulture);
return ((System.Drawing.Icon)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Hard_Disk {
get {
object obj = ResourceManager.GetObject("Hard_Disk", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap icons {
get {
object obj = ResourceManager.GetObject("icons", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Icon similar to (Icon).
/// </summary>
internal static System.Drawing.Icon icons1 {
get {
object obj = ResourceManager.GetObject("icons1", resourceCulture);
return ((System.Drawing.Icon)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap KryptonBSActual {
get {
object obj = ResourceManager.GetObject("KryptonBSActual", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap KryptonCBActual {
get {
object obj = ResourceManager.GetObject("KryptonCBActual", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap KryptonGActual {
get {
object obj = ResourceManager.GetObject("KryptonGActual", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap KryptonHActual {
get {
object obj = ResourceManager.GetObject("KryptonHActual", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap KryptonHGActual {
get {
object obj = ResourceManager.GetObject("KryptonHGActual", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap KryptonLActual {
get {
object obj = ResourceManager.GetObject("KryptonLActual", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap KryptonNav {
get {
object obj = ResourceManager.GetObject("KryptonNav", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap KryptonPActual {
get {
object obj = ResourceManager.GetObject("KryptonPActual", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap KryptonRibbon {
get {
object obj = ResourceManager.GetObject("KryptonRibbon", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap KryptonSCActual {
get {
object obj = ResourceManager.GetObject("KryptonSCActual", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap KryptonT {
get {
object obj = ResourceManager.GetObject("KryptonT", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap KryptonTMS {
get {
object obj = ResourceManager.GetObject("KryptonTMS", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap KryptonTrackBar {
get {
object obj = ResourceManager.GetObject("KryptonTrackBar", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap KTextBox {
get {
object obj = ResourceManager.GetObject("KTextBox", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap light_bulb {
get {
object obj = ResourceManager.GetObject("light_bulb", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Open {
get {
object obj = ResourceManager.GetObject("Open", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap palette {
get {
object obj = ResourceManager.GetObject("palette", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap palette_1_ {
get {
object obj = ResourceManager.GetObject("palette_1_", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Icon similar to (Icon).
/// </summary>
internal static System.Drawing.Icon palette1 {
get {
object obj = ResourceManager.GetObject("palette1", resourceCulture);
return ((System.Drawing.Icon)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap theme {
get {
object obj = ResourceManager.GetObject("theme", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Icon similar to (Icon).
/// </summary>
internal static System.Drawing.Icon theme1 {
get {
object obj = ResourceManager.GetObject("theme1", resourceCulture);
return ((System.Drawing.Icon)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap theme256 {
get {
object obj = ResourceManager.GetObject("theme256", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap TopB {
get {
object obj = ResourceManager.GetObject("TopB", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap TopBS {
get {
object obj = ResourceManager.GetObject("TopBS", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap TopCB {
get {
object obj = ResourceManager.GetObject("TopCB", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap TopDT {
get {
object obj = ResourceManager.GetObject("TopDT", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap TopGrid {
get {
object obj = ResourceManager.GetObject("TopGrid", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap TopGroup {
get {
object obj = ResourceManager.GetObject("TopGroup", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap TopH {
get {
object obj = ResourceManager.GetObject("TopH", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap TopHG {
get {
object obj = ResourceManager.GetObject("TopHG", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap TopInputControls {
get {
object obj = ResourceManager.GetObject("TopInputControls", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap TopNavigate {
get {
object obj = ResourceManager.GetObject("TopNavigate", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap TopPanel {
get {
object obj = ResourceManager.GetObject("TopPanel", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap TopRB {
get {
object obj = ResourceManager.GetObject("TopRB", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap TopRibbon {
get {
object obj = ResourceManager.GetObject("TopRibbon", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap TopSC {
get {
object obj = ResourceManager.GetObject("TopSC", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap TopT {
get {
object obj = ResourceManager.GetObject("TopT", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap TopTMS {
get {
object obj = ResourceManager.GetObject("TopTMS", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap TopTrackBar1 {
get {
object obj = ResourceManager.GetObject("TopTrackBar1", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap ui_label_link {
get {
object obj = ResourceManager.GetObject("ui_label_link", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}
| 37.967302 | 180 | 0.537139 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy-Archive/Krypton-Toolkit-Suite-Extended-NET-5.470 | Source/Krypton Toolkit Suite Extended/Applications/Palette Creator/Properties/Resources.Designer.cs | 27,870 | C# |
#region Header
////////////////////////////////////////////////////////////////////////////////////
//
// File Description: Custom Meta
// ---------------------------------------------------------------------------------
// Date Created : March 30, 2014
// Author : Rob van Oostenrijk
// ---------------------------------------------------------------------------------
// Change History
// Date Modified :
// Changed By :
// Change Description :
//
////////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace TcmCDService.Contracts
{
/// <summary>
/// <see cref="CustomMetaType" /> defines the <see cref="CustomMeta" /> data types
/// </summary>
[DataContract(Namespace = "urn:TcmCDService", Name = "customMetaType")]
public enum CustomMetaType
{
/// <summary>
/// <see cref="T:System.String" /> value
/// </summary>
[EnumMember(Value = "String")]
String = 1,
/// <summary>
/// <see cref="T:System.DateTime" /> value
/// </summary>
[EnumMember(Value = "Date")]
Date = 2,
/// <summary>
/// <see cref="T:System.Float" /> value
/// </summary>
[EnumMember(Value = "Float")]
Float = 3
}
/// <summary>
/// <see cref="CustomMeta" /> allows serialization of <see cref="T:Tridion.ContentDelivery.Meta.CustomMeta" />
/// </summary>
[DataContract(Namespace = "urn:TcmCDService", Name = "customMeta")]
public class CustomMeta
{
/// <summary>
/// Gets or sets the <see cref="CustomMeta" /> name.
/// </summary>
/// <value>
/// The <see cref="CustomMeta" /> name.
/// </value>
[DataMember(Name = "name", EmitDefaultValue = false, Order = 1)]
public String Name { get; set; }
/// <summary>
/// Gets or sets the <see cref="CustomMeta" /> <see cref="CustomMetaType" />
/// </summary>
/// <value>
/// The <see cref="CustomMeta" /> <see cref="CustomMetaType" />
/// </value>
[DataMember(Name = "dataType", EmitDefaultValue = false, Order = 2)]
public CustomMetaType DataType { get; set; }
/// <summary>
/// Gets or sets the <see cref="CustomMeta" /> <see cref="I:System.Collections.Generic.IEnumerable{System.String}" /> values.
/// </summary>
/// <value>
/// The <see cref="CustomMeta" /> <see cref="I:System.Collections.Generic.IEnumerable{System.String}" /> values or null
/// </value>
[DataMember(Name = "stringValues", EmitDefaultValue = false, Order = 3)]
public IEnumerable<String> StringValues { get; set; }
/// <summary>
/// Gets or sets the <see cref="CustomMeta" /> <see cref="I:System.Collections.Generic.IEnumerable{System.DateTime}" /> values.
/// </summary>
/// <value>
/// The <see cref="CustomMeta" /> <see cref="I:System.Collections.Generic.IEnumerable{System.DateTime}" /> values or null
/// </value>
[DataMember(Name = "dateTimeValues", EmitDefaultValue = false, Order = 4)]
public IEnumerable<DateTime> DateTimeValues { get; set; }
/// <summary>
/// Gets or sets the <see cref="CustomMeta" /> <see cref="I:System.Collections.Generic.IEnumerable{System.Single}" /> values.
/// </summary>
/// <value>
/// The <see cref="CustomMeta" /> <see cref="I:System.Collections.Generic.IEnumerable{System.Single}" /> values or null
/// </value>
[DataMember(Name = "floatValues", EmitDefaultValue = false, Order = 5)]
public IEnumerable<float> FloatValues { get; set; }
}
}
| 35.525773 | 129 | 0.579512 | [
"Apache-2.0"
] | TcmExtensions/TcmCDService | TcmCDService.Contracts/CustomMeta.cs | 3,448 | C# |
using KinectX.Data;
using KinectX.IO;
using KinectX.Meta;
using KinectX.Registration;
using Microsoft.Kinect;
using NLog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Discovery;
using System.Threading;
namespace KinectX.Network
{
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]
[ServiceContract]
public class KxServer
{
private static ILogger _logger = LogManager.GetCurrentClassLogger();
private static CancellationTokenSource _cancallationTokenSrc = new CancellationTokenSource();
private ushort[] depthShortBuffer = new ushort[KinectSettings.DEPTH_PIXEL_COUNT];
private byte[] yuvByteBuffer = new byte[KinectSettings.COLOR_PIXEL_COUNT * 2];
private byte[] rgbByteBuffer = new byte[KinectSettings.COLOR_PIXEL_COUNT * 4];
private AutoResetEvent depthFrameReady = new AutoResetEvent(false);
private AutoResetEvent yuvFrameReady = new AutoResetEvent(false);
private AutoResetEvent rgbFrameReady = new AutoResetEvent(false);
private AutoResetEvent jpegFrameReady = new AutoResetEvent(false);
private AutoResetEvent audioFrameReady = new AutoResetEvent(false);
private Queue<byte[]> audioFrameQueue = new Queue<byte[]>();
private string _lastFilePath;
public KxServer()
{
_logger.Info("Constructing server...");
lock (KxBuffer.instance.depthFrameReady)
KxBuffer.instance.depthFrameReady.Add(this.depthFrameReady);
lock (KxBuffer.instance.yuvFrameReady)
KxBuffer.instance.yuvFrameReady.Add(this.yuvFrameReady);
lock (KxBuffer.instance.rgbFrameReady)
KxBuffer.instance.rgbFrameReady.Add(this.rgbFrameReady);
lock (KxBuffer.instance.audioFrameReady)
KxBuffer.instance.audioFrameReady.Add(this.audioFrameReady);
lock (KxBuffer.instance.audioFrameQueues)
KxBuffer.instance.audioFrameQueues.Add(this.audioFrameQueue);
OperationContext.Current.Channel.Closed += Channel_Closed;
}
private void Channel_Closed(object sender, EventArgs e)
{
_logger.Info("Closing channel...");
lock (KxBuffer.instance.depthFrameReady)
KxBuffer.instance.depthFrameReady.Remove(this.depthFrameReady);
lock (KxBuffer.instance.yuvFrameReady)
KxBuffer.instance.yuvFrameReady.Remove(this.yuvFrameReady);
lock (KxBuffer.instance.rgbFrameReady)
KxBuffer.instance.rgbFrameReady.Remove(this.rgbFrameReady);
lock (KxBuffer.instance.audioFrameReady)
KxBuffer.instance.audioFrameReady.Remove(this.audioFrameReady);
lock (KxBuffer.instance.audioFrameQueues)
KxBuffer.instance.audioFrameQueues.Remove(this.audioFrameQueue);
}
[OperationContract]
public long LastColorExposureTimeTicks()
{
return KxBuffer.instance.lastColorExposureTimeTicks;
}
[OperationContract]
public float LastColorGain()
{
return KxBuffer.instance.lastColorGain;
}
[OperationContract]
public bool IsCameraAvailable()
{
_logger.Info("Checking camera availability...");
try
{
var available = KinectSensor.GetDefault().IsAvailable;
return available;
}
catch (Exception e)
{
_logger.Error(e);
}
return false;
}
[OperationContract]
public ushort[] LatestDepthImage()
{
_logger.Info("Getting latest depth image...");
try
{
this.depthFrameReady.WaitOne();
lock (KxBuffer.instance.depthShortBuffer)
Buffer.BlockCopy((Array)KxBuffer.instance.depthShortBuffer, 0, (Array)this.depthShortBuffer, 0, KinectSettings.DEPTH_PIXEL_COUNT * 2);
}
catch (Exception e)
{
_logger.Error(e);
}
return this.depthShortBuffer;
}
[OperationContract]
public int GetArucoMarkerCount()
{
var yu2 = LatestYUVImage();
var colorCv = new CvColor(yu2);
//Find and draw (make sure it can be found)
var markers = Vision.FindAruco(colorCv);
return markers.Count;
}
[OperationContract]
public byte[] FusionCameraPose()
{
//Create a defined registration pattern - in this case a cube
var cube = CoordinateDefinition.Microcube();
var yu2 = LatestYUVImage();
var colorCv = new CvColor(yu2);
//Find and draw (make sure it can be found)
var markers = Vision.FindAruco(colorCv);
if (!markers.Any()) { return PoseFormatter.PoseToBytes(new double[4, 4]); }//zeros
//Calculate pose
var depth = LatestDepthImage();
CameraSpacePoint[] _3dImage = new CameraSpacePoint[KinectSettings.COLOR_PIXEL_COUNT];
KxBuffer.instance.coordinateMapper.MapColorFrameToCameraSpace(depth, _3dImage);
var cvCameraSpace = new CvCameraSpace(_3dImage);
var kxTransform = Vision.GetPoseFromImage(cube, cvCameraSpace, markers);
var pose = kxTransform.FusionCameraPose;
return PoseFormatter.PoseToBytes(pose);
}
[OperationContract]
public byte[] CameraPose()
{
//Create a defined registration pattern - in this case a cube
var cube = CoordinateDefinition.Microcube();
var yu2 = LatestYUVImage();
var colorCv = new CvColor(yu2);
//Find and draw (make sure it can be found)
var markers = Vision.FindAruco(colorCv);
if (!markers.Any()) { return PoseFormatter.PoseToBytes(new double[4, 4]); }//zeros
//Calculate pose
var depth = LatestDepthImage();
CameraSpacePoint[] _3dImage = new CameraSpacePoint[KinectSettings.COLOR_PIXEL_COUNT];
KxBuffer.instance.coordinateMapper.MapColorFrameToCameraSpace(depth, _3dImage);
var cvCameraSpace = new CvCameraSpace(_3dImage);
var kxTransform = Vision.GetPoseFromImage(cube, cvCameraSpace, markers);
var pose = kxTransform.CameraPose;
return PoseFormatter.PoseToBytes(pose);
}
[OperationContract]
public bool RecordXef(TimeSpan duration)
{
try
{
_logger.Log(LogLevel.Info, $"Requested xef recording - {duration.TotalMilliseconds} ms.");
var current = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
_lastFilePath = Path.Combine(current, "record.xef");
if (File.Exists(_lastFilePath))
File.Delete(_lastFilePath);
Xef.Record(_lastFilePath, duration);
Thread.Sleep((int)duration.Add(TimeSpan.FromSeconds(2)).TotalMilliseconds);
_logger.Log(LogLevel.Info, $"Recording successful. Sending bytes from xef recording - {_lastFilePath}");
return true;
}
catch (Exception e)
{
_logger.Log(LogLevel.Error, e.ToString());
return false;
}
}
[OperationContract]
public byte[] LastRecording()
{
if (_lastFilePath == null || !File.Exists(_lastFilePath)) { return new byte[0]; }
return File.ReadAllBytes(_lastFilePath);
}
[OperationContract]
public byte[] LatestJPEGImage()
{
return new byte[0];
}
[OperationContract]
public byte[] LatestRGBImage()
{
this.rgbFrameReady.WaitOne();
lock (KxBuffer.instance.rgbByteBuffer)
Buffer.BlockCopy((Array)KxBuffer.instance.rgbByteBuffer, 0, (Array)this.rgbByteBuffer, 0, KinectSettings.COLOR_PIXEL_COUNT * 4);
return this.rgbByteBuffer;
}
[OperationContract]
public byte[] LatestYUVImage()
{
_logger.Info("YUV frame requested...");
this.yuvFrameReady.WaitOne();
_logger.Info("YUV frame ready. Copying frame...");
lock (KxBuffer.instance.yuvFrameReady)
Buffer.BlockCopy((Array)KxBuffer.instance.yuvByteBuffer, 0, (Array)this.yuvByteBuffer, 0, KinectSettings.COLOR_PIXEL_COUNT * 2);
_logger.Info("Returning frame");
return this.yuvByteBuffer;
}
[OperationContract]
public byte[] LatestAudio()
{
this.audioFrameReady.WaitOne();
lock (KxBuffer.instance.audioFrameQueues)
{
byte[] numArray = new byte[this.audioFrameQueue.Count * 1024];
int count = this.audioFrameQueue.Count;
for (int index = 0; index < count; ++index)
Array.Copy((Array)this.audioFrameQueue.Dequeue(), 0, (Array)numArray, 1024 * index, 1024);
return numArray;
}
}
public async static void Start()
{
try
{
await System.Threading.Tasks.Task.Run(() =>
{
_logger.Info("Starting Kinect service...");
KxBuffer.StartBuffer();
ServiceHost serviceHost = new ServiceHost(typeof(KxServer));
serviceHost.Description.Behaviors.Add(new ServiceDiscoveryBehavior());
serviceHost.AddServiceEndpoint(new UdpDiscoveryEndpoint());
serviceHost.Open();
_logger.Info("Kinect listener service!");
Console.ReadLine();
}, KxServer._cancallationTokenSrc.Token);
}
catch (Exception e)
{
_logger.Error(e);
Stop();
}
}
public static void Stop()
{
try
{
_logger.Info("Stopping Kinect service...");
KxServer._cancallationTokenSrc.Cancel();
}
catch (Exception e)
{
_logger.Error(e);
Stop();
}
}
}
}
| 37.921429 | 154 | 0.590695 | [
"MIT"
] | rexcardan/KinectX | KinectX/Network/KxServer.cs | 10,620 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Runtime.Remoting.Contexts;
using PewPew_Paradise.Maths;
using System.Diagnostics;
using System.Windows.Threading;
namespace PewPew_Paradise.GameLogic
{
/// <summary>
/// class that implements the core game functions
/// </summary>
public class GameManager
{
public static string GameAssetPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "PewPew_Paradise_Assets");
/// <summary>
/// Screen in game units
/// </summary>
public const double GameUnitSize = 16.0;
/// <summary>
/// Resolution of screen art (map) in pixels
/// </summary>
public const double GameResolution = 256.0;
//Update Thread
private static int _minimumDelta;
//Update Event
public delegate void UpdateDelegate();
public static event UpdateDelegate OnPreUpdate;
public static event UpdateDelegate OnUpdate;
public static event UpdateDelegate OnPostUpdate;
//Timer for update call
private static DispatcherTimer _dispatherTimer = new DispatcherTimer();
//variables used to calculate DeltaTime
private static double _lastTime;
private static double _deltaTime;
private static Stopwatch _stopWatch = new Stopwatch();
private static bool _running;
/// <summary>
/// Get the elapsed time in milliseconds between two Update() calls
/// </summary>
public static double DeltaTime
{
get
{
return _deltaTime;
}
}
/// <summary>
/// Initialize GameManager
/// </summary>
/// <param name="frameRate"></param>
///
public static void Init(int frameRate)
{
FrameRate = frameRate;
SpriteManager.LoadImage("Images/Sprites/Characters/MrPlaceHolder.png", "MrPlaceHolder");
}
/// <summary>
/// Get or set the frame rate of the game
/// </summary>
public static int FrameRate
{
get
{
return 1000 / (_minimumDelta + 1);
}
set
{
_minimumDelta = Math.Max(1,1000 / value - 1);
}
}
/// <summary>
/// Function that calls the OnUpdate event [Do not call]
/// </summary>
protected static void Update(object state, EventArgs e)
{
_deltaTime = _stopWatch.Elapsed.TotalMilliseconds - _lastTime;
OnPreUpdate?.Invoke();
OnUpdate?.Invoke();
OnPostUpdate?.Invoke();
_lastTime = _stopWatch.ElapsedMilliseconds;
}
/// <summary>
/// Start the game Update loop
/// </summary>
public static void Begin()
{
if (!_running)
{
_running = true;
_lastTime = 0;
_stopWatch.Reset();
_stopWatch.Start();
_dispatherTimer.Interval = TimeSpan.FromMilliseconds(_minimumDelta);
_dispatherTimer.Tick += Update;
_dispatherTimer.Start();
}
}
/// <summary>
/// Stop the game Update loop
/// </summary>
public static void Stop()
{
if (_running)
{
_running = false;
_stopWatch.Stop();
_dispatherTimer.Stop();
_dispatherTimer.Tick -= Update;
}
}
}
}
| 27.482014 | 187 | 0.548953 | [
"MIT"
] | Peter226/PewPew-Paradise | PewPew Paradise/GameLogic/GameManager.cs | 3,822 | C# |
using Business.Abstract;
using Core.Helpers;
using DataAccess.Abstract;
using Entities;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace Business.Concrete
{
public class AuthManager : IAuthService
{
private ICustomerDal customerDal;
private readonly AppSettings appSettings;
public AuthManager(ICustomerDal customerDal, IOptions<AppSettings> appSettings)
{
this.customerDal = customerDal;
this.appSettings = appSettings.Value;
}
public (Customer, string) Login(string idNo, string password)
{
Customer customer = customerDal.Get(x => x.IdNo == idNo && x.Password == password);
if (customer == null) return (null, null);
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, customer.IdNo)
}),
Expires = DateTime.UtcNow.AddMinutes(1),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var createdToken = tokenHandler.CreateToken(tokenDescriptor);
string token = tokenHandler.WriteToken(createdToken);
customer.Password = null;
return (customer, token);
}
public string Register(Customer customer)
{
Customer tempCustomer = customerDal.Get(x => x.IdNo == customer.IdNo);
if (tempCustomer != null) return string.Empty; //user exists
customerDal.Add(customer);
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, customer.IdNo)
}),
Expires = DateTime.UtcNow.AddMinutes(1),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var createToken = tokenHandler.CreateToken(tokenDescriptor);
string token = tokenHandler.WriteToken(createToken);
return token;
}
}
}
| 33.493827 | 130 | 0.624401 | [
"MIT"
] | guvenbank/guvenbank.api | Guvenbank.API/Business/Concrete/AuthManager.cs | 2,715 | C# |
using System;
namespace NHM.Common.Enums
{
/// <summary>
/// AlgorithmType enum should/must mirror the values from https://www.nicehash.com/algorithm
/// </summary>
public enum AlgorithmType
{
INVALID = -2,
NONE = -1,
#region NiceHashAPI
[Obsolete("UNUSED Algorithm")]
Scrypt = 0,
[Obsolete("UNUSED Algorithm")]
SHA256 = 1,
[Obsolete("UNUSED Algorithm")]
ScryptNf = 2,
[Obsolete("UNUSED Algorithm")]
X11 = 3,
[Obsolete("UNUSED Algorithm")]
X13 = 4,
[Obsolete("UNUSED Algorithm")]
Keccak = 5,
[Obsolete("UNUSED Algorithm")]
X15 = 6,
[Obsolete("UNUSED Algorithm")]
Nist5 = 7,
[Obsolete("UNUSED Algorithm")]
NeoScrypt = 8,
[Obsolete("UNUSED Algorithm")]
Lyra2RE = 9,
[Obsolete("UNUSED Algorithm")]
WhirlpoolX = 10,
[Obsolete("UNUSED Algorithm")]
Qubit = 11,
[Obsolete("UNUSED Algorithm")]
Quark = 12,
[Obsolete("UNUSED Algorithm")]
Axiom = 13,
[Obsolete("UNUSED Algorithm")]
Lyra2REv2 = 14,
[Obsolete("UNUSED Algorithm")]
ScryptJaneNf16 = 15,
[Obsolete("UNUSED Algorithm")]
Blake256r8 = 16,
[Obsolete("UNUSED Algorithm")]
Blake256r14 = 17,
[Obsolete("UNUSED Algorithm")]
Blake256r8vnl = 18,
[Obsolete("UNUSED Algorithm")]
Hodl = 19,
//[Obsolete("UNUSED Algorithm")]
DaggerHashimoto = 20,
[Obsolete("UNUSED Algorithm. USED only as second algorithm.")]
Decred = 21,
[Obsolete("UNUSED Algorithm")]
CryptoNight = 22,
[Obsolete("UNUSED Algorithm")]
Lbry = 23,
[Obsolete("UNUSED Algorithm")]
Equihash = 24,
[Obsolete("UNUSED Algorithm")]
Pascal = 25,
[Obsolete("UNUSED Algorithm")]
X11Gost = 26,
[Obsolete("UNUSED Algorithm")]
Sia = 27,
[Obsolete("UNUSED Algorithm. USED only as second algorithm.")]
Blake2s = 28,
[Obsolete("UNUSED Algorithm")]
Skunk = 29,
[Obsolete("UNUSED Algorithm")]
CryptoNightV7 = 30,
[Obsolete("UNUSED Algorithm")]
CryptoNightHeavy = 31,
//[Obsolete("UNUSED Algorithm")]
Lyra2Z = 32,
//[Obsolete("UNUSED Algorithm")]
X16R = 33,
[Obsolete("UNUSED Algorithm")]
CryptoNightV8 = 34,
[Obsolete("UNUSED Algorithm")]
SHA256AsicBoost = 35,
//[Obsolete("UNUSED Algorithm")]
ZHash = 36,
[Obsolete("UNUSED Algorithm. Replaced by BeamV2")]
Beam = 37,
//[Obsolete("UNUSED Algorithm")]
GrinCuckaroo29 = 38,
//[Obsolete("UNUSED Algorithm")]
GrinCuckatoo31 = 39,
//[Obsolete("UNUSED Algorithm")]
Lyra2REv3 = 40,
[Obsolete("NOT SUPPORTED. UNUSED Algorithm")]
MTP = 41,
//[Obsolete("UNUSED Algorithm")]
CryptoNightR = 42,
//[Obsolete("UNUSED Algorithm")]
CuckooCycle = 43,
//[Obsolete("UNUSED Algorithm")]
GrinCuckarood29 = 44,
//[Obsolete("UNUSED Algorithm")]
BeamV2 = 45,
//[Obsolete("UNUSED Algorithm")]
X16Rv2 = 46,
#endregion // NiceHashAPI
}
public static class AlgorithmTypeExtensionMethods
{
#pragma warning disable 0618
public static string GetUnitPerSecond(this AlgorithmType algorithmType)
{
switch (algorithmType)
{
case AlgorithmType.Equihash:
case AlgorithmType.ZHash:
case AlgorithmType.Beam:
case AlgorithmType.BeamV2:
return "Sol/s";
case AlgorithmType.GrinCuckaroo29:
case AlgorithmType.GrinCuckatoo31:
case AlgorithmType.CuckooCycle:
case AlgorithmType.GrinCuckarood29:
return "G/s";
default:
return "H/s";
}
}
#pragma warning restore 0618
public static (string name, bool ok) GetName(this AlgorithmType algorithmType)
{
const string NA = "N/A";
try
{
var name = Enum.GetName(typeof(AlgorithmType), algorithmType) ?? NA; // get name or not available
var ok = name != NA;
return (name, ok);
}
catch
{
return (NA, false);
}
}
public static string GetNameFromAlgorithmTypes(this AlgorithmType[] ids)
{
var names = new string[ids.Length];
for (int i = 0; i < ids.Length; i++)
{
var (name, _) = ids[i].GetName();
// TODO should we check if ok?
names[i] = name;
}
return string.Join("+", names);
}
}
}
| 30.901235 | 113 | 0.522773 | [
"MIT"
] | Torino777/NiceHashMiner | src/NHM.Common/Enums/AlgorithmType.cs | 5,008 | C# |
namespace TerritoryTools.Web.MainSite.Services
{
public class AuthMessageSenderOptions
{
public string SendGridUser { get; set; }
public string SendGridKey { get; set; }
public string AuthEmailFromEmailAddress { get; set; }
public string AuthEmailFromName { get; set; }
public string AuthEmailTo { get; set; }
}
} | 33.272727 | 61 | 0.663934 | [
"MIT"
] | territorytools/territory-tools | Web/MainSite/Services/AuthMessageSenderOptions.cs | 368 | C# |
//
// Author: Atsushi Enomoto <atsushi@ximian.com>
//
// Copyright (C) 2009,2010 Novell, Inc (http://www.novell.com)
//
// 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;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace System.ServiceModel.Discovery.Version11
{
[XmlSchemaProvider ("GetSchema")]
public class ResolveCriteria11 : IXmlSerializable
{
public static ResolveCriteria11 FromResolveCriteria (ResolveCriteria resolveCriteria)
{
return new ResolveCriteria11 (resolveCriteria);
}
static readonly DiscoveryVersion version = DiscoveryVersion.WSDiscovery11;
static XmlSchema schema = ResolveCriteria.BuildSchema (version);
public static XmlQualifiedName GetSchema (XmlSchemaSet schemaSet)
{
EndpointAddress10.GetSchema (schemaSet);
schemaSet.Add (schema);
return new XmlQualifiedName ("ResolveType", version.Namespace);
}
internal ResolveCriteria11 (ResolveCriteria source)
{
this.source = source;
}
ResolveCriteria source;
public XmlSchema GetSchema ()
{
return null;
}
public void ReadXml (XmlReader reader)
{
source = ResolveCriteria.ReadXml (reader, version);
}
public ResolveCriteria ToResolveCriteria ()
{
if (source == null)
throw new InvalidOperationException ("Call ReadXml method first before calling this method");
return source;
}
public void WriteXml (XmlWriter writer)
{
source.WriteXml (writer, version);
}
}
}
| 31.593023 | 97 | 0.760766 | [
"Apache-2.0"
] | 121468615/mono | mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.Version11/ResolveCriteria11.cs | 2,717 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** 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.Aws.AppMesh.Inputs
{
public sealed class VirtualServiceSpecProviderVirtualRouterGetArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The name of the virtual router that is acting as a service provider. Must be between 1 and 255 characters in length.
/// </summary>
[Input("virtualRouterName", required: true)]
public Input<string> VirtualRouterName { get; set; } = null!;
public VirtualServiceSpecProviderVirtualRouterGetArgs()
{
}
}
}
| 32.423077 | 128 | 0.695136 | [
"ECL-2.0",
"Apache-2.0"
] | RafalSumislawski/pulumi-aws | sdk/dotnet/AppMesh/Inputs/VirtualServiceSpecProviderVirtualRouterGetArgs.cs | 843 | C# |
namespace AnxPro.Api.Models
{
public enum OrderType
{
IMMEDIATE_OR_CANCEL,
LIMIT,
MARKET
}
}
| 13 | 28 | 0.561538 | [
"MIT"
] | RobJohnston/AnxPro.Api | src/AnxPro.Api/Models/Enums/OrderType.cs | 132 | C# |
using UnityEngine;
using System.Collections; using FastCollections;
using System.Collections.Generic;
namespace RTSLockstep
{
/// <summary>
/// Essentially a collection of LSVariables belonging to a single object (i.e. Ability)
/// </summary>
public sealed class LSVariableContainer
{
static readonly FastList<int> bufferCompareHashes = new FastList<int>();
static readonly FastList<LSVariable> bufferVariables = new FastList<LSVariable>();
private LSVariable[] _variables;
public LSVariable[] Variables {get {return _variables;}}
public LSVariableContainer (IEnumerable<LSVariable> trackedVariables) {
bufferVariables.FastClear(); //Recycle the buffer
foreach (LSVariable variable in trackedVariables) {
bufferVariables.Add(variable);
}
_variables = bufferVariables.ToArray();
}
public int Hash () {
int hash = int.MaxValue / 2;
//Iterate through and generate hash from variables
foreach (LSVariable variable in this.Variables) {
hash ^= variable.Hash();
}
return hash;
}
public void Reset () {
//Iterate through and reset every varaible
foreach (LSVariable vari in this.Variables) {
vari.Reset();
}
}
public IEnumerable<LSVariable> GetDesyncs (int[] compareHashes) {
if (compareHashes.Length != Variables.Length) {
throw new System.Exception("There are not the same amount of hashes to compare to!");
}
for (int i = 0; i < this.Variables.Length; i++) {
LSVariable variable = this.Variables[i];
if (compareHashes[i] != variable.Hash()) {
yield return variable;
}
}
}
public int[] GetCompareHashes () {
bufferCompareHashes.FastClear();
for (int i = 0; i < this.Variables.Length; i++) {
bufferCompareHashes.Add (Variables[i].Hash());
}
return bufferCompareHashes.ToArray();
}
}
} | 35.645161 | 101 | 0.576018 | [
"MIT"
] | mrdav30/LockstepRTSEngine | Assets/Core/Game/Determinism/LSVariableContainer.cs | 2,212 | C# |
//------------------------------------------------------------------------------
// <自动生成>
// 此代码由工具生成。
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </自动生成>
//------------------------------------------------------------------------------
namespace EIS.WebBase.SysFolder.WorkFlow {
public partial class FlowErrorInfo {
/// <summary>
/// Head1 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlHead Head1;
/// <summary>
/// form1 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
}
}
| 25.5 | 81 | 0.411765 | [
"MIT"
] | chen1993nian/CPMPlatform | Dev/SysFolder/WorkFlow/FlowErrorInfo.aspx.designer.cs | 1,137 | C# |
using SQLiteTool.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using SQLiteTool.Util;
using SQLiteTool.ViewModels;
namespace SQLiteTool.Views
{
/// <summary>
/// CreateDatabase.xaml 的交互逻辑
/// </summary>
public partial class CreateDatabase : Window
{
CreateDatabaseViewModel context;
public CreateDatabase()
{
InitializeComponent();
context = new CreateDatabaseViewModel();
this.DataContext = context;
GlobalData.CreateInstance().createDatabaseViewModel = context;
}
}
}
| 24.710526 | 75 | 0.669862 | [
"Apache-2.0"
] | zhaotianff/SQLiteTool | Views/CreateDatabase.xaml.cs | 951 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace DataAccess.Env
{
/// <summary>
/// All could come from a config
/// </summary>
public static class Commons
{
public const string MESSAGE_QUEUE = "Top_Queue";
public const string DBName = "cashsample";
}
}
| 20.25 | 56 | 0.648148 | [
"MIT"
] | menfra/RabbitMQ_Kubernetes | DataAccess/Env/Commons.cs | 326 | C# |
// ReSharper disable once CheckNamespace
namespace Umbraco.Core
{
static partial class Constants
{
public static class Locks
{
public const int Servers = -331;
}
}
}
| 17.916667 | 44 | 0.590698 | [
"MIT"
] | Abhith/Umbraco-CMS | src/Umbraco.Core/Persistence/Constants-Locks.cs | 217 | C# |
// Copyright (c) DNN Software. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using Dnn.DynamicContent;
using DotNetNuke.Entities.Content;
using DotNetNuke.Tests.Utilities;
using Moq;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
namespace Dnn.Tests.DynamicContent.UnitTests
{
[TestFixture]
public class DynamicContentItemManagerTests
{
private JObject _testJson = new JObject(
new JProperty("contentTypeId", Constants.CONTENTTYPE_ValidContentTypeId),
new JProperty("content",
new JObject(
new JProperty("field",
new JArray(
new JObject(
new JProperty("name", "FieldName1"),
new JProperty("value", 1)
),
new JObject(
new JProperty("name", "FieldName2"),
new JProperty("value", true)
),
new JObject(
new JProperty("name", "FieldName3"),
new JProperty("value", "abc")
)
)
)
)
)
);
[TearDown]
public void TearDown()
{
FieldDefinitionManager.ClearInstance();
}
[Test]
public void AddContentItem_Throws_On_Null_ContentItem()
{
//Arrange
var controller = new DynamicContentItemManager();
//Act, Assert
Assert.Throws<ArgumentNullException>(() => controller.AddContentItem(null));
}
[Test]
public void AddContentItem_Throws_On_Null_ContentType_Property_Of_ContentItem()
{
//Arrange
var controller = new DynamicContentItemManager();
var contentItem = new DynamicContentItem(Constants.PORTAL_ValidPortalId);
//Act, Assert
Assert.Throws<ArgumentNullException>(() => controller.AddContentItem(contentItem));
}
[Test]
public void AddContentItem_Throws_On_Negative_ContentTypeId_Property_Of_ContentType_Property_Of_ContentItem()
{
//Arrange
var controller = new DynamicContentItemManager();
var contentItem = new DynamicContentItem(new DynamicContentType() {PortalId = Constants.PORTAL_ValidPortalId});
//Act, Assert
Assert.Throws<ArgumentOutOfRangeException>(() => controller.AddContentItem(contentItem));
}
[Test]
public void AddContentItem_Throws_On_Negative_ModuleId_Property_Of_ContentItem()
{
//Arrange
var controller = new DynamicContentItemManager();
var contentTypeId = Constants.CONTENTTYPE_ValidContentTypeId;
var mockFieldDefinitionController = new Mock<IFieldDefinitionManager>();
mockFieldDefinitionController.Setup(f => f.GetFieldDefinitions(contentTypeId))
.Returns(new List<FieldDefinition>().AsQueryable());
FieldDefinitionManager.SetTestableInstance(mockFieldDefinitionController.Object);
var contentItem = new DynamicContentItem(GetContentType(contentTypeId, Constants.PORTAL_ValidPortalId));
//Act, Assert
Assert.Throws<ArgumentOutOfRangeException>(() => controller.AddContentItem(contentItem));
}
[Test]
public void AddContentItem_Calls_ContentController_AddContentItem()
{
//Arrange
var controller = new DynamicContentItemManager();
var contentTypeId = Constants.CONTENTTYPE_ValidContentTypeId;
var portalId = Constants.PORTAL_ValidPortalId;
var mockFieldDefinitionController = new Mock<IFieldDefinitionManager>();
mockFieldDefinitionController.Setup(f => f.GetFieldDefinitions(contentTypeId))
.Returns(new List<FieldDefinition>().AsQueryable());
FieldDefinitionManager.SetTestableInstance(mockFieldDefinitionController.Object);
var dynamicContent = new DynamicContentItem(GetContentType(contentTypeId, portalId))
{
ModuleId = Constants.MODULE_ValidId
};
var mockContentController = new Mock<IContentController>();
ContentController.SetTestableInstance(mockContentController.Object);
//Act
controller.AddContentItem(dynamicContent);
//Assert
mockContentController.Verify((c) => c.AddContentItem(It.IsAny<ContentItem>()), Times.Once);
}
[Test]
public void AddContentItem_Calls_ContentController_AddContentItem_With_Valid_ContentItem()
{
//Arrange
var moduleId = Constants.MODULE_ValidId;
var portalId = Constants.PORTAL_ValidPortalId;
var controller = new DynamicContentItemManager();
var contentTypeId = Constants.CONTENTTYPE_ValidContentTypeId;
var mockFieldDefinitionController = new Mock<IFieldDefinitionManager>();
mockFieldDefinitionController.Setup(f => f.GetFieldDefinitions(contentTypeId))
.Returns(new List<FieldDefinition>().AsQueryable());
FieldDefinitionManager.SetTestableInstance(mockFieldDefinitionController.Object);
var mockContentTypeController = new Mock<IDynamicContentTypeManager>();
mockContentTypeController.Setup(c => c.GetContentTypes(portalId, false))
.Returns(new List<DynamicContentType>() { GetContentType(contentTypeId, portalId) }.AsQueryable());
DynamicContentTypeManager.SetTestableInstance(mockContentTypeController.Object);
var dynamicContent = new DynamicContentItem(GetContentType(contentTypeId, portalId))
{
ModuleId = moduleId
};
dynamicContent.Fields["FieldName1"].Value = 1;
dynamicContent.Fields["FieldName2"].Value = true;
dynamicContent.Fields["FieldName3"].Value = "abc";
ContentItem contentItem = null;
var mockContentController = new Mock<IContentController>();
mockContentController.Setup(c => c.AddContentItem(It.IsAny<ContentItem>()))
.Callback<ContentItem>((c) => contentItem = c);
ContentController.SetTestableInstance(mockContentController.Object);
//Act
controller.AddContentItem(dynamicContent);
//Assert
Assert.AreEqual(-1, contentItem.TabID);
Assert.AreEqual(moduleId, contentItem.ModuleID);
Assert.AreEqual(contentTypeId, contentItem.ContentTypeId);
Assert.AreEqual(String.Empty, contentItem.ContentKey);
Assert.AreEqual(_testJson.ToString(), contentItem.Content);
}
[Test]
public void CreateContentItem_Throws_On_Null_ContentType()
{
//Arrange
var controller = new DynamicContentItemManager();
DynamicContentType contentType = null;
//Act, Assert
// ReSharper disable once ExpressionIsAlwaysNull
Assert.Throws<ArgumentNullException>(() => controller.CreateContentItem(Constants.MODULE_ValidId, contentType));
}
[Test]
public void CreateContentItem_Throws_If_ContentType_Has_Negative_PortalId()
{
//Arrange
var controller = new DynamicContentItemManager();
var contentType = new DynamicContentType() {PortalId = Constants.PORTAL_InValidPortalId };
//Act, Assert
Assert.Throws<ArgumentOutOfRangeException>(() => controller.CreateContentItem(Constants.MODULE_ValidId, contentType));
}
[Test]
public void CreateContentItem_Throws_If_ContentType_Has_No_Fields_Defined()
{
//Arrange
var controller = new DynamicContentItemManager();
var contentType = new DynamicContentType() { PortalId = Constants.PORTAL_ValidPortalId };
var mockFieldDefinitionController = new Mock<IFieldDefinitionManager>();
mockFieldDefinitionController.Setup(c => c.GetFieldDefinitions(It.IsAny<int>()))
.Returns(new List<FieldDefinition>().AsQueryable());
FieldDefinitionManager.SetTestableInstance(mockFieldDefinitionController.Object);
//Act, Assert
Assert.Throws<InvalidOperationException>(() => controller.CreateContentItem(Constants.MODULE_ValidId, contentType));
}
[Test]
public void CreateContentItem_Returns_Valid_DyamicContentItem()
{
//Arrange
var contentTypeId = Constants.CONTENTTYPE_ValidContentTypeId;
var portalId = Constants.PORTAL_ValidPortalId;
var moduleId = Constants.MODULE_ValidId;
var mockFieldDefinitionController = new Mock<IFieldDefinitionManager>();
mockFieldDefinitionController.Setup(f => f.GetFieldDefinitions(contentTypeId))
.Returns(new List<FieldDefinition>().AsQueryable());
FieldDefinitionManager.SetTestableInstance(mockFieldDefinitionController.Object);
var controller = new DynamicContentItemManager();
//Act
var contentType = GetContentType(contentTypeId, portalId);
var dynamicContent = controller.CreateContentItem(moduleId, contentType);
//Assert
Assert.AreSame(contentType, dynamicContent.ContentType);
Assert.AreEqual(contentType.FieldDefinitions.Count, dynamicContent.Fields.Count);
Assert.AreEqual(portalId, dynamicContent.PortalId);
Assert.AreEqual(moduleId, dynamicContent.ModuleId);
foreach (var field in contentType.FieldDefinitions)
{
Assert.AreSame(field, dynamicContent.Fields[field.Name].Definition);
}
}
[Test]
public void CreateContentItem_Overload_Throws_On_Null_ContentItem()
{
//Arrange
var controller = new DynamicContentItemManager();
ContentItem contentItem = null;
//Act, Assert
// ReSharper disable once ExpressionIsAlwaysNull
Assert.Throws<ArgumentNullException>(() => controller.CreateContentItem(Constants.PORTAL_ValidPortalId, contentItem));
}
[Test]
public void CreateContentItem_Overload_Throws_On_Negative_PortalId()
{
//Arrange
var controller = new DynamicContentItemManager();
//Act, Assert
Assert.Throws<ArgumentOutOfRangeException>(() => controller.CreateContentItem(Constants.PORTAL_InValidPortalId, new ContentItem()));
}
[Test]
public void CreateContentItem_Overload_Throws_On_Null_Or_Empty_Content()
{
//Arrange
var controller = new DynamicContentItemManager();
//Act, Assert
Assert.Throws<ArgumentException>(() => controller.CreateContentItem(Constants.PORTAL_ValidPortalId, new ContentItem()));
}
[Test]
public void CreateContentItem_Overload_Returns_Valid_Content()
{
//Arrange
var controller = new DynamicContentItemManager();
var contentTypeId = Constants.CONTENTTYPE_ValidContentTypeId;
var portalId = Constants.PORTAL_ValidPortalId;
var moduleId = Constants.MODULE_ValidId;
var mockFieldDefinitionController = new Mock<IFieldDefinitionManager>();
mockFieldDefinitionController.Setup(f => f.GetFieldDefinitions(contentTypeId))
.Returns(new List<FieldDefinition>().AsQueryable());
FieldDefinitionManager.SetTestableInstance(mockFieldDefinitionController.Object);
var contentType = GetContentType(contentTypeId, portalId);
var mockContentTypeController = new Mock<IDynamicContentTypeManager>();
mockContentTypeController.Setup(c => c.GetContentTypes(portalId, false))
.Returns(new List<DynamicContentType>() { contentType }.AsQueryable());
DynamicContentTypeManager.SetTestableInstance(mockContentTypeController.Object);
var contentItem = new ContentItem { Content = _testJson.ToString(), ModuleID = moduleId };
//Act
var dynamicContent = controller.CreateContentItem(portalId, contentItem);
//Assert
Assert.AreEqual(contentTypeId, dynamicContent.ContentType.ContentTypeId);
Assert.AreEqual(contentType.FieldDefinitions.Count, dynamicContent.Fields.Count);
Assert.AreEqual(portalId, dynamicContent.PortalId);
Assert.AreEqual(moduleId, dynamicContent.ModuleId);
foreach (var field in contentType.FieldDefinitions)
{
Assert.AreSame(field, dynamicContent.Fields[field.Name].Definition);
}
}
[Test]
public void DeleteContentItem_Throws_On_Null_ContentItem()
{
//Arrange
var controller = new DynamicContentItemManager();
//Act, Assert
Assert.Throws<ArgumentNullException>(() => controller.DeleteContentItem(null));
}
[Test]
public void DeleteContentItem_Throws_On_Negative_ContentItemId()
{
//Arrange
var controller = new DynamicContentItemManager();
var contentItem = new DynamicContentItem(Constants.PORTAL_ValidPortalId);
//Act, Assert
Assert.Throws<ArgumentOutOfRangeException>(() => controller.DeleteContentItem(contentItem));
}
[Test]
public void DeleteContentItem_Calls_ContentController_UpdateContentItem()
{
//Arrange
var contentItemId = Constants.CONTENT_ValidContentItemId;
var controller = new DynamicContentItemManager();
var contentItem = new DynamicContentItem(Constants.PORTAL_ValidPortalId) {ContentItemId = contentItemId};
var mockContentController = new Mock<IContentController>();
ContentController.SetTestableInstance(mockContentController.Object);
//Act
controller.DeleteContentItem(contentItem);
//Assert
mockContentController.Verify((c) => c.DeleteContentItem(contentItemId), Times.Once);
}
[Test]
public void UpdateContentItem_Throws_On_Null_ContentItem()
{
//Arrange
var controller = new DynamicContentItemManager();
//Act, Assert
Assert.Throws<ArgumentNullException>(() => controller.UpdateContentItem(null));
}
[Test]
public void UpdateContentItem_Throws_On_Negative_ContentItemId()
{
//Arrange
var controller = new DynamicContentItemManager();
var contentItem = new DynamicContentItem(Constants.PORTAL_ValidPortalId);
//Act, Assert
Assert.Throws<ArgumentOutOfRangeException>(() => controller.UpdateContentItem(contentItem));
}
[Test]
public void UpdateContentItem_Throws_On_Null_ContentType_Property_Of_ContentItem()
{
//Arrange
var controller = new DynamicContentItemManager();
var contentItem = new DynamicContentItem(Constants.PORTAL_ValidPortalId)
{
ContentItemId = Constants.CONTENT_ValidContentItemId
};
//Act, Assert
Assert.Throws<ArgumentNullException>(() => controller.UpdateContentItem(contentItem));
}
[Test]
public void UpdateContentItem_Throws_On_Negative_ContentTypeId_Property_Of_ContentType_Property_Of_ContentItem()
{
//Arrange
var controller = new DynamicContentItemManager();
var contentItem = new DynamicContentItem(new DynamicContentType() {PortalId = Constants.PORTAL_ValidPortalId})
{
ContentItemId = Constants.CONTENT_ValidContentItemId
};
//Act, Assert
Assert.Throws<ArgumentOutOfRangeException>(() => controller.UpdateContentItem(contentItem));
}
[Test]
public void UpdateContentItem_Throws_On_Negative_ModuleId_Property_Of_ContentItem()
{
//Arrange
var controller = new DynamicContentItemManager();
var contentTypeId = Constants.CONTENTTYPE_ValidContentTypeId;
var mockFieldDefinitionController = new Mock<IFieldDefinitionManager>();
mockFieldDefinitionController.Setup(f => f.GetFieldDefinitions(contentTypeId))
.Returns(new List<FieldDefinition>().AsQueryable());
FieldDefinitionManager.SetTestableInstance(mockFieldDefinitionController.Object);
var contentItem = new DynamicContentItem(GetContentType(contentTypeId, Constants.PORTAL_ValidPortalId))
{
ContentItemId = Constants.CONTENT_ValidContentItemId
};
//Act, Assert
Assert.Throws<ArgumentOutOfRangeException>(() => controller.UpdateContentItem(contentItem));
}
[Test]
public void UpdateContentItem_Calls_ContentController_UpdateContentItem()
{
//Arrange
var controller = new DynamicContentItemManager();
var contentTypeId = Constants.CONTENTTYPE_ValidContentTypeId;
var portalId = Constants.PORTAL_ValidPortalId;
var mockFieldDefinitionController = new Mock<IFieldDefinitionManager>();
mockFieldDefinitionController.Setup(f => f.GetFieldDefinitions(contentTypeId))
.Returns(new List<FieldDefinition>().AsQueryable());
FieldDefinitionManager.SetTestableInstance(mockFieldDefinitionController.Object);
var dynamicContent = new DynamicContentItem(GetContentType(contentTypeId, portalId))
{
ModuleId = Constants.MODULE_ValidId,
ContentItemId = Constants.CONTENT_ValidContentItemId
};
var mockContentController = new Mock<IContentController>();
ContentController.SetTestableInstance(mockContentController.Object);
//Act
controller.UpdateContentItem(dynamicContent);
//Assert
mockContentController.Verify((c) => c.UpdateContentItem(It.IsAny<ContentItem>()), Times.Once);
}
[Test]
public void UpdateContentItem_Calls_ContentController_UpdateContentItem_With_Valid_ContentItem()
{
//Arrange
var moduleId = Constants.MODULE_ValidId;
var portalId = Constants.PORTAL_ValidPortalId;
var contentItemId = Constants.CONTENT_ValidContentItemId;
var controller = new DynamicContentItemManager();
var contentTypeId = Constants.CONTENTTYPE_ValidContentTypeId;
var mockFieldDefinitionController = new Mock<IFieldDefinitionManager>();
mockFieldDefinitionController.Setup(f => f.GetFieldDefinitions(contentTypeId))
.Returns(new List<FieldDefinition>().AsQueryable());
FieldDefinitionManager.SetTestableInstance(mockFieldDefinitionController.Object);
var mockContentTypeController = new Mock<IDynamicContentTypeManager>();
mockContentTypeController.Setup(c => c.GetContentTypes(portalId, false))
.Returns(new List<DynamicContentType>() { GetContentType(contentTypeId, portalId) }.AsQueryable());
DynamicContentTypeManager.SetTestableInstance(mockContentTypeController.Object);
var dynamicContent = new DynamicContentItem(GetContentType(contentTypeId, portalId))
{
ModuleId = moduleId,
ContentItemId = contentItemId
};
dynamicContent.Fields["FieldName1"].Value = 1;
dynamicContent.Fields["FieldName2"].Value = true;
dynamicContent.Fields["FieldName3"].Value = "abc";
ContentItem contentItem = null;
var mockContentController = new Mock<IContentController>();
mockContentController.Setup(c => c.UpdateContentItem(It.IsAny<ContentItem>()))
.Callback<ContentItem>((c) => contentItem = c);
ContentController.SetTestableInstance(mockContentController.Object);
//Act
controller.UpdateContentItem(dynamicContent);
//Assert
Assert.AreEqual(-1, contentItem.TabID);
Assert.AreEqual(contentItemId, contentItem.ContentItemId);
Assert.AreEqual(moduleId, contentItem.ModuleID);
Assert.AreEqual(contentTypeId, contentItem.ContentTypeId);
Assert.AreEqual(String.Empty, contentItem.ContentKey);
Assert.AreEqual(_testJson.ToString(), contentItem.Content);
}
private DynamicContentType GetContentType(int contentTypeId, int portalId)
{
var contentType = new DynamicContentType() { ContentTypeId = contentTypeId, PortalId = portalId };
contentType.FieldDefinitions.Add(new FieldDefinition() { ContentTypeId = contentTypeId, Name = "FieldName1" });
contentType.FieldDefinitions.Add(new FieldDefinition() { ContentTypeId = contentTypeId, Name = "FieldName2" });
contentType.FieldDefinitions.Add(new FieldDefinition() { ContentTypeId = contentTypeId, Name = "FieldName3" });
return contentType;
}
}
}
| 44.175097 | 144 | 0.621378 | [
"MIT"
] | 51Degrees/Dnn.Platform | DNN Platform/Tests/Dnn.Tests.DynamicContent.UnitTests/DynamicContentItemManagerTests.cs | 22,708 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using JustSaying.Messaging.MessageProcessingStrategies;
using JustSaying.Messaging.Monitoring;
using NSubstitute;
using Shouldly;
using Xunit;
namespace JustSaying.UnitTests.Messaging.MessageProcessingStrategies
{
public class ThreadSafeCounter
{
private int _count;
public void Increment()
{
Interlocked.Increment(ref _count);
}
public int Count => _count;
}
public class MessageLoopTests
{
private const int MinTaskDuration = 100;
private const int TaskDurationVariance = 20;
private const int ConcurrencyLevel = 20;
private const int MaxAmazonBatchSize = 10;
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(10)]
[InlineData(20)]
public async Task SimulatedListenLoop_ProcessedAllMessages(int numberOfMessagesToProcess)
{
var fakeMonitor = Substitute.For<IMessageMonitor>();
var messageProcessingStrategy = new Throttled(ConcurrencyLevel, fakeMonitor);
var counter = new ThreadSafeCounter();
var watch = new Stopwatch();
watch.Start();
var actions = BuildFakeIncomingMessages(numberOfMessagesToProcess, counter);
await ListenLoopExecuted(actions, messageProcessingStrategy);
watch.Stop();
await Task.Delay(2000);
counter.Count.ShouldBe(numberOfMessagesToProcess);
}
[Theory]
[InlineData(2, 1)]
[InlineData(3, 2)]
[InlineData(6, 5)]
[InlineData(11, 10)]
[InlineData(100, 90)]
[InlineData(30, 20)]
[InlineData(1000, 900)]
public async Task SimulatedListenLoop_WhenThrottlingOccurs_CallsMessageMonitor(int messageCount, int capacity)
{
messageCount.ShouldBeGreaterThan(capacity, "To cause throttling, message count must be over capacity");
var fakeMonitor = Substitute.For<IMessageMonitor>();
var messageProcessingStrategy = new Throttled(capacity, fakeMonitor);
var counter = new ThreadSafeCounter();
var actions = BuildFakeIncomingMessages(messageCount, counter);
await ListenLoopExecuted(actions, messageProcessingStrategy);
fakeMonitor.Received().IncrementThrottlingStatistic();
fakeMonitor.Received().HandleThrottlingTime(Arg.Any<TimeSpan>());
}
[Theory]
[InlineData(1, 1)]
[InlineData(1, 2)]
[InlineData(2, 2)]
[InlineData(5, 10)]
[InlineData(10, 50)]
[InlineData(50, 50)]
public async Task SimulatedListenLoop_WhenThrottlingDoesNotOccur_DoNotCallMessageMonitor(int messageCount, int capacity)
{
messageCount.ShouldBeLessThanOrEqualTo(capacity,
"To avoid throttling, message count must be not be over capacity");
var fakeMonitor = Substitute.For<IMessageMonitor>();
var messageProcessingStrategy = new Throttled(capacity, fakeMonitor);
var counter = new ThreadSafeCounter();
var actions = BuildFakeIncomingMessages(messageCount, counter);
await ListenLoopExecuted(actions, messageProcessingStrategy);
fakeMonitor.DidNotReceive().IncrementThrottlingStatistic();
}
private static async Task ListenLoopExecuted(Queue<Func<Task>> actions,
IMessageProcessingStrategy messageProcessingStrategy)
{
var initalActionCount = (double)actions.Count;
var timeoutSeconds = MinTaskDuration + (initalActionCount / 100);
var timeout = TimeSpan.FromSeconds(timeoutSeconds);
var stopwatch = Stopwatch.StartNew();
while (actions.Any())
{
var batch = GetFromFakeSnsQueue(actions, messageProcessingStrategy.AvailableWorkers);
foreach (var action in batch)
{
await messageProcessingStrategy.StartWorker(action, CancellationToken.None);
}
if (!actions.Any())
{
break;
}
messageProcessingStrategy.AvailableWorkers.ShouldBeGreaterThanOrEqualTo(0);
await messageProcessingStrategy.WaitForAvailableWorkers();
messageProcessingStrategy.AvailableWorkers.ShouldBeGreaterThan(0);
stopwatch.Elapsed.ShouldBeLessThanOrEqualTo(timeout,
$"ListenLoopExecuted took longer than timeout of {timeoutSeconds}s, with {actions.Count} of {initalActionCount} messages remaining");
}
}
private static IList<Func<Task>> GetFromFakeSnsQueue(Queue<Func<Task>> actions, int requestedBatchSize)
{
var batchSize = Math.Min(requestedBatchSize, MaxAmazonBatchSize);
batchSize = Math.Min(batchSize, actions.Count);
var batch = new List<Func<Task>>();
for (var i = 0; i < batchSize; i++)
{
batch.Add(actions.Dequeue());
}
return batch;
}
private static Queue<Func<Task>> BuildFakeIncomingMessages(int numberOfMessagesToCreate, ThreadSafeCounter counter)
{
var random = new Random();
var actions = new Queue<Func<Task>>();
for (var i = 0; i != numberOfMessagesToCreate; i++)
{
var duration = MinTaskDuration + random.Next(TaskDurationVariance);
var action = new Func<Task>(async () =>
{
await Task.Delay(duration);
counter.Increment();
});
actions.Enqueue(action);
}
return actions;
}
}
}
| 35.023392 | 153 | 0.61663 | [
"Apache-2.0"
] | JarrodJ83/JustSaying | JustSaying.UnitTests/Messaging/MessageProcessingStrategies/MessageLoopTests.cs | 5,989 | C# |
namespace BashSoftProgram.Contracts
{
using System;
using System.Collections.Generic;
public interface IStudent : IComparable<IStudent>
{
string UserName { get; }
IReadOnlyDictionary<string, ICourse> EnrolledCourses { get; }
IReadOnlyDictionary<string, double> MarksByCourseName { get; }
void EnrollInCourse(ICourse course);
void SetMarksInCourse(string courseName, params int[] scores);
}
}
| 24.105263 | 70 | 0.687773 | [
"MIT"
] | krasiymihajlov/Soft-Uni-practices | C# OOP Advanced/00. BashSoft/BashSoftProgram/Contracts/Models/IStudent.cs | 460 | C# |
using System.Threading.Tasks;
using Flurl;
using Flurl.Http;
using Marten;
using MassTransit;
using NetCoreIntegrationTestsSample.Infrastructure;
using V1 = NetCoreIntegrationTestsSample.Expenses.Contracts.Expenses.V1;
namespace NetCoreIntegrationTestsSample.Expenses
{
public class CreateExpenseConsumer : IConsumer<V1.Messages.CreateExpenseCommand>
{
private readonly IDocumentStore _documentStore;
private readonly ExchangeService _exchangeService;
public CreateExpenseConsumer(
IDocumentStore documentStore,
ExchangeService exchangeService)
{
_documentStore = documentStore;
_exchangeService = exchangeService;
}
public async Task Consume(ConsumeContext<V1.Messages.CreateExpenseCommand> context)
{
var exchangeRate = await _exchangeService
.GetExchangeRateFromPLNToEUR();
using var session = _documentStore.OpenSession();
session.Store(new DbExpense()
{
Id = context.Message.Id,
Date = context.Message.Date,
Title = context.Message.Title,
TotalAmountInPLN = context.Message.TotalAmountInPLN,
TotalAmountInEUR = context.Message.TotalAmountInPLN * exchangeRate
});
await session.SaveChangesAsync();
await context.Publish(new V1.Messages.ExpenseCreatedEvent()
{
Id = context.Message.Id
});
}
}
public class ExchangeService
{
private readonly ExchangeServiceConfig _exchangeServiceConfig;
public ExchangeService(ExchangeServiceConfig exchangeServiceConfig)
{
_exchangeServiceConfig = exchangeServiceConfig;
}
public async Task<decimal> GetExchangeRateFromPLNToEUR()
{
var amountInEUR = await _exchangeServiceConfig
.Url
.AppendPathSegment("exchange")
.SetQueryParams(new
{
to = "EUR",
from = "PLN"
})
.WithHeaders(new
{
x_rapidapi_key = _exchangeServiceConfig.XRapidAPIKey,
x_rapidapi_host = _exchangeServiceConfig.XRapidAPIHost,
useQueryString = true
}, replaceUnderscoreWithHyphen: true)
.GetStringAsync();
return decimal.Parse(amountInEUR);
}
}
} | 32.734177 | 91 | 0.595901 | [
"MIT"
] | ifs-and-whiles/net-core-integration-tests | NetCoreIntegrationTestsSample/NetCoreIntegrationTestsSample/Expenses/CreateExpenseConsumer.cs | 2,588 | C# |
namespace SoundDeck.Core.Interop
{
using System;
using System.Runtime.InteropServices;
/// <summary>
/// Provides interoperability for "combase.dll".
/// </summary>
public static class Combase
{
/// <summary>
/// Gets the activation factory for the specified runtime class.
/// </summary>
/// <param name="activatableClassId">The ID of the activatable class.</param>
/// <param name="iid">The reference ID of the interface.</param>
/// <param name="factory">The activation factory.</param>
[DllImport("combase.dll", PreserveSig = false)]
public static extern void RoGetActivationFactory(
[MarshalAs(UnmanagedType.HString)] string activatableClassId,
[In] ref Guid iid,
[Out, MarshalAs(UnmanagedType.IInspectable)] out object factory);
/// <summary>
/// Creates a new HSTRING based on the specified source string.
/// </summary>
/// <param name="src">A null-terminated string to use as the source for the new HSTRING. To create a new, empty, or NULL string, pass NULL for sourceString and 0 for length.</param>
/// <param name="length">The length of sourceString, in Unicode characters. Must be 0 if sourceString is NULL.</param>
/// <param name="hstring">A pointer to the newly created HSTRING, or NULL if an error occurs. Any existing content in string is overwritten. The HSTRING is a standard handle type..</param>
[DllImport("combase.dll", PreserveSig = false)]
public static extern void WindowsCreateString(
[MarshalAs(UnmanagedType.LPWStr)] string src,
[In] uint length,
[Out] out IntPtr hstring);
}
}
| 48.388889 | 196 | 0.648106 | [
"MIT"
] | GeekyEggo/SoundDeck | src/SoundDeck.Core/Interop/Combase.cs | 1,742 | C# |
using NServiceBus.Logging;
using System;
using System.Threading.Tasks;
using NServiceBus;
using NServiceBus.MessageRouting.RoutingSlips;
class Program
{
static ILog log = LogManager.GetLogger(typeof(Program));
static async Task Main()
{
Console.Title = "Samples.RoutingSlips.Sender";
var endpointConfiguration = new EndpointConfiguration("Samples.RoutingSlips.Sender");
endpointConfiguration.UsePersistence<LearningPersistence>();
endpointConfiguration.UseTransport<LearningTransport>();
#region enableRoutingSlips
endpointConfiguration.EnableFeature<RoutingSlips>();
#endregion
var endpoint = await Endpoint.Start(endpointConfiguration)
.ConfigureAwait(false);
Console.WriteLine("Press Enter to send a message");
Console.WriteLine("Press any other key to exit");
#region alternate
var toggle = false;
while (true)
{
var key = Console.ReadKey();
if (key.Key != ConsoleKey.Enter)
{
break;
}
if (toggle)
{
await SendToABC(endpoint).ConfigureAwait(false);
}
else
{
await SendToAC(endpoint).ConfigureAwait(false);
}
toggle = !toggle;
}
#endregion
await endpoint.Stop()
.ConfigureAwait(false);
}
#region SendAC
static Task SendToAC(IEndpointInstance endpoint)
{
var sequentialProcess = new SequentialProcess
{
StepAInfo = "Foo",
StepCInfo = "Baz",
};
log.Info("Sending message for step A, C");
return endpoint.Route(sequentialProcess, Guid.NewGuid(),
"Samples.RoutingSlips.StepA",
"Samples.RoutingSlips.StepC",
"Samples.RoutingSlips.ResultHost");
}
#endregion
#region SendABC
static Task SendToABC(IEndpointInstance endpoint)
{
#region multi-message-Send
var sequentialProcess = new SequentialProcess
{
StepAInfo = "Foo",
StepBInfo = "Bar",
StepCInfo = "Baz",
};
#endregion
log.Info("Sending message for step A, B, C");
return endpoint.Route(sequentialProcess, Guid.NewGuid(),
"Samples.RoutingSlips.StepA",
"Samples.RoutingSlips.StepB",
"Samples.RoutingSlips.StepC",
"Samples.RoutingSlips.ResultHost");
}
#endregion
} | 29.422222 | 94 | 0.567598 | [
"Apache-2.0"
] | Cogax/docs.particular.net | samples/routing-slips/MessageRouting_3/Sender/Program.cs | 2,559 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.NimbleStudio")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AmazonNimbleStudio. Amazon Nimble Studio is a virtual studio service that empowers visual effects, animation, and interactive content teams to create content securely within a scalable, private cloud service.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.7.4.43")] | 48.5625 | 288 | 0.756757 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/NimbleStudio/Properties/AssemblyInfo.cs | 1,554 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading.Tasks;
using Orleans.Transactions.Abstractions;
using Orleans.Core;
using Orleans.Runtime;
using Orleans.Storage;
namespace Orleans.Transactions
{
internal class TransactionalStateStorageProviderWrapper<TState> : ITransactionalStateStorage<TState>
where TState : class, new()
{
private readonly IStorageProvider storageProvider;
private readonly IGrainActivationContext context;
private readonly ConcurrentDictionary<string, IStorage<TransactionalStateRecord<TState>>> stateStorages;
public TransactionalStateStorageProviderWrapper(IStorageProvider storageProvider, IGrainActivationContext context)
{
this.storageProvider = storageProvider;
this.context = context;
this.stateStorages = new ConcurrentDictionary<string, IStorage<TransactionalStateRecord<TState>>>();
}
public async Task<TransactionalStorageLoadResponse<TState>> Load(string stateName)
{
IStorage<TransactionalStateRecord<TState>> stateStorage = GetStateStorage(stateName);
await stateStorage.ReadStateAsync();
return new TransactionalStorageLoadResponse<TState>(stateStorage.Etag, stateStorage.State.CommittedState, stateStorage.State.Metadata, stateStorage.State.PendingStates);
}
public async Task<string> Persist(string stateName, string expectedETag, string metadata, List<PendingTransactionState<TState>> statesToPrepare)
{
IStorage<TransactionalStateRecord<TState>> stateStorage = GetStateStorage(stateName);
if (stateStorage.Etag != expectedETag)
throw new ArgumentException(nameof(expectedETag), "Etag does not match");
stateStorage.State.Metadata = metadata;
foreach(PendingTransactionState<TState> pendingState in statesToPrepare.Where(s => !stateStorage.State.PendingStates.Contains(s)))
{
stateStorage.State.PendingStates.Add(pendingState);
}
await stateStorage.WriteStateAsync();
return stateStorage.Etag;
}
public async Task<string> Confirm(string stateName, string expectedETag, string metadata, string transactionIdToCommit)
{
IStorage<TransactionalStateRecord<TState>> stateStorage = GetStateStorage(stateName);
if (stateStorage.Etag != expectedETag)
throw new ArgumentException(nameof(expectedETag), "Etag does not match");
stateStorage.State.Metadata = metadata;
PendingTransactionState<TState> committedState = stateStorage.State.PendingStates.FirstOrDefault(pending => transactionIdToCommit == pending.TransactionId);
if (committedState != null)
{
stateStorage.State.CommittedTransactionId = committedState.TransactionId;
stateStorage.State.CommittedState = committedState.State;
stateStorage.State.PendingStates = stateStorage.State.PendingStates.Where(pending => pending.SequenceId > committedState.SequenceId).ToList();
}
await stateStorage.WriteStateAsync();
return stateStorage.Etag;
}
private IStorage<TransactionalStateRecord<TState>> GetStateStorage(string stateName)
{
return this.stateStorages.GetOrAdd(stateName, name => new StateStorageBridge<TransactionalStateRecord<TState>>(name, this.context.GrainInstance.GrainReference, storageProvider));
}
}
[Serializable]
public class TransactionalStateRecord<TState>
where TState : class, new()
{
public TState CommittedState { get; set; } = new TState();
public string CommittedTransactionId { get; set; }
public string Metadata { get; set; }
public List<PendingTransactionState<TState>> PendingStates { get; set; } = new List<PendingTransactionState<TState>>();
}
} | 48.807229 | 190 | 0.706492 | [
"MIT"
] | seralexeev/orleans | src/Orleans.Transactions/State/TransactionalStateStorageProviderWrapper.cs | 4,053 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Aula2505
{
public partial class About : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
} | 17.352941 | 60 | 0.677966 | [
"Apache-2.0"
] | gabyjabonski/Aulas-Asp.net | Aula2505/Aula2505/About.aspx.cs | 297 | C# |
// Copyright (c) 2013 SharpYaml - Alexandre Mutel
//
// 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.
//
// -------------------------------------------------------------------------------
// SharpYaml is a fork of YamlDotNet https://github.com/aaubry/YamlDotNet
// published with the following license:
// -------------------------------------------------------------------------------
//
// Copyright (c) 2008, 2009, 2010, 2011, 2012 Antoine Aubry
//
// 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;
using System.Globalization;
namespace SharpYaml.Events
{
/// <summary>
/// Represents a document end event.
/// </summary>
public class DocumentEnd : ParsingEvent, IDocumentEnd
{
/// <summary>
/// Gets a value indicating the variation of depth caused by this event.
/// The value can be either -1, 0 or 1. For start events, it will be 1,
/// for end events, it will be -1, and for the remaining events, it will be 0.
/// </summary>
public override int NestingIncrease {
get {
return -1;
}
}
/// <summary>
/// Gets the event type, which allows for simpler type comparisons.
/// </summary>
internal override EventType Type {
get {
return EventType.YAML_DOCUMENT_END_EVENT;
}
}
private readonly bool isImplicit;
/// <summary>
/// Gets a value indicating whether this instance is implicit.
/// </summary>
/// <value>
/// <c>true</c> if this instance is implicit; otherwise, <c>false</c>.
/// </value>
public bool IsImplicit
{
get
{
return isImplicit;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="DocumentEnd"/> class.
/// </summary>
/// <param name="isImplicit">Indicates whether the event is implicit.</param>
/// <param name="start">The start position of the event.</param>
/// <param name="end">The end position of the event.</param>
public DocumentEnd(bool isImplicit, Mark start, Mark end)
: base(start, end)
{
this.isImplicit = isImplicit;
}
/// <summary>
/// Initializes a new instance of the <see cref="DocumentEnd"/> class.
/// </summary>
/// <param name="isImplicit">Indicates whether the event is implicit.</param>
public DocumentEnd(bool isImplicit)
: this(isImplicit, Mark.Empty, Mark.Empty)
{
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"Document end [isImplicit = {0}]",
isImplicit
);
}
}
} | 38.503937 | 105 | 0.664826 | [
"MIT"
] | vasily-kirichenko/SharpYaml | SharpYaml/Events/DocumentEnd.cs | 4,890 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using MLAPI;
using MLAPI.Extensions;
using MLAPI.NetworkVariable;
namespace IdlessChaye.TouhouWaltz
{
public class Bullet : NetworkBehaviour
{
public enum BulletType
{
Big,
Middle,
Small
}
public ulong owner;
NetworkObjectPool _poolToReturn;
NetworkVariableFloat _size = new NetworkVariableFloat();
public void Config(ulong owner, float lifetime, NetworkObjectPool poolToReturn, BulletType type)
{
this.owner = owner;
_poolToReturn = poolToReturn;
InitByType(type);
if (IsServer)
{
// This is bad code don't use invoke.
Invoke(nameof(DestroyBullet), lifetime);
}
}
private void InitByType(BulletType type)
{
switch (type)
{
case BulletType.Big:
_size.Value = Const.BulletSizeBig;
break;
case BulletType.Middle:
_size.Value = Const.BulletSizeMiddle;
break;
case BulletType.Small:
_size.Value = Const.BulletSizeSmall;
break;
}
}
public override void NetworkStart()
{
transform.localScale = _size.Value * Vector3.one;
}
public void DestroyBullet()
{
if (!NetworkObject.IsSpawned)
{
return;
}
//Vector3 pos = transform.position;
//pos.z = -2;
//GameObject ex = Instantiate(explosionParticle, pos, Quaternion.identity);
//Destroy(ex, 0.5f);
NetworkObject.Despawn();
_poolToReturn.ReturnNetworkObject(NetworkObject);
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (!IsServer || !NetworkObject.IsSpawned)
return;
var player = collision.GetComponent<Player>();
if (player != null && player.PlayerID != owner)
{
player.TakeDamage(1);
DestroyBullet();
}
}
}
}
| 19.433333 | 98 | 0.683819 | [
"MIT"
] | IdlessChaye/TouhouWaltz | Assets/TouhouWaltz/Scripts/TouhouWaltz/Battle/Bullet.cs | 1,749 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LeetCode.Naive.Problems
{
/// <summary>
/// Problem: https://leetcode.com/problems/maximum-length-of-repeated-subarray/
/// Submission: https://leetcode.com/submissions/detail/250028236/
/// </summary>
internal class P0718
{
public class Solution
{
public int FindLength(int[] A, int[] B)
{
var map = new int[A.Length][];
var max = int.MinValue;
for (int i = 0; i < A.Length; i++)
{
map[i] = new int[B.Length];
for (int j = 0; j < B.Length; j++)
{
if (A[i] != B[j])
{
map[i][j] = 0;
}
else
{
if (i == 0 || j == 0)
map[i][j] = 1;
else
map[i][j] = map[i - 1][j - 1] + 1;
}
max = Math.Max(max, map[i][j]);
}
}
//return 0;
return max;
}
}
}
}
| 21.88 | 85 | 0.418647 | [
"MIT"
] | viacheslave/leetcode-naive | c#/Problems/P0718.cs | 1,094 | 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.
// Code taken from ASP.NET file xsp\System\Web\httpserverutility.cs
// Don't entity encode high chars (160 to 256)
#define ENTITY_ENCODE_HIGH_ASCII_CHARS
namespace System.Windows.Forms
{
using System;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Drawing;
using System.Reflection;
using System.Globalization;
using System.ComponentModel;
using System.Windows.Forms.Internal;
using System.Security.Permissions;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell"]/*' />
/// <devdoc>
/// <para>Identifies a cell in the dataGridView.</para>
/// </devdoc>
[
TypeConverterAttribute(typeof(DataGridViewCellConverter))
]
public abstract class DataGridViewCell : DataGridViewElement, ICloneable, IDisposable
{
private const TextFormatFlags textFormatSupportedFlags = TextFormatFlags.SingleLine | /*TextFormatFlags.NoFullWidthCharacterBreak |*/ TextFormatFlags.WordBreak | TextFormatFlags.NoPrefix;
private const int DATAGRIDVIEWCELL_constrastThreshold = 1000;
private const int DATAGRIDVIEWCELL_highConstrastThreshold = 2000;
private const int DATAGRIDVIEWCELL_maxToolTipLength = 288;
private const int DATAGRIDVIEWCELL_maxToolTipCutOff = 256;
private const int DATAGRIDVIEWCELL_toolTipEllipsisLength = 3;
private const string DATAGRIDVIEWCELL_toolTipEllipsis = "...";
private const byte DATAGRIDVIEWCELL_flagAreaNotSet = 0x00;
private const byte DATAGRIDVIEWCELL_flagDataArea = 0x01;
private const byte DATAGRIDVIEWCELL_flagErrorArea = 0x02;
internal const byte DATAGRIDVIEWCELL_iconMarginWidth = 4; // 4 pixels of margin on the left and right of icons
internal const byte DATAGRIDVIEWCELL_iconMarginHeight = 4; // 4 pixels of margin on the top and bottom of icons
private const byte DATAGRIDVIEWCELL_iconsWidth = 12; // all icons are 12 pixels wide - make sure that it stays that way
private const byte DATAGRIDVIEWCELL_iconsHeight = 11; // all icons are 11 pixels tall - make sure that it stays that way
private static bool isScalingInitialized = false;
internal static byte iconsWidth = DATAGRIDVIEWCELL_iconsWidth;
internal static byte iconsHeight = DATAGRIDVIEWCELL_iconsHeight;
internal static readonly int PropCellValue = PropertyStore.CreateKey();
private static readonly int PropCellContextMenuStrip = PropertyStore.CreateKey();
private static readonly int PropCellErrorText = PropertyStore.CreateKey();
private static readonly int PropCellStyle = PropertyStore.CreateKey();
private static readonly int PropCellValueType = PropertyStore.CreateKey();
private static readonly int PropCellTag = PropertyStore.CreateKey();
private static readonly int PropCellToolTipText = PropertyStore.CreateKey();
private static readonly int PropCellAccessibilityObject = PropertyStore.CreateKey();
private static Bitmap errorBmp = null;
private PropertyStore propertyStore; // Contains all properties that are not always set.
private DataGridViewRow owningRow;
private DataGridViewColumn owningColumn;
private static Type stringType = typeof(string); // cache the string type for performance
private byte flags; // see DATAGRIDVIEWCELL_flag* consts above
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.DataGridViewCell"]/*' />
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Windows.Forms.DataGridViewCell'/> class.
/// </para>
/// </devdoc>
protected DataGridViewCell() : base()
{
if (!isScalingInitialized) {
if (DpiHelper.IsScalingRequired) {
iconsWidth = (byte)DpiHelper.LogicalToDeviceUnitsX(DATAGRIDVIEWCELL_iconsWidth);
iconsHeight = (byte)DpiHelper.LogicalToDeviceUnitsY(DATAGRIDVIEWCELL_iconsHeight);
}
isScalingInitialized = true;
}
this.propertyStore = new PropertyStore();
this.StateInternal = DataGridViewElementStates.None;
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.Finalize"]/*' />
~DataGridViewCell()
{
Dispose(false);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.AccessibilityObject"]/*' />
[
Browsable(false)
]
public AccessibleObject AccessibilityObject
{
get
{
AccessibleObject result = (AccessibleObject) this.Properties.GetObject(PropCellAccessibilityObject);
if (result == null)
{
result = this.CreateAccessibilityInstance();
this.Properties.SetObject(PropCellAccessibilityObject, result);
}
return result;
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.ColumnIndex"]/*' />
/// <devdoc>
/// <para>Gets or sets the Index of a column in the <see cref='System.Windows.Forms.DataGrid'/> control.</para>
/// </devdoc>
public int ColumnIndex
{
get
{
if (this.owningColumn == null)
{
return -1;
}
return this.owningColumn.Index;
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.ContentBounds"]/*' />
[
Browsable(false)
]
public Rectangle ContentBounds
{
get
{
return GetContentBounds(this.RowIndex);
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.ContextMenuStrip"]/*' />
[
DefaultValue(null)
]
public virtual ContextMenuStrip ContextMenuStrip
{
get
{
return GetContextMenuStrip(this.RowIndex);
}
set
{
this.ContextMenuStripInternal = value;
}
}
private ContextMenuStrip ContextMenuStripInternal
{
get
{
return (ContextMenuStrip)this.Properties.GetObject(PropCellContextMenuStrip);
}
set
{
ContextMenuStrip oldValue = (ContextMenuStrip)this.Properties.GetObject(PropCellContextMenuStrip);
if (oldValue != value)
{
EventHandler disposedHandler = new EventHandler(DetachContextMenuStrip);
if (oldValue != null)
{
oldValue.Disposed -= disposedHandler;
}
this.Properties.SetObject(PropCellContextMenuStrip, value);
if (value != null)
{
value.Disposed += disposedHandler;
}
if (this.DataGridView != null)
{
this.DataGridView.OnCellContextMenuStripChanged(this);
}
}
}
}
private byte CurrentMouseLocation
{
get
{
return (byte) (this.flags & (DATAGRIDVIEWCELL_flagDataArea | DATAGRIDVIEWCELL_flagErrorArea));
}
set
{
this.flags = (byte)(this.flags & ~(DATAGRIDVIEWCELL_flagDataArea | DATAGRIDVIEWCELL_flagErrorArea));
this.flags |= value;
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.DefaultNewRowValue"]/*' />
[
Browsable(false)
]
public virtual object DefaultNewRowValue
{
get
{
return null;
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.Displayed"]/*' />
[
Browsable(false)
]
public virtual bool Displayed
{
get
{
Debug.Assert((this.State & DataGridViewElementStates.Displayed) == 0);
if (this.DataGridView == null)
{
// No detached element is displayed.
return false;
}
if (this.DataGridView != null && this.RowIndex >= 0 && this.ColumnIndex >= 0)
{
Debug.Assert(this.DataGridView.Rows.GetRowState(this.RowIndex) == this.DataGridView.Rows.SharedRow(this.RowIndex).State);
return this.owningColumn.Displayed && this.owningRow.Displayed;
}
return false;
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.EditedFormattedValue"]/*' />
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Advanced)
]
public object EditedFormattedValue
{
get
{
if (this.DataGridView == null)
{
return null;
}
Debug.Assert(this.RowIndex >= -1);
DataGridViewCellStyle dataGridViewCellStyle = GetInheritedStyle(null, this.RowIndex, false);
return GetEditedFormattedValue(GetValue(this.RowIndex), this.RowIndex, ref dataGridViewCellStyle, DataGridViewDataErrorContexts.Formatting);
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.EditType"]/*' />
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Advanced)
]
public virtual Type EditType
{
get
{
return typeof(System.Windows.Forms.DataGridViewTextBoxEditingControl);
}
}
private static Bitmap ErrorBitmap
{
get
{
if (errorBmp == null)
{
errorBmp = GetBitmap("DataGridViewRow.error.bmp");
}
return errorBmp;
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.ErrorIconBounds"]/*' />
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Advanced),
SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods") // ErrorIconBounds/GetErrorIconBounds existence is intentional
]
public Rectangle ErrorIconBounds
{
get
{
return GetErrorIconBounds(this.RowIndex);
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.ErrorText"]/*' />
[
Browsable(false)
]
public string ErrorText
{
get
{
return GetErrorText(this.RowIndex);
}
set
{
this.ErrorTextInternal = value;
}
}
private string ErrorTextInternal
{
get
{
object errorText = this.Properties.GetObject(PropCellErrorText);
return (errorText == null) ? string.Empty : (string)errorText;
}
set
{
string errorText = this.ErrorTextInternal;
if (!string.IsNullOrEmpty(value) || this.Properties.ContainsObject(PropCellErrorText))
{
this.Properties.SetObject(PropCellErrorText, value);
}
if (this.DataGridView != null && !errorText.Equals(this.ErrorTextInternal))
{
this.DataGridView.OnCellErrorTextChanged(this);
}
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.FormattedValue"]/*' />
[
Browsable(false)
]
public object FormattedValue
{
get
{
if (this.DataGridView == null)
{
return null;
}
Debug.Assert(this.RowIndex >= -1);
DataGridViewCellStyle dataGridViewCellStyle = GetInheritedStyle(null, this.RowIndex, false);
return GetFormattedValue(this.RowIndex, ref dataGridViewCellStyle, DataGridViewDataErrorContexts.Formatting);
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.FormattedValueType"]/*' />
[
Browsable(false)
]
public virtual Type FormattedValueType
{
get
{
return this.ValueType;
}
}
private TypeConverter FormattedValueTypeConverter
{
get
{
TypeConverter formattedValueTypeConverter = null;
if (this.FormattedValueType != null)
{
if (this.DataGridView != null)
{
formattedValueTypeConverter = this.DataGridView.GetCachedTypeConverter(this.FormattedValueType);
}
else
{
formattedValueTypeConverter = TypeDescriptor.GetConverter(this.FormattedValueType);
}
}
return formattedValueTypeConverter;
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.Frozen"]/*' />
[
Browsable(false)
]
public virtual bool Frozen
{
get
{
Debug.Assert((this.State & DataGridViewElementStates.Frozen) == 0);
if (this.DataGridView != null && this.RowIndex >= 0 && this.ColumnIndex >= 0)
{
Debug.Assert(this.DataGridView.Rows.GetRowState(this.RowIndex) == this.DataGridView.Rows.SharedRow(this.RowIndex).State);
return this.owningColumn.Frozen && this.owningRow.Frozen;
}
else if (this.owningRow != null && (this.owningRow.DataGridView == null || this.RowIndex >= 0))
{
return this.owningRow.Frozen;
}
return false;
}
}
internal bool HasErrorText
{
get
{
return this.Properties.ContainsObject(PropCellErrorText) && this.Properties.GetObject(PropCellErrorText) != null;
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.HasStyle"]/*' />
[
Browsable(false)
]
public bool HasStyle
{
get
{
return this.Properties.ContainsObject(PropCellStyle) && this.Properties.GetObject(PropCellStyle) != null;
}
}
internal bool HasToolTipText
{
get
{
return this.Properties.ContainsObject(PropCellToolTipText) && this.Properties.GetObject(PropCellToolTipText) != null;
}
}
internal bool HasValue
{
get
{
return this.Properties.ContainsObject(PropCellValue) && this.Properties.GetObject(PropCellValue) != null;
}
}
internal virtual bool HasValueType
{
get
{
return this.Properties.ContainsObject(PropCellValueType) && this.Properties.GetObject(PropCellValueType) != null;
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.InheritedState"]/*' />
[
Browsable(false),
SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods") // InheritedState/GetInheritedState existence is intentional
]
public DataGridViewElementStates InheritedState
{
get
{
return GetInheritedState(this.RowIndex);
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.InheritedStyle"]/*' />
[
Browsable(false),
SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods") // InheritedStyle/GetInheritedStyle existence is intentional
]
public DataGridViewCellStyle InheritedStyle
{
get
{
// this.RowIndex could be -1 if:
// - the developer makes a mistake & calls dataGridView1.Rows.SharedRow(y).Cells(x).InheritedStyle.
// - the InheritedStyle of a ColumnHeaderCell is accessed.
return GetInheritedStyleInternal(this.RowIndex);
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.IsInEditMode"]/*' />
[
Browsable(false)
]
public bool IsInEditMode
{
get
{
if (this.DataGridView == null)
{
return false;
}
if (this.RowIndex == -1)
{
throw new InvalidOperationException(string.Format(SR.DataGridView_InvalidOperationOnSharedCell));
}
Point ptCurrentCell = this.DataGridView.CurrentCellAddress;
return ptCurrentCell.X != -1 &&
ptCurrentCell.X == this.ColumnIndex &&
ptCurrentCell.Y == this.RowIndex &&
this.DataGridView.IsCurrentCellInEditMode;
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.OwningColumn"]/*' />
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Advanced)
]
public DataGridViewColumn OwningColumn
{
get
{
return this.owningColumn;
}
}
internal DataGridViewColumn OwningColumnInternal
{
set
{
this.owningColumn = value;
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.OwningRow"]/*' />
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Advanced)
]
public DataGridViewRow OwningRow
{
get
{
return this.owningRow;
}
}
internal DataGridViewRow OwningRowInternal
{
set
{
this.owningRow = value;
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.PreferredSize"]/*' />
[
Browsable(false)
]
public Size PreferredSize
{
get
{
return GetPreferredSize(this.RowIndex);
}
}
internal PropertyStore Properties
{
get
{
return this.propertyStore;
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.ReadOnly"]/*' />
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public virtual bool ReadOnly
{
get
{
if ((this.State & DataGridViewElementStates.ReadOnly) != 0)
{
return true;
}
if (this.owningRow != null && (this.owningRow.DataGridView == null || this.RowIndex >= 0) && this.owningRow.ReadOnly)
{
return true;
}
if (this.DataGridView != null && this.RowIndex >= 0 && this.ColumnIndex >= 0)
{
Debug.Assert(this.DataGridView.Rows.GetRowState(this.RowIndex) == this.DataGridView.Rows.SharedRow(this.RowIndex).State);
return this.owningColumn.ReadOnly;
}
return false;
}
set
{
if (this.DataGridView != null)
{
if (this.RowIndex == -1)
{
throw new InvalidOperationException(string.Format(SR.DataGridView_InvalidOperationOnSharedCell));
}
Debug.Assert(this.ColumnIndex >= 0);
// When the whole grid is read-only, we ignore the request.
if (value != this.ReadOnly && !this.DataGridView.ReadOnly)
{
this.DataGridView.OnDataGridViewElementStateChanging(this, -1, DataGridViewElementStates.ReadOnly);
this.DataGridView.SetReadOnlyCellCore(this.ColumnIndex, this.RowIndex, value); // this may trigger a call to set_ReadOnlyInternal
}
}
else
{
if (this.owningRow == null)
{
if (value != this.ReadOnly)
{
// We do not allow the read-only flag of a cell to be changed before it is added to a row.
throw new InvalidOperationException(string.Format(SR.DataGridViewCell_CannotSetReadOnlyState));
}
}
else
{
this.owningRow.SetReadOnlyCellCore(this, value);
}
}
}
}
internal bool ReadOnlyInternal
{
set
{
Debug.Assert(value != this.ReadOnly);
if (value)
{
this.StateInternal = this.State | DataGridViewElementStates.ReadOnly;
}
else
{
this.StateInternal = this.State & ~DataGridViewElementStates.ReadOnly;
}
if (this.DataGridView != null)
{
this.DataGridView.OnDataGridViewElementStateChanged(this, -1, DataGridViewElementStates.ReadOnly);
}
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.Resizable"]/*' />
[
Browsable(false)
]
public virtual bool Resizable
{
get
{
Debug.Assert((this.State & DataGridViewElementStates.Resizable) == 0);
if (this.owningRow != null && (this.owningRow.DataGridView == null || this.RowIndex >= 0) && this.owningRow.Resizable == DataGridViewTriState.True)
{
return true;
}
if (this.DataGridView != null && this.RowIndex >= 0 && this.ColumnIndex >= 0)
{
Debug.Assert(this.DataGridView.Rows.GetRowState(this.RowIndex) == this.DataGridView.Rows.SharedRow(this.RowIndex).State);
return this.owningColumn.Resizable == DataGridViewTriState.True;
}
return false;
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.RowIndex"]/*' />
/// <devdoc>
/// <para>Gets or sets the index of a row in the <see cref='System.Windows.Forms.DataGrid'/> control.</para>
/// </devdoc>
[
Browsable(false)
]
public int RowIndex
{
get
{
if (this.owningRow == null)
{
return -1;
}
return this.owningRow.Index;
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.Selected"]/*' />
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public virtual bool Selected
{
get
{
if ((this.State & DataGridViewElementStates.Selected) != 0)
{
return true;
}
if (this.owningRow != null && (this.owningRow.DataGridView == null || this.RowIndex >= 0) && this.owningRow.Selected)
{
return true;
}
if (this.DataGridView != null && this.RowIndex >= 0 && this.ColumnIndex >= 0)
{
Debug.Assert(this.DataGridView.Rows.GetRowState(this.RowIndex) == this.DataGridView.Rows.SharedRow(this.RowIndex).State);
return this.owningColumn.Selected;
}
return false;
}
set
{
if (this.DataGridView != null)
{
if (this.RowIndex == -1)
{
throw new InvalidOperationException(string.Format(SR.DataGridView_InvalidOperationOnSharedCell));
}
Debug.Assert(this.ColumnIndex >= 0);
this.DataGridView.SetSelectedCellCoreInternal(this.ColumnIndex, this.RowIndex, value); // this may trigger a call to set_SelectedInternal
}
else if (value)
{
// We do not allow the selection of a cell to be set before the row gets added to the dataGridView.
throw new InvalidOperationException(string.Format(SR.DataGridViewCell_CannotSetSelectedState));
}
}
}
internal bool SelectedInternal
{
set
{
Debug.Assert(value != this.Selected);
if (value)
{
this.StateInternal = this.State | DataGridViewElementStates.Selected;
}
else
{
this.StateInternal = this.State & ~DataGridViewElementStates.Selected;
}
if (this.DataGridView != null)
{
this.DataGridView.OnDataGridViewElementStateChanged(this, -1, DataGridViewElementStates.Selected);
}
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.Size"]/*' />
[
Browsable(false),
SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods") // Size/GetSize existence is intentional
]
public Size Size
{
get
{
return GetSize(this.RowIndex);
}
}
internal Rectangle StdBorderWidths
{
get
{
if (this.DataGridView != null)
{
DataGridViewAdvancedBorderStyle dataGridViewAdvancedBorderStylePlaceholder = new DataGridViewAdvancedBorderStyle(), dgvabsEffective;
dgvabsEffective = AdjustCellBorderStyle(this.DataGridView.AdvancedCellBorderStyle,
dataGridViewAdvancedBorderStylePlaceholder,
false /*singleVerticalBorderAdded*/,
false /*singleHorizontalBorderAdded*/,
false /*isFirstDisplayedColumn*/,
false /*isFirstDisplayedRow*/);
return BorderWidths(dgvabsEffective);
}
else
{
return Rectangle.Empty;
}
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.Style"]/*' />
[
Browsable(true)
]
public DataGridViewCellStyle Style
{
get
{
DataGridViewCellStyle dgvcs = (DataGridViewCellStyle)this.Properties.GetObject(PropCellStyle);
if (dgvcs == null)
{
dgvcs = new DataGridViewCellStyle();
dgvcs.AddScope(this.DataGridView, DataGridViewCellStyleScopes.Cell);
this.Properties.SetObject(PropCellStyle, dgvcs);
}
return dgvcs;
}
set
{
DataGridViewCellStyle dgvcs = null;
if (this.HasStyle)
{
dgvcs = this.Style;
dgvcs.RemoveScope(DataGridViewCellStyleScopes.Cell);
}
if (value != null || this.Properties.ContainsObject(PropCellStyle))
{
if (value != null)
{
value.AddScope(this.DataGridView, DataGridViewCellStyleScopes.Cell);
}
this.Properties.SetObject(PropCellStyle, value);
}
if (((dgvcs != null && value == null) ||
(dgvcs == null && value != null) ||
(dgvcs != null && value != null && !dgvcs.Equals(this.Style))) && this.DataGridView != null)
{
this.DataGridView.OnCellStyleChanged(this);
}
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.Tag"]/*' />
[
SRCategory(nameof(SR.CatData)),
Localizable(false),
Bindable(true),
SRDescription(nameof(SR.ControlTagDescr)),
DefaultValue(null),
TypeConverter(typeof(StringConverter))
]
public object Tag
{
get
{
return this.Properties.GetObject(PropCellTag);
}
set
{
if (value != null || this.Properties.ContainsObject(PropCellTag))
{
this.Properties.SetObject(PropCellTag, value);
}
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.ToolTipText"]/*' />
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public string ToolTipText
{
get
{
return GetToolTipText(this.RowIndex);
}
set
{
this.ToolTipTextInternal = value;
}
}
private string ToolTipTextInternal
{
get
{
object toolTipText = this.Properties.GetObject(PropCellToolTipText);
return (toolTipText == null) ? string.Empty : (string)toolTipText;
}
set
{
string toolTipText = this.ToolTipTextInternal;
if (!String.IsNullOrEmpty(value) || this.Properties.ContainsObject(PropCellToolTipText))
{
this.Properties.SetObject(PropCellToolTipText, value);
}
if (this.DataGridView != null && !toolTipText.Equals(this.ToolTipTextInternal))
{
this.DataGridView.OnCellToolTipTextChanged(this);
}
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.Value"]/*' />
[
Browsable(false)
]
public object Value
{
get
{
Debug.Assert(this.RowIndex >= -1);
return GetValue(this.RowIndex);
}
set
{
Debug.Assert(this.RowIndex >= -1);
SetValue(this.RowIndex, value);
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.ValueType"]/*' />
[
Browsable(false)
]
public virtual Type ValueType
{
get
{
Type cellValueType = (Type) this.Properties.GetObject(PropCellValueType);
if (cellValueType == null && this.OwningColumn != null)
{
cellValueType = this.OwningColumn.ValueType;
}
return cellValueType;
}
set
{
if (value != null || this.Properties.ContainsObject(PropCellValueType))
{
this.Properties.SetObject(PropCellValueType, value);
}
}
}
private TypeConverter ValueTypeConverter
{
get
{
TypeConverter valueTypeConverter = null;
if (this.OwningColumn != null)
{
valueTypeConverter = this.OwningColumn.BoundColumnConverter;
}
if (valueTypeConverter == null && this.ValueType != null)
{
if (this.DataGridView != null)
{
valueTypeConverter = this.DataGridView.GetCachedTypeConverter(this.ValueType);
}
else
{
valueTypeConverter = TypeDescriptor.GetConverter(this.ValueType);
}
}
return valueTypeConverter;
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.Visible"]/*' />
[
Browsable(false)
]
public virtual bool Visible
{
get
{
Debug.Assert((this.State & DataGridViewElementStates.Visible) == 0);
if (this.DataGridView != null && this.RowIndex >= 0 && this.ColumnIndex >= 0)
{
Debug.Assert(this.DataGridView.Rows.GetRowState(this.RowIndex) == this.DataGridView.Rows.SharedRow(this.RowIndex).State);
return this.owningColumn.Visible && this.owningRow.Visible;
}
else if (this.owningRow != null && (this.owningRow.DataGridView == null || this.RowIndex >= 0))
{
return this.owningRow.Visible;
}
return false;
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.AdjustCellBorderStyle"]/*' />
[
EditorBrowsable(EditorBrowsableState.Advanced)
]
public virtual DataGridViewAdvancedBorderStyle AdjustCellBorderStyle(DataGridViewAdvancedBorderStyle dataGridViewAdvancedBorderStyleInput,
DataGridViewAdvancedBorderStyle dataGridViewAdvancedBorderStylePlaceholder,
bool singleVerticalBorderAdded,
bool singleHorizontalBorderAdded,
bool isFirstDisplayedColumn,
bool isFirstDisplayedRow)
{
switch (dataGridViewAdvancedBorderStyleInput.All)
{
case DataGridViewAdvancedCellBorderStyle.OutsetPartial:
Debug.Fail("DataGridViewRow.AdjustCellBorderStyle - Unexpected DataGridViewAdvancedCellBorderStyle.OutsetPartial");
break;
case DataGridViewAdvancedCellBorderStyle.Single:
if (this.DataGridView != null && this.DataGridView.RightToLeftInternal)
{
dataGridViewAdvancedBorderStylePlaceholder.LeftInternal = DataGridViewAdvancedCellBorderStyle.Single;
dataGridViewAdvancedBorderStylePlaceholder.RightInternal = (isFirstDisplayedColumn && singleVerticalBorderAdded) ? DataGridViewAdvancedCellBorderStyle.Single : DataGridViewAdvancedCellBorderStyle.None;
}
else
{
dataGridViewAdvancedBorderStylePlaceholder.LeftInternal = (isFirstDisplayedColumn && singleVerticalBorderAdded) ? DataGridViewAdvancedCellBorderStyle.Single : DataGridViewAdvancedCellBorderStyle.None;
dataGridViewAdvancedBorderStylePlaceholder.RightInternal = DataGridViewAdvancedCellBorderStyle.Single;
}
dataGridViewAdvancedBorderStylePlaceholder.TopInternal = (isFirstDisplayedRow && singleHorizontalBorderAdded) ? DataGridViewAdvancedCellBorderStyle.Single : DataGridViewAdvancedCellBorderStyle.None;
dataGridViewAdvancedBorderStylePlaceholder.BottomInternal = DataGridViewAdvancedCellBorderStyle.Single;
return dataGridViewAdvancedBorderStylePlaceholder;
case DataGridViewAdvancedCellBorderStyle.NotSet:
if (this.DataGridView != null && this.DataGridView.AdvancedCellBorderStyle == dataGridViewAdvancedBorderStyleInput)
{
switch (this.DataGridView.CellBorderStyle)
{
case DataGridViewCellBorderStyle.SingleVertical:
if (this.DataGridView.RightToLeftInternal)
{
dataGridViewAdvancedBorderStylePlaceholder.LeftInternal = DataGridViewAdvancedCellBorderStyle.Single;
dataGridViewAdvancedBorderStylePlaceholder.RightInternal = (isFirstDisplayedColumn && singleVerticalBorderAdded) ? DataGridViewAdvancedCellBorderStyle.Single : DataGridViewAdvancedCellBorderStyle.None;
}
else
{
dataGridViewAdvancedBorderStylePlaceholder.LeftInternal = (isFirstDisplayedColumn && singleVerticalBorderAdded) ? DataGridViewAdvancedCellBorderStyle.Single : DataGridViewAdvancedCellBorderStyle.None;
dataGridViewAdvancedBorderStylePlaceholder.RightInternal = DataGridViewAdvancedCellBorderStyle.Single;
}
dataGridViewAdvancedBorderStylePlaceholder.TopInternal = DataGridViewAdvancedCellBorderStyle.None;
dataGridViewAdvancedBorderStylePlaceholder.BottomInternal = DataGridViewAdvancedCellBorderStyle.None;
return dataGridViewAdvancedBorderStylePlaceholder;
case DataGridViewCellBorderStyle.SingleHorizontal:
dataGridViewAdvancedBorderStylePlaceholder.LeftInternal = DataGridViewAdvancedCellBorderStyle.None;
dataGridViewAdvancedBorderStylePlaceholder.RightInternal = DataGridViewAdvancedCellBorderStyle.None;
dataGridViewAdvancedBorderStylePlaceholder.TopInternal = (isFirstDisplayedRow && singleHorizontalBorderAdded) ? DataGridViewAdvancedCellBorderStyle.Single : DataGridViewAdvancedCellBorderStyle.None;
dataGridViewAdvancedBorderStylePlaceholder.BottomInternal = DataGridViewAdvancedCellBorderStyle.Single;
return dataGridViewAdvancedBorderStylePlaceholder;
}
}
break;
}
return dataGridViewAdvancedBorderStyleInput;
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.BorderWidths"]/*' />
protected virtual Rectangle BorderWidths(DataGridViewAdvancedBorderStyle advancedBorderStyle)
{
Rectangle rect = new Rectangle();
rect.X = (advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.None) ? 0 : 1;
if (advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.OutsetDouble || advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.InsetDouble)
{
rect.X++;
}
rect.Y = (advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.None) ? 0 : 1;
if (advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.OutsetDouble || advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.InsetDouble)
{
rect.Y++;
}
rect.Width = (advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.None) ? 0 : 1;
if (advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.OutsetDouble || advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.InsetDouble)
{
rect.Width++;
}
rect.Height = (advancedBorderStyle.Bottom == DataGridViewAdvancedCellBorderStyle.None) ? 0 : 1;
if (advancedBorderStyle.Bottom == DataGridViewAdvancedCellBorderStyle.OutsetDouble || advancedBorderStyle.Bottom == DataGridViewAdvancedCellBorderStyle.InsetDouble)
{
rect.Height++;
}
if (this.owningColumn != null)
{
if (this.DataGridView != null && this.DataGridView.RightToLeftInternal)
{
rect.X += this.owningColumn.DividerWidth;
}
else
{
rect.Width += this.owningColumn.DividerWidth;
}
}
if (this.owningRow != null)
{
rect.Height += this.owningRow.DividerHeight;
}
return rect;
}
// Called when the row that owns the editing control gets unshared.
// Too late in the product cycle to make this a public method.
internal virtual void CacheEditingControl()
{
}
/* Unused at this point.
internal DataGridViewElementStates CellStateFromColumnRowStates()
{
Debug.Assert(this.DataGridView != null);
Debug.Assert(this.RowIndex >= 0);
return CellStateFromColumnRowStates(this.owningRow.State);
}*/
internal DataGridViewElementStates CellStateFromColumnRowStates(DataGridViewElementStates rowState)
{
Debug.Assert(this.DataGridView != null);
Debug.Assert(this.ColumnIndex >= 0);
DataGridViewElementStates orFlags = DataGridViewElementStates.ReadOnly | DataGridViewElementStates.Resizable | DataGridViewElementStates.Selected;
DataGridViewElementStates andFlags = DataGridViewElementStates.Displayed | DataGridViewElementStates.Frozen | DataGridViewElementStates.Visible;
DataGridViewElementStates cellState = (this.owningColumn.State & orFlags);
cellState |= (rowState & orFlags);
cellState |= ((this.owningColumn.State & andFlags) & (rowState & andFlags));
return cellState;
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.ClickUnsharesRow"]/*' />
[
SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly") // Unshares is OK.
]
protected virtual bool ClickUnsharesRow(DataGridViewCellEventArgs e)
{
return false;
}
internal bool ClickUnsharesRowInternal(DataGridViewCellEventArgs e)
{
return ClickUnsharesRow(e);
}
internal void CloneInternal(DataGridViewCell dataGridViewCell)
{
if (this.HasValueType)
{
dataGridViewCell.ValueType = this.ValueType;
}
if (this.HasStyle)
{
dataGridViewCell.Style = new DataGridViewCellStyle(this.Style);
}
if (this.HasErrorText)
{
dataGridViewCell.ErrorText = this.ErrorTextInternal;
}
if (this.HasToolTipText)
{
dataGridViewCell.ToolTipText = this.ToolTipTextInternal;
}
if (this.ContextMenuStripInternal != null)
{
dataGridViewCell.ContextMenuStrip = this.ContextMenuStripInternal.Clone();
}
dataGridViewCell.StateInternal = this.State & ~DataGridViewElementStates.Selected;
dataGridViewCell.Tag = this.Tag;
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.Clone"]/*' />
public virtual object Clone()
{
DataGridViewCell dataGridViewCell = (DataGridViewCell) System.Activator.CreateInstance(this.GetType());
CloneInternal(dataGridViewCell);
return dataGridViewCell;
}
internal static int ColorDistance(Color color1, Color color2)
{
int deltaR = color1.R - color2.R;
int deltaG = color1.G - color2.G;
int deltaB = color1.B - color2.B;
return deltaR * deltaR + deltaG * deltaG + deltaB * deltaB;
}
internal void ComputeBorderStyleCellStateAndCellBounds(int rowIndex,
out DataGridViewAdvancedBorderStyle dgvabsEffective,
out DataGridViewElementStates cellState,
out Rectangle cellBounds)
{
Debug.Assert(this.DataGridView != null);
bool singleVerticalBorderAdded = !this.DataGridView.RowHeadersVisible && this.DataGridView.AdvancedCellBorderStyle.All == DataGridViewAdvancedCellBorderStyle.Single;
bool singleHorizontalBorderAdded = !this.DataGridView.ColumnHeadersVisible && this.DataGridView.AdvancedCellBorderStyle.All == DataGridViewAdvancedCellBorderStyle.Single;
DataGridViewAdvancedBorderStyle dataGridViewAdvancedBorderStylePlaceholder = new DataGridViewAdvancedBorderStyle();
if (rowIndex > -1 && this.OwningColumn != null)
{
// Inner cell case
dgvabsEffective = AdjustCellBorderStyle(this.DataGridView.AdvancedCellBorderStyle,
dataGridViewAdvancedBorderStylePlaceholder,
singleVerticalBorderAdded,
singleHorizontalBorderAdded,
this.ColumnIndex == this.DataGridView.FirstDisplayedColumnIndex /*isFirstDisplayedColumn*/,
rowIndex == this.DataGridView.FirstDisplayedRowIndex /*isFirstDisplayedRow*/);
DataGridViewElementStates rowState = this.DataGridView.Rows.GetRowState(rowIndex);
cellState = this.CellStateFromColumnRowStates(rowState);
cellState |= this.State;
}
else if (this.OwningColumn != null)
{
// Column header cell case
Debug.Assert(rowIndex == -1);
Debug.Assert(this is DataGridViewColumnHeaderCell, "if the row index == -1 and we have an owning column this should be a column header cell");
DataGridViewColumn dataGridViewColumn = this.DataGridView.Columns.GetLastColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.None);
bool isLastVisibleColumn = (dataGridViewColumn != null && dataGridViewColumn.Index == this.ColumnIndex);
dgvabsEffective = this.DataGridView.AdjustColumnHeaderBorderStyle(this.DataGridView.AdvancedColumnHeadersBorderStyle,
dataGridViewAdvancedBorderStylePlaceholder,
this.ColumnIndex == this.DataGridView.FirstDisplayedColumnIndex,
isLastVisibleColumn);
cellState = this.OwningColumn.State | this.State;
}
else if (this.OwningRow != null)
{
// Row header cell case
Debug.Assert(this is DataGridViewRowHeaderCell);
dgvabsEffective = this.OwningRow.AdjustRowHeaderBorderStyle(this.DataGridView.AdvancedRowHeadersBorderStyle,
dataGridViewAdvancedBorderStylePlaceholder,
singleVerticalBorderAdded,
singleHorizontalBorderAdded,
rowIndex == this.DataGridView.FirstDisplayedRowIndex /*isFirstDisplayedRow*/,
rowIndex == this.DataGridView.Rows.GetLastRow(DataGridViewElementStates.Visible) /*isLastVisibleRow*/);
cellState = this.OwningRow.GetState(rowIndex) | this.State;
}
else
{
Debug.Assert(this.OwningColumn == null);
Debug.Assert(this.OwningRow == null);
Debug.Assert(rowIndex == -1);
// TopLeft header cell case
dgvabsEffective = this.DataGridView.AdjustedTopLeftHeaderBorderStyle;
cellState = this.State;
}
cellBounds = new Rectangle(new Point(0, 0), GetSize(rowIndex));
}
internal Rectangle ComputeErrorIconBounds(Rectangle cellValueBounds)
{
if (cellValueBounds.Width >= DATAGRIDVIEWCELL_iconMarginWidth * 2 + iconsWidth &&
cellValueBounds.Height >= DATAGRIDVIEWCELL_iconMarginHeight * 2 + iconsHeight)
{
Rectangle bmpRect = new Rectangle(this.DataGridView.RightToLeftInternal ?
cellValueBounds.Left + DATAGRIDVIEWCELL_iconMarginWidth :
cellValueBounds.Right - DATAGRIDVIEWCELL_iconMarginWidth - iconsWidth,
cellValueBounds.Y + (cellValueBounds.Height - iconsHeight) / 2,
iconsWidth,
iconsHeight);
return bmpRect;
}
else
{
return Rectangle.Empty;
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.ContentClickUnsharesRow"]/*' />
[
SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly") // Unshares is OK.
]
protected virtual bool ContentClickUnsharesRow(DataGridViewCellEventArgs e)
{
return false;
}
internal bool ContentClickUnsharesRowInternal(DataGridViewCellEventArgs e)
{
return ContentClickUnsharesRow(e);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.ContentDoubleClickUnsharesRow"]/*' />
[
SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly") // Unshares is OK.
]
protected virtual bool ContentDoubleClickUnsharesRow(DataGridViewCellEventArgs e)
{
return false;
}
internal bool ContentDoubleClickUnsharesRowInternal(DataGridViewCellEventArgs e)
{
return ContentDoubleClickUnsharesRow(e);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.CreateAccessibilityInstance"]/*' />
protected virtual AccessibleObject CreateAccessibilityInstance()
{
return new DataGridViewCellAccessibleObject(this);
}
private void DetachContextMenuStrip(object sender, EventArgs e)
{
this.ContextMenuStripInternal = null;
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.DetachEditingControl"]/*' />
[
EditorBrowsable(EditorBrowsableState.Advanced)
]
public virtual void DetachEditingControl()
{
DataGridView dgv = this.DataGridView;
if (dgv == null || dgv.EditingControl == null)
{
throw new InvalidOperationException();
}
if (dgv.EditingControl.ParentInternal != null)
{
if (dgv.EditingControl.ContainsFocus)
{
ContainerControl cc = dgv.GetContainerControlInternal() as ContainerControl;
if (cc != null && (dgv.EditingControl == cc.ActiveControl || dgv.EditingControl.Contains(cc.ActiveControl)))
{
dgv.FocusInternal();
}
else
{
// We don't want the grid to get the keyboard focus
// when the editing control gets parented to the parking window,
// because some other window is in the middle of receiving the focus.
UnsafeNativeMethods.SetFocus(new HandleRef(null, IntPtr.Zero));
}
}
Debug.Assert(dgv.EditingControl.ParentInternal == dgv.EditingPanel);
Debug.Assert(dgv.EditingPanel.Controls.Contains(dgv.EditingControl));
dgv.EditingPanel.Controls.Remove(dgv.EditingControl);
Debug.Assert(dgv.EditingControl.ParentInternal == null);
}
if (dgv.EditingPanel.ParentInternal != null)
{
Debug.Assert(dgv.EditingPanel.ParentInternal == dgv);
Debug.Assert(dgv.Controls.Contains(dgv.EditingPanel));
((DataGridView.DataGridViewControlCollection)dgv.Controls).RemoveInternal(dgv.EditingPanel);
Debug.Assert(dgv.EditingPanel.ParentInternal == null);
}
Debug.Assert(dgv.EditingControl.ParentInternal == null);
Debug.Assert(dgv.EditingPanel.ParentInternal == null);
Debug.Assert(dgv.EditingPanel.Controls.Count == 0);
// Since the tooltip is removed when the editing control is shown,
// the CurrentMouseLocation is reset to DATAGRIDVIEWCELL_flagAreaNotSet
// so that the tooltip appears again on mousemove after the editing.
this.CurrentMouseLocation = DATAGRIDVIEWCELL_flagAreaNotSet;
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.Dispose"]/*' />
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.Dispose2"]/*' />
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
ContextMenuStrip contextMenuStrip = (ContextMenuStrip)this.ContextMenuStripInternal;
if (contextMenuStrip != null)
{
contextMenuStrip.Disposed -= new EventHandler(DetachContextMenuStrip);
}
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.DoubleClickUnsharesRow"]/*' />
[
SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly") // Unshares is OK.
]
protected virtual bool DoubleClickUnsharesRow(DataGridViewCellEventArgs e)
{
return false;
}
internal bool DoubleClickUnsharesRowInternal(DataGridViewCellEventArgs e)
{
return DoubleClickUnsharesRow(e);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.EnterUnsharesRow"]/*' />
[
SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly") // Unshares is OK.
]
protected virtual bool EnterUnsharesRow(int rowIndex, bool throughMouseClick)
{
return false;
}
internal bool EnterUnsharesRowInternal(int rowIndex, bool throughMouseClick)
{
return EnterUnsharesRow(rowIndex, throughMouseClick);
}
internal static void FormatPlainText(string s, bool csv, TextWriter output, ref bool escapeApplied)
{
if (s == null)
{
return;
}
int cb = s.Length;
for (int i = 0; i < cb; i++)
{
char ch = s[i];
switch (ch)
{
case '"':
if (csv)
{
output.Write("\"\"");
escapeApplied = true;
}
else
{
output.Write('"');
}
break;
case ',':
if (csv)
{
escapeApplied = true;
}
output.Write(',');
break;
case '\t':
if (!csv)
{
output.Write(' ');
}
else
{
output.Write('\t');
}
break;
default:
output.Write(ch);
break;
}
}
if (escapeApplied)
{
output.Write('"'); // terminating double-quote.
// the caller is responsible for inserting the opening double-quote.
}
}
// Code taken from ASP.NET file xsp\System\Web\httpserverutility.cs
internal static void FormatPlainTextAsHtml(string s, TextWriter output)
{
if (s == null)
{
return;
}
int cb = s.Length;
char prevCh = '\0';
for (int i = 0; i < cb; i++)
{
char ch = s[i];
switch (ch)
{
case '<':
output.Write("<");
break;
case '>':
output.Write(">");
break;
case '"':
output.Write(""");
break;
case '&':
output.Write("&");
break;
case ' ':
if (prevCh == ' ')
{
output.Write(" ");
}
else
{
output.Write(ch);
}
break;
case '\r':
// Ignore \r, only handle \n
break;
case '\n':
output.Write("<br>");
break;
//
default:
#if ENTITY_ENCODE_HIGH_ASCII_CHARS
// The seemingly arbitrary 160 comes from RFC
if (ch >= 160 && ch < 256)
{
output.Write("&#");
output.Write(((int)ch).ToString(NumberFormatInfo.InvariantInfo));
output.Write(';');
break;
}
#endif // ENTITY_ENCODE_HIGH_ASCII_CHARS
output.Write(ch);
break;
}
prevCh = ch;
}
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static Bitmap GetBitmap(string bitmapName)
{
Bitmap b = new Bitmap(typeof(DataGridViewCell), bitmapName);
b.MakeTransparent();
if (DpiHelper.IsScalingRequired) {
Bitmap scaledBitmap = DpiHelper.CreateResizedBitmap(b, new Size(iconsWidth, iconsHeight));
if (scaledBitmap != null) {
b.Dispose();
b = scaledBitmap;
}
}
return b;
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.GetClipboardContent"]/*' />
protected virtual object GetClipboardContent(int rowIndex,
bool firstCell,
bool lastCell,
bool inFirstRow,
bool inLastRow,
string format)
{
if (this.DataGridView == null)
{
return null;
}
// Header Cell classes override this implementation - this implementation is only for inner cells
if (rowIndex < 0 || rowIndex >= this.DataGridView.Rows.Count)
{
throw new ArgumentOutOfRangeException(nameof(rowIndex));
}
// Assuming (like in other places in this class) that the formatted value is independent of the style colors.
DataGridViewCellStyle dataGridViewCellStyle = GetInheritedStyle(null, rowIndex, false);
object formattedValue = null;
if (this.DataGridView.IsSharedCellSelected(this, rowIndex))
{
formattedValue = GetEditedFormattedValue(GetValue(rowIndex), rowIndex, ref dataGridViewCellStyle, DataGridViewDataErrorContexts.Formatting | DataGridViewDataErrorContexts.ClipboardContent);
}
StringBuilder sb = new StringBuilder(64);
if (String.Equals(format, DataFormats.Html, StringComparison.OrdinalIgnoreCase))
{
if (firstCell)
{
if (inFirstRow)
{
sb.Append("<TABLE>");
}
sb.Append("<TR>");
}
sb.Append("<TD>");
if (formattedValue != null)
{
FormatPlainTextAsHtml(formattedValue.ToString(), new StringWriter(sb, CultureInfo.CurrentCulture));
}
else
{
sb.Append(" ");
}
sb.Append("</TD>");
if (lastCell)
{
sb.Append("</TR>");
if (inLastRow)
{
sb.Append("</TABLE>");
}
}
return sb.ToString();
}
else
{
bool csv = String.Equals(format, DataFormats.CommaSeparatedValue, StringComparison.OrdinalIgnoreCase);
if (csv ||
String.Equals(format, DataFormats.Text, StringComparison.OrdinalIgnoreCase) ||
String.Equals(format, DataFormats.UnicodeText, StringComparison.OrdinalIgnoreCase))
{
if (formattedValue != null)
{
if (firstCell && lastCell && inFirstRow && inLastRow)
{
sb.Append(formattedValue.ToString());
}
else
{
bool escapeApplied = false;
int insertionPoint = sb.Length;
FormatPlainText(formattedValue.ToString(), csv, new StringWriter(sb, CultureInfo.CurrentCulture), ref escapeApplied);
if (escapeApplied)
{
Debug.Assert(csv);
sb.Insert(insertionPoint, '"');
}
}
}
if (lastCell)
{
if (!inLastRow)
{
sb.Append((char)Keys.Return);
sb.Append((char)Keys.LineFeed);
}
}
else
{
sb.Append(csv ? ',' : (char)Keys.Tab);
}
return sb.ToString();
}
else
{
return null;
}
}
}
internal object GetClipboardContentInternal(int rowIndex,
bool firstCell,
bool lastCell,
bool inFirstRow,
bool inLastRow,
string format)
{
return GetClipboardContent(rowIndex, firstCell, lastCell, inFirstRow, inLastRow, format);
}
internal ContextMenuStrip GetContextMenuStrip(int rowIndex)
{
ContextMenuStrip contextMenuStrip = this.ContextMenuStripInternal;
if (this.DataGridView != null &&
(this.DataGridView.VirtualMode || this.DataGridView.DataSource != null))
{
contextMenuStrip = this.DataGridView.OnCellContextMenuStripNeeded(this.ColumnIndex, rowIndex, contextMenuStrip);
}
return contextMenuStrip;
}
internal void GetContrastedPens(Color baseline, ref Pen darkPen, ref Pen lightPen)
{
Debug.Assert(this.DataGridView != null);
int darkDistance = ColorDistance(baseline, SystemColors.ControlDark);
int lightDistance = ColorDistance(baseline, SystemColors.ControlLightLight);
if (SystemInformation.HighContrast)
{
if (darkDistance < DATAGRIDVIEWCELL_highConstrastThreshold)
{
darkPen = this.DataGridView.GetCachedPen(ControlPaint.DarkDark(baseline));
}
else
{
darkPen = this.DataGridView.GetCachedPen(SystemColors.ControlDark);
}
if (lightDistance < DATAGRIDVIEWCELL_highConstrastThreshold)
{
lightPen = this.DataGridView.GetCachedPen(ControlPaint.LightLight(baseline));
}
else
{
lightPen = this.DataGridView.GetCachedPen(SystemColors.ControlLightLight);
}
}
else
{
if (darkDistance < DATAGRIDVIEWCELL_constrastThreshold)
{
darkPen = this.DataGridView.GetCachedPen(ControlPaint.Dark(baseline));
}
else
{
darkPen = this.DataGridView.GetCachedPen(SystemColors.ControlDark);
}
if (lightDistance < DATAGRIDVIEWCELL_constrastThreshold)
{
lightPen = this.DataGridView.GetCachedPen(ControlPaint.Light(baseline));
}
else
{
lightPen = this.DataGridView.GetCachedPen(SystemColors.ControlLightLight);
}
}
}
#if DGV_GDI
internal void GetContrastedWindowsPens(Color baseline, ref WindowsPen darkPen, ref WindowsPen lightPen)
{
Debug.Assert(this.DataGridView != null);
int darkDistance = ColorDistance(baseline, SystemColors.ControlDark);
int lightDistance = ColorDistance(baseline, SystemColors.ControlLightLight);
if (SystemInformation.HighContrast)
{
if (darkDistance < DATAGRIDVIEWCELL_highConstrastThreshold)
{
darkPen = this.DataGridView.GetCachedWindowsPen(ControlPaint.DarkDark(baseline));
}
else
{
darkPen = this.DataGridView.GetCachedWindowsPen(SystemColors.ControlDark);
}
if (lightDistance < DATAGRIDVIEWCELL_highConstrastThreshold)
{
lightPen = this.DataGridView.GetCachedWindowsPen(ControlPaint.LightLight(baseline));
}
else
{
lightPen = this.DataGridView.GetCachedWindowsPen(SystemColors.ControlLightLight);
}
}
else
{
if (darkDistance < DATAGRIDVIEWCELL_constrastThreshold)
{
darkPen = this.DataGridView.GetCachedWindowsPen(ControlPaint.Dark(baseline));
}
else
{
darkPen = this.DataGridView.GetCachedWindowsPen(SystemColors.ControlDark);
}
if (lightDistance < DATAGRIDVIEWCELL_constrastThreshold)
{
lightPen = this.DataGridView.GetCachedWindowsPen(ControlPaint.Light(baseline));
}
else
{
lightPen = this.DataGridView.GetCachedWindowsPen(SystemColors.ControlLightLight);
}
}
}
#endif // DGV_GDI
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.GetContentBounds1"]/*' />
public Rectangle GetContentBounds(int rowIndex)
{
if (this.DataGridView == null)
{
return Rectangle.Empty;
}
DataGridViewCellStyle dataGridViewCellStyle = GetInheritedStyle(null, rowIndex, false /*includeColors*/);
using (Graphics g = WindowsFormsUtils.CreateMeasurementGraphics())
{
return GetContentBounds(g, dataGridViewCellStyle, rowIndex);
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.GetContentBounds2"]/*' />
protected virtual Rectangle GetContentBounds(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex)
{
return Rectangle.Empty;
}
internal object GetEditedFormattedValue(object value, int rowIndex, ref DataGridViewCellStyle dataGridViewCellStyle, DataGridViewDataErrorContexts context)
{
Debug.Assert(this.DataGridView != null);
Point ptCurrentCell = this.DataGridView.CurrentCellAddress;
if (this.ColumnIndex == ptCurrentCell.X && rowIndex == ptCurrentCell.Y)
{
IDataGridViewEditingControl dgvectl = (IDataGridViewEditingControl)this.DataGridView.EditingControl;
if (dgvectl != null)
{
return dgvectl.GetEditingControlFormattedValue(context);
}
IDataGridViewEditingCell dgvecell = this as IDataGridViewEditingCell;
if (dgvecell != null && this.DataGridView.IsCurrentCellInEditMode)
{
return dgvecell.GetEditingCellFormattedValue(context);
}
return GetFormattedValue(value, rowIndex, ref dataGridViewCellStyle, null, null, context);
}
return GetFormattedValue(value, rowIndex, ref dataGridViewCellStyle, null, null, context);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.GetEditedFormattedValue"]/*' />
public object GetEditedFormattedValue(int rowIndex, DataGridViewDataErrorContexts context)
{
if (this.DataGridView == null)
{
return null;
}
DataGridViewCellStyle dataGridViewCellStyle = GetInheritedStyle(null, rowIndex, false /*includeColors*/);
return GetEditedFormattedValue(GetValue(rowIndex), rowIndex, ref dataGridViewCellStyle, context);
}
internal Rectangle GetErrorIconBounds(int rowIndex)
{
Debug.Assert(this.DataGridView != null);
DataGridViewCellStyle dataGridViewCellStyle = GetInheritedStyle(null, rowIndex, false /*includeColors*/);
using (Graphics g = WindowsFormsUtils.CreateMeasurementGraphics())
{
return GetErrorIconBounds(g, dataGridViewCellStyle, rowIndex);
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.GetErrorIconBounds"]/*' />
protected virtual Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex)
{
return Rectangle.Empty;
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.GetErrorText"]/*' />
protected internal virtual string GetErrorText(int rowIndex)
{
string errorText = string.Empty;
object objErrorText = this.Properties.GetObject(PropCellErrorText);
if (objErrorText != null)
{
errorText = (string) objErrorText;
}
else if (this.DataGridView != null &&
rowIndex != -1 &&
rowIndex != this.DataGridView.NewRowIndex &&
this.OwningColumn != null &&
this.OwningColumn.IsDataBound &&
this.DataGridView.DataConnection != null)
{
errorText = this.DataGridView.DataConnection.GetError(this.OwningColumn.BoundColumnIndex, this.ColumnIndex, rowIndex);
}
if (this.DataGridView != null && (this.DataGridView.VirtualMode || this.DataGridView.DataSource != null) &&
this.ColumnIndex >= 0 && rowIndex >= 0)
{
errorText = this.DataGridView.OnCellErrorTextNeeded(this.ColumnIndex, rowIndex, errorText);
}
return errorText;
}
internal object GetFormattedValue(int rowIndex, ref DataGridViewCellStyle cellStyle, DataGridViewDataErrorContexts context)
{
if (this.DataGridView == null)
{
return null;
}
else
{
return GetFormattedValue(GetValue(rowIndex), rowIndex, ref cellStyle, null, null, context);
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.GetFormattedValue"]/*' />
[
SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference") // using ref is OK.
]
protected virtual object GetFormattedValue(object value,
int rowIndex,
ref DataGridViewCellStyle cellStyle,
TypeConverter valueTypeConverter,
TypeConverter formattedValueTypeConverter,
DataGridViewDataErrorContexts context)
{
if (this.DataGridView == null)
{
return null;
}
DataGridViewCellFormattingEventArgs gdvcfe = this.DataGridView.OnCellFormatting(this.ColumnIndex, rowIndex, value, this.FormattedValueType, cellStyle);
cellStyle = gdvcfe.CellStyle;
bool formattingApplied = gdvcfe.FormattingApplied;
Object formattedValue = gdvcfe.Value;
bool checkFormattedValType = true;
if (!formattingApplied &&
this.FormattedValueType != null &&
(formattedValue == null || !this.FormattedValueType.IsAssignableFrom(formattedValue.GetType())))
{
try
{
formattedValue = Formatter.FormatObject(formattedValue,
this.FormattedValueType,
valueTypeConverter == null ? this.ValueTypeConverter : valueTypeConverter, /*sourceConverter*/
formattedValueTypeConverter == null ? this.FormattedValueTypeConverter : formattedValueTypeConverter, /*targetConverter*/
cellStyle.Format,
cellStyle.FormatProvider,
cellStyle.NullValue,
cellStyle.DataSourceNullValue);
}
catch (Exception exception)
{
if (ClientUtils.IsCriticalException(exception))
{
throw;
}
// Formatting failed, raise OnDataError event.
DataGridViewDataErrorEventArgs dgvdee = new DataGridViewDataErrorEventArgs(exception,
this.ColumnIndex,
rowIndex,
context);
RaiseDataError(dgvdee);
if (dgvdee.ThrowException)
{
throw dgvdee.Exception;
}
checkFormattedValType = false;
}
}
if (checkFormattedValType &&
(formattedValue == null || this.FormattedValueType == null || !this.FormattedValueType.IsAssignableFrom(formattedValue.GetType())))
{
if (formattedValue == null &&
cellStyle.NullValue == null &&
this.FormattedValueType != null &&
!typeof(System.ValueType).IsAssignableFrom(this.FormattedValueType))
{
// null is an acceptable formatted value
return null;
}
Exception exception = null;
if (this.FormattedValueType == null)
{
exception = new FormatException(string.Format(SR.DataGridViewCell_FormattedValueTypeNull));
}
else
{
exception = new FormatException(string.Format(SR.DataGridViewCell_FormattedValueHasWrongType));
}
DataGridViewDataErrorEventArgs dgvdee = new DataGridViewDataErrorEventArgs(exception,
this.ColumnIndex,
rowIndex,
context);
RaiseDataError(dgvdee);
if (dgvdee.ThrowException)
{
throw dgvdee.Exception;
}
}
return formattedValue;
}
static internal DataGridViewFreeDimension GetFreeDimensionFromConstraint(Size constraintSize)
{
if (constraintSize.Width < 0 || constraintSize.Height < 0)
{
throw new ArgumentException(string.Format(SR.InvalidArgument, "constraintSize", constraintSize.ToString()));
}
if (constraintSize.Width == 0)
{
if (constraintSize.Height == 0)
{
return DataGridViewFreeDimension.Both;
}
else
{
return DataGridViewFreeDimension.Width;
}
}
else
{
if (constraintSize.Height == 0)
{
return DataGridViewFreeDimension.Height;
}
else
{
throw new ArgumentException(string.Format(SR.InvalidArgument, "constraintSize", constraintSize.ToString()));
}
}
}
internal int GetHeight(int rowIndex)
{
if (this.DataGridView == null)
{
return -1;
}
Debug.Assert(this.owningRow != null);
return this.owningRow.GetHeight(rowIndex);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.GetInheritedContextMenuStrip"]/*' />
public virtual ContextMenuStrip GetInheritedContextMenuStrip(int rowIndex)
{
if (this.DataGridView != null)
{
if (rowIndex < 0 || rowIndex >= this.DataGridView.Rows.Count)
{
throw new ArgumentOutOfRangeException(nameof(rowIndex));
}
if (this.ColumnIndex < 0)
{
throw new InvalidOperationException();
}
Debug.Assert(this.ColumnIndex < this.DataGridView.Columns.Count);
}
ContextMenuStrip contextMenuStrip = GetContextMenuStrip(rowIndex);
if (contextMenuStrip != null)
{
return contextMenuStrip;
}
if (this.owningRow != null)
{
contextMenuStrip = this.owningRow.GetContextMenuStrip(rowIndex);
if (contextMenuStrip != null)
{
return contextMenuStrip;
}
}
if (this.owningColumn != null)
{
contextMenuStrip = this.owningColumn.ContextMenuStrip;
if (contextMenuStrip != null)
{
return contextMenuStrip;
}
}
if (this.DataGridView != null)
{
return this.DataGridView.ContextMenuStrip;
}
else
{
return null;
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.GetInheritedState"]/*' />
public virtual DataGridViewElementStates GetInheritedState(int rowIndex)
{
DataGridViewElementStates state = this.State | DataGridViewElementStates.ResizableSet;
if (this.DataGridView == null)
{
Debug.Assert(this.RowIndex == -1);
if (rowIndex != -1)
{
throw new ArgumentException(string.Format(SR.InvalidArgument, "rowIndex", rowIndex.ToString(CultureInfo.CurrentCulture)));
}
if (this.owningRow != null)
{
state |= (this.owningRow.GetState(-1) & (DataGridViewElementStates.Frozen | DataGridViewElementStates.ReadOnly | DataGridViewElementStates.Selected | DataGridViewElementStates.Visible));
if (this.owningRow.GetResizable(rowIndex) == DataGridViewTriState.True)
{
state |= DataGridViewElementStates.Resizable;
}
}
return state;
}
// Header Cell classes override this implementation - this implementation is only for inner cells
if (rowIndex < 0 || rowIndex >= this.DataGridView.Rows.Count)
{
throw new ArgumentOutOfRangeException(nameof(rowIndex));
}
Debug.Assert(this.owningColumn != null);
Debug.Assert(this.owningRow != null);
Debug.Assert(this.ColumnIndex >= 0);
if (this.DataGridView.Rows.SharedRow(rowIndex) != this.owningRow)
{
throw new ArgumentException(string.Format(SR.InvalidArgument, "rowIndex", rowIndex.ToString(CultureInfo.CurrentCulture)));
}
DataGridViewElementStates rowEffectiveState = this.DataGridView.Rows.GetRowState(rowIndex);
state |= (rowEffectiveState & (DataGridViewElementStates.ReadOnly | DataGridViewElementStates.Selected));
state |= (this.owningColumn.State & (DataGridViewElementStates.ReadOnly | DataGridViewElementStates.Selected));
if (this.owningRow.GetResizable(rowIndex) == DataGridViewTriState.True ||
this.owningColumn.Resizable == DataGridViewTriState.True)
{
state |= DataGridViewElementStates.Resizable;
}
if (this.owningColumn.Visible && this.owningRow.GetVisible(rowIndex))
{
state |= DataGridViewElementStates.Visible;
if (this.owningColumn.Displayed && this.owningRow.GetDisplayed(rowIndex))
{
state |= DataGridViewElementStates.Displayed;
}
}
if (this.owningColumn.Frozen && this.owningRow.GetFrozen(rowIndex))
{
state |= DataGridViewElementStates.Frozen;
}
#if DEBUG
DataGridViewElementStates stateDebug = DataGridViewElementStates.ResizableSet;
if (this.Displayed)
{
stateDebug |= DataGridViewElementStates.Displayed;
}
if (this.Frozen)
{
stateDebug |= DataGridViewElementStates.Frozen;
}
if (this.ReadOnly)
{
stateDebug |= DataGridViewElementStates.ReadOnly;
}
if (this.Resizable)
{
stateDebug |= DataGridViewElementStates.Resizable;
}
if (this.Selected)
{
stateDebug |= DataGridViewElementStates.Selected;
}
if (this.Visible)
{
stateDebug |= DataGridViewElementStates.Visible;
}
Debug.Assert(state == stateDebug || this.DataGridView.Rows.SharedRow(rowIndex).Index == -1);
#endif
return state;
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.GetInheritedStyle"]/*' />
public virtual DataGridViewCellStyle GetInheritedStyle(DataGridViewCellStyle inheritedCellStyle, int rowIndex, bool includeColors)
{
if (this.DataGridView == null)
{
throw new InvalidOperationException(string.Format(SR.DataGridView_CellNeedsDataGridViewForInheritedStyle));
}
if (rowIndex < 0 || rowIndex >= this.DataGridView.Rows.Count)
{
throw new ArgumentOutOfRangeException(nameof(rowIndex));
}
if (this.ColumnIndex < 0)
{
throw new InvalidOperationException();
}
Debug.Assert(this.ColumnIndex < this.DataGridView.Columns.Count);
DataGridViewCellStyle inheritedCellStyleTmp;
if (inheritedCellStyle == null)
{
inheritedCellStyleTmp = this.DataGridView.PlaceholderCellStyle;
if (!includeColors)
{
inheritedCellStyleTmp.BackColor = Color.Empty;
inheritedCellStyleTmp.ForeColor = Color.Empty;
inheritedCellStyleTmp.SelectionBackColor = Color.Empty;
inheritedCellStyleTmp.SelectionForeColor = Color.Empty;
}
}
else
{
inheritedCellStyleTmp = inheritedCellStyle;
}
DataGridViewCellStyle cellStyle = null;
if (this.HasStyle)
{
cellStyle = this.Style;
Debug.Assert(cellStyle != null);
}
DataGridViewCellStyle rowStyle = null;
if (this.DataGridView.Rows.SharedRow(rowIndex).HasDefaultCellStyle)
{
rowStyle = this.DataGridView.Rows.SharedRow(rowIndex).DefaultCellStyle;
Debug.Assert(rowStyle != null);
}
DataGridViewCellStyle columnStyle = null;
if (this.owningColumn.HasDefaultCellStyle)
{
columnStyle = this.owningColumn.DefaultCellStyle;
Debug.Assert(columnStyle != null);
}
DataGridViewCellStyle dataGridViewStyle = this.DataGridView.DefaultCellStyle;
Debug.Assert(dataGridViewStyle != null);
if (includeColors)
{
if (cellStyle != null && !cellStyle.BackColor.IsEmpty)
{
inheritedCellStyleTmp.BackColor = cellStyle.BackColor;
}
else if (rowStyle != null && !rowStyle.BackColor.IsEmpty)
{
inheritedCellStyleTmp.BackColor = rowStyle.BackColor;
}
else if (!this.DataGridView.RowsDefaultCellStyle.BackColor.IsEmpty &&
(rowIndex % 2 == 0 || this.DataGridView.AlternatingRowsDefaultCellStyle.BackColor.IsEmpty))
{
inheritedCellStyleTmp.BackColor = this.DataGridView.RowsDefaultCellStyle.BackColor;
}
else if (rowIndex % 2 == 1 && !this.DataGridView.AlternatingRowsDefaultCellStyle.BackColor.IsEmpty)
{
inheritedCellStyleTmp.BackColor = this.DataGridView.AlternatingRowsDefaultCellStyle.BackColor;
}
else if (columnStyle != null && !columnStyle.BackColor.IsEmpty)
{
inheritedCellStyleTmp.BackColor = columnStyle.BackColor;
}
else
{
inheritedCellStyleTmp.BackColor = dataGridViewStyle.BackColor;
}
if (cellStyle != null && !cellStyle.ForeColor.IsEmpty)
{
inheritedCellStyleTmp.ForeColor = cellStyle.ForeColor;
}
else if (rowStyle != null && !rowStyle.ForeColor.IsEmpty)
{
inheritedCellStyleTmp.ForeColor = rowStyle.ForeColor;
}
else if (!this.DataGridView.RowsDefaultCellStyle.ForeColor.IsEmpty &&
(rowIndex % 2 == 0 || this.DataGridView.AlternatingRowsDefaultCellStyle.ForeColor.IsEmpty))
{
inheritedCellStyleTmp.ForeColor = this.DataGridView.RowsDefaultCellStyle.ForeColor;
}
else if (rowIndex % 2 == 1 && !this.DataGridView.AlternatingRowsDefaultCellStyle.ForeColor.IsEmpty)
{
inheritedCellStyleTmp.ForeColor = this.DataGridView.AlternatingRowsDefaultCellStyle.ForeColor;
}
else if (columnStyle != null && !columnStyle.ForeColor.IsEmpty)
{
inheritedCellStyleTmp.ForeColor = columnStyle.ForeColor;
}
else
{
inheritedCellStyleTmp.ForeColor = dataGridViewStyle.ForeColor;
}
if (cellStyle != null && !cellStyle.SelectionBackColor.IsEmpty)
{
inheritedCellStyleTmp.SelectionBackColor = cellStyle.SelectionBackColor;
}
else if (rowStyle != null && !rowStyle.SelectionBackColor.IsEmpty)
{
inheritedCellStyleTmp.SelectionBackColor = rowStyle.SelectionBackColor;
}
else if (!this.DataGridView.RowsDefaultCellStyle.SelectionBackColor.IsEmpty &&
(rowIndex % 2 == 0 || this.DataGridView.AlternatingRowsDefaultCellStyle.SelectionBackColor.IsEmpty))
{
inheritedCellStyleTmp.SelectionBackColor = this.DataGridView.RowsDefaultCellStyle.SelectionBackColor;
}
else if (rowIndex % 2 == 1 && !this.DataGridView.AlternatingRowsDefaultCellStyle.SelectionBackColor.IsEmpty)
{
inheritedCellStyleTmp.SelectionBackColor = this.DataGridView.AlternatingRowsDefaultCellStyle.SelectionBackColor;
}
else if (columnStyle != null && !columnStyle.SelectionBackColor.IsEmpty)
{
inheritedCellStyleTmp.SelectionBackColor = columnStyle.SelectionBackColor;
}
else
{
inheritedCellStyleTmp.SelectionBackColor = dataGridViewStyle.SelectionBackColor;
}
if (cellStyle != null && !cellStyle.SelectionForeColor.IsEmpty)
{
inheritedCellStyleTmp.SelectionForeColor = cellStyle.SelectionForeColor;
}
else if (rowStyle != null && !rowStyle.SelectionForeColor.IsEmpty)
{
inheritedCellStyleTmp.SelectionForeColor = rowStyle.SelectionForeColor;
}
else if (!this.DataGridView.RowsDefaultCellStyle.SelectionForeColor.IsEmpty &&
(rowIndex % 2 == 0 || this.DataGridView.AlternatingRowsDefaultCellStyle.SelectionForeColor.IsEmpty))
{
inheritedCellStyleTmp.SelectionForeColor = this.DataGridView.RowsDefaultCellStyle.SelectionForeColor;
}
else if (rowIndex % 2 == 1 && !this.DataGridView.AlternatingRowsDefaultCellStyle.SelectionForeColor.IsEmpty)
{
inheritedCellStyleTmp.SelectionForeColor = this.DataGridView.AlternatingRowsDefaultCellStyle.SelectionForeColor;
}
else if (columnStyle != null && !columnStyle.SelectionForeColor.IsEmpty)
{
inheritedCellStyleTmp.SelectionForeColor = columnStyle.SelectionForeColor;
}
else
{
inheritedCellStyleTmp.SelectionForeColor = dataGridViewStyle.SelectionForeColor;
}
}
if (cellStyle != null && cellStyle.Font != null)
{
inheritedCellStyleTmp.Font = cellStyle.Font;
}
else if (rowStyle != null && rowStyle.Font != null)
{
inheritedCellStyleTmp.Font = rowStyle.Font;
}
else if (this.DataGridView.RowsDefaultCellStyle.Font != null &&
(rowIndex % 2 == 0 || this.DataGridView.AlternatingRowsDefaultCellStyle.Font == null))
{
inheritedCellStyleTmp.Font = this.DataGridView.RowsDefaultCellStyle.Font;
}
else if (rowIndex % 2 == 1 && this.DataGridView.AlternatingRowsDefaultCellStyle.Font != null)
{
inheritedCellStyleTmp.Font = this.DataGridView.AlternatingRowsDefaultCellStyle.Font;
}
else if (columnStyle != null && columnStyle.Font != null)
{
inheritedCellStyleTmp.Font = columnStyle.Font;
}
else
{
inheritedCellStyleTmp.Font = dataGridViewStyle.Font;
}
if (cellStyle != null && !cellStyle.IsNullValueDefault)
{
inheritedCellStyleTmp.NullValue = cellStyle.NullValue;
}
else if (rowStyle != null && !rowStyle.IsNullValueDefault)
{
inheritedCellStyleTmp.NullValue = rowStyle.NullValue;
}
else if (!this.DataGridView.RowsDefaultCellStyle.IsNullValueDefault &&
(rowIndex % 2 == 0 || this.DataGridView.AlternatingRowsDefaultCellStyle.IsNullValueDefault))
{
inheritedCellStyleTmp.NullValue = this.DataGridView.RowsDefaultCellStyle.NullValue;
}
else if (rowIndex % 2 == 1 &&
!this.DataGridView.AlternatingRowsDefaultCellStyle.IsNullValueDefault)
{
inheritedCellStyleTmp.NullValue = this.DataGridView.AlternatingRowsDefaultCellStyle.NullValue;
}
else if (columnStyle != null && !columnStyle.IsNullValueDefault)
{
inheritedCellStyleTmp.NullValue = columnStyle.NullValue;
}
else
{
inheritedCellStyleTmp.NullValue = dataGridViewStyle.NullValue;
}
if (cellStyle != null && !cellStyle.IsDataSourceNullValueDefault)
{
inheritedCellStyleTmp.DataSourceNullValue = cellStyle.DataSourceNullValue;
}
else if (rowStyle != null && !rowStyle.IsDataSourceNullValueDefault)
{
inheritedCellStyleTmp.DataSourceNullValue = rowStyle.DataSourceNullValue;
}
else if (!this.DataGridView.RowsDefaultCellStyle.IsDataSourceNullValueDefault &&
(rowIndex % 2 == 0 || this.DataGridView.AlternatingRowsDefaultCellStyle.IsDataSourceNullValueDefault))
{
inheritedCellStyleTmp.DataSourceNullValue = this.DataGridView.RowsDefaultCellStyle.DataSourceNullValue;
}
else if (rowIndex % 2 == 1 &&
!this.DataGridView.AlternatingRowsDefaultCellStyle.IsDataSourceNullValueDefault)
{
inheritedCellStyleTmp.DataSourceNullValue = this.DataGridView.AlternatingRowsDefaultCellStyle.DataSourceNullValue;
}
else if (columnStyle != null && !columnStyle.IsDataSourceNullValueDefault)
{
inheritedCellStyleTmp.DataSourceNullValue = columnStyle.DataSourceNullValue;
}
else
{
inheritedCellStyleTmp.DataSourceNullValue = dataGridViewStyle.DataSourceNullValue;
}
if (cellStyle != null && cellStyle.Format.Length != 0)
{
inheritedCellStyleTmp.Format = cellStyle.Format;
}
else if (rowStyle != null && rowStyle.Format.Length != 0)
{
inheritedCellStyleTmp.Format = rowStyle.Format;
}
else if (this.DataGridView.RowsDefaultCellStyle.Format.Length != 0 &&
(rowIndex % 2 == 0 || this.DataGridView.AlternatingRowsDefaultCellStyle.Format.Length == 0))
{
inheritedCellStyleTmp.Format = this.DataGridView.RowsDefaultCellStyle.Format;
}
else if (rowIndex % 2 == 1 && this.DataGridView.AlternatingRowsDefaultCellStyle.Format.Length != 0)
{
inheritedCellStyleTmp.Format = this.DataGridView.AlternatingRowsDefaultCellStyle.Format;
}
else if (columnStyle != null && columnStyle.Format.Length != 0)
{
inheritedCellStyleTmp.Format = columnStyle.Format;
}
else
{
inheritedCellStyleTmp.Format = dataGridViewStyle.Format;
}
if (cellStyle != null && !cellStyle.IsFormatProviderDefault)
{
inheritedCellStyleTmp.FormatProvider = cellStyle.FormatProvider;
}
else if (rowStyle != null && !rowStyle.IsFormatProviderDefault)
{
inheritedCellStyleTmp.FormatProvider = rowStyle.FormatProvider;
}
else if (!this.DataGridView.RowsDefaultCellStyle.IsFormatProviderDefault &&
(rowIndex % 2 == 0 || this.DataGridView.AlternatingRowsDefaultCellStyle.IsFormatProviderDefault))
{
inheritedCellStyleTmp.FormatProvider = this.DataGridView.RowsDefaultCellStyle.FormatProvider;
}
else if (rowIndex % 2 == 1 && !this.DataGridView.AlternatingRowsDefaultCellStyle.IsFormatProviderDefault)
{
inheritedCellStyleTmp.FormatProvider = this.DataGridView.AlternatingRowsDefaultCellStyle.FormatProvider;
}
else if (columnStyle != null && !columnStyle.IsFormatProviderDefault)
{
inheritedCellStyleTmp.FormatProvider = columnStyle.FormatProvider;
}
else
{
inheritedCellStyleTmp.FormatProvider = dataGridViewStyle.FormatProvider;
}
if (cellStyle != null && cellStyle.Alignment != DataGridViewContentAlignment.NotSet)
{
inheritedCellStyleTmp.AlignmentInternal = cellStyle.Alignment;
}
else if (rowStyle != null && rowStyle.Alignment != DataGridViewContentAlignment.NotSet)
{
inheritedCellStyleTmp.AlignmentInternal = rowStyle.Alignment;
}
else if (this.DataGridView.RowsDefaultCellStyle.Alignment != DataGridViewContentAlignment.NotSet &&
(rowIndex % 2 == 0 || this.DataGridView.AlternatingRowsDefaultCellStyle.Alignment == DataGridViewContentAlignment.NotSet))
{
inheritedCellStyleTmp.AlignmentInternal = this.DataGridView.RowsDefaultCellStyle.Alignment;
}
else if (rowIndex % 2 == 1 && this.DataGridView.AlternatingRowsDefaultCellStyle.Alignment != DataGridViewContentAlignment.NotSet)
{
inheritedCellStyleTmp.AlignmentInternal = this.DataGridView.AlternatingRowsDefaultCellStyle.Alignment;
}
else if (columnStyle != null && columnStyle.Alignment != DataGridViewContentAlignment.NotSet)
{
inheritedCellStyleTmp.AlignmentInternal = columnStyle.Alignment;
}
else
{
Debug.Assert(dataGridViewStyle.Alignment != DataGridViewContentAlignment.NotSet);
inheritedCellStyleTmp.AlignmentInternal = dataGridViewStyle.Alignment;
}
if (cellStyle != null && cellStyle.WrapMode != DataGridViewTriState.NotSet)
{
inheritedCellStyleTmp.WrapModeInternal = cellStyle.WrapMode;
}
else if (rowStyle != null && rowStyle.WrapMode != DataGridViewTriState.NotSet)
{
inheritedCellStyleTmp.WrapModeInternal = rowStyle.WrapMode;
}
else if (this.DataGridView.RowsDefaultCellStyle.WrapMode != DataGridViewTriState.NotSet &&
(rowIndex % 2 == 0 || this.DataGridView.AlternatingRowsDefaultCellStyle.WrapMode == DataGridViewTriState.NotSet))
{
inheritedCellStyleTmp.WrapModeInternal = this.DataGridView.RowsDefaultCellStyle.WrapMode;
}
else if (rowIndex % 2 == 1 && this.DataGridView.AlternatingRowsDefaultCellStyle.WrapMode != DataGridViewTriState.NotSet)
{
inheritedCellStyleTmp.WrapModeInternal = this.DataGridView.AlternatingRowsDefaultCellStyle.WrapMode;
}
else if (columnStyle != null && columnStyle.WrapMode != DataGridViewTriState.NotSet)
{
inheritedCellStyleTmp.WrapModeInternal = columnStyle.WrapMode;
}
else
{
Debug.Assert(dataGridViewStyle.WrapMode != DataGridViewTriState.NotSet);
inheritedCellStyleTmp.WrapModeInternal = dataGridViewStyle.WrapMode;
}
if (cellStyle != null && cellStyle.Tag != null)
{
inheritedCellStyleTmp.Tag = cellStyle.Tag;
}
else if (rowStyle != null && rowStyle.Tag != null)
{
inheritedCellStyleTmp.Tag = rowStyle.Tag;
}
else if (this.DataGridView.RowsDefaultCellStyle.Tag != null &&
(rowIndex % 2 == 0 || this.DataGridView.AlternatingRowsDefaultCellStyle.Tag == null))
{
inheritedCellStyleTmp.Tag = this.DataGridView.RowsDefaultCellStyle.Tag;
}
else if (rowIndex % 2 == 1 && this.DataGridView.AlternatingRowsDefaultCellStyle.Tag != null)
{
inheritedCellStyleTmp.Tag = this.DataGridView.AlternatingRowsDefaultCellStyle.Tag;
}
else if (columnStyle != null && columnStyle.Tag != null)
{
inheritedCellStyleTmp.Tag = columnStyle.Tag;
}
else
{
inheritedCellStyleTmp.Tag = dataGridViewStyle.Tag;
}
if (cellStyle != null && cellStyle.Padding != Padding.Empty)
{
inheritedCellStyleTmp.PaddingInternal = cellStyle.Padding;
}
else if (rowStyle != null && rowStyle.Padding != Padding.Empty)
{
inheritedCellStyleTmp.PaddingInternal = rowStyle.Padding;
}
else if (this.DataGridView.RowsDefaultCellStyle.Padding != Padding.Empty &&
(rowIndex % 2 == 0 || this.DataGridView.AlternatingRowsDefaultCellStyle.Padding == Padding.Empty))
{
inheritedCellStyleTmp.PaddingInternal = this.DataGridView.RowsDefaultCellStyle.Padding;
}
else if (rowIndex % 2 == 1 && this.DataGridView.AlternatingRowsDefaultCellStyle.Padding != Padding.Empty)
{
inheritedCellStyleTmp.PaddingInternal = this.DataGridView.AlternatingRowsDefaultCellStyle.Padding;
}
else if (columnStyle != null && columnStyle.Padding != Padding.Empty)
{
inheritedCellStyleTmp.PaddingInternal = columnStyle.Padding;
}
else
{
inheritedCellStyleTmp.PaddingInternal = dataGridViewStyle.Padding;
}
return inheritedCellStyleTmp;
}
internal DataGridViewCellStyle GetInheritedStyleInternal(int rowIndex)
{
return GetInheritedStyle(null, rowIndex, true /*includeColors*/);
}
internal int GetPreferredHeight(int rowIndex, int width)
{
Debug.Assert(width > 0);
if (this.DataGridView == null)
{
return -1;
}
DataGridViewCellStyle dataGridViewCellStyle = GetInheritedStyle(null, rowIndex, false);
using( Graphics g = WindowsFormsUtils.CreateMeasurementGraphics())
{
return GetPreferredSize(g, dataGridViewCellStyle, rowIndex, new Size(width, 0)).Height;
}
}
internal Size GetPreferredSize(int rowIndex)
{
if (this.DataGridView == null)
{
return new Size(-1, -1);
}
DataGridViewCellStyle dataGridViewCellStyle = GetInheritedStyle(null, rowIndex, false);
using (Graphics g = WindowsFormsUtils.CreateMeasurementGraphics())
{
return GetPreferredSize(g, dataGridViewCellStyle, rowIndex, Size.Empty);
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.GetPreferredSize"]/*' />
protected virtual Size GetPreferredSize(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex, Size constraintSize)
{
return new Size(-1, -1);
}
internal static int GetPreferredTextHeight(Graphics g,
bool rightToLeft,
string text,
DataGridViewCellStyle cellStyle,
int maxWidth,
out bool widthTruncated)
{
Debug.Assert(maxWidth > 0);
TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(rightToLeft, cellStyle.Alignment, cellStyle.WrapMode);
if (cellStyle.WrapMode == DataGridViewTriState.True)
{
return DataGridViewCell.MeasureTextHeight(g, text, cellStyle.Font, maxWidth, flags, out widthTruncated);
}
else
{
Size size = DataGridViewCell.MeasureTextSize(g, text, cellStyle.Font, flags);
widthTruncated = size.Width > maxWidth;
return size.Height;
}
}
internal int GetPreferredWidth(int rowIndex, int height)
{
Debug.Assert(height > 0);
if (this.DataGridView == null)
{
return -1;
}
DataGridViewCellStyle dataGridViewCellStyle = GetInheritedStyle(null, rowIndex, false);
using (Graphics g = WindowsFormsUtils.CreateMeasurementGraphics())
{
return GetPreferredSize(g, dataGridViewCellStyle, rowIndex, new Size(0, height)).Width;
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.GetSize"]/*' />
protected virtual Size GetSize(int rowIndex)
{
if (this.DataGridView == null)
{
return new Size(-1, -1);
}
if (rowIndex == -1)
{
throw new InvalidOperationException(string.Format(SR.DataGridView_InvalidPropertyGetOnSharedCell, "Size"));
}
Debug.Assert(this.owningColumn != null);
Debug.Assert(this.owningRow != null);
return new Size(this.owningColumn.Thickness, this.owningRow.GetHeight(rowIndex));
}
private string GetToolTipText(int rowIndex)
{
string toolTipText = this.ToolTipTextInternal;
if (this.DataGridView != null &&
(this.DataGridView.VirtualMode || this.DataGridView.DataSource != null))
{
toolTipText = this.DataGridView.OnCellToolTipTextNeeded(this.ColumnIndex, rowIndex, toolTipText);
}
return toolTipText;
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.GetValue"]/*' />
protected virtual object GetValue(int rowIndex)
{
DataGridView dataGridView = this.DataGridView;
if (dataGridView != null)
{
if (rowIndex < 0 || rowIndex >= dataGridView.Rows.Count)
{
throw new ArgumentOutOfRangeException(nameof(rowIndex));
}
if (this.ColumnIndex < 0)
{
throw new InvalidOperationException();
}
Debug.Assert(this.ColumnIndex < dataGridView.Columns.Count);
}
if (dataGridView == null ||
(dataGridView.AllowUserToAddRowsInternal && rowIndex > -1 && rowIndex == dataGridView.NewRowIndex && rowIndex != dataGridView.CurrentCellAddress.Y) ||
(!dataGridView.VirtualMode && this.OwningColumn != null && !this.OwningColumn.IsDataBound) ||
rowIndex == -1 ||
this.ColumnIndex == -1)
{
return this.Properties.GetObject(PropCellValue);
}
else if (this.OwningColumn != null && this.OwningColumn.IsDataBound)
{
DataGridView.DataGridViewDataConnection dataConnection = dataGridView.DataConnection;
if (dataConnection == null)
{
return null;
}
else if (dataConnection.CurrencyManager.Count <= rowIndex)
{
return this.Properties.GetObject(PropCellValue);
}
else
{
return dataConnection.GetValue(this.OwningColumn.BoundColumnIndex, this.ColumnIndex, rowIndex);
}
}
else
{
Debug.Assert(rowIndex >= 0);
Debug.Assert(this.ColumnIndex >= 0);
return dataGridView.OnCellValueNeeded(this.ColumnIndex, rowIndex);
}
}
internal object GetValueInternal(int rowIndex)
{
return GetValue(rowIndex);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.InitializeEditingControl"]/*' />
[
EditorBrowsable(EditorBrowsableState.Advanced)
]
public virtual void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
{
DataGridView dgv = this.DataGridView;
if (dgv == null || dgv.EditingControl == null)
{
throw new InvalidOperationException();
}
// Only add the control to the dataGridView's children if this hasn't been done yet since
// InitializeEditingControl can be called several times.
if (dgv.EditingControl.ParentInternal == null)
{
// Add editing control to the dataGridView hierarchy
dgv.EditingControl.CausesValidation = dgv.CausesValidation;
dgv.EditingPanel.CausesValidation = dgv.CausesValidation;
dgv.EditingControl.Visible = true;
Debug.Assert(!dgv.EditingPanel.ContainsFocus);
dgv.EditingPanel.Visible = false;
Debug.Assert(dgv.EditingPanel.ParentInternal == null);
dgv.Controls.Add(dgv.EditingPanel);
dgv.EditingPanel.Controls.Add(dgv.EditingControl);
Debug.Assert(dgv.IsSharedCellVisible(this, rowIndex));
}
Debug.Assert(dgv.EditingControl.ParentInternal == dgv.EditingPanel);
Debug.Assert(dgv.EditingPanel.ParentInternal == dgv);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.KeyDownUnsharesRow"]/*' />
[
SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly") // Unshares is OK.
]
protected virtual bool KeyDownUnsharesRow(KeyEventArgs e, int rowIndex)
{
return false;
}
internal bool KeyDownUnsharesRowInternal(KeyEventArgs e, int rowIndex)
{
return KeyDownUnsharesRow(e, rowIndex);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.KeyEntersEditMode"]/*' />
public virtual bool KeyEntersEditMode(KeyEventArgs e)
{
return false;
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.KeyPressUnsharesRow"]/*' />
[
SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly") // Unshares is OK.
]
protected virtual bool KeyPressUnsharesRow(KeyPressEventArgs e, int rowIndex)
{
return false;
}
internal bool KeyPressUnsharesRowInternal(KeyPressEventArgs e, int rowIndex)
{
return KeyPressUnsharesRow(e, rowIndex);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.KeyUpUnsharesRow"]/*' />
[
SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly") // Unshares is OK.
]
protected virtual bool KeyUpUnsharesRow(KeyEventArgs e, int rowIndex)
{
return false;
}
internal bool KeyUpUnsharesRowInternal(KeyEventArgs e, int rowIndex)
{
return KeyUpUnsharesRow(e, rowIndex);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.LeaveUnsharesRow"]/*' />
[
SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly") // Unshares is OK.
]
protected virtual bool LeaveUnsharesRow(int rowIndex, bool throughMouseClick)
{
return false;
}
internal bool LeaveUnsharesRowInternal(int rowIndex, bool throughMouseClick)
{
return LeaveUnsharesRow(rowIndex, throughMouseClick);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.MeasureTextHeight1"]/*' />
[
EditorBrowsable(EditorBrowsableState.Advanced)
]
public static int MeasureTextHeight(Graphics graphics, string text, Font font, int maxWidth, TextFormatFlags flags)
{
bool widthTruncated;
return DataGridViewCell.MeasureTextHeight(graphics, text, font, maxWidth, flags, out widthTruncated);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.MeasureTextHeight2"]/*' />
[
EditorBrowsable(EditorBrowsableState.Advanced),
SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters"), // We don't want to use IDeviceContext here.
SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters") // out param OK here.
]
public static int MeasureTextHeight(Graphics graphics, string text, Font font, int maxWidth, TextFormatFlags flags, out bool widthTruncated)
{
if (graphics == null)
{
throw new ArgumentNullException(nameof(graphics));
}
if (font == null)
{
throw new ArgumentNullException(nameof(font));
}
if (maxWidth <= 0)
{
throw new ArgumentOutOfRangeException(nameof(maxWidth), string.Format(SR.InvalidLowBoundArgument, "maxWidth", (maxWidth).ToString(CultureInfo.CurrentCulture), (0).ToString(CultureInfo.CurrentCulture)));
}
if (!DataGridViewUtilities.ValidTextFormatFlags(flags))
{
throw new InvalidEnumArgumentException(nameof(flags), (int) flags, typeof(TextFormatFlags));
}
flags &= textFormatSupportedFlags;
// Dont use passed in graphics so we can optimze measurement
Size requiredSize = TextRenderer.MeasureText(text, font, new Size(maxWidth, System.Int32.MaxValue), flags);
widthTruncated = (requiredSize.Width > maxWidth);
return requiredSize.Height;
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.MeasureTextPreferredSize"]/*' />
[
EditorBrowsable(EditorBrowsableState.Advanced)
]
public static Size MeasureTextPreferredSize(Graphics graphics, string text, Font font, float maxRatio, TextFormatFlags flags)
{
if (graphics == null)
{
throw new ArgumentNullException(nameof(graphics));
}
if (font == null)
{
throw new ArgumentNullException(nameof(font));
}
if (maxRatio <= 0.0F)
{
throw new ArgumentOutOfRangeException(nameof(maxRatio), string.Format(SR.InvalidLowBoundArgument, "maxRatio", (maxRatio).ToString(CultureInfo.CurrentCulture), "0.0"));
}
if (!DataGridViewUtilities.ValidTextFormatFlags(flags))
{
throw new InvalidEnumArgumentException(nameof(flags), (int) flags, typeof(TextFormatFlags));
}
if (string.IsNullOrEmpty(text))
{
return new Size(0, 0);
}
Size textOneLineSize = DataGridViewCell.MeasureTextSize(graphics, text, font, flags);
if ((float)(textOneLineSize.Width / textOneLineSize.Height) <= maxRatio)
{
return textOneLineSize;
}
flags &= textFormatSupportedFlags;
float maxWidth = (float) (textOneLineSize.Width * textOneLineSize.Width) / (float) textOneLineSize.Height / maxRatio * 1.1F;
Size textSize;
do
{
// Dont use passed in graphics so we can optimze measurement
textSize = TextRenderer.MeasureText(text, font, new Size((int)maxWidth, System.Int32.MaxValue), flags);
if ((float)(textSize.Width / textSize.Height) <= maxRatio || textSize.Width > (int)maxWidth)
{
return textSize;
}
maxWidth = (float)textSize.Width * 0.9F;
}
while (maxWidth > 1.0F);
return textSize;
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.MeasureTextSize"]/*' />
[
EditorBrowsable(EditorBrowsableState.Advanced),
SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters") // We don't want to use IDeviceContext here.
]
public static Size MeasureTextSize(Graphics graphics, string text, Font font, TextFormatFlags flags)
{
if (graphics == null)
{
throw new ArgumentNullException(nameof(graphics));
}
if (font == null)
{
throw new ArgumentNullException(nameof(font));
}
if (!DataGridViewUtilities.ValidTextFormatFlags(flags))
{
throw new InvalidEnumArgumentException(nameof(flags), (int) flags, typeof(TextFormatFlags));
}
flags &= textFormatSupportedFlags;
// Dont use passed in graphics so we can optimze measurement
return TextRenderer.MeasureText(text, font, new Size(System.Int32.MaxValue, System.Int32.MaxValue), flags);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.MeasureTextWidth"]/*' />
[
EditorBrowsable(EditorBrowsableState.Advanced)
]
public static int MeasureTextWidth(Graphics graphics, string text, Font font, int maxHeight, TextFormatFlags flags)
{
if (maxHeight <= 0)
{
throw new ArgumentOutOfRangeException(nameof(maxHeight), string.Format(SR.InvalidLowBoundArgument, "maxHeight", (maxHeight).ToString(CultureInfo.CurrentCulture), (0).ToString(CultureInfo.CurrentCulture)));
}
Size oneLineSize = DataGridViewCell.MeasureTextSize(graphics, text, font, flags);
if (oneLineSize.Height >= maxHeight || (flags & TextFormatFlags.SingleLine) != 0)
{
return oneLineSize.Width;
}
else
{
flags &= textFormatSupportedFlags;
int lastFittingWidth = oneLineSize.Width;
float maxWidth = (float) lastFittingWidth * 0.9F;
Size textSize;
do
{
// Dont use passed in graphics so we can optimze measurement
textSize = TextRenderer.MeasureText(text, font, new Size((int)maxWidth, maxHeight), flags);
if (textSize.Height > maxHeight || textSize.Width > (int)maxWidth)
{
return lastFittingWidth;
}
else
{
lastFittingWidth = (int)maxWidth;
maxWidth = (float)textSize.Width * 0.9F;
}
}
while (maxWidth > 1.0F);
Debug.Assert(textSize.Height <= maxHeight);
return lastFittingWidth;
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.MouseClickUnsharesRow"]/*' />
[
SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly") // Unshares is OK.
]
protected virtual bool MouseClickUnsharesRow(DataGridViewCellMouseEventArgs e)
{
return false;
}
internal bool MouseClickUnsharesRowInternal(DataGridViewCellMouseEventArgs e)
{
return MouseClickUnsharesRow(e);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.MouseDoubleClickUnsharesRow"]/*' />
[
SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly") // Unshares is OK.
]
protected virtual bool MouseDoubleClickUnsharesRow(DataGridViewCellMouseEventArgs e)
{
return false;
}
internal bool MouseDoubleClickUnsharesRowInternal(DataGridViewCellMouseEventArgs e)
{
return MouseDoubleClickUnsharesRow(e);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.MouseDownUnsharesRow"]/*' />
[
SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly") // Unshares is OK.
]
protected virtual bool MouseDownUnsharesRow(DataGridViewCellMouseEventArgs e)
{
return false;
}
internal bool MouseDownUnsharesRowInternal(DataGridViewCellMouseEventArgs e)
{
return MouseDownUnsharesRow(e);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.MouseEnterUnsharesRow"]/*' />
[
SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly") // Unshares is OK.
]
protected virtual bool MouseEnterUnsharesRow(int rowIndex)
{
return false;
}
internal bool MouseEnterUnsharesRowInternal(int rowIndex)
{
return MouseEnterUnsharesRow(rowIndex);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.MouseLeaveUnsharesRow"]/*' />
[
SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly") // Unshares is OK.
]
protected virtual bool MouseLeaveUnsharesRow(int rowIndex)
{
return false;
}
internal bool MouseLeaveUnsharesRowInternal(int rowIndex)
{
return MouseLeaveUnsharesRow(rowIndex);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.MouseMoveUnsharesRow"]/*' />
[
SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly") // Unshares is OK.
]
protected virtual bool MouseMoveUnsharesRow(DataGridViewCellMouseEventArgs e)
{
return false;
}
internal bool MouseMoveUnsharesRowInternal(DataGridViewCellMouseEventArgs e)
{
return MouseMoveUnsharesRow(e);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.MouseUpUnsharesRow"]/*' />
[
SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly") // Unshares is OK.
]
protected virtual bool MouseUpUnsharesRow(DataGridViewCellMouseEventArgs e)
{
return false;
}
internal bool MouseUpUnsharesRowInternal(DataGridViewCellMouseEventArgs e)
{
return MouseUpUnsharesRow(e);
}
private void OnCellDataAreaMouseEnterInternal(int rowIndex)
{
Debug.Assert(this.DataGridView != null);
if (!this.DataGridView.ShowCellToolTips)
{
return;
}
// Don't show a tooltip for edited cells with an editing control
Point ptCurrentCell = this.DataGridView.CurrentCellAddress;
if (ptCurrentCell.X != -1 &&
ptCurrentCell.X == this.ColumnIndex &&
ptCurrentCell.Y == rowIndex &&
this.DataGridView.EditingControl != null)
{
Debug.Assert(this.DataGridView.IsCurrentCellInEditMode);
return;
}
// get the tool tip string
string toolTipText = GetToolTipText(rowIndex);
if (String.IsNullOrEmpty(toolTipText))
{
if (this.FormattedValueType == stringType)
{
if (rowIndex != -1 && this.OwningColumn != null)
{
int width = GetPreferredWidth(rowIndex, this.OwningRow.Height);
int height = GetPreferredHeight(rowIndex, this.OwningColumn.Width);
if (this.OwningColumn.Width < width || this.OwningRow.Height < height)
{
DataGridViewCellStyle dataGridViewCellStyle = GetInheritedStyle(null, rowIndex, false /*includeColors*/);
string editedFormattedValue = GetEditedFormattedValue(GetValue(rowIndex),
rowIndex,
ref dataGridViewCellStyle,
DataGridViewDataErrorContexts.Display) as string;
if (!string.IsNullOrEmpty(editedFormattedValue))
{
toolTipText = TruncateToolTipText(editedFormattedValue);
}
}
}
else if ((rowIndex != -1 && this.OwningRow != null && this.DataGridView.RowHeadersVisible && this.DataGridView.RowHeadersWidth > 0 && this.OwningColumn == null) ||
rowIndex == -1)
{
// we are on a header cell.
Debug.Assert(this is DataGridViewHeaderCell);
string stringValue = GetValue(rowIndex) as string;
if (!string.IsNullOrEmpty(stringValue))
{
DataGridViewCellStyle dataGridViewCellStyle = GetInheritedStyle(null, rowIndex, false);
using (Graphics g = WindowsFormsUtils.CreateMeasurementGraphics())
{
Rectangle contentBounds = GetContentBounds(g, dataGridViewCellStyle, rowIndex);
bool widthTruncated = false;
int preferredHeight = 0;
if (contentBounds.Width > 0)
{
preferredHeight = DataGridViewCell.GetPreferredTextHeight(g,
this.DataGridView.RightToLeftInternal,
stringValue,
dataGridViewCellStyle,
contentBounds.Width,
out widthTruncated);
}
else
{
widthTruncated = true;
}
if (preferredHeight > contentBounds.Height || widthTruncated)
{
toolTipText = TruncateToolTipText(stringValue);
}
}
}
}
}
}
else if (this.DataGridView.IsRestricted)
{
// In semi trust (demand for AllWindows fails), we truncate the tooltip at 256 if it exceeds 288 characters.
toolTipText = TruncateToolTipText(toolTipText);
}
if (!String.IsNullOrEmpty(toolTipText))
{
this.DataGridView.ActivateToolTip(true /*activate*/, toolTipText, this.ColumnIndex, rowIndex);
}
// for debugging
// Console.WriteLine("OnCellDATA_AreaMouseENTER. ToolTipText : " + toolTipText);
}
private void OnCellDataAreaMouseLeaveInternal()
{
if (this.DataGridView.IsDisposed)
{
return;
}
this.DataGridView.ActivateToolTip(false /*activate*/, string.Empty, -1, -1);
// for debugging
// Console.WriteLine("OnCellDATA_AreaMouseLEAVE");
}
private void OnCellErrorAreaMouseEnterInternal(int rowIndex)
{
string errorText = GetErrorText(rowIndex);
Debug.Assert(!String.IsNullOrEmpty(errorText), "if we entered the cell error area then an error was painted, so we should have an error");
this.DataGridView.ActivateToolTip(true /*activate*/, errorText, this.ColumnIndex, rowIndex);
// for debugging
// Console.WriteLine("OnCellERROR_AreaMouseENTER. ErrorText : " + errorText);
}
private void OnCellErrorAreaMouseLeaveInternal()
{
this.DataGridView.ActivateToolTip(false /*activate*/, string.Empty, -1, -1);
// for debugging
// Console.WriteLine("OnCellERROR_AreaMouseLEAVE");
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.OnClick"]/*' />
protected virtual void OnClick(DataGridViewCellEventArgs e)
{
}
internal void OnClickInternal(DataGridViewCellEventArgs e)
{
OnClick(e);
}
internal void OnCommonChange()
{
if (this.DataGridView != null && !this.DataGridView.IsDisposed && !this.DataGridView.Disposing)
{
if (this.RowIndex == -1)
{
// Invalidate and autosize column
this.DataGridView.OnColumnCommonChange(this.ColumnIndex);
}
else
{
// Invalidate and autosize cell
this.DataGridView.OnCellCommonChange(this.ColumnIndex, this.RowIndex);
}
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.OnContentClick"]/*' />
protected virtual void OnContentClick(DataGridViewCellEventArgs e)
{
}
internal void OnContentClickInternal(DataGridViewCellEventArgs e)
{
OnContentClick(e);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.OnContentDoubleClick"]/*' />
protected virtual void OnContentDoubleClick(DataGridViewCellEventArgs e)
{
}
internal void OnContentDoubleClickInternal(DataGridViewCellEventArgs e)
{
OnContentDoubleClick(e);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.OnDoubleClick"]/*' />
protected virtual void OnDoubleClick(DataGridViewCellEventArgs e)
{
}
internal void OnDoubleClickInternal(DataGridViewCellEventArgs e)
{
OnDoubleClick(e);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.OnEnter"]/*' />
protected virtual void OnEnter(int rowIndex, bool throughMouseClick)
{
}
internal void OnEnterInternal(int rowIndex, bool throughMouseClick)
{
OnEnter(rowIndex, throughMouseClick);
}
internal void OnKeyDownInternal(KeyEventArgs e, int rowIndex)
{
OnKeyDown(e, rowIndex);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.OnKeyDown"]/*' />
protected virtual void OnKeyDown(KeyEventArgs e, int rowIndex)
{
}
internal void OnKeyPressInternal(KeyPressEventArgs e, int rowIndex)
{
OnKeyPress(e, rowIndex);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.OnKeyPress"]/*' />
protected virtual void OnKeyPress(KeyPressEventArgs e, int rowIndex)
{
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.OnKeyUp"]/*' />
protected virtual void OnKeyUp(KeyEventArgs e, int rowIndex)
{
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.OnKeyUp"]/*' />
internal void OnKeyUpInternal(KeyEventArgs e, int rowIndex)
{
OnKeyUp(e, rowIndex);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.OnLeave"]/*' />
protected virtual void OnLeave(int rowIndex, bool throughMouseClick)
{
}
internal void OnLeaveInternal(int rowIndex, bool throughMouseClick)
{
OnLeave(rowIndex, throughMouseClick);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.OnMouseClick"]/*' />
protected virtual void OnMouseClick(DataGridViewCellMouseEventArgs e)
{
}
internal void OnMouseClickInternal(DataGridViewCellMouseEventArgs e)
{
OnMouseClick(e);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.OnMouseDoubleClick"]/*' />
protected virtual void OnMouseDoubleClick(DataGridViewCellMouseEventArgs e)
{
}
internal void OnMouseDoubleClickInternal(DataGridViewCellMouseEventArgs e)
{
OnMouseDoubleClick(e);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.OnMouseDown"]/*' />
protected virtual void OnMouseDown(DataGridViewCellMouseEventArgs e)
{
}
internal void OnMouseDownInternal(DataGridViewCellMouseEventArgs e)
{
this.DataGridView.CellMouseDownInContentBounds = GetContentBounds(e.RowIndex).Contains(e.X, e.Y);
if (((this.ColumnIndex < 0 || e.RowIndex < 0) && this.DataGridView.ApplyVisualStylesToHeaderCells) ||
((this.ColumnIndex >= 0 && e.RowIndex >= 0) && this.DataGridView.ApplyVisualStylesToInnerCells))
{
DataGridView.InvalidateCell(this.ColumnIndex, e.RowIndex);
}
OnMouseDown(e);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.OnMouseEnter"]/*' />
protected virtual void OnMouseEnter(int rowIndex)
{
}
internal void OnMouseEnterInternal(int rowIndex)
{
OnMouseEnter(rowIndex);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.OnMouseLeave"]/*' />
protected virtual void OnMouseLeave(int rowIndex)
{
}
internal void OnMouseLeaveInternal(int rowIndex)
{
switch (this.CurrentMouseLocation)
{
case DATAGRIDVIEWCELL_flagDataArea:
OnCellDataAreaMouseLeaveInternal();
break;
case DATAGRIDVIEWCELL_flagErrorArea:
OnCellErrorAreaMouseLeaveInternal();
break;
case DATAGRIDVIEWCELL_flagAreaNotSet:
break;
default:
Debug.Assert(false, "there are only three possible choices for the CurrentMouseLocation");
break;
}
this.CurrentMouseLocation = DATAGRIDVIEWCELL_flagAreaNotSet;
OnMouseLeave(rowIndex);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.OnMouseMove"]/*' />
protected virtual void OnMouseMove(DataGridViewCellMouseEventArgs e)
{
}
internal void OnMouseMoveInternal(DataGridViewCellMouseEventArgs e)
{
byte mouseLocation = this.CurrentMouseLocation;
UpdateCurrentMouseLocation(e);
Debug.Assert(this.CurrentMouseLocation != DATAGRIDVIEWCELL_flagAreaNotSet);
switch (mouseLocation)
{
case DATAGRIDVIEWCELL_flagAreaNotSet:
if (this.CurrentMouseLocation == DATAGRIDVIEWCELL_flagDataArea)
{
OnCellDataAreaMouseEnterInternal(e.RowIndex);
}
else
{
OnCellErrorAreaMouseEnterInternal(e.RowIndex);
}
break;
case DATAGRIDVIEWCELL_flagDataArea:
if (this.CurrentMouseLocation == DATAGRIDVIEWCELL_flagErrorArea)
{
OnCellDataAreaMouseLeaveInternal();
OnCellErrorAreaMouseEnterInternal(e.RowIndex);
}
break;
case DATAGRIDVIEWCELL_flagErrorArea:
if (this.CurrentMouseLocation == DATAGRIDVIEWCELL_flagDataArea)
{
OnCellErrorAreaMouseLeaveInternal();
OnCellDataAreaMouseEnterInternal(e.RowIndex);
}
break;
default:
Debug.Fail("there are only three choices for CurrentMouseLocation");
break;
}
OnMouseMove(e);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.OnMouseUp"]/*' />
protected virtual void OnMouseUp(DataGridViewCellMouseEventArgs e)
{
}
internal void OnMouseUpInternal(DataGridViewCellMouseEventArgs e)
{
int x = e.X;
int y = e.Y;
if (((this.ColumnIndex < 0 || e.RowIndex < 0) && this.DataGridView.ApplyVisualStylesToHeaderCells) ||
((this.ColumnIndex >= 0 && e.RowIndex >= 0) && this.DataGridView.ApplyVisualStylesToInnerCells))
{
this.DataGridView.InvalidateCell(this.ColumnIndex, e.RowIndex);
}
if (e.Button == MouseButtons.Left && GetContentBounds(e.RowIndex).Contains(x, y))
{
this.DataGridView.OnCommonCellContentClick(e.ColumnIndex, e.RowIndex, e.Clicks > 1);
}
if (this.DataGridView != null && e.ColumnIndex < this.DataGridView.Columns.Count && e.RowIndex < this.DataGridView.Rows.Count)
{
OnMouseUp(e);
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.OnDataGridViewChanged"]/*' />
protected override void OnDataGridViewChanged()
{
if (this.HasStyle)
{
if (this.DataGridView == null)
{
this.Style.RemoveScope(DataGridViewCellStyleScopes.Cell);
}
else
{
this.Style.AddScope(this.DataGridView, DataGridViewCellStyleScopes.Cell);
}
}
base.OnDataGridViewChanged();
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.Paint"]/*' />
protected virtual void Paint(Graphics graphics,
Rectangle clipBounds,
Rectangle cellBounds,
int rowIndex,
DataGridViewElementStates cellState,
object value,
object formattedValue,
string errorText,
DataGridViewCellStyle cellStyle,
DataGridViewAdvancedBorderStyle advancedBorderStyle,
DataGridViewPaintParts paintParts)
{
}
internal void PaintInternal(Graphics graphics,
Rectangle clipBounds,
Rectangle cellBounds,
int rowIndex,
DataGridViewElementStates cellState,
object value,
object formattedValue,
string errorText,
DataGridViewCellStyle cellStyle,
DataGridViewAdvancedBorderStyle advancedBorderStyle,
DataGridViewPaintParts paintParts)
{
Paint(graphics,
clipBounds,
cellBounds,
rowIndex,
cellState,
value,
formattedValue,
errorText,
cellStyle,
advancedBorderStyle,
paintParts);
}
internal static bool PaintBackground(DataGridViewPaintParts paintParts)
{
return (paintParts & DataGridViewPaintParts.Background) != 0;
}
internal static bool PaintBorder(DataGridViewPaintParts paintParts)
{
return (paintParts & DataGridViewPaintParts.Border) != 0;
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.PaintBorder"]/*' />
protected virtual void PaintBorder(Graphics graphics,
Rectangle clipBounds,
Rectangle bounds,
DataGridViewCellStyle cellStyle,
DataGridViewAdvancedBorderStyle advancedBorderStyle)
{
if (graphics == null)
{
throw new ArgumentNullException(nameof(graphics));
}
if (cellStyle == null)
{
throw new ArgumentNullException(nameof(cellStyle));
}
if (this.DataGridView == null)
{
return;
}
// Using system colors for non-single grid colors for now
int y1, y2;
Pen penControlDark = null, penControlLightLight = null;
Pen penBackColor = this.DataGridView.GetCachedPen(cellStyle.BackColor);
Pen penGridColor = this.DataGridView.GridPen;
GetContrastedPens(cellStyle.BackColor, ref penControlDark, ref penControlLightLight);
int dividerThickness = this.owningColumn == null ? 0 : this.owningColumn.DividerWidth;
if (dividerThickness != 0)
{
if (dividerThickness > bounds.Width)
{
dividerThickness = bounds.Width;
}
Color dividerWidthColor;
switch (advancedBorderStyle.Right)
{
case DataGridViewAdvancedCellBorderStyle.Single:
dividerWidthColor = this.DataGridView.GridPen.Color;
break;
case DataGridViewAdvancedCellBorderStyle.Inset:
dividerWidthColor = SystemColors.ControlLightLight;
break;
default: /* ie DataGridViewAdvancedCellBorderStyle.Outset, DataGridViewAdvancedCellBorderStyle.OutsetPartial, DataGridViewAdvancedCellBorderStyle.None */
dividerWidthColor = SystemColors.ControlDark;
break;
}
graphics.FillRectangle(this.DataGridView.GetCachedBrush(dividerWidthColor),
this.DataGridView.RightToLeftInternal ? bounds.X : bounds.Right - dividerThickness,
bounds.Y,
dividerThickness,
bounds.Height);
if (this.DataGridView.RightToLeftInternal)
{
bounds.X += dividerThickness;
}
bounds.Width -= dividerThickness;
if (bounds.Width <= 0)
{
return;
}
}
dividerThickness = this.owningRow == null ? 0 : this.owningRow.DividerHeight;
if (dividerThickness != 0)
{
if (dividerThickness > bounds.Height)
{
dividerThickness = bounds.Height;
}
Color dividerHeightColor;
switch (advancedBorderStyle.Bottom)
{
case DataGridViewAdvancedCellBorderStyle.Single:
dividerHeightColor = this.DataGridView.GridPen.Color;
break;
case DataGridViewAdvancedCellBorderStyle.Inset:
dividerHeightColor = SystemColors.ControlLightLight;
break;
default: /* ie DataGridViewAdvancedCellBorderStyle.Outset, DataGridViewAdvancedCellBorderStyle.OutsetPartial, DataGridViewAdvancedCellBorderStyle.None */
dividerHeightColor = SystemColors.ControlDark;
break;
}
graphics.FillRectangle(this.DataGridView.GetCachedBrush(dividerHeightColor), bounds.X, bounds.Bottom - dividerThickness, bounds.Width, dividerThickness);
bounds.Height -= dividerThickness;
if (bounds.Height <= 0)
{
return;
}
}
if (advancedBorderStyle.All == DataGridViewAdvancedCellBorderStyle.None)
{
return;
}
switch (advancedBorderStyle.Left)
{
case DataGridViewAdvancedCellBorderStyle.Single:
graphics.DrawLine(penGridColor, bounds.X, bounds.Y, bounds.X, bounds.Bottom - 1);
break;
case DataGridViewAdvancedCellBorderStyle.Inset:
graphics.DrawLine(penControlDark, bounds.X, bounds.Y, bounds.X, bounds.Bottom - 1);
break;
case DataGridViewAdvancedCellBorderStyle.Outset:
graphics.DrawLine(penControlLightLight, bounds.X, bounds.Y, bounds.X, bounds.Bottom - 1);
break;
case DataGridViewAdvancedCellBorderStyle.OutsetPartial:
y1 = bounds.Y + 2;
y2 = bounds.Bottom - 3;
if (advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.OutsetDouble ||
advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.InsetDouble)
{
y1++;
}
else if (advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.None)
{
y1--;
}
graphics.DrawLine(penBackColor, bounds.X, bounds.Y, bounds.X, bounds.Bottom - 1);
graphics.DrawLine(penControlLightLight, bounds.X, y1, bounds.X, y2);
break;
case DataGridViewAdvancedCellBorderStyle.OutsetDouble:
y1 = bounds.Y + 1;
y2 = bounds.Bottom - 1;
if (advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.OutsetPartial ||
advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.None)
{
y1--;
}
if (advancedBorderStyle.Bottom == DataGridViewAdvancedCellBorderStyle.OutsetPartial)
{
y2++;
}
graphics.DrawLine(penControlDark, bounds.X, bounds.Y, bounds.X, bounds.Bottom - 1);
graphics.DrawLine(penControlLightLight, bounds.X + 1, y1, bounds.X + 1, y2);
break;
case DataGridViewAdvancedCellBorderStyle.InsetDouble:
y1 = bounds.Y + 1;
y2 = bounds.Bottom - 1;
if (advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.OutsetPartial ||
advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.None)
{
y1--;
}
if (advancedBorderStyle.Bottom == DataGridViewAdvancedCellBorderStyle.OutsetPartial)
{
y2++;
}
graphics.DrawLine(penControlLightLight, bounds.X, bounds.Y, bounds.X, bounds.Bottom - 1);
graphics.DrawLine(penControlDark, bounds.X + 1, y1, bounds.X + 1, y2);
break;
}
switch (advancedBorderStyle.Right)
{
case DataGridViewAdvancedCellBorderStyle.Single:
graphics.DrawLine(penGridColor, bounds.Right - 1, bounds.Y, bounds.Right - 1, bounds.Bottom - 1);
break;
case DataGridViewAdvancedCellBorderStyle.Inset:
graphics.DrawLine(penControlLightLight, bounds.Right - 1, bounds.Y, bounds.Right - 1, bounds.Bottom - 1);
break;
case DataGridViewAdvancedCellBorderStyle.Outset:
graphics.DrawLine(penControlDark, bounds.Right - 1, bounds.Y, bounds.Right - 1, bounds.Bottom - 1);
break;
case DataGridViewAdvancedCellBorderStyle.OutsetPartial:
y1 = bounds.Y + 2;
y2 = bounds.Bottom - 3;
if (advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.OutsetDouble ||
advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.InsetDouble)
{
y1++;
}
else if (advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.None)
{
y1--;
}
graphics.DrawLine(penBackColor, bounds.Right - 1, bounds.Y, bounds.Right - 1, bounds.Bottom - 1);
graphics.DrawLine(penControlDark, bounds.Right - 1, y1, bounds.Right - 1, y2);
break;
case DataGridViewAdvancedCellBorderStyle.OutsetDouble:
y1 = bounds.Y + 1;
y2 = bounds.Bottom - 1;
if (advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.OutsetPartial ||
advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.None)
{
y1--;
}
if (advancedBorderStyle.Bottom == DataGridViewAdvancedCellBorderStyle.OutsetPartial)
{
y2++;
}
graphics.DrawLine(penControlDark, bounds.Right - 2, bounds.Y, bounds.Right - 2, bounds.Bottom - 1);
graphics.DrawLine(penControlLightLight, bounds.Right - 1, y1, bounds.Right - 1, y2);
break;
case DataGridViewAdvancedCellBorderStyle.InsetDouble:
y1 = bounds.Y + 1;
y2 = bounds.Bottom - 1;
if (advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.OutsetPartial ||
advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.None)
{
y1--;
}
if (advancedBorderStyle.Bottom == DataGridViewAdvancedCellBorderStyle.OutsetPartial ||
advancedBorderStyle.Bottom == DataGridViewAdvancedCellBorderStyle.Inset)
{
y2++;
}
graphics.DrawLine(penControlLightLight, bounds.Right - 2, bounds.Y, bounds.Right - 2, bounds.Bottom - 1);
graphics.DrawLine(penControlDark, bounds.Right - 1, y1, bounds.Right - 1, y2);
break;
}
int x1, x2;
switch (advancedBorderStyle.Top)
{
case DataGridViewAdvancedCellBorderStyle.Single:
graphics.DrawLine(penGridColor, bounds.X, bounds.Y, bounds.Right - 1, bounds.Y);
break;
case DataGridViewAdvancedCellBorderStyle.Inset:
x1 = bounds.X;
x2 = bounds.Right - 1;
if (advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.OutsetDouble ||
advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.InsetDouble)
{
x1++;
}
if (advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.Inset ||
advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.Outset)
{
x2--;
}
graphics.DrawLine(penControlDark, x1, bounds.Y, x2, bounds.Y);
break;
case DataGridViewAdvancedCellBorderStyle.Outset:
x1 = bounds.X;
x2 = bounds.Right - 1;
if (advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.OutsetDouble ||
advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.InsetDouble)
{
x1++;
}
if (advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.Inset ||
advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.Outset)
{
x2--;
}
graphics.DrawLine(penControlLightLight, x1, bounds.Y, x2, bounds.Y);
break;
case DataGridViewAdvancedCellBorderStyle.OutsetPartial:
x1 = bounds.X;
x2 = bounds.Right - 1;
if (advancedBorderStyle.Left != DataGridViewAdvancedCellBorderStyle.None /* && advancedBorderStyle.Left != DataGridViewAdvancedCellBorderStyle.OutsetPartial*/)
{
x1++;
if (advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.OutsetDouble ||
advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.InsetDouble)
{
x1++;
}
}
if (advancedBorderStyle.Right != DataGridViewAdvancedCellBorderStyle.None /* && advancedBorderStyle.Right != DataGridViewAdvancedCellBorderStyle.OutsetPartial*/)
{
x2--;
if (advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.OutsetDouble ||
advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.InsetDouble)
{
x2--;
}
}
graphics.DrawLine(penBackColor, x1, bounds.Y, x2, bounds.Y);
graphics.DrawLine(penControlLightLight, x1 + 1, bounds.Y, x2 - 1, bounds.Y);
break;
case DataGridViewAdvancedCellBorderStyle.OutsetDouble:
x1 = bounds.X;
if (advancedBorderStyle.Left != DataGridViewAdvancedCellBorderStyle.OutsetPartial &&
advancedBorderStyle.Left != DataGridViewAdvancedCellBorderStyle.None)
{
x1++;
}
x2 = bounds.Right - 2;
if (advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.OutsetPartial ||
advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.None)
{
x2++;
}
graphics.DrawLine(penControlDark, bounds.X, bounds.Y, bounds.Right - 1, bounds.Y);
graphics.DrawLine(penControlLightLight, x1, bounds.Y + 1, x2, bounds.Y + 1);
break;
case DataGridViewAdvancedCellBorderStyle.InsetDouble:
x1 = bounds.X;
if (advancedBorderStyle.Left != DataGridViewAdvancedCellBorderStyle.OutsetPartial &&
advancedBorderStyle.Left != DataGridViewAdvancedCellBorderStyle.None)
{
x1++;
}
x2 = bounds.Right - 2;
if (advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.OutsetPartial ||
advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.None)
{
x2++;
}
graphics.DrawLine(penControlLightLight, bounds.X, bounds.Y, bounds.Right - 1, bounds.Y);
graphics.DrawLine(penControlDark, x1, bounds.Y + 1, x2, bounds.Y + 1);
break;
}
switch (advancedBorderStyle.Bottom)
{
case DataGridViewAdvancedCellBorderStyle.Single:
graphics.DrawLine(penGridColor, bounds.X, bounds.Bottom - 1, bounds.Right - 1, bounds.Bottom - 1);
break;
case DataGridViewAdvancedCellBorderStyle.Inset:
x2 = bounds.Right - 1;
if (advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.InsetDouble)
{
x2--;
}
graphics.DrawLine(penControlLightLight, bounds.X, bounds.Bottom - 1, x2, bounds.Bottom - 1);
break;
case DataGridViewAdvancedCellBorderStyle.Outset:
x1 = bounds.X;
x2 = bounds.Right - 1;
if (advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.InsetDouble ||
advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.OutsetDouble)
{
x2--;
}
graphics.DrawLine(penControlDark, x1, bounds.Bottom - 1, x2, bounds.Bottom - 1);
break;
case DataGridViewAdvancedCellBorderStyle.OutsetPartial:
x1 = bounds.X;
x2 = bounds.Right - 1;
if (advancedBorderStyle.Left != DataGridViewAdvancedCellBorderStyle.None /* && advancedBorderStyle.Left != DataGridViewAdvancedCellBorderStyle.OutsetPartial*/)
{
x1++;
if (advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.OutsetDouble ||
advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.InsetDouble)
{
x1++;
}
}
if (advancedBorderStyle.Right != DataGridViewAdvancedCellBorderStyle.None /* && advancedBorderStyle.Right != DataGridViewAdvancedCellBorderStyle.OutsetPartial*/)
{
x2--;
if (advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.OutsetDouble ||
advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.InsetDouble)
{
x2--;
}
}
graphics.DrawLine(penBackColor, x1, bounds.Bottom - 1, x2, bounds.Bottom - 1);
graphics.DrawLine(penControlDark, x1 + 1, bounds.Bottom - 1, x2 - 1, bounds.Bottom - 1);
break;
}
#if DGV_GDI
// Using system colors for non-single grid colors for now
int y1, y2;
WindowsPen penControlDark = null, penControlLightLight = null;
WindowsPen penBackColor = this.DataGridView.GetCachedWindowsPen(cellStyle.BackColor);
WindowsPen penGridColor = this.DataGridView.GetCachedWindowsPen(this.DataGridView.GridColor);
GetContrastedWindowsPens(cellStyle.BackColor, ref penControlDark, ref penControlLightLight);
using (WindowsGraphics windowsGraphics = WindowsGraphics.FromGraphics(graphics))
{
int dividerThickness = this.owningColumn == null ? 0 : this.owningColumn.DividerWidth;
if (dividerThickness != 0)
{
if (dividerThickness > bounds.Width)
{
dividerThickness = bounds.Width;
}
Color dividerWidthColor;
switch (advancedBorderStyle.Right)
{
case DataGridViewAdvancedCellBorderStyle.Single:
dividerWidthColor = this.DataGridView.GridPen.Color;
break;
case DataGridViewAdvancedCellBorderStyle.Inset:
dividerWidthColor = SystemColors.ControlLightLight;
break;
default: /* ie DataGridViewAdvancedCellBorderStyle.Outset, DataGridViewAdvancedCellBorderStyle.OutsetPartial, DataGridViewAdvancedCellBorderStyle.None */
dividerWidthColor = SystemColors.ControlDark;
break;
}
windowsGraphics.FillRectangle(this.DataGridView.GetCachedWindowsBrush(dividerWidthColor),
this.DataGridView.RightToLeftInternal ? bounds.X : bounds.Right - dividerThickness,
bounds.Y,
dividerThickness,
bounds.Height);
if (this.DataGridView.RightToLeftInternal)
{
bounds.X += dividerThickness;
}
bounds.Width -= dividerThickness;
if (bounds.Width <= 0)
{
return;
}
}
dividerThickness = this.owningRow == null ? 0 : this.owningRow.DividerHeight;
if (dividerThickness != 0)
{
if (dividerThickness > bounds.Height)
{
dividerThickness = bounds.Height;
}
Color dividerHeightColor;
switch (advancedBorderStyle.Bottom)
{
case DataGridViewAdvancedCellBorderStyle.Single:
dividerHeightColor = this.DataGridView.GridPen.Color;
break;
case DataGridViewAdvancedCellBorderStyle.Inset:
dividerHeightColor = SystemColors.ControlLightLight;
break;
default: /* ie DataGridViewAdvancedCellBorderStyle.Outset, DataGridViewAdvancedCellBorderStyle.OutsetPartial, DataGridViewAdvancedCellBorderStyle.None */
dividerHeightColor = SystemColors.ControlDark;
break;
}
windowsGraphics.FillRectangle(this.DataGridView.GetCachedWindowsBrush(dividerHeightColor), bounds.X, bounds.Bottom - dividerThickness, bounds.Width, dividerThickness);
bounds.Height -= dividerThickness;
if (bounds.Height <= 0)
{
return;
}
}
if (advancedBorderStyle.All == DataGridViewAdvancedCellBorderStyle.None)
{
return;
}
switch (advancedBorderStyle.Left)
{
case DataGridViewAdvancedCellBorderStyle.Single:
windowsGraphics.DrawLine(penGridColor, bounds.X, bounds.Y, bounds.X, bounds.Bottom - 1);
break;
case DataGridViewAdvancedCellBorderStyle.Inset:
windowsGraphics.DrawLine(penControlDark, bounds.X, bounds.Y, bounds.X, bounds.Bottom - 1);
break;
case DataGridViewAdvancedCellBorderStyle.Outset:
windowsGraphics.DrawLine(penControlLightLight, bounds.X, bounds.Y, bounds.X, bounds.Bottom - 1);
break;
case DataGridViewAdvancedCellBorderStyle.OutsetPartial:
y1 = bounds.Y + 2;
y2 = bounds.Bottom - 3;
if (advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.OutsetDouble ||
advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.InsetDouble)
{
y1++;
}
else if (advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.None)
{
y1--;
}
windowsGraphics.DrawLine(penBackColor, bounds.X, bounds.Y, bounds.X, bounds.Bottom - 1);
windowsGraphics.DrawLine(penControlLightLight, bounds.X, y1, bounds.X, y2);
break;
case DataGridViewAdvancedCellBorderStyle.OutsetDouble:
y1 = bounds.Y + 1;
y2 = bounds.Bottom - 1;
if (advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.OutsetPartial ||
advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.None)
{
y1--;
}
if (advancedBorderStyle.Bottom == DataGridViewAdvancedCellBorderStyle.OutsetPartial)
{
y2++;
}
windowsGraphics.DrawLine(penControlDark, bounds.X, bounds.Y, bounds.X, bounds.Bottom - 1);
windowsGraphics.DrawLine(penControlLightLight, bounds.X + 1, y1, bounds.X + 1, y2);
break;
case DataGridViewAdvancedCellBorderStyle.InsetDouble:
y1 = bounds.Y + 1;
y2 = bounds.Bottom - 1;
if (advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.OutsetPartial ||
advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.None)
{
y1--;
}
if (advancedBorderStyle.Bottom == DataGridViewAdvancedCellBorderStyle.OutsetPartial)
{
y2++;
}
windowsGraphics.DrawLine(penControlLightLight, bounds.X, bounds.Y, bounds.X, bounds.Bottom - 1);
windowsGraphics.DrawLine(penControlDark, bounds.X + 1, y1, bounds.X + 1, y2);
break;
}
switch (advancedBorderStyle.Right)
{
case DataGridViewAdvancedCellBorderStyle.Single:
windowsGraphics.DrawLine(penGridColor, bounds.Right - 1, bounds.Y, bounds.Right - 1, bounds.Bottom - 1);
break;
case DataGridViewAdvancedCellBorderStyle.Inset:
windowsGraphics.DrawLine(penControlLightLight, bounds.Right - 1, bounds.Y, bounds.Right - 1, bounds.Bottom - 1);
break;
case DataGridViewAdvancedCellBorderStyle.Outset:
windowsGraphics.DrawLine(penControlDark, bounds.Right - 1, bounds.Y, bounds.Right - 1, bounds.Bottom - 1);
break;
case DataGridViewAdvancedCellBorderStyle.OutsetPartial:
y1 = bounds.Y + 2;
y2 = bounds.Bottom - 3;
if (advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.OutsetDouble ||
advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.InsetDouble)
{
y1++;
}
else if (advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.None)
{
y1--;
}
windowsGraphics.DrawLine(penBackColor, bounds.Right - 1, bounds.Y, bounds.Right - 1, bounds.Bottom - 1);
windowsGraphics.DrawLine(penControlDark, bounds.Right - 1, y1, bounds.Right - 1, y2);
break;
case DataGridViewAdvancedCellBorderStyle.OutsetDouble:
y1 = bounds.Y + 1;
y2 = bounds.Bottom - 1;
if (advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.OutsetPartial ||
advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.None)
{
y1--;
}
if (advancedBorderStyle.Bottom == DataGridViewAdvancedCellBorderStyle.OutsetPartial)
{
y2++;
}
windowsGraphics.DrawLine(penControlDark, bounds.Right - 2, bounds.Y, bounds.Right - 2, bounds.Bottom - 1);
windowsGraphics.DrawLine(penControlLightLight, bounds.Right - 1, y1, bounds.Right - 1, y2);
break;
case DataGridViewAdvancedCellBorderStyle.InsetDouble:
y1 = bounds.Y + 1;
y2 = bounds.Bottom - 1;
if (advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.OutsetPartial ||
advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.None)
{
y1--;
}
if (advancedBorderStyle.Bottom == DataGridViewAdvancedCellBorderStyle.OutsetPartial ||
advancedBorderStyle.Bottom == DataGridViewAdvancedCellBorderStyle.Inset)
{
y2++;
}
windowsGraphics.DrawLine(penControlLightLight, bounds.Right - 2, bounds.Y, bounds.Right - 2, bounds.Bottom - 1);
windowsGraphics.DrawLine(penControlDark, bounds.Right - 1, y1, bounds.Right - 1, y2);
break;
}
int x1, x2;
switch (advancedBorderStyle.Top)
{
case DataGridViewAdvancedCellBorderStyle.Single:
windowsGraphics.DrawLine(penGridColor, bounds.X, bounds.Y, bounds.Right - 1, bounds.Y);
break;
case DataGridViewAdvancedCellBorderStyle.Inset:
x1 = bounds.X;
x2 = bounds.Right - 1;
if (advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.OutsetDouble ||
advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.InsetDouble)
{
x1++;
}
if (advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.Inset ||
advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.Outset)
{
x2--;
}
windowsGraphics.DrawLine(penControlDark, x1, bounds.Y, x2, bounds.Y);
break;
case DataGridViewAdvancedCellBorderStyle.Outset:
x1 = bounds.X;
x2 = bounds.Right - 1;
if (advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.OutsetDouble ||
advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.InsetDouble)
{
x1++;
}
if (advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.Inset ||
advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.Outset)
{
x2--;
}
windowsGraphics.DrawLine(penControlLightLight, x1, bounds.Y, x2, bounds.Y);
break;
case DataGridViewAdvancedCellBorderStyle.OutsetPartial:
x1 = bounds.X;
x2 = bounds.Right - 1;
if (advancedBorderStyle.Left != DataGridViewAdvancedCellBorderStyle.None /* && advancedBorderStyle.Left != DataGridViewAdvancedCellBorderStyle.OutsetPartial*/)
{
x1++;
if (advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.OutsetDouble ||
advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.InsetDouble)
{
x1++;
}
}
if (advancedBorderStyle.Right != DataGridViewAdvancedCellBorderStyle.None /* && advancedBorderStyle.Right != DataGridViewAdvancedCellBorderStyle.OutsetPartial*/)
{
x2--;
if (advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.OutsetDouble ||
advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.InsetDouble)
{
x2--;
}
}
windowsGraphics.DrawLine(penBackColor, x1, bounds.Y, x2, bounds.Y);
windowsGraphics.DrawLine(penControlLightLight, x1 + 1, bounds.Y, x2 - 1, bounds.Y);
break;
case DataGridViewAdvancedCellBorderStyle.OutsetDouble:
x1 = bounds.X;
if (advancedBorderStyle.Left != DataGridViewAdvancedCellBorderStyle.OutsetPartial &&
advancedBorderStyle.Left != DataGridViewAdvancedCellBorderStyle.None)
{
x1++;
}
x2 = bounds.Right - 2;
if (advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.OutsetPartial ||
advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.None)
{
x2++;
}
windowsGraphics.DrawLine(penControlDark, bounds.X, bounds.Y, bounds.Right - 1, bounds.Y);
windowsGraphics.DrawLine(penControlLightLight, x1, bounds.Y + 1, x2, bounds.Y + 1);
break;
case DataGridViewAdvancedCellBorderStyle.InsetDouble:
x1 = bounds.X;
if (advancedBorderStyle.Left != DataGridViewAdvancedCellBorderStyle.OutsetPartial &&
advancedBorderStyle.Left != DataGridViewAdvancedCellBorderStyle.None)
{
x1++;
}
x2 = bounds.Right - 2;
if (advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.OutsetPartial ||
advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.None)
{
x2++;
}
windowsGraphics.DrawLine(penControlLightLight, bounds.X, bounds.Y, bounds.Right - 1, bounds.Y);
windowsGraphics.DrawLine(penControlDark, x1, bounds.Y + 1, x2, bounds.Y + 1);
break;
}
switch (advancedBorderStyle.Bottom)
{
case DataGridViewAdvancedCellBorderStyle.Single:
windowsGraphics.DrawLine(penGridColor, bounds.X, bounds.Bottom - 1, bounds.Right - 1, bounds.Bottom - 1);
break;
case DataGridViewAdvancedCellBorderStyle.Inset:
x2 = bounds.Right - 1;
if (advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.InsetDouble)
{
x2--;
}
windowsGraphics.DrawLine(penControlLightLight, bounds.X, bounds.Bottom - 1, x2, bounds.Bottom - 1);
break;
case DataGridViewAdvancedCellBorderStyle.Outset:
x1 = bounds.X;
x2 = bounds.Right - 1;
if (advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.InsetDouble ||
advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.OutsetDouble)
{
x2--;
}
windowsGraphics.DrawLine(penControlDark, x1, bounds.Bottom - 1, x2, bounds.Bottom - 1);
break;
case DataGridViewAdvancedCellBorderStyle.OutsetPartial:
x1 = bounds.X;
x2 = bounds.Right - 1;
if (advancedBorderStyle.Left != DataGridViewAdvancedCellBorderStyle.None /* && advancedBorderStyle.Left != DataGridViewAdvancedCellBorderStyle.OutsetPartial*/)
{
x1++;
if (advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.OutsetDouble ||
advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.InsetDouble)
{
x1++;
}
}
if (advancedBorderStyle.Right != DataGridViewAdvancedCellBorderStyle.None /* && advancedBorderStyle.Right != DataGridViewAdvancedCellBorderStyle.OutsetPartial*/)
{
x2--;
if (advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.OutsetDouble ||
advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.InsetDouble)
{
x2--;
}
}
windowsGraphics.DrawLine(penBackColor, x1, bounds.Bottom - 1, x2, bounds.Bottom - 1);
windowsGraphics.DrawLine(penControlDark, x1 + 1, bounds.Bottom - 1, x2 - 1, bounds.Bottom - 1);
break;
}
}
#endif // DGV_GDI
}
internal static bool PaintContentBackground(DataGridViewPaintParts paintParts)
{
return (paintParts & DataGridViewPaintParts.ContentBackground) != 0;
}
internal static bool PaintContentForeground(DataGridViewPaintParts paintParts)
{
return (paintParts & DataGridViewPaintParts.ContentForeground) != 0;
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.PaintErrorIcon"]/*' />
protected virtual void PaintErrorIcon(Graphics graphics, Rectangle clipBounds, Rectangle cellValueBounds, string errorText)
{
if (!string.IsNullOrEmpty(errorText) &&
cellValueBounds.Width >= DATAGRIDVIEWCELL_iconMarginWidth*2+iconsWidth &&
cellValueBounds.Height >= DATAGRIDVIEWCELL_iconMarginHeight * 2 + iconsHeight)
{
PaintErrorIcon(graphics, ComputeErrorIconBounds(cellValueBounds));
}
}
[SuppressMessage("Microsoft.Reliability", "CA2002:DoNotLockOnObjectsWithWeakIdentity")]
private static void PaintErrorIcon(Graphics graphics, Rectangle iconBounds)
{
Bitmap bmp = DataGridViewCell.ErrorBitmap;
if (bmp != null)
{
lock (bmp)
{
graphics.DrawImage(bmp, iconBounds, 0, 0, iconsWidth, iconsHeight, GraphicsUnit.Pixel);
}
}
}
internal void PaintErrorIcon(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex, Rectangle cellBounds, Rectangle cellValueBounds, string errorText)
{
if (!string.IsNullOrEmpty(errorText) &&
cellValueBounds.Width >= DATAGRIDVIEWCELL_iconMarginWidth * 2 + iconsWidth &&
cellValueBounds.Height >= DATAGRIDVIEWCELL_iconMarginHeight * 2 + iconsHeight)
{
Rectangle iconBounds = GetErrorIconBounds(graphics, cellStyle, rowIndex);
if (iconBounds.Width >= DATAGRIDVIEWCELL_iconMarginWidth && iconBounds.Height >= iconsHeight)
{
iconBounds.X += cellBounds.X;
iconBounds.Y += cellBounds.Y;
PaintErrorIcon(graphics, iconBounds);
}
}
}
internal static bool PaintErrorIcon(DataGridViewPaintParts paintParts)
{
return (paintParts & DataGridViewPaintParts.ErrorIcon) != 0;
}
internal static bool PaintFocus(DataGridViewPaintParts paintParts)
{
return (paintParts & DataGridViewPaintParts.Focus) != 0;
}
static internal void PaintPadding(Graphics graphics,
Rectangle bounds,
DataGridViewCellStyle cellStyle,
Brush br,
bool rightToLeft)
{
Rectangle rectPadding;
if (rightToLeft)
{
rectPadding = new Rectangle(bounds.X, bounds.Y, cellStyle.Padding.Right, bounds.Height);
graphics.FillRectangle(br, rectPadding);
rectPadding.X = bounds.Right - cellStyle.Padding.Left;
rectPadding.Width = cellStyle.Padding.Left;
graphics.FillRectangle(br, rectPadding);
rectPadding.X = bounds.Left + cellStyle.Padding.Right;
}
else
{
rectPadding = new Rectangle(bounds.X, bounds.Y, cellStyle.Padding.Left, bounds.Height);
graphics.FillRectangle(br, rectPadding);
rectPadding.X = bounds.Right - cellStyle.Padding.Right;
rectPadding.Width = cellStyle.Padding.Right;
graphics.FillRectangle(br, rectPadding);
rectPadding.X = bounds.Left + cellStyle.Padding.Left;
}
rectPadding.Y = bounds.Y;
rectPadding.Width = bounds.Width - cellStyle.Padding.Horizontal;
rectPadding.Height = cellStyle.Padding.Top;
graphics.FillRectangle(br, rectPadding);
rectPadding.Y = bounds.Bottom - cellStyle.Padding.Bottom;
rectPadding.Height = cellStyle.Padding.Bottom;
graphics.FillRectangle(br, rectPadding);
}
internal static bool PaintSelectionBackground(DataGridViewPaintParts paintParts)
{
return (paintParts & DataGridViewPaintParts.SelectionBackground) != 0;
}
internal void PaintWork(Graphics graphics,
Rectangle clipBounds,
Rectangle cellBounds,
int rowIndex,
DataGridViewElementStates cellState,
DataGridViewCellStyle cellStyle,
DataGridViewAdvancedBorderStyle advancedBorderStyle,
DataGridViewPaintParts paintParts)
{
Debug.Assert(this.DataGridView != null);
DataGridView dataGridView = this.DataGridView;
int columnIndex = this.ColumnIndex;
object formattedValue, value = GetValue(rowIndex);
string errorText = GetErrorText(rowIndex);
if (columnIndex > -1 && rowIndex > -1)
{
formattedValue = GetEditedFormattedValue(value, rowIndex, ref cellStyle, DataGridViewDataErrorContexts.Formatting | DataGridViewDataErrorContexts.Display);
}
else
{
// No formatting applied on header cells.
formattedValue = value;
}
DataGridViewCellPaintingEventArgs dgvcpe = dataGridView.CellPaintingEventArgs;
dgvcpe.SetProperties(graphics,
clipBounds,
cellBounds,
rowIndex,
columnIndex,
cellState,
value,
formattedValue,
errorText,
cellStyle,
advancedBorderStyle,
paintParts);
dataGridView.OnCellPainting(dgvcpe);
if (dgvcpe.Handled)
{
return;
}
Paint(graphics,
clipBounds,
cellBounds,
rowIndex,
cellState,
value,
formattedValue,
errorText,
cellStyle,
advancedBorderStyle,
paintParts);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.ParseFormattedValue"]/*' />
public virtual object ParseFormattedValue(object formattedValue,
DataGridViewCellStyle cellStyle,
TypeConverter formattedValueTypeConverter,
TypeConverter valueTypeConverter)
{
return ParseFormattedValueInternal(this.ValueType, formattedValue, cellStyle, formattedValueTypeConverter, valueTypeConverter);
}
internal object ParseFormattedValueInternal(Type valueType,
object formattedValue,
DataGridViewCellStyle cellStyle,
TypeConverter formattedValueTypeConverter,
TypeConverter valueTypeConverter)
{
if (cellStyle == null)
{
throw new ArgumentNullException(nameof(cellStyle));
}
if (this.FormattedValueType == null)
{
throw new FormatException(string.Format(SR.DataGridViewCell_FormattedValueTypeNull));
}
if (valueType == null)
{
throw new FormatException(string.Format(SR.DataGridViewCell_ValueTypeNull));
}
if (formattedValue == null ||
!this.FormattedValueType.IsAssignableFrom(formattedValue.GetType()))
{
throw new ArgumentException(string.Format(SR.DataGridViewCell_FormattedValueHasWrongType), "formattedValue");
}
return Formatter.ParseObject(formattedValue,
valueType,
this.FormattedValueType,
valueTypeConverter == null ? this.ValueTypeConverter : valueTypeConverter /*sourceConverter*/,
formattedValueTypeConverter == null ? this.FormattedValueTypeConverter : formattedValueTypeConverter /*targetConverter*/,
cellStyle.FormatProvider,
cellStyle.NullValue,
cellStyle.IsDataSourceNullValueDefault ? Formatter.GetDefaultDataSourceNullValue(valueType) : cellStyle.DataSourceNullValue);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.PositionEditingControl"]/*' />
[
EditorBrowsable(EditorBrowsableState.Advanced)
]
public virtual void PositionEditingControl(
bool setLocation,
bool setSize,
Rectangle cellBounds,
Rectangle cellClip,
DataGridViewCellStyle cellStyle,
bool singleVerticalBorderAdded,
bool singleHorizontalBorderAdded,
bool isFirstDisplayedColumn,
bool isFirstDisplayedRow)
{
Rectangle editingControlBounds = PositionEditingPanel(cellBounds,
cellClip,
cellStyle,
singleVerticalBorderAdded,
singleHorizontalBorderAdded,
isFirstDisplayedColumn,
isFirstDisplayedRow);
if (setLocation)
{
this.DataGridView.EditingControl.Location = new Point(editingControlBounds.X, editingControlBounds.Y);
}
if (setSize)
{
this.DataGridView.EditingControl.Size = new Size(editingControlBounds.Width, editingControlBounds.Height);
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.PositionEditingPanel"]/*' />
[
EditorBrowsable(EditorBrowsableState.Advanced),
SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters") // singleVerticalBorderAdded/singleHorizontalBorderAdded names are OK
]
// Positions the editing panel and returns the normal bounds of the editing control, within the editing panel.
public virtual Rectangle PositionEditingPanel(Rectangle cellBounds,
Rectangle cellClip,
DataGridViewCellStyle cellStyle,
bool singleVerticalBorderAdded,
bool singleHorizontalBorderAdded,
bool isFirstDisplayedColumn,
bool isFirstDisplayedRow)
{
if (this.DataGridView == null)
{
throw new InvalidOperationException();
}
DataGridViewAdvancedBorderStyle dataGridViewAdvancedBorderStylePlaceholder = new DataGridViewAdvancedBorderStyle(), dgvabsEffective;
dgvabsEffective = AdjustCellBorderStyle(this.DataGridView.AdvancedCellBorderStyle,
dataGridViewAdvancedBorderStylePlaceholder,
singleVerticalBorderAdded,
singleHorizontalBorderAdded,
isFirstDisplayedColumn,
isFirstDisplayedRow);
Rectangle borderAndPaddingWidths = BorderWidths(dgvabsEffective);
borderAndPaddingWidths.X += cellStyle.Padding.Left;
borderAndPaddingWidths.Y += cellStyle.Padding.Top;
borderAndPaddingWidths.Width += cellStyle.Padding.Right;
borderAndPaddingWidths.Height += cellStyle.Padding.Bottom;
int xEditingPanel, wEditingPanel = cellBounds.Width;
int xEditingControl, wEditingControl;
int yEditingPanel, hEditingPanel = cellBounds.Height;
int yEditingControl, hEditingControl;
if (cellClip.X - cellBounds.X >= borderAndPaddingWidths.X)
{
xEditingPanel = cellClip.X;
wEditingPanel -= cellClip.X - cellBounds.X;
}
else
{
xEditingPanel = cellBounds.X + borderAndPaddingWidths.X;
wEditingPanel -= borderAndPaddingWidths.X;
}
if (cellClip.Right <= cellBounds.Right - borderAndPaddingWidths.Width)
{
wEditingPanel -= cellBounds.Right - cellClip.Right;
}
else
{
wEditingPanel -= borderAndPaddingWidths.Width;
}
xEditingControl = cellBounds.X - cellClip.X;
wEditingControl = cellBounds.Width - borderAndPaddingWidths.X - borderAndPaddingWidths.Width;
if (cellClip.Y - cellBounds.Y >= borderAndPaddingWidths.Y)
{
yEditingPanel = cellClip.Y;
hEditingPanel -= cellClip.Y - cellBounds.Y;
}
else
{
yEditingPanel = cellBounds.Y + borderAndPaddingWidths.Y;
hEditingPanel -= borderAndPaddingWidths.Y;
}
if (cellClip.Bottom <= cellBounds.Bottom - borderAndPaddingWidths.Height)
{
hEditingPanel -= cellBounds.Bottom - cellClip.Bottom;
}
else
{
hEditingPanel -= borderAndPaddingWidths.Height;
}
yEditingControl = cellBounds.Y - cellClip.Y;
hEditingControl = cellBounds.Height - borderAndPaddingWidths.Y - borderAndPaddingWidths.Height;
this.DataGridView.EditingPanel.Location = new Point(xEditingPanel, yEditingPanel);
this.DataGridView.EditingPanel.Size = new Size(wEditingPanel, hEditingPanel);
/*
if (this.DataGridView.RightToLeftInternal)
{
xEditingControl = wEditingPanel - xEditingControl - wEditingControl;
}
*/
return new Rectangle(xEditingControl, yEditingControl, wEditingControl, hEditingControl);
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.SetValue"]/*' />
protected virtual bool SetValue(int rowIndex, object value)
{
object originalValue = null;
DataGridView dataGridView = this.DataGridView;
if (dataGridView != null && !dataGridView.InSortOperation)
{
originalValue = GetValue(rowIndex);
}
if (dataGridView != null && this.OwningColumn != null && this.OwningColumn.IsDataBound)
{
DataGridView.DataGridViewDataConnection dataConnection = dataGridView.DataConnection;
if (dataConnection == null)
{
return false;
}
else if (dataConnection.CurrencyManager.Count <= rowIndex)
{
if (value != null || this.Properties.ContainsObject(PropCellValue))
{
this.Properties.SetObject(PropCellValue, value);
}
}
else
{
if (dataConnection.PushValue(this.OwningColumn.BoundColumnIndex, this.ColumnIndex, rowIndex, value))
{
if (this.DataGridView == null || this.OwningRow == null || this.OwningRow.DataGridView == null)
{
// As a result of pushing the value in the back end, the data grid view row and/or data grid view cell
// became disconnected from the DataGridView.
// Return true because the operation succeded.
// However, because the row which was edited became disconnected from the DataGridView,
// do not mark the current row in the data grid view as being dirty.
// And because the data grid view cell which was edited became disconnected from the data grid view
// do not fire CellValueChanged event.
return true;
}
if (this.OwningRow.Index == this.DataGridView.CurrentCellAddress.Y)
{
// The user programatically changed a value in the current row.
// The DataGridView already opened a transaction for the current row.
// All is left to do is to mark the current row in the DataGridView as being dirty.
this.DataGridView.IsCurrentRowDirtyInternal = true;
}
}
else
{
return false;
}
}
}
else if (dataGridView == null ||
!dataGridView.VirtualMode ||
rowIndex == -1 ||
this.ColumnIndex == -1)
{
if (value != null || this.Properties.ContainsObject(PropCellValue))
{
this.Properties.SetObject(PropCellValue, value);
}
}
else
{
Debug.Assert(rowIndex >= 0);
Debug.Assert(this.ColumnIndex >= 0);
dataGridView.OnCellValuePushed(this.ColumnIndex, rowIndex, value);
}
if (dataGridView != null &&
!dataGridView.InSortOperation &&
((originalValue == null && value != null) ||
(originalValue != null && value == null) ||
(originalValue != null && !value.Equals(originalValue))))
{
RaiseCellValueChanged(new DataGridViewCellEventArgs(this.ColumnIndex, rowIndex));
}
return true;
}
internal bool SetValueInternal(int rowIndex, object value)
{
return SetValue(rowIndex, value);
}
internal static bool TextFitsInBounds(Graphics graphics, string text, Font font, Size maxBounds, TextFormatFlags flags)
{
bool widthTruncated;
int requiredHeight = DataGridViewCell.MeasureTextHeight(graphics, text, font, maxBounds.Width, flags, out widthTruncated);
return requiredHeight <= maxBounds.Height && !widthTruncated;
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.ToString"]/*' />
/// <devdoc>
/// <para>
/// Gets the row Index and column Index of the cell.
/// </para>
/// </devdoc>
public override string ToString()
{
return "DataGridViewCell { ColumnIndex=" + this.ColumnIndex.ToString(CultureInfo.CurrentCulture) + ", RowIndex=" + this.RowIndex.ToString(CultureInfo.CurrentCulture) + " }";
}
private static string TruncateToolTipText(string toolTipText)
{
if (toolTipText.Length > DATAGRIDVIEWCELL_maxToolTipLength)
{
StringBuilder sb = new StringBuilder(toolTipText.Substring(0, DATAGRIDVIEWCELL_maxToolTipCutOff), DATAGRIDVIEWCELL_maxToolTipCutOff + DATAGRIDVIEWCELL_toolTipEllipsisLength);
sb.Append(DATAGRIDVIEWCELL_toolTipEllipsis);
return sb.ToString();
}
return toolTipText;
}
private void UpdateCurrentMouseLocation(DataGridViewCellMouseEventArgs e)
{
if (GetErrorIconBounds(e.RowIndex).Contains(e.X, e.Y))
{
this.CurrentMouseLocation = DATAGRIDVIEWCELL_flagErrorArea;
}
else
{
this.CurrentMouseLocation = DATAGRIDVIEWCELL_flagDataArea;
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCellAccessibleObject"]/*' />
[
System.Runtime.InteropServices.ComVisible(true)
]
protected class DataGridViewCellAccessibleObject : AccessibleObject
{
private int[] runtimeId = null; // Used by UIAutomation
DataGridViewCell owner;
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCellAccessibleObject.DataGridViewCellAccessibleObject1"]/*' />
public DataGridViewCellAccessibleObject()
{
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCellAccessibleObject.DataGridViewCellAccessibleObject2"]/*' />
public DataGridViewCellAccessibleObject(DataGridViewCell owner)
{
this.owner = owner;
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCellAccessibleObject.Bounds"]/*' />
public override Rectangle Bounds
{
get
{
return this.GetAccessibleObjectBounds(GetAccessibleObjectParent());
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCellAccessibleObject.DefaultAction"]/*' />
public override string DefaultAction
{
get
{
if (this.Owner == null)
{
throw new InvalidOperationException(string.Format(SR.DataGridViewCellAccessibleObject_OwnerNotSet));
}
if (!this.Owner.ReadOnly)
{
return string.Format(SR.DataGridView_AccCellDefaultAction);
}
else
{
return String.Empty;
}
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCellAccessibleObject.Help"]/*' />
public override string Help
{
get
{
if (AccessibilityImprovements.Level2)
{
return null;
}
return this.owner.GetType().Name + "(" + owner.GetType().BaseType.Name + ")";
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCellAccessibleObject.Name"]/*' />
public override string Name
{
get
{
if (this.owner == null)
{
throw new InvalidOperationException(string.Format(SR.DataGridViewCellAccessibleObject_OwnerNotSet));
}
if (this.owner.OwningColumn != null)
{
string name = string.Format(SR.DataGridView_AccDataGridViewCellName, this.owner.OwningColumn.HeaderText, this.owner.OwningRow.Index);
if (AccessibilityImprovements.Level3 && owner.OwningColumn.SortMode != DataGridViewColumnSortMode.NotSortable)
{
DataGridViewCell dataGridViewCell = this.Owner;
DataGridView dataGridView = dataGridViewCell.DataGridView;
if (dataGridViewCell.OwningColumn != null &&
dataGridViewCell.OwningColumn == dataGridView.SortedColumn)
{
name += ", " + (dataGridView.SortOrder == SortOrder.Ascending
? SR.SortedAscendingAccessibleStatus
: SR.SortedDescendingAccessibleStatus);
}
else
{
name += ", " + SR.NotSortedAccessibleStatus;
}
}
return name;
}
else
{
return String.Empty;
}
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCellAccessibleObject.Owner"]/*' />
public DataGridViewCell Owner
{
get
{
return this.owner;
}
set
{
if (this.owner != null)
{
throw new InvalidOperationException(string.Format(SR.DataGridViewCellAccessibleObject_OwnerAlreadySet));
}
this.owner = value;
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCellAccessibleObject.Parent"]/*' />
public override AccessibleObject Parent
{
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
get
{
return this.ParentPrivate;
}
}
private AccessibleObject ParentPrivate
{
get
{
if (this.owner == null)
{
throw new InvalidOperationException(string.Format(SR.DataGridViewCellAccessibleObject_OwnerNotSet));
}
if (this.owner.OwningRow == null)
{
return null;
}
else
{
return this.owner.OwningRow.AccessibilityObject;
}
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCellAccessibleObject.Role"]/*' />
public override AccessibleRole Role
{
get
{
return AccessibleRole.Cell;
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCellAccessibleObject.State"]/*' />
public override AccessibleStates State
{
get
{
if (this.owner == null)
{
throw new InvalidOperationException(string.Format(SR.DataGridViewCellAccessibleObject_OwnerNotSet));
}
AccessibleStates state = AccessibleStates.Selectable | AccessibleStates.Focusable;
if (this.owner == this.owner.DataGridView.CurrentCell)
{
state |= AccessibleStates.Focused;
}
if (this.owner.Selected)
{
state |= AccessibleStates.Selected;
}
if (AccessibilityImprovements.Level1 && this.owner.ReadOnly)
{
state |= AccessibleStates.ReadOnly;
}
Rectangle cellBounds;
if (this.owner.OwningColumn != null && this.owner.OwningRow != null)
{
cellBounds = this.owner.DataGridView.GetCellDisplayRectangle(this.owner.OwningColumn.Index, this.owner.OwningRow.Index, false /*cutOverflow*/);
}
else if (this.owner.OwningRow != null)
{
cellBounds = this.owner.DataGridView.GetCellDisplayRectangle(-1, this.owner.OwningRow.Index, false /*cutOverflow*/);
}
else if (this.owner.OwningColumn != null)
{
cellBounds = this.owner.DataGridView.GetCellDisplayRectangle(this.owner.OwningColumn.Index, -1, false /*cutOverflow*/);
}
else
{
cellBounds = this.owner.DataGridView.GetCellDisplayRectangle(-1, -1, false /*cutOverflow*/);
}
if (!cellBounds.IntersectsWith(this.owner.DataGridView.ClientRectangle))
{
state |= AccessibleStates.Offscreen;
}
return state;
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCellAccessibleObject.Value"]/*' />
public override string Value
{
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
get
{
if (this.owner == null)
{
throw new InvalidOperationException(string.Format(SR.DataGridViewCellAccessibleObject_OwnerNotSet));
}
object formattedValue = this.owner.FormattedValue;
string formattedValueAsString = formattedValue as string;
if (formattedValue == null || (formattedValueAsString != null && String.IsNullOrEmpty(formattedValueAsString)))
{
return string.Format(SR.DataGridView_AccNullValue);
}
else if (formattedValueAsString != null)
{
return formattedValueAsString;
}
else if (this.owner.OwningColumn != null)
{
TypeConverter converter = this.owner.FormattedValueTypeConverter;
if (converter != null && converter.CanConvertTo(typeof(string)))
{
return converter.ConvertToString(formattedValue);
}
else
{
return formattedValue.ToString();
}
}
else
{
return String.Empty;
}
}
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
set
{
if (this.owner is DataGridViewHeaderCell)
{
return;
}
if (this.owner.ReadOnly)
{
return;
}
if (this.owner.OwningRow == null)
{
return;
}
if (this.owner.DataGridView.IsCurrentCellInEditMode)
{
// EndEdit before setting the accessible object value.
// This way the value being edited is validated.
this.owner.DataGridView.EndEdit();
}
DataGridViewCellStyle dataGridViewCellStyle = this.owner.InheritedStyle;
// Format string "True" to boolean True.
object formattedValue = this.owner.GetFormattedValue(value,
this.owner.OwningRow.Index,
ref dataGridViewCellStyle,
null /*formattedValueTypeConverter*/ ,
null /*valueTypeConverter*/,
DataGridViewDataErrorContexts.Formatting);
// Parse the formatted value and push it into the back end.
this.owner.Value = owner.ParseFormattedValue(formattedValue,
dataGridViewCellStyle,
null /*formattedValueTypeConverter*/,
null /*valueTypeConverter*/);
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCellAccessibleObject.DoDefaultAction"]/*' />
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public override void DoDefaultAction()
{
if (this.owner == null)
{
throw new InvalidOperationException(string.Format(SR.DataGridViewCellAccessibleObject_OwnerNotSet));
}
DataGridViewCell dataGridViewCell = (DataGridViewCell)this.Owner;
DataGridView dataGridView = dataGridViewCell.DataGridView;
if (dataGridViewCell is DataGridViewHeaderCell)
{
return;
}
if (dataGridView != null && dataGridViewCell.RowIndex == -1)
{
throw new InvalidOperationException(string.Format(SR.DataGridView_InvalidOperationOnSharedCell));
}
Select(AccessibleSelection.TakeFocus | AccessibleSelection.TakeSelection);
Debug.Assert(dataGridView.CurrentCell == dataGridViewCell, "the result of selecting the cell should have made this cell the current cell");
if (dataGridViewCell.ReadOnly)
{
// don't edit if the cell is read only
return;
}
if (dataGridViewCell.EditType != null)
{
if (dataGridView.InBeginEdit || dataGridView.InEndEdit)
{
// don't enter or exit editing mode if the control
// is in the middle of doing that already.
return;
}
if (dataGridView.IsCurrentCellInEditMode)
{
// stop editing
dataGridView.EndEdit();
}
else if (dataGridView.EditMode != DataGridViewEditMode.EditProgrammatically)
{
// start editing
dataGridView.BeginEdit(true /*selectAll*/);
}
}
}
internal Rectangle GetAccessibleObjectBounds(AccessibleObject parentAccObject)
{
if (this.owner == null)
{
throw new InvalidOperationException(string.Format(SR.DataGridViewCellAccessibleObject_OwnerNotSet));
}
if (this.owner.OwningColumn == null)
{
return Rectangle.Empty;
}
// use the accessibility bounds from the parent row acc obj
Rectangle rowRect = parentAccObject.Bounds;
Rectangle columnRect;
int firstVisibleColumnIndex = this.owner.DataGridView.Columns.ColumnIndexToActualDisplayIndex(this.owner.DataGridView.FirstDisplayedScrollingColumnIndex, DataGridViewElementStates.Visible);
int visibleColumnIndex = this.owner.DataGridView.Columns.ColumnIndexToActualDisplayIndex(this.owner.ColumnIndex, DataGridViewElementStates.Visible);
bool rowHeadersVisible = this.owner.DataGridView.RowHeadersVisible;
if (visibleColumnIndex < firstVisibleColumnIndex)
{
// Get the bounds for the cell to the RIGHT
columnRect = parentAccObject.GetChild(visibleColumnIndex
+ 1 // + 1 for the next cell to the RIGHT
+ (rowHeadersVisible ? 1 : 0)).Bounds; // + 1 but only if the row headers are visible
// From the bounds of the cell to the RIGHT decrement the width of the owning column
if (this.Owner.DataGridView.RightToLeft == RightToLeft.No)
{
columnRect.X -= this.owner.OwningColumn.Width;
}
else
{
columnRect.X = columnRect.Right;
}
columnRect.Width = this.owner.OwningColumn.Width;
}
else if (visibleColumnIndex == firstVisibleColumnIndex)
{
columnRect = this.owner.DataGridView.GetColumnDisplayRectangle(this.owner.ColumnIndex, false /*cutOverflow*/);
int negOffset = this.owner.DataGridView.FirstDisplayedScrollingColumnHiddenWidth;
if (negOffset != 0)
{
if (this.owner.DataGridView.RightToLeft == RightToLeft.No)
{
columnRect.X -= negOffset;
}
columnRect.Width += negOffset;
}
columnRect = this.owner.DataGridView.RectangleToScreen(columnRect);
}
else
{
// Get the bounds for the cell to the LEFT
columnRect = parentAccObject.GetChild(visibleColumnIndex
- 1 // -1 because we want the previous cell to the LEFT
+ (rowHeadersVisible ? 1 : 0)).Bounds; // +1 but only if the row headers are visible
// From the bounds of the cell to the LEFT increment the width of the owning column
if (this.owner.DataGridView.RightToLeft == RightToLeft.No)
{
columnRect.X = columnRect.Right;
}
else
{
columnRect.X -= this.owner.OwningColumn.Width;
}
columnRect.Width = this.owner.OwningColumn.Width;
}
rowRect.X = columnRect.X;
rowRect.Width = columnRect.Width;
return rowRect;
}
private AccessibleObject GetAccessibleObjectParent()
{
// If this is one of our types, use the shortcut provided by ParentPrivate property.
// Otherwise, use the Parent property.
if (this.owner is DataGridViewButtonCell ||
this.owner is DataGridViewCheckBoxCell ||
this.owner is DataGridViewComboBoxCell ||
this.owner is DataGridViewImageCell ||
this.owner is DataGridViewLinkCell ||
this.owner is DataGridViewTextBoxCell)
{
return this.ParentPrivate;
}
else
{
return this.Parent;
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCellAccessibleObject.GetChild"]/*' />
public override AccessibleObject GetChild(int index)
{
if (this.owner == null)
{
throw new InvalidOperationException(string.Format(SR.DataGridViewCellAccessibleObject_OwnerNotSet));
}
if (this.owner.DataGridView.EditingControl != null &&
this.owner.DataGridView.IsCurrentCellInEditMode &&
this.owner.DataGridView.CurrentCell == this.owner &&
index == 0)
{
return this.owner.DataGridView.EditingControl.AccessibilityObject;
}
else
{
return null;
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCellAccessibleObject.GetChildCount"]/*' />
public override int GetChildCount()
{
if (this.owner == null)
{
throw new InvalidOperationException(string.Format(SR.DataGridViewCellAccessibleObject_OwnerNotSet));
}
if (this.owner.DataGridView.EditingControl != null &&
this.owner.DataGridView.IsCurrentCellInEditMode &&
this.owner.DataGridView.CurrentCell == this.owner)
{
return 1;
}
else
{
return 0;
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCellAccessibleObject.GetFocused"]/*' />
public override AccessibleObject GetFocused()
{
return null;
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCellAccessibleObject.GetSelected"]/*' />
public override AccessibleObject GetSelected()
{
return null;
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCellAccessibleObject.Navigate"]/*' />
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public override AccessibleObject Navigate(AccessibleNavigation navigationDirection)
{
if (this.owner == null)
{
throw new InvalidOperationException(string.Format(SR.DataGridViewCellAccessibleObject_OwnerNotSet));
}
if (this.owner.OwningColumn == null || this.owner.OwningRow == null)
{
return null;
}
switch (navigationDirection)
{
case AccessibleNavigation.Right:
if (this.owner.DataGridView.RightToLeft == RightToLeft.No)
{
return NavigateForward(true /*wrapAround*/);
}
else
{
return NavigateBackward(true /*wrapAround*/);
}
case AccessibleNavigation.Next:
return NavigateForward(false /*wrapAround*/);
case AccessibleNavigation.Left:
if (this.owner.DataGridView.RightToLeft == RightToLeft.No)
{
return NavigateBackward(true /*wrapAround*/);
}
else
{
return NavigateForward(true /*wrapAround*/);
}
case AccessibleNavigation.Previous:
return NavigateBackward(false /*wrapAround*/);
case AccessibleNavigation.Up:
if (this.owner.OwningRow.Index == this.owner.DataGridView.Rows.GetFirstRow(DataGridViewElementStates.Visible))
{
if (this.owner.DataGridView.ColumnHeadersVisible)
{
// Return the column header accessible object.
return this.owner.OwningColumn.HeaderCell.AccessibilityObject;
}
else
{
return null;
}
}
else
{
int previousVisibleRow = this.owner.DataGridView.Rows.GetPreviousRow(this.owner.OwningRow.Index, DataGridViewElementStates.Visible);
return this.owner.DataGridView.Rows[previousVisibleRow].Cells[this.owner.OwningColumn.Index].AccessibilityObject;
}
case AccessibleNavigation.Down:
if (this.owner.OwningRow.Index == this.owner.DataGridView.Rows.GetLastRow(DataGridViewElementStates.Visible))
{
return null;
}
else
{
int nextVisibleRow = this.owner.DataGridView.Rows.GetNextRow(this.owner.OwningRow.Index, DataGridViewElementStates.Visible);
return this.owner.DataGridView.Rows[nextVisibleRow].Cells[this.owner.OwningColumn.Index].AccessibilityObject;
}
default:
return null;
}
}
private AccessibleObject NavigateBackward(bool wrapAround)
{
if (this.owner.OwningColumn == this.owner.DataGridView.Columns.GetFirstColumn(DataGridViewElementStates.Visible))
{
if (wrapAround)
{
// Return the last accessible object in the previous row
AccessibleObject previousRow = this.Owner.OwningRow.AccessibilityObject.Navigate(AccessibleNavigation.Previous);
if (previousRow != null && previousRow.GetChildCount() > 0)
{
return previousRow.GetChild(previousRow.GetChildCount() - 1);
}
else
{
return null;
}
}
else
{
// return the row header cell if the row headers are visible.
if (this.owner.DataGridView.RowHeadersVisible)
{
return this.owner.OwningRow.AccessibilityObject.GetChild(0);
}
else
{
return null;
}
}
}
else
{
int previousVisibleColumnIndex = this.owner.DataGridView.Columns.GetPreviousColumn(this.owner.OwningColumn,
DataGridViewElementStates.Visible,
DataGridViewElementStates.None).Index;
return this.owner.OwningRow.Cells[previousVisibleColumnIndex].AccessibilityObject;
}
}
private AccessibleObject NavigateForward(bool wrapAround)
{
if (this.owner.OwningColumn == this.owner.DataGridView.Columns.GetLastColumn(DataGridViewElementStates.Visible,
DataGridViewElementStates.None))
{
if (wrapAround)
{
// Return the first cell in the next visible row.
//
AccessibleObject nextRow = this.Owner.OwningRow.AccessibilityObject.Navigate(AccessibleNavigation.Next);
if (nextRow != null && nextRow.GetChildCount() > 0)
{
if (this.Owner.DataGridView.RowHeadersVisible)
{
return nextRow.GetChild(1);
}
else
{
return nextRow.GetChild(0);
}
}
else
{
return null;
}
}
else
{
return null;
}
}
else
{
int nextVisibleColumnIndex = this.owner.DataGridView.Columns.GetNextColumn(this.owner.OwningColumn,
DataGridViewElementStates.Visible,
DataGridViewElementStates.None).Index;
return this.owner.OwningRow.Cells[nextVisibleColumnIndex].AccessibilityObject;
}
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCellAccessibleObject.Select"]/*' />
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public override void Select(AccessibleSelection flags)
{
if (this.owner == null)
{
throw new InvalidOperationException(string.Format(SR.DataGridViewCellAccessibleObject_OwnerNotSet));
}
if ((flags & AccessibleSelection.TakeFocus) == AccessibleSelection.TakeFocus)
{
this.owner.DataGridView.FocusInternal();
}
if ((flags & AccessibleSelection.TakeSelection) == AccessibleSelection.TakeSelection)
{
this.owner.Selected = true;
this.owner.DataGridView.CurrentCell = this.owner; // Do not change old selection
}
if ((flags & AccessibleSelection.AddSelection) == AccessibleSelection.AddSelection)
{
// it seems that in any circumstances a cell can become selected
this.owner.Selected = true;
}
if ((flags & AccessibleSelection.RemoveSelection) == AccessibleSelection.RemoveSelection &&
(flags & (AccessibleSelection.AddSelection | AccessibleSelection.TakeSelection)) == 0)
{
this.owner.Selected = false;
}
}
internal override int[] RuntimeId
{
get
{
if (runtimeId == null)
{
runtimeId = new int[2];
runtimeId[0] = RuntimeIDFirstItem; // first item is static - 0x2a
runtimeId[1] = this.GetHashCode();
}
return runtimeId;
}
}
internal override bool IsIAccessibleExSupported()
{
if (AccessibilityImprovements.Level2)
{
return true;
}
return base.IsIAccessibleExSupported();
}
#region IRawElementProviderFragment Implementation
internal override Rectangle BoundingRectangle
{
get
{
return this.Bounds;
}
}
internal override UnsafeNativeMethods.IRawElementProviderFragmentRoot FragmentRoot
{
get
{
return owner.DataGridView.AccessibilityObject;
}
}
internal override UnsafeNativeMethods.IRawElementProviderFragment FragmentNavigate(UnsafeNativeMethods.NavigateDirection direction)
{
if (this.owner == null)
{
throw new InvalidOperationException(string.Format(SR.DataGridViewCellAccessibleObject_OwnerNotSet));
}
if (this.owner.OwningColumn == null || this.owner.OwningRow == null)
{
return null;
}
switch (direction)
{
case UnsafeNativeMethods.NavigateDirection.Parent:
return this.owner.OwningRow.AccessibilityObject;
case UnsafeNativeMethods.NavigateDirection.NextSibling:
return NavigateForward(false);
case UnsafeNativeMethods.NavigateDirection.PreviousSibling:
return NavigateBackward(false);
case UnsafeNativeMethods.NavigateDirection.FirstChild:
case UnsafeNativeMethods.NavigateDirection.LastChild:
if (this.owner.DataGridView.CurrentCell == this.owner &&
this.owner.DataGridView.EditingControl != null)
{
return this.owner.DataGridView.EditingPanelAccessibleObject;
}
break;
default:
return null;
}
return null;
}
#endregion
#region IRawElementProviderSimple Implementation
internal override object GetPropertyValue(int propertyID)
{
if (AccessibilityImprovements.Level3)
{
switch (propertyID)
{
case NativeMethods.UIA_NamePropertyId:
return this.Name;
case NativeMethods.UIA_HasKeyboardFocusPropertyId:
return owner.Selected;
case NativeMethods.UIA_IsEnabledPropertyId:
return owner.DataGridView.Enabled;
case NativeMethods.UIA_HelpTextPropertyId:
return this.Help ?? string.Empty;
case NativeMethods.UIA_IsKeyboardFocusablePropertyId:
return (this.State & AccessibleStates.Focusable) == AccessibleStates.Focusable;
case NativeMethods.UIA_IsPasswordPropertyId:
return false;
case NativeMethods.UIA_IsOffscreenPropertyId:
return (this.State & AccessibleStates.Offscreen) == AccessibleStates.Offscreen;
case NativeMethods.UIA_AccessKeyPropertyId:
return string.Empty;
case NativeMethods.UIA_GridItemContainingGridPropertyId:
return this.Owner.DataGridView.AccessibilityObject;
}
}
if (propertyID == NativeMethods.UIA_IsTableItemPatternAvailablePropertyId)
{
return IsPatternSupported(NativeMethods.UIA_TableItemPatternId);
}
else if (propertyID == NativeMethods.UIA_IsGridItemPatternAvailablePropertyId)
{
return IsPatternSupported(NativeMethods.UIA_GridItemPatternId);
}
return base.GetPropertyValue(propertyID);
}
internal override bool IsPatternSupported(int patternId)
{
if (AccessibilityImprovements.Level3 &&
(patternId.Equals(NativeMethods.UIA_LegacyIAccessiblePatternId) ||
patternId.Equals(NativeMethods.UIA_InvokePatternId)))
{
return true;
}
if ((patternId == NativeMethods.UIA_TableItemPatternId ||
patternId == NativeMethods.UIA_GridItemPatternId) &&
// We don't want to implement patterns for header cells
this.owner.ColumnIndex != -1 && this.owner.RowIndex != -1)
{
return true;
}
return base.IsPatternSupported(patternId);
}
#endregion
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
internal override UnsafeNativeMethods.IRawElementProviderSimple[] GetRowHeaderItems()
{
if (this.owner.DataGridView.RowHeadersVisible && this.owner.OwningRow.HasHeaderCell)
{
return new UnsafeNativeMethods.IRawElementProviderSimple[1] { this.owner.OwningRow.HeaderCell.AccessibilityObject };
}
return null;
}
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
internal override UnsafeNativeMethods.IRawElementProviderSimple[] GetColumnHeaderItems()
{
if (this.owner.DataGridView.ColumnHeadersVisible && this.owner.OwningColumn.HasHeaderCell)
{
return new UnsafeNativeMethods.IRawElementProviderSimple[1] { this.owner.OwningColumn.HeaderCell.AccessibilityObject };
}
return null;
}
internal override int Row
{
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
get
{
return this.owner.OwningRow != null ? this.owner.OwningRow.Index : -1;
}
}
internal override int Column
{
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
get
{
return this.owner.OwningColumn != null ? this.owner.OwningColumn.Index : -1;
}
}
internal override UnsafeNativeMethods.IRawElementProviderSimple ContainingGrid
{
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
get
{
return this.owner.DataGridView.AccessibilityObject;
}
}
}
}
}
| 44.053729 | 237 | 0.52791 | [
"MIT"
] | OliaG/winforms | src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCell.cs | 245,159 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Gov.Jag.Spice.Interfaces
{
using Microsoft.Rest;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Regardingobjectidbulkoperationspicerequiredchecks operations.
/// </summary>
public partial interface IRegardingobjectidbulkoperationspicerequiredchecks
{
/// <summary>
/// Get regardingobjectid_bulkoperation_spice_requiredchecks from
/// spice_requiredcheckses
/// </summary>
/// <param name='activityid'>
/// key: activityid of spice_requiredchecks
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<MicrosoftDynamicsCRMbulkoperation>> GetWithHttpMessagesAsync(string activityid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| 39.807692 | 330 | 0.654106 | [
"Apache-2.0"
] | BrendanBeachBC/jag-spd-spice | interfaces/Dynamics-Autorest/IRegardingobjectidbulkoperationspicerequiredchecks.cs | 2,070 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.