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
sequence | repository_name
stringlengths 7
92
| path
stringlengths 3
249
| size
int64 5
1.04M
| lang
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|
using Upgrade;
using System.Collections.Generic;
using Ship;
using BoardTools;
using ActionsList;
using System;
using SubPhases;
using System.Linq;
using UnityEngine;
namespace UpgradesList.SecondEdition
{
public class Ruthless : GenericUpgrade
{
public Ruthless() : base()
{
UpgradeInfo = new UpgradeCardInfo(
"Ruthless",
UpgradeType.Talent,
cost: 1,
abilityType: typeof(Abilities.SecondEdition.RuthlessAbility),
restriction: new FactionRestriction(Faction.Imperial),
seImageNumber: 13
);
}
}
}
namespace Abilities.SecondEdition
{
public class RuthlessAbility : GenericAbility
{
public override void ActivateAbility()
{
HostShip.OnGenerateDiceModifications += AddDiceModification;
}
public override void DeactivateAbility()
{
HostShip.OnGenerateDiceModifications -= AddDiceModification;
}
private void AddDiceModification(GenericShip host)
{
GenericAction newAction = new RuthlessDiceModification
{
ImageUrl = HostUpgrade.ImageUrl,
HostShip = host,
Source = HostUpgrade
};
host.AddAvailableDiceModification(newAction);
}
public void StartAbility(Action callback)
{
RegisterAbilityTrigger(TriggerTypes.OnAbilityDirect, StartSelectShipForAbility);
Triggers.ResolveTriggers(TriggerTypes.OnAbilityDirect, delegate
{
Combat.DiceRollAttack.ChangeWorstResultTo(DieSide.Success);
callback();
});
}
private void StartSelectShipForAbility(object sender, System.EventArgs e)
{
SelectTargetForAbility(
ShipIsSelected,
FilterTargets,
GetAiPriority,
HostShip.Owner.PlayerNo,
HostUpgrade.UpgradeInfo.Name,
"Choose another friendly ship near the defender: that ship will suffer 1 damage and you will change 1 die result to Hit",
HostUpgrade,
showSkipButton: false
);
}
private void ShipIsSelected()
{
DamageSourceEventArgs ruthlessDamage = new DamageSourceEventArgs()
{
Source = HostShip,
DamageType = DamageTypes.CardAbility
};
TargetShip.Damage.TryResolveDamage(1, ruthlessDamage, SelectShipSubPhase.FinishSelection);
}
private bool FilterTargets(GenericShip ship)
{
return FilterTargetsByShipRange(ship, Combat.Defender, 0, 1) && FilterByTargetType(ship, new List<TargetTypes>() { TargetTypes.OtherFriendly });
}
private bool FilterTargetsByShipRange(GenericShip targetShip, GenericShip rangeFromShip, int minRange, int maxRange)
{
DistanceInfo distInfo = new DistanceInfo(targetShip, rangeFromShip);
return distInfo.Range >= minRange && distInfo.Range <= maxRange;
}
private int GetAiPriority(GenericShip ship)
{
if (ship.State.HullCurrent == 1) return 0;
return ship.State.HullCurrent + ship.State.ShieldsCurrent;
}
}
}
namespace ActionsList
{
public class RuthlessDiceModification : GenericAction
{
public RuthlessDiceModification()
{
Name = DiceModificationName = "Ruthless";
}
public override void ActionEffect(Action callBack)
{
(Source.UpgradeAbilities[0] as Abilities.SecondEdition.RuthlessAbility).StartAbility(callBack);
}
public override bool IsDiceModificationAvailable()
{
if (Combat.AttackStep != CombatStep.Attack) return false;
// The team argument is relative to the ship it's measuring from, not the host of this ability, so we need to query for enemies of the defender
List<GenericShip> friendlyShipsAtRange1FromTarget = Board.GetShipsAtRange(Combat.Defender, new Vector2(0, 1), Team.Type.Enemy);
return friendlyShipsAtRange1FromTarget.Any(n => n.ShipId != HostShip.ShipId);
}
public override int GetDiceModificationPriority()
{
int result = 0;
if ((Combat.DiceRollAttack.Blanks > 0) || (Combat.DiceRollAttack.Focuses > 0))
{
// The team argument is relative to the ship it's measuring from, not the host of this ability, so we need to query for enemies of the defender
List<GenericShip> friendlyShipsAtRange1FromTarget = Board.GetShipsAtRange(Combat.Defender, new Vector2(0, 1), Team.Type.Enemy);
if (friendlyShipsAtRange1FromTarget.Any(n => n.ShipId != HostShip.ShipId && n.State.HullCurrent > 0)) result = 33;
}
return result;
}
}
} | 34.479452 | 159 | 0.615415 | [
"MIT"
] | nickell-andrew/FlyCasual | Assets/Scripts/Model/Content/SecondEdition/Upgrades/Talent/Ruthless.cs | 5,036 | C# |
using System.Collections;
using System.Collections.Generic;
using Tactics.Events;
using Tactics.Models;
using UnityEngine;
namespace Tactics.Controllers
{
public class TileController : MonoBehaviour
{
public MapEvent selectTileOnMap;
public MapEvent clearTilesOnMap;
public VoidEvent resetTilesOnMap;
public UIEvent showTerraUI;
public UIEvent hideTerraUI;
public Tile tile;
public Collider2D[] mouseOverlapColliders;
/*-------------------------------------------------
* Event Handlers
--------------------------------------------------*/
public void Start()
{
this.mouseOverlapColliders = new Collider2D[2];
}
public void OnMouseDown()
{
if (this.tile.active && !this.tile.occupant) {
SelectTileOnMap(this.tile);
}
else if (!this.tile.occupant) {
ResetTilesOnMap();
}
}
public void HandleMouseHover()
{
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
int numColliders = Physics2D.OverlapPointNonAlloc(mousePosition, this.mouseOverlapColliders);
if (numColliders == 0)
{
HideTerraUI();
return;
}
foreach (Collider2D collider in mouseOverlapColliders)
{
GameObject colliderGameObject = collider.gameObject;
if (colliderGameObject.tag == "Tile")
{
Terra colliderTerra = colliderGameObject.GetComponent<Tile>().GetTerra();
// TerraformOverlay terraformOverlay = colliderGameObject.GetComponent<Tile>().terraformOverlay;
ShowTerraUI(colliderTerra);
break;
}
}
}
public void Update()
{
HandleMouseHover();
}
public void OnSetActiveState(TileEventData tileEventData)
{
if (this.tile == tileEventData.tile)
{
tileEventData.tile.SetActiveState(tileEventData.activeState);
}
}
public void OnClearActiveState(TileEventData tileEventData)
{
if (this.tile == tileEventData.tile)
{
tileEventData.tile.ClearActiveState();
}
}
public void OnCleartile(TileEventData tileEventData)
{
if (this.tile == tileEventData.tile)
{
Tile tileToClear = tileEventData.tile;
tileToClear.ClearTile();
}
}
public void OnOccupyTile(TileEventData tileEventData)
{
if (this.tile == tileEventData.tile)
{
Tile tileToOccupy = tileEventData.tile;
Character occupant = tileEventData.character;
tileToOccupy.SetOccupant(occupant);
}
}
public void OnUnoccupyTile(TileEventData tileEventData)
{
if (this.tile == tileEventData.tile)
{
Tile tileToUnoccupy = tileEventData.tile;
tileToUnoccupy.ClearOccupant();
}
}
public void OnShowOverlay(TileEventData tileEventData)
{
if (this.tile == tileEventData.tile)
{
tileEventData.tile.ShowOverlay(
tileEventData.overlayImageKey,
tileEventData.overlayType
);
}
}
public void OnClearOverlay(TileEventData tileEventData)
{
if (this.tile == tileEventData.tile)
{
tileEventData.tile.ClearOverlay(
tileEventData.overlayType
);
}
}
/*-------------------------------------------------
* Helpers
--------------------------------------------------*/
private void SelectTileOnMap(Tile tile)
{
RaiseSelectTileMapEvent(tile);
}
private void ClearTilesOnMap()
{
RaiseClearTilesMapEvent();
}
private void ResetTilesOnMap()
{
RaiseResetTilesMapEvent();
}
private void ShowTerraUI(Terra terra)
{
RaiseShowTerraUIEvent(terra);
}
private void HideTerraUI()
{
RaiseHideTerraUIEvent();
}
/*-------------------------------------------------
* Event Triggers
--------------------------------------------------*/
private void RaiseSelectTileMapEvent(Tile tile)
{
MapEventData mapEventData = new MapEventData();
mapEventData.tile = tile;
selectTileOnMap.Raise(mapEventData);
}
private void RaiseClearTilesMapEvent()
{
MapEventData mapEventData = new MapEventData();
clearTilesOnMap.Raise(mapEventData);
}
private void RaiseResetTilesMapEvent()
{
resetTilesOnMap.Raise();
}
private void RaiseShowTerraUIEvent(Terra terra)
{
UIEventData uiEventData = new UIEventData();
uiEventData.terra = terra;
this.showTerraUI.Raise(uiEventData);
}
private void RaiseHideTerraUIEvent()
{
UIEventData uIEventData = new UIEventData();
this.hideTerraUI.Raise(uIEventData);
}
}
}
| 28.995074 | 117 | 0.483011 | [
"MIT"
] | Joraffe/tactics_mvc | Assets/Scripts/Controllers/TileControllers/TileController.cs | 5,888 | C# |
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Smooth.Algebraics;
using Smooth.Delegates;
using Smooth.Slinq;
#if !UNITY_3_5
namespace Smooth.Slinq.Test {
#endif
public class WhereTakeSelectAggregateLinq : MonoBehaviour {
private void Update() {
for (int i = 0; i < SlinqTest.loops; ++i) {
SlinqTest.tuples1.Where(t => true).Take(int.MaxValue).Select(t => t).Aggregate(0, (acc, t) => 0);
}
}
}
#if !UNITY_3_5
}
#endif
| 20.08 | 101 | 0.709163 | [
"MIT"
] | PoisonousJohn/smooth.foundations | Assets/Smooth/Foundations/Slinq/Test/WhereTakeSelectAggregateLinq.cs | 502 | 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.Purview.V20201201Preview.Inputs
{
/// <summary>
/// The private link service connection state.
/// </summary>
public sealed class PrivateLinkServiceConnectionStateArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The required actions.
/// </summary>
[Input("actionsRequired")]
public Input<string>? ActionsRequired { get; set; }
/// <summary>
/// The description.
/// </summary>
[Input("description")]
public Input<string>? Description { get; set; }
/// <summary>
/// The status.
/// </summary>
[Input("status")]
public InputUnion<string, Pulumi.AzureNative.Purview.V20201201Preview.Status>? Status { get; set; }
public PrivateLinkServiceConnectionStateArgs()
{
}
}
}
| 28.414634 | 107 | 0.624034 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Purview/V20201201Preview/Inputs/PrivateLinkServiceConnectionStateArgs.cs | 1,165 | C# |
using System.Threading.Tasks;
using Rnx.Abstractions.Buffers;
using Rnx.Abstractions.Execution;
using Rnx.Abstractions.Tasks;
namespace Rnx.Tasks.Reliak.Minification
{
public abstract class MinificationTask : RnxTask
{
protected abstract string Minify(string input);
public override void Execute(IBuffer input, IBuffer output, IExecutionContext executionContext)
{
Parallel.ForEach(input.ElementsPartitioner, e =>
{
e.Text = Minify(e.Text);
output.Add(e);
});
}
}
} | 26.409091 | 103 | 0.640275 | [
"MIT"
] | rnx-io/Rnx.Tasks.Reliak | src/Rnx.Tasks.Reliak.Minification/MinificationTask.cs | 583 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media.Media3D;
using System.Collections.ObjectModel;
namespace InterProcCommunication.Specific
{
public enum MessagePositionInSeq
{
SINGLE_MESSAGE = 0,
SEQUENCE_START_MESSAGE = 1,
SEQUENCE_END_MESSAGE = 2,
MESSAGE_INSIDE_SEQUENCE = 3,
UNKNOWN = 4
}
public enum MessageAction
{
NONE = 0,
DELETE = 1,
CREATE = 2,
UPDATE = 3
}
public enum MessageCode
{
ENTITY_START = 0,
// comp-specific
COMP_ID = 1,
COMP_AUTOM_GEN = 2,
COMP_DESCR = 3,
// parameter-specific
PARAM_SEQUENCE = 4,
PARAM_NAME = 5,
PARAM_VALUE = 6,
// geometric relationship-specific
GR_SEQUENCE = 7,
GR_ID = 8,
GR_NAME = 9,
GR_STATE_TYPE = 10,
GR_STATE_ISREALIZED = 11,
GR_GEOM_IDS_X = 12,
GR_GEOM_IDS_Y = 13,
GR_GEOM_IDS_Z = 14,
GR_GEOM_IDS_W = 50,
GR_GEOM_CS = 15,
GR_TRANSF_WC2LC = 16,
GR_TRANSF_LC2WC = 17,
GR_INST_SIZE = 31,
GR_INST_NWE_ID = 32,
GR_INST_NWE_NAME = 33,
GR_INST_PATH = 34,
GR_INST_VAL_X = 35,
GR_INST_VAL_Y = 36,
GR_INST_VAL_Z = 37,
// messaging pipeline specific
MSG_POSITION = 18,
MSG_COMP_PARENT_ID = 19,
MSG_COMP_REPRESENTATION_ID = 20, // of the representation -> for automatic generation
MSG_COMP_REPRESENTATION_PARENT_ID = 21, // of the parent representation -> for automatic generation
MSG_COMP_REF_IDS_SEQUENCE = 22,
MSG_COMP_REF_ID = 23,
// action on transfer to original sender
MSG_COMP_ACTION = 40
}
public class ComponentMessage
{
#region STATIC
public const string MESSAGE = "MESSAGE";
public const string END_OF_MESSAGE = "EOF";
public static System.IFormatProvider NR_FORMATTER = new System.Globalization.NumberFormatInfo();
public const string INFINITY = "\U0000221E";
public const string NAN = "NaN";
public static string MessagePositionInSeqToString(MessagePositionInSeq _mpis)
{
switch(_mpis)
{
case MessagePositionInSeq.SINGLE_MESSAGE:
return "SINGLE_MESSAGE";
case MessagePositionInSeq.SEQUENCE_START_MESSAGE:
return "SEQUENCE_START_MESSAGE";
case MessagePositionInSeq.SEQUENCE_END_MESSAGE:
return "SEQUENCE_END_MESSAGE";
case MessagePositionInSeq.MESSAGE_INSIDE_SEQUENCE:
return "MESSAGE_INSIDE_SEQUENCE";
default:
return "UNKNOWN";
}
}
public static MessagePositionInSeq StringToMessagePositionInSeq(string _mpis)
{
if (string.IsNullOrEmpty(_mpis)) return MessagePositionInSeq.UNKNOWN;
switch(_mpis)
{
case "SINGLE_MESSAGE":
return MessagePositionInSeq.SINGLE_MESSAGE;
case "SEQUENCE_START_MESSAGE":
return MessagePositionInSeq.SEQUENCE_START_MESSAGE;
case "SEQUENCE_END_MESSAGE":
return MessagePositionInSeq.SEQUENCE_END_MESSAGE;
case "MESSAGE_INSIDE_SEQUENCE":
return MessagePositionInSeq.MESSAGE_INSIDE_SEQUENCE;
default:
return MessagePositionInSeq.UNKNOWN;
}
}
public static string MessageActionToString(MessageAction _action)
{
switch(_action)
{
case MessageAction.CREATE:
return "CREATE";
case MessageAction.DELETE:
return "DELETE";
case MessageAction.UPDATE:
return "UPDATE";
default:
return "NONE";
}
}
public static MessageAction StringToMessageAction(string _action)
{
if (string.IsNullOrEmpty(_action)) return MessageAction.NONE;
switch(_action)
{
case "CREATE":
return MessageAction.CREATE;
case "DELETE":
return MessageAction.DELETE;
case "UPDATE":
return MessageAction.UPDATE;
default:
return MessageAction.NONE;
}
}
public static ComponentMessage GetDummyMessage(MessagePositionInSeq _pos)
{
return new ComponentMessage(_pos, -1L, -1L, true, "Dummy Message", new List<long>(), new Dictionary<string, double>(),
new List<GeometricRelationship>{ new GeometricRelationship(-1L, "Dummy", new Relation2GeomState{ Type = Relation2GeomType.NONE, IsRealized = false},
new Point4D(-1, -1, -1, -1), Matrix3D.Identity, Matrix3D.Identity, Matrix3D.Identity)}, -1L, -1L, MessageAction.NONE);
}
public static ComponentMessage MessageForSelection(long _comp_id_to_select)
{
return new ComponentMessage(MessagePositionInSeq.SINGLE_MESSAGE, -1L, _comp_id_to_select, true, "Dummy Message", new List<long>(), new Dictionary<string, double>(),
new List<GeometricRelationship>{ new GeometricRelationship(-1L, "Dummy", new Relation2GeomState{ Type = Relation2GeomType.NONE, IsRealized = false},
new Point4D(-1, -1, -1, -1), Matrix3D.Identity, Matrix3D.Identity, Matrix3D.Identity)}, -1L, -1L, MessageAction.NONE);
}
#endregion
#region STATIC COMPARISON
/// <summary>
/// <para>This method should be used to retrieve the id of an automatically generated component.</para>
/// </summary>
/// <param name="_cmsg_query"></param>
/// <param name="_cmsg_test"></param>
/// <returns></returns>
public static bool HaveSameContent(ComponentMessage _cmsg_query, ComponentMessage _cmsg_test)
{
if (_cmsg_query == null && _cmsg_test == null) return true;
if (_cmsg_query != null && _cmsg_test == null) return false;
if (_cmsg_query == null && _cmsg_test != null) return false;
// component properties
if (_cmsg_query.comp_automatically_generated != _cmsg_test.comp_automatically_generated) return false;
// if (_cmsg_query.comp_descr != _cmsg_test.comp_descr) return false; this cannot be checked
if (_cmsg_query.comp_ref_ids != null && _cmsg_test.comp_ref_ids == null) return false;
if (_cmsg_query.comp_ref_ids == null && _cmsg_test.comp_ref_ids != null) return false;
if (_cmsg_query.comp_ref_ids != null && _cmsg_test.comp_ref_ids != null)
{
int nrRefs = _cmsg_query.comp_ref_ids.Count;
if (_cmsg_test.comp_ref_ids.Count != nrRefs) return false;
if (nrRefs > 0)
{
bool same_comp_ref_ids = _cmsg_query.comp_ref_ids.Zip(_cmsg_test.comp_ref_ids, (x, y) => x == y).Aggregate(true, (a, x) => a && x);
if (!same_comp_ref_ids) return false;
}
}
bool same_comp_params = ComponentMessage.LogicalEquality(_cmsg_query.comp_params, _cmsg_test.comp_params);
if (!same_comp_params) return false;
// component geometric relationships
bool same_gr = GeometricRelationship.HaveListsWSameContent(_cmsg_query.geom_relationships, _cmsg_test.geom_relationships);
if (!same_gr) return false;
return true;
}
private static bool LogicalEquality(Dictionary<string, double> _d1, Dictionary<string, double> _d2)
{
if (_d1 == null && _d2 != null) return false;
if (_d1 != null && _d2 == null) return false;
if (_d1 == null && _d2 == null) return true;
int nrD1 = _d1.Count;
if (nrD1 != _d2.Count) return false;
List<string> d1_keys = _d1.OrderBy(x => x.Key).Select(x => x.Key).ToList();
List<string> d2_keys = _d2.OrderBy(x => x.Key).Select(x => x.Key).ToList();
bool same_keys = d1_keys.SequenceEqual(d2_keys);
if (!same_keys) return false;
List<double> d1_values = _d1.OrderBy(x => x.Key).Select(x => x.Value).ToList();
List<double> d2_values = _d2.OrderBy(x => x.Key).Select(x => x.Value).ToList();
bool same_values = d1_values.Zip(d2_values, (x, y) => GeometricTransformations.LogicalEquality(x, y)).Aggregate(true, (a, x) => a && x);
if (!same_values) return false;
return true;
}
#endregion
#region CLASS MEMBERS
// structure
protected MessagePositionInSeq msg_pos;
protected long comp_parent_id;
protected List<long> comp_ref_ids; // saves the ids of referenced components
// data
protected long comp_id;
protected string comp_descr;
protected bool comp_automatically_generated;
protected Dictionary<string, double> comp_params;
protected List<GeometricRelationship> geom_relationships;
// for automatically generated components with an automatically generated parent
protected long comp_rep_id;
protected long comp_rep_parent_id;
// action
protected MessageAction action_to_take;
#endregion
#region PROPERTIES (Get only)
// structure
public MessagePositionInSeq MsgPos { get { return this.msg_pos; } }
public long CompParentID { get { return this.comp_parent_id; } }
public ReadOnlyCollection<long> CompRefIds { get { return this.comp_ref_ids.AsReadOnly(); } }
// data
public long CompID { get { return this.comp_id; } }
public string CompDescr { get { return this.comp_descr; } }
public bool CompAutomaticallyGenerated { get { return this.comp_automatically_generated; } }
public double this[string index]
{
get
{
if (this.comp_params.ContainsKey(index))
return this.comp_params[index];
else
return double.NaN;
}
}
public ReadOnlyCollection<GeometricRelationship> GeomRelationships { get { return this.geom_relationships.AsReadOnly(); } }
public Relation2GeomType GeomType
{
get
{
if (this.GeomRelationships.Count == 0)
return Relation2GeomType.NONE;
else
return this.geom_relationships[0].GrState.Type;
}
}
public bool GeomRelRealized
{
get
{
if (this.GeomRelationships.Count == 0)
return false;
else
return this.geom_relationships[0].GrState.IsRealized;
}
}
// for automatically generated components with an automatically generated parent
public long CompRepID { get { return this.comp_rep_id; } }
public long CompRepParentID { get { return this.comp_rep_parent_id; } }
public MessageAction ActionToTake { get { return this.action_to_take; } }
#endregion
#region .CTOR
public ComponentMessage(MessagePositionInSeq _pos, long _comp_parent_id, long _comp_id, bool _comp_ag, string _comp_descr,
List<long> _ref_ids, Dictionary<string, double> _comp_params, List<GeometricRelationship> _geom_rel,
long _comp_rep_id, long _comp_rep_parent_id, MessageAction _action_to_take)
{
// structural info
this.msg_pos = _pos;
this.comp_parent_id = _comp_parent_id;
this.comp_rep_id = _comp_rep_id;
this.comp_rep_parent_id = _comp_rep_parent_id;
this.action_to_take = _action_to_take;
// component info
this.comp_id = _comp_id;
this.comp_automatically_generated = _comp_ag;
this.comp_descr = _comp_descr;
this.comp_ref_ids = _ref_ids;
this.comp_params = _comp_params;
this.geom_relationships = new List<GeometricRelationship>();
if (_geom_rel != null && _geom_rel.Count > 0)
this.geom_relationships = new List<GeometricRelationship>(_geom_rel);
}
#endregion
#region ToString
public override string ToString()
{
StringBuilder sb = new StringBuilder();
// mark start
sb.AppendLine(((int)MessageCode.ENTITY_START).ToString()); // 0
sb.AppendLine(ComponentMessage.MESSAGE); // MESSAGE
// message position in sequence
sb.AppendLine(((int)MessageCode.MSG_POSITION).ToString());
sb.AppendLine(ComponentMessage.MessagePositionInSeqToString(this.msg_pos));
// parent component id
sb.AppendLine(((int)MessageCode.MSG_COMP_PARENT_ID).ToString());
sb.AppendLine(this.comp_parent_id.ToString());
// ids of referenced components
sb.AppendLine(((int)MessageCode.MSG_COMP_REF_IDS_SEQUENCE).ToString());
sb.AppendLine(this.comp_ref_ids.Count.ToString());
foreach(long id in this.comp_ref_ids)
{
sb.AppendLine(((int)MessageCode.MSG_COMP_REF_ID).ToString());
sb.AppendLine(id.ToString());
}
// comp
sb.AppendLine(((int)MessageCode.COMP_ID).ToString());
sb.AppendLine(this.comp_id.ToString());
sb.AppendLine(((int)MessageCode.COMP_AUTOM_GEN).ToString());
string tmp = (this.comp_automatically_generated) ? "1" : "0";
sb.AppendLine(tmp);
sb.AppendLine(((int)MessageCode.COMP_DESCR).ToString());
sb.AppendLine(this.comp_descr);
// comp parameters
if (this.comp_params != null && this.comp_params.Count > 0)
{
sb.AppendLine(((int)MessageCode.PARAM_SEQUENCE).ToString());
sb.AppendLine(this.comp_params.Count.ToString());
foreach (var entry in this.comp_params)
{
sb.AppendLine(((int)MessageCode.PARAM_NAME).ToString());
sb.AppendLine(entry.Key);
sb.AppendLine(((int)MessageCode.PARAM_VALUE).ToString());
sb.AppendLine(entry.Value.ToString(ComponentMessage.NR_FORMATTER));
}
}
// geometric relationships
sb.AppendLine(((int)MessageCode.GR_SEQUENCE).ToString());
sb.AppendLine(this.geom_relationships.Count.ToString());
foreach(GeometricRelationship gr in this.geom_relationships)
{
sb.AppendLine(((int)MessageCode.GR_ID).ToString());
sb.AppendLine(gr.GrID.ToString());
sb.AppendLine(((int)MessageCode.GR_NAME).ToString());
sb.AppendLine(gr.GrName);
sb.AppendLine(((int)MessageCode.GR_STATE_TYPE).ToString());
sb.AppendLine(GeometryUtils.Relationship2GeometryToString(gr.GrState.Type));
sb.AppendLine(((int)MessageCode.GR_STATE_ISREALIZED).ToString());
string tmp_gr = (gr.GrState.IsRealized) ? "1" : "0";
sb.AppendLine(tmp_gr);
sb.AppendLine(((int)MessageCode.GR_GEOM_IDS_X).ToString());
sb.AppendLine(gr.GrIds.X.ToString());
sb.AppendLine(((int)MessageCode.GR_GEOM_IDS_Y).ToString());
sb.AppendLine(gr.GrIds.Y.ToString());
sb.AppendLine(((int)MessageCode.GR_GEOM_IDS_Z).ToString());
sb.AppendLine(gr.GrIds.Z.ToString());
sb.AppendLine(((int)MessageCode.GR_GEOM_IDS_W).ToString());
sb.AppendLine(gr.GrIds.W.ToString());
sb.AppendLine(((int)MessageCode.GR_GEOM_CS).ToString());
sb.AppendLine(gr.GrUCS.ToString(ComponentMessage.NR_FORMATTER));
// instance information
sb.AppendLine(((int)MessageCode.GR_INST_SIZE).ToString());
sb.AppendLine(gr.InstSize.Count.ToString());
foreach (double entry in gr.InstSize)
{
sb.AppendLine(((int)MessageCode.GR_INST_VAL_X).ToString());
sb.AppendLine(entry.ToString(ComponentMessage.NR_FORMATTER));
}
sb.AppendLine(((int)MessageCode.GR_INST_NWE_ID).ToString());
sb.AppendLine(gr.InstNWeId.ToString());
sb.AppendLine(((int)MessageCode.GR_INST_NWE_NAME).ToString());
sb.AppendLine(gr.InstNWeName);
sb.AppendLine(((int)MessageCode.GR_INST_PATH).ToString());
sb.AppendLine(gr.InstPath.Count.ToString());
foreach (Point3D vertex in gr.InstPath)
{
sb.AppendLine(((int)MessageCode.GR_INST_VAL_X).ToString());
sb.AppendLine(vertex.X.ToString(ComponentMessage.NR_FORMATTER));
sb.AppendLine(((int)MessageCode.GR_INST_VAL_Y).ToString());
sb.AppendLine(vertex.Y.ToString(ComponentMessage.NR_FORMATTER));
sb.AppendLine(((int)MessageCode.GR_INST_VAL_Z).ToString());
sb.AppendLine(vertex.Z.ToString(ComponentMessage.NR_FORMATTER));
}
// transforms
sb.AppendLine(((int)MessageCode.GR_TRANSF_WC2LC).ToString());
sb.AppendLine(gr.GrTrWC2LC.ToString(ComponentMessage.NR_FORMATTER));
// SHOULD COME LAST!
sb.AppendLine(((int)MessageCode.GR_TRANSF_LC2WC).ToString());
sb.AppendLine(gr.GrTrLC2WC.ToString(ComponentMessage.NR_FORMATTER));
}
// structural info from the representations (for automatically generated components)
sb.AppendLine(((int)MessageCode.MSG_COMP_REPRESENTATION_ID).ToString());
sb.AppendLine(this.comp_rep_id.ToString());
sb.AppendLine(((int)MessageCode.MSG_COMP_REPRESENTATION_PARENT_ID).ToString());
sb.AppendLine(this.comp_rep_parent_id.ToString());
// action to take on return to original sender
sb.AppendLine(((int)MessageCode.MSG_COMP_ACTION).ToString());
sb.AppendLine(ComponentMessage.MessageActionToString(this.action_to_take));
// done
sb.AppendLine(((int)MessageCode.ENTITY_START).ToString()); // 0
sb.AppendLine(ComponentMessage.END_OF_MESSAGE); // EOF
return sb.ToString();
}
#endregion
#region FromString
public static ComponentMessage FromString(string _msg)
{
ComponentMessageParser parser = new ComponentMessageParser();
parser.TranslateMessage(_msg);
return parser.ParsedMsg;
}
#endregion
}
}
| 38.889109 | 195 | 0.584093 | [
"Unlicense"
] | bph-tuwien/SIMULTAN_Stand_29_09_2017 | EngineTest/Apps/InterProcCommunication/Specific/ComponentMessage.cs | 19,641 | C# |
/*=============================================================================
*
* (C) Copyright 2013, Michael Carlisle ([email protected])
*
* http://www.TheCodeKing.co.uk
*
* All rights reserved.
* The code and information is provided "as-is" without waranty of any kind,
* either expressed or implied.
*
*=============================================================================
*/
namespace XDMessaging
{
/// <summary>
/// This defines the tranport modes that can be used for interprocess communication.
/// </summary>
public enum XDTransportMode
{
/// <summary>
/// Use this mode for efficant communication between applications running within the
/// context of a Desktop, such as Windows Forms or WPF.
/// </summary>
HighPerformanceUI,
/// <summary>
/// Use Compatibility mode when using non-UI components such as Windows Services.
/// </summary>
Compatibility,
/// <summary>
/// Use RemoteNetwork to broadcast to physically seperated servers.
/// </summary>
RemoteNetwork
}
} | 33.676471 | 95 | 0.540611 | [
"MIT"
] | Icenium/XDMessaging.Net | Source/XDMessaging.Core/XDTransportMode.cs | 1,147 | C# |
namespace Sinema_Proje {
public partial class sinemailkDataSet {
}
}
namespace Sinema_Proje.sinemailkDataSetTableAdapters {
public partial class film_kayitTableAdapter {
}
}
| 15.142857 | 54 | 0.683962 | [
"MIT"
] | mfrkndmrl/BiletSatisiOtomasyonu | Sinema-Proje/sinemailkDataSet.cs | 214 | C# |
#nullable disable
using System.Diagnostics;
using System.Reflection;
using System.Resources;
using F0.CodeAnalysis.Diagnostics;
namespace F0.Tests
{
public class AssemblyInfoTests
{
private static readonly Version version = new(0, 8, 0, 0);
static AssemblyInfoTests()
{
EnsureThatAssemblyUnderTestIsLoaded();
}
[Fact]
public void AssemblyInfo_DefaultCulture_English()
{
var assembly = GetAnalyzerAssembly();
var attribute = assembly.GetCustomAttribute<NeutralResourcesLanguageAttribute>();
attribute.Should().NotBeNull();
attribute.CultureName.Should().Be("en");
attribute.Location.Should().Be(UltimateResourceFallbackLocation.MainAssembly);
}
[Fact]
public void AssemblyInfo_AnalyzerAssemblyHasNeitherPubliclyExposedTypesNorMembers_TheAssemblyIsNotCLSCompliant()
{
var assembly = GetAnalyzerAssembly();
var attribute = assembly.GetCustomAttribute<CLSCompliantAttribute>();
attribute.Should().NotBeNull();
attribute.IsCompliant.Should().BeFalse();
}
private static Assembly GetAnalyzerAssembly()
{
var displayName = $"F0.Analyzers, Version={version}, Culture=neutral, PublicKeyToken=null";
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
var assembly = assemblies.Single(a => a.FullName.Equals(displayName, StringComparison.InvariantCulture));
return assembly;
}
/// <summary>
/// On <strong>.NET Core</strong>, <em>xUnit.net</em> loads the Assembly Under Test (<c>ProjectReference</c>) already automatically,
/// without using any Type in test code. However, not on <strong>.NET Framework</strong>.
/// </summary>
[Conditional("NET472")]
private static void EnsureThatAssemblyUnderTestIsLoaded()
=> _ = new F00001GoToStatementConsideredHarmful();
}
}
| 30.37931 | 134 | 0.752554 | [
"MIT"
] | Flash0ver/F0.Analyzers | source/test/F0.Analyzers.Tests/AssemblyInfoTests.cs | 1,762 | C# |
using System;
partial class Person
{
public void WriteProperties(int years)
{
Console.WriteLine(
$"Name: {Name}, age in {years} years: {AgeInSomeYears(years)}.");
}
public void WritePropertiesShort(int years)
{
Console.WriteLine(
$"Name: {Name}.");
}
}
| 16.058824 | 68 | 0.666667 | [
"MIT"
] | Speak91/Nordic-it-netcore | Lesson_11/ClassWork/L11_C15_partial_classes_live_demo/Person.Output.cs | 275 | C# |
using Microsoft.Data.SqlClient;
using NServiceBus.Attachments.Sql;
using NServiceBus.Pipeline;
class DeleteBehaviorRegistration :
RegisterStep
{
public DeleteBehaviorRegistration(Func<Task<SqlConnection>> connectionBuilder, IPersister persister)
: base(
stepId: $"{AssemblyHelper.Name}DeleteBehavior",
behavior: typeof(DeleteBehavior),
description: "Performs cleanup of attachments for the current message.",
factoryMethod: _ => new DeleteBehavior(connectionBuilder, persister))
{
}
} | 34.875 | 104 | 0.715054 | [
"MIT"
] | SimonCropp/NServiceBus.Attachments | src/Attachments.Sql/Incoming/DeleteBehaviorRegistration.cs | 560 | C# |
using EventFlow.Aggregates;
using EventFlow.Extensions;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Szlem.Domain;
using Szlem.Engine.Interfaces;
using Szlem.Models.Users;
using Szlem.SchoolManagement.Impl;
using Szlem.SchoolManagement.Impl.Events;
using Xunit;
namespace Szlem.SchoolManagement.Tests
{
public class RegisterSchoolTests
{
[Fact(DisplayName = "Rejestracja szkoły musi zawierać nazwę, miasto, adres i co najmniej jeden kontakt")]
public void Submission_must_contain__name_city_address_and_at_least_one_contact_with_email_or_phone_number()
{
var command = new RegisterSchool.Command() {
Name = string.Empty, City = string.Empty, Address = string.Empty,
ContactData = Array.Empty<ContactData>()
};
var school = new SchoolAggregate(SchoolId.New);
var now = NodaTime.SystemClock.Instance.GetCurrentInstant();
var result = school.RegisterSchool(now, command, new ApplicationUser());
Assert.False(result.IsSuccess);
var error = Assert.IsType<Error.ValidationFailed>(result.Error);
Assert.Contains(RegisterSchool_Messages.SchoolName_CannotBeEmpty, error.Failures[nameof(command.Name)]);
Assert.Contains(RegisterSchool_Messages.City_CannotBeEmpty, error.Failures[nameof(command.City)]);
Assert.Contains(RegisterSchool_Messages.Address_Cannot_be_empty, error.Failures[nameof(command.Address)]);
Assert.Contains(RegisterSchool_Messages.ContactData_cannot_be_empty, error.Failures[nameof(command.ContactData)]);
}
[Fact(DisplayName = "Każdy kontakt w rejestracji szkoły musi zawierać email lub telefon")]
public void Each_contact_must_contain_email_or_phone_number()
{
var command = new RegisterSchool.Command() {
Name = "I Liceum Ogólnokształcące",
City = "Gdańsk",
Address = "Wały Piastowskie 6",
ContactData = new[] {
new ContactData() { Name = "sekretariat" }
}
};
var school = new SchoolAggregate(SchoolId.New);
var now = NodaTime.SystemClock.Instance.GetCurrentInstant();
var result = school.RegisterSchool(now, command, new ApplicationUser());
Assert.False(result.IsSuccess);
var error = Assert.IsType<Error.ValidationFailed>(result.Error);
Assert.Collection(error.Failures,
first => {
Assert.Equal($"{nameof(command.ContactData)}[0].{nameof(ContactData.PhoneNumber)}", first.PropertyName);
Assert.Single(first.Errors, RegisterSchool_Messages.Either_ContactData_PhoneNumber_or_ContactData_EmailAddress_must_be_provided);
},
second =>
{
Assert.Equal($"{nameof(command.ContactData)}[0].{nameof(ContactData.EmailAddress)}", second.PropertyName);
Assert.Single(second.Errors, RegisterSchool_Messages.Either_ContactData_PhoneNumber_or_ContactData_EmailAddress_must_be_provided);
});
}
[Fact(DisplayName = "Emaile i numery telefonów nie mogą się powtarzać w danych kontaktowych")]
public void Emails_and_phone_numbers_cannot_be_duplicates()
{
var command = new RegisterSchool.Command() {
Name = "I Liceum Ogólnokształcące",
City = "Gdańsk",
Address = "Wały Piastowskie 6",
ContactData = new[] {
new ContactData() { Name = "sekretariat", EmailAddress = EmailAddress.Parse("[email protected]"), PhoneNumber = PhoneNumber.Parse("58 301-67-34") },
new ContactData() { Name = "dyrektor", EmailAddress = EmailAddress.Parse("[email protected]"), PhoneNumber = PhoneNumber.Parse("58 301-67-34") }
}
};
var school = new SchoolAggregate(SchoolId.New);
var now = NodaTime.SystemClock.Instance.GetCurrentInstant();
var result = school.RegisterSchool(now, command, new ApplicationUser());
Assert.False(result.IsSuccess);
var error = Assert.IsType<Error.ValidationFailed>(result.Error);
var failure = Assert.Single(error.Failures);
Assert.Equal(nameof(command.ContactData), failure.PropertyName);
Assert.All(failure.Errors, message => Assert.Equal(RegisterSchool_Messages.ContactData_emails_and_phone_numbers_cannot_repeat_themselves, message));
}
[Fact(DisplayName = "Po rejestracji szkoły, handler zwraca Id szkoły")]
public async Task After_submission__handler_returns_school_Id()
{
var command = new RegisterSchool.Command() {
Name = "I Liceum Ogólnokształcące",
City = "Gdańsk",
Address = "Wały Piastowskie 6",
ContactData = new[] {
new ContactData() {
Name = "sekretariat",
EmailAddress = EmailAddress.Parse("[email protected]"),
PhoneNumber = PhoneNumber.Parse("58 301-67-34") },
}
};
var sp = new ServiceProviderBuilder().BuildServiceProvider();
using (var scope = sp.CreateScope())
{
var aggregateStore = scope.ServiceProvider.GetRequiredService<IAggregateStore>();
var userAccessor = Mock.Of<IUserAccessor>(
mock => mock.GetUser() == Task.FromResult(new ApplicationUser() { Id = Guid.NewGuid() }),
MockBehavior.Strict);
var handler = new RegisterSchoolHandler(NodaTime.SystemClock.Instance, userAccessor, aggregateStore);
var result = await handler.Handle(command, CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.IsType<Guid>(result.Value);
}
}
[Fact(DisplayName = "Po rejestracji szkoły, baza zawiera agregat szkoły")]
public async Task After_submission__database_contains_school_aggregate()
{
var command = new RegisterSchool.Command() {
Name = "I Liceum Ogólnokształcące",
City = "Gdańsk",
Address = "Wały Piastowskie 6",
ContactData = new[] {
new ContactData() {
Name = "sekretariat",
EmailAddress = EmailAddress.Parse("[email protected]"),
PhoneNumber = PhoneNumber.Parse("58 301-67-34") },
}
};
Guid guid;
var sp = new ServiceProviderBuilder().BuildServiceProvider();
using (var scope = sp.CreateScope())
{
var userAccessor = Mock.Of<IUserAccessor>(
mock => mock.GetUser() == Task.FromResult(new ApplicationUser() { Id = Guid.NewGuid() }),
MockBehavior.Strict);
var aggregateStore = scope.ServiceProvider.GetRequiredService<IAggregateStore>();
var handler = new RegisterSchoolHandler(NodaTime.SystemClock.Instance, userAccessor, aggregateStore);
var result = await handler.Handle(command, CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.IsType<Guid>(result.Value);
guid = result.Value;
}
using (var scope = sp.CreateScope())
{
var aggregateStore = scope.ServiceProvider.GetRequiredService<IAggregateStore>();
var school = await aggregateStore.LoadAsync<SchoolAggregate, SchoolId>(SchoolId.With(guid), CancellationToken.None);
Assert.NotNull(school);
Assert.False(school.IsNew);
}
}
[Fact(DisplayName = "Po rejestracji szkoły, agregat zawiera event SchoolSubmitted")]
public void After_submission__aggregate_contains_SchoolRegistered_event()
{
var command = new RegisterSchool.Command() {
Name = "I Liceum Ogólnokształcące",
City = "Gdańsk",
Address = "Wały Piastowskie 6",
ContactData = new[] {
new ContactData() {
Name = "sekretariat",
EmailAddress = EmailAddress.Parse("[email protected]"),
PhoneNumber = PhoneNumber.Parse("58 301-67-34") },
}
};
var school = new SchoolAggregate(SchoolId.New);
var registeringUser = new ApplicationUser() { Id = Guid.NewGuid() };
var result = school.RegisterSchool(NodaTime.SystemClock.Instance.GetCurrentInstant(), command, registeringUser);
Assert.True(result.IsSuccess);
var uncommittedEvent = Assert.Single(school.UncommittedEvents, e => e.AggregateEvent is SchoolRegistered);
var @event = Assert.IsType<SchoolRegistered>(uncommittedEvent.AggregateEvent);
Assert.Equal(registeringUser.Id, @event.RegisteringUserId);
Assert.Equal(command.Name, @event.Name);
Assert.Equal(command.City, @event.City);
var contactData = Assert.Single(command.ContactData);
Assert.Equal("sekretariat", contactData.Name);
Assert.Equal(EmailAddress.Parse("[email protected]"), contactData.EmailAddress);
Assert.Equal(PhoneNumber.Parse("58 301-67-34"), contactData.PhoneNumber);
}
}
}
| 49.872449 | 168 | 0.609616 | [
"MIT"
] | Yaevh/fcc-net50-bug-repro-2 | test/Engine/Szlem.SchoolManagement.Tests/RegisterSchoolTests.cs | 9,817 | C# |
using Sudoku.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Z3;
using System.Security.Cryptography;
using System.Globalization;
using System.Diagnostics;
namespace sudoku.Z3
{
public class Z3Solver : ISudokuSolver
{
Context _ctx = new Context();
// 9x9 matrix of integer variables
IntExpr[][] X = new IntExpr[9][];
private BoolExpr sudoku_c;
public Z3Solver()
{
PrepareGenericConstraints();
}
private void PrepareGenericConstraints()
{
for (uint i = 0; i < 9; i++)
{
X[i] = new IntExpr[9];
for (uint j = 0; j < 9; j++)
X[i][j] = (IntExpr)_ctx.MkConst(_ctx.MkSymbol("x_" + (i + 1) + "_" + (j + 1)), _ctx.IntSort);
}
// each cell contains a value in {1, ..., 9}
Expr[][] cells_c = new Expr[9][];
for (uint i = 0; i < 9; i++)
{
cells_c[i] = new BoolExpr[9];
for (uint j = 0; j < 9; j++)
cells_c[i][j] = _ctx.MkAnd(_ctx.MkLe(_ctx.MkInt(1), X[i][j]),
_ctx.MkLe(X[i][j], _ctx.MkInt(9)));
}
// each row contains a digit at most once
BoolExpr[] rows_c = new BoolExpr[9];
for (uint i = 0; i < 9; i++)
rows_c[i] = _ctx.MkDistinct(X[i]);
// each column contains a digit at most once
BoolExpr[] cols_c = new BoolExpr[9];
for (uint j = 0; j < 9; j++)
{
IntExpr[] column = new IntExpr[9];
for (uint i = 0; i < 9; i++)
column[i] = X[i][j];
cols_c[j] = _ctx.MkDistinct(column);
}
// each 3x3 square contains a digit at most once
BoolExpr[][] sq_c = new BoolExpr[3][];
for (uint i0 = 0; i0 < 3; i0++)
{
sq_c[i0] = new BoolExpr[3];
for (uint j0 = 0; j0 < 3; j0++)
{
IntExpr[] square = new IntExpr[9];
for (uint i = 0; i < 3; i++)
for (uint j = 0; j < 3; j++)
square[3 * i + j] = X[3 * i0 + i][3 * j0 + j];
sq_c[i0][j0] = _ctx.MkDistinct(square);
}
}
sudoku_c = _ctx.MkTrue();
foreach (BoolExpr[] t in cells_c)
sudoku_c = _ctx.MkAnd(_ctx.MkAnd(t), sudoku_c);
sudoku_c = _ctx.MkAnd(_ctx.MkAnd(rows_c), sudoku_c);
sudoku_c = _ctx.MkAnd(_ctx.MkAnd(cols_c), sudoku_c);
foreach (BoolExpr[] t in sq_c)
sudoku_c = _ctx.MkAnd(_ctx.MkAnd(t), sudoku_c);
}
Sudoku.Core.Sudoku SudokuExample(Sudoku.Core.Sudoku instance)
{
BoolExpr instance_c = _ctx.MkTrue();
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++)
instance_c = _ctx.MkAnd(instance_c,
(BoolExpr)
_ctx.MkITE(_ctx.MkEq(_ctx.MkInt(instance.GetCell(i,j)), _ctx.MkInt(0)),
_ctx.MkTrue(),
_ctx.MkEq(X[i][j], _ctx.MkInt(instance.GetCell(i, j)))));
Solver s = _ctx.MkSolver();
s.Assert(sudoku_c);
s.Assert(instance_c);
if (s.Check() == Status.SATISFIABLE)
{
Model m = s.Model;
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++){
instance.SetCell(i, j, ((IntNum)m.Evaluate(X[i][j])).Int);
}
return instance;
}
else
{
Console.WriteLine("Failed to solve sudoku");
return instance;
}
}
public Sudoku.Core.Sudoku Solve(Sudoku.Core.Sudoku s)
{
// Z3Solver z3 = new Z3Solver();
return SudokuExample(s);
}
}
} | 32.944882 | 113 | 0.43762 | [
"MIT"
] | LucasAbbkr/MSMIN5IN31-20-Sudoku | sudoku.Z3/Z3Solver.cs | 4,186 | C# |
using Improbable.Gdk.Core;
using System;
using System.Collections.Generic;
using Unity.Entities;
using PointSchema = MdgSchema.Common.Point;
namespace MDG.Common.Systems.Point
{
[DisableAutoCreation]
[UpdateInGroup(typeof(SpatialOSUpdateGroup))]
public class PointRequestSystem : ComponentSystem
{
public class PointRequestPayload
{
public int pointUpdate;
public List<Action<PointSchema.Point.UpdatePoints.ReceivedResponse>> callbacks;
}
private Dictionary<long, PointRequestPayload> requestIdToPayload;
private Dictionary<EntityId, PointRequestPayload> pointRequests;
private CommandSystem commandSystem;
protected override void OnCreate()
{
base.OnCreate();
pointRequests = new Dictionary<EntityId, PointRequestPayload>();
requestIdToPayload = new Dictionary<long, PointRequestPayload>();
commandSystem = World.GetExistingSystem<CommandSystem>();
}
// Maybe make it take in something else to construct point request here to avoid including it in every file.
// Add callback here. Callback will undo point update if fails, etc.
public void AddPointRequest(PointSchema.PointRequest pointRequest, Action<PointSchema.Point.UpdatePoints.ReceivedResponse> callback = null)
{
if (pointRequests.TryGetValue(pointRequest.EntityUpdating, out PointRequestPayload pointRequestPayload))
{
pointRequestPayload.pointUpdate += pointRequest.PointUpdate;
if (callback != null)
{
pointRequestPayload.callbacks.Add(callback);
}
pointRequests[pointRequest.EntityUpdating] = pointRequestPayload;
}
else
{
List<Action<PointSchema.Point.UpdatePoints.ReceivedResponse>> callbacks = new List<Action<PointSchema.Point.UpdatePoints.ReceivedResponse>>();
if (callback != null)
{
callbacks.Add(callback);
}
pointRequests.Add(pointRequest.EntityUpdating, new PointRequestPayload
{
callbacks = callbacks,
pointUpdate = pointRequest.PointUpdate
});
}
}
protected override void OnUpdate()
{
Entities.ForEach((ref SpatialEntityId spatialEntityId, ref PointSchema.Point.Component point) =>
{
EntityId entityId = spatialEntityId.EntityId;
if (pointRequests.TryGetValue(entityId, out PointRequestPayload pointRequestPayload))
{
PointSchema.PointRequest pointRequest = new PointSchema.PointRequest
{
EntityUpdating = entityId,
PointUpdate = pointRequestPayload.pointUpdate
};
long requestId = commandSystem.SendCommand(new PointSchema.Point.UpdatePoints.Request
{
TargetEntityId = entityId,
Payload = pointRequest
});
requestIdToPayload[requestId] = pointRequestPayload;
}
});
pointRequests.Clear();
// Process response only ever other frame.
ProcessPointResponses();
}
private void ProcessPointResponses()
{
if (requestIdToPayload.Count > 0)
{
var responses = commandSystem.GetResponses<PointSchema.Point.UpdatePoints.ReceivedResponse>();
for (int i = 0; i<responses.Count; ++i)
{
ref readonly var response = ref responses[i];
if (requestIdToPayload.TryGetValue(response.RequestId, out PointRequestPayload pointRequest))
{
requestIdToPayload.Remove(response.RequestId);
switch (response.StatusCode)
{
case Improbable.Worker.CInterop.StatusCode.Success:
for (int j = 0; j < pointRequest.callbacks.Count; ++j)
{
pointRequest.callbacks[j]?.Invoke(response);
}
break;
case Improbable.Worker.CInterop.StatusCode.Timeout:
// Requeue.
UnityEngine.Debug.Log("Timed out");
pointRequests.Add(response.EntityId, pointRequest);
break;
default:
// Throw error.
UnityEngine.Debug.LogError(response.Message);
break;
}
}
}
}
}
}
} | 42.466667 | 158 | 0.537677 | [
"MIT"
] | ChristianBasiga/MDG | workers/unity/Assets/MDG/Scripts/Common/Systems/Points/PointRequestSystem.cs | 5,098 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#if FEATURE_WIN32_REGISTRY
using System.Collections.Generic;
using Microsoft.Win32;
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Build.Shared
{
/// <summary>
/// Helper methods that simplify registry access.
/// </summary>
internal static class RegistryHelper
{
/// <summary>
/// Given a baseKey and a subKey, get all of the subkeys names.
/// </summary>
/// <param name="baseKey">The base registry key.</param>
/// <param name="subkey">The subkey</param>
/// <returns>An enumeration of strings.</returns>
internal static IEnumerable<string> GetSubKeyNames(RegistryKey baseKey, string subkey)
{
IEnumerable<string> subKeys = null;
using (RegistryKey subKey = baseKey.OpenSubKey(subkey))
{
if (subKey != null)
{
subKeys = subKey.GetSubKeyNames();
}
}
return subKeys;
}
/// <summary>
/// Given a baseKey and subKey, get the default value of the subKey.
/// </summary>
/// <param name="baseKey">The base registry key.</param>
/// <param name="subkey">The subkey</param>
/// <returns>A string containing the default value.</returns>
internal static string GetDefaultValue(RegistryKey baseKey, string subkey)
{
string value = null;
using (RegistryKey key = baseKey.OpenSubKey(subkey))
{
if (key != null && key.ValueCount > 0)
{
value = (string)key.GetValue("");
}
}
return value;
}
/// <summary>
/// Given a hive and a hive view open the base key
/// RegistryKey baseKey = RegistryKey.OpenBaseKey(hive, view);
/// </summary>
/// <param name="hive">The hive.</param>
/// <param name="view">The hive view</param>
/// <returns>A registry Key for the given baseKey and view</returns>
internal static RegistryKey OpenBaseKey(RegistryHive hive, RegistryView view)
{
RegistryKey key = RegistryKey.OpenBaseKey(hive, view);
return key;
}
}
}
#endif | 34.621622 | 101 | 0.574161 | [
"MIT"
] | 0n1zz/main | src/Shared/RegistryHelper.cs | 2,564 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.TestCommon;
using Microsoft.Web.UnitTestUtil;
namespace Microsoft.Web.Mvc.Test
{
public class MailToExtensionsTest
{
[Fact]
public void MailToWithoutEmailThrowsArgumentNullException()
{
HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());
Assert.ThrowsArgumentNull(() => html.Mailto("link text", null), "emailAddress");
}
[Fact]
public void MailToWithoutLinkTextThrowsArgumentNullException()
{
HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());
Assert.ThrowsArgumentNull(() => html.Mailto(null, "[email protected]"), "linkText");
}
[Fact]
public void MailToWithLinkTextAndEmailRendersProperElement()
{
HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());
MvcHtmlString result = html.Mailto("This is a test", "[email protected]");
Assert.Equal("<a href=\"mailto:[email protected]\">This is a test</a>", result.ToHtmlString());
}
[Fact]
public void MailToWithLinkTextEmailAndHtmlAttributesRendersAttributes()
{
HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());
MvcHtmlString result = html.Mailto("This is a test", "[email protected]", new { title = "this is a test" });
Assert.Equal("<a href=\"mailto:[email protected]\" title=\"this is a test\">This is a test</a>", result.ToHtmlString());
}
[Fact]
public void MailToWithLinkTextEmailAndHtmlAttributesDictionaryRendersAttributes()
{
HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());
MvcHtmlString result = html.Mailto("This is a test", "[email protected]", new RouteValueDictionary(new { title = "this is a test" }));
Assert.Equal("<a href=\"mailto:[email protected]\" title=\"this is a test\">This is a test</a>", result.ToHtmlString());
}
[Fact]
public void MailToWithSubjectAndHtmlAttributesRendersAttributes()
{
HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());
MvcHtmlString result = html.Mailto("This is a test", "[email protected]", "The subject", new { title = "this is a test" });
Assert.Equal("<a href=\"mailto:[email protected]?subject=The subject\" title=\"this is a test\">This is a test</a>", result.ToHtmlString());
}
[Fact]
public void MailToWithSubjectAndHtmlAttributesDictionaryRendersAttributes()
{
HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());
MvcHtmlString result = html.Mailto("This is a test", "[email protected]", "The subject", new RouteValueDictionary(new { title = "this is a test" }));
Assert.Equal("<a href=\"mailto:[email protected]?subject=The subject\" title=\"this is a test\">This is a test</a>", result.ToHtmlString());
}
[Fact]
public void MailToAttributeEncodesEmail()
{
HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());
MvcHtmlString result = html.Mailto("This is a test", "te\">[email protected]");
Assert.Equal("<a href=\"mailto:te">[email protected]\">This is a test</a>", result.ToHtmlString());
}
[Fact]
public void MailToWithMultipleRecipientsRendersWithCommas()
{
HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());
MvcHtmlString result = html.Mailto("This is a test", "te\">[email protected],[email protected]");
Assert.Equal("<a href=\"mailto:te">[email protected],[email protected]\">This is a test</a>", result.ToHtmlString());
}
[Fact]
public void MailToWithSubjectAppendsSubjectQuery()
{
HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());
MvcHtmlString result = html.Mailto("This is a test", "[email protected]", "This is the subject");
Assert.Equal("<a href=\"mailto:[email protected]?subject=This is the subject\">This is a test</a>", result.ToHtmlString());
}
[Fact]
public void MailToWithCopyOnlyAppendsCopyQuery()
{
HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());
MvcHtmlString result = html.Mailto("This is a test", "[email protected]", null, null, "[email protected]", null, null);
Assert.Equal("<a href=\"mailto:[email protected][email protected]\">This is a test</a>", result.ToHtmlString());
}
[Fact]
public void MailToWithMultipartBodyRendersProperMailtoEncoding()
{
HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());
string body = "Line one" + Environment.NewLine
+ "Line two" + Environment.NewLine
+ "Line three";
MvcHtmlString result = html.Mailto("email me", "[email protected]", null, body, null, null, null);
Assert.Equal("<a href=\"mailto:[email protected]?body=Line one%0ALine two%0ALine three\">email me</a>", result.ToHtmlString());
}
[Fact]
public void MailToWithAllValuesProvidedRendersCorrectTag()
{
HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());
string body = "Line one" + Environment.NewLine
+ "Line two" + Environment.NewLine
+ "Line three";
MvcHtmlString result = html.Mailto("email me", "[email protected]", "the subject", body, "[email protected]", "[email protected]", new { title = "email test" });
string expected = @"<a href=""mailto:[email protected]?subject=the subject&[email protected]&[email protected]&body=Line one%0ALine two%0ALine three"" title=""email test"">email me</a>";
Assert.Equal(expected, result.ToHtmlString());
}
[Fact]
public void MailToWithAttributesWithUnderscores()
{
HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());
string body = "Line one" + Environment.NewLine
+ "Line two" + Environment.NewLine
+ "Line three";
MvcHtmlString result = html.Mailto("email me", "[email protected]", "the subject", body, "[email protected]", "[email protected]", new { foo_bar = "baz" });
string expected = @"<a foo-bar=""baz"" href=""mailto:[email protected]?subject=the subject&[email protected]&[email protected]&body=Line one%0ALine two%0ALine three"">email me</a>";
Assert.Equal(expected, result.ToHtmlString());
}
}
}
| 51.601449 | 211 | 0.636147 | [
"Apache-2.0"
] | Darth-Fx/AspNetMvcStack | test/Microsoft.Web.Mvc.Test/Test/MailToExtensionsTest.cs | 7,123 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace EMIEWebPortal.DataModel
{
using System;
using System.Collections.Generic;
public partial class TestPassPrimSecMapping
{
public int TestPassPrimSecCriteriaId { get; set; }
public int TestPassId { get; set; }
public int PrimSecCriteriaId { get; set; }
public Nullable<int> CreatedById { get; set; }
public Nullable<System.DateTime> CreatedDate { get; set; }
public Nullable<int> ModifiedById { get; set; }
public Nullable<System.DateTime> ModifiedDate { get; set; }
public Nullable<bool> IsActive { get; set; }
public virtual TestPass TestPass { get; set; }
}
}
| 37.793103 | 85 | 0.567518 | [
"MIT"
] | DalavanCloud/enterprise-mode-site-list-portal | EMIEWebPortal.DataModel/TestPassPrimSecMapping.cs | 1,096 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using System.Net.Http;
using ApiUtil;
using ApiUtil.DataClasses;
namespace DGPLattice.Screens.User
{
public partial class frmEditSelf : Form
{
HttpClient _httpClient;
MainForm _main;
public frmEditSelf(HttpClient httpClient, MainForm mainForm)
{
InitializeComponent();
try
{
_httpClient = httpClient;
_main = mainForm;
// populate the form with current values
Populate();
}
catch (Exception ex)
{
RemoteErrLog.LogException(_main.UserName, _main.Password, _main.SvcUrl, "DGP Lattice", "frmEditSelf", ex);
MessageBox.Show(ex.Message, "frmEditSelf", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
///
/// </summary>
private void Populate()
{
try
{
// lookup method data using global id value
Dictionary<string, string> methparams = new Dictionary<string, string>();
methparams.Add(CommonFields.SchemaFlag, "true");
methparams.Add(APIUserFields.UserGID, _main.UserGID);
MsgUtil msgUtil = new MsgUtil();
ResInfo methresult = msgUtil.ApiMethHelper("UserSelf.GetInfo.base",
_main.UserName,
_main.Password,
methparams,
_httpClient,
_main.SvcUrl);
if (methresult != null && methresult.RCode == APIResult.OK && methresult.DType == APIData.DataTable)
{
CmnUtil cmnUtil = new CmnUtil();
DataTable methtable = cmnUtil.XmlToTable(methresult.RVal);
if (methtable.Rows.Count > 0)
{
foreach (DataRow dr in methtable.Rows)
{
tbxGlobalID.Text = dr[CommonFields.rec_gid].ToString();
tbxUserName.Text = dr[APIUserFields.UserName].ToString();
tbxFirstName.Text = dr[APIUserFields.FirstName].ToString();
tbxMiddleName.Text = dr[APIUserFields.MiddleName].ToString();
tbxLastName.Text = dr[APIUserFields.LastName].ToString();
tbxEmail.Text = dr[APIUserFields.Email].ToString();
}
}
}
}
catch (Exception ex)
{
RemoteErrLog.LogException(_main.UserName, _main.Password, _main.SvcUrl, "DGP Lattice", "frmEditSelf.Populate", ex);
MessageBox.Show(ex.Message, "frmEditSelf.Populate", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
if (CheckFields())
{
Dictionary<string, string> methparams = new Dictionary<string, string>();
methparams.Add(CommonFields.rec_gid, tbxGlobalID.Text);
methparams.Add(APIUserFields.FirstName, tbxFirstName.Text);
methparams.Add(APIUserFields.MiddleName, tbxMiddleName.Text);
methparams.Add(APIUserFields.LastName, tbxLastName.Text);
methparams.Add(APIUserFields.Email, tbxEmail.Text);
MsgUtil msgUtil = new MsgUtil();
ResInfo methresult = msgUtil.ApiMethHelper("UserSelf.Save.base",
_main.UserName,
_main.Password,
methparams,
_httpClient,
_main.SvcUrl);
if (methresult.RCode.ToUpper() == APIResult.OK)
{
// close the dialog
this.Close();
}
else
{
// error saving method info: display error message
MessageBox.Show(methresult.RVal, methresult.RCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("You must provide values for all required fields", "Required Field Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
RemoteErrLog.LogException(_main.UserName, _main.Password, _main.SvcUrl, "DGP Lattice", "frmEditSelf.btnSave_Click", ex);
MessageBox.Show(ex.Message, "frmEditSelf.btnSave_Click", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private bool CheckFields()
{
bool fieldsOK = true;
if (tbxGlobalID.Text == null || tbxGlobalID.Text == "") fieldsOK = false;
if (tbxUserName.Text == null || tbxUserName.Text == "") fieldsOK = false;
if (tbxFirstName.Text == null || tbxFirstName.Text == "") fieldsOK = false;
if (tbxLastName.Text == null || tbxLastName.Text == "") fieldsOK = false;
if (tbxEmail.Text == null || tbxEmail.Text == "") fieldsOK = false;
return fieldsOK;
}
}
}
| 40.818792 | 155 | 0.476817 | [
"Apache-2.0"
] | alanrahn/GitHub_DGP | SourceCode/Client/DGPLattice/Screens/User/frmEditSelf.cs | 6,084 | C# |
#region PDFsharp - A .NET library for processing PDF
//
// Authors:
// Klaus Potzesny
//
// Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany)
//
// http://www.PdfSharpCore.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
namespace Didstopia.PDFSharp.Drawing.BarCodes
{
/// <summary>
/// Implementation of the Code 2 of 5 bar code.
/// </summary>
public class Code2of5Interleaved : ThickThinBarCode
{
/// <summary>
/// Initializes a new instance of Interleaved2of5.
/// </summary>
public Code2of5Interleaved()
: base("", XSize.Empty, CodeDirection.LeftToRight)
{}
/// <summary>
/// Initializes a new instance of Interleaved2of5.
/// </summary>
public Code2of5Interleaved(string code)
: base(code, XSize.Empty, CodeDirection.LeftToRight)
{}
/// <summary>
/// Initializes a new instance of Interleaved2of5.
/// </summary>
public Code2of5Interleaved(string code, XSize size)
: base(code, size, CodeDirection.LeftToRight)
{}
/// <summary>
/// Initializes a new instance of Interleaved2of5.
/// </summary>
public Code2of5Interleaved(string code, XSize size, CodeDirection direction)
: base(code, size, direction)
{}
/// <summary>
/// Returns an array of size 5 that represents the thick (true) and thin (false) lines or spaces
/// representing the specified digit.
/// </summary>
/// <param name="digit">The digit to represent.</param>
static bool[] ThickAndThinLines(int digit)
{
return Lines[digit];
}
static bool[][] Lines =
{
new bool[] {false, false, true, true, false},
new bool[] {true, false, false, false, true},
new bool[] {false, true, false, false, true},
new bool[] {true, true, false, false, false},
new bool[] {false, false, true, false, true},
new bool[] {true, false, true, false, false},
new bool[] {false, true, true, false, false},
new bool[] {false, false, false, true, true},
new bool[] {true, false, false, true, false},
new bool[] {false, true, false, true, false},
};
/// <summary>
/// Renders the bar code.
/// </summary>
protected internal override void Render(XGraphics gfx, XBrush brush, XFont font, XPoint position)
{
XGraphicsState state = gfx.Save();
BarCodeRenderInfo info = new BarCodeRenderInfo(gfx, brush, font, position);
InitRendering(info);
info.CurrPosInString = 0;
//info.CurrPos = info.Center - Size / 2;
info.CurrPos = position - CodeBase.CalcDistance(AnchorType.TopLeft, Anchor, Size);
if (TurboBit)
RenderTurboBit(info, true);
RenderStart(info);
while (info.CurrPosInString < Text.Length)
RenderNextPair(info);
RenderStop(info);
if (TurboBit)
RenderTurboBit(info, false);
if (TextLocation != TextLocation.None)
RenderText(info);
gfx.Restore(state);
}
/// <summary>
/// Calculates the thick and thin line widths,
/// taking into account the required rendering size.
/// </summary>
internal override void CalcThinBarWidth(BarCodeRenderInfo info)
{
/*
* The total width is the sum of the following parts:
* Starting lines = 4 * thin
* +
* Code Representation = (2 * thick + 3 * thin) * code.Length
* +
* Stopping lines = 1 * thick + 2 * thin
*
* with r = relation ( = thick / thin), this results in
*
* Total width = (6 + r + (2 * r + 3) * text.Length) * thin
*/
double thinLineAmount = 6 + WideNarrowRatio + (2 * WideNarrowRatio + 3) * Text.Length;
info.ThinBarWidth = Size.Width / thinLineAmount;
}
private void RenderStart(BarCodeRenderInfo info)
{
RenderBar(info, false);
RenderGap(info, false);
RenderBar(info, false);
RenderGap(info, false);
}
private void RenderStop(BarCodeRenderInfo info)
{
RenderBar(info, true);
RenderGap(info, false);
RenderBar(info, false);
}
/// <summary>
/// Renders the next digit pair as bar code element.
/// </summary>
private void RenderNextPair(BarCodeRenderInfo info)
{
int digitForLines = int.Parse(Text[info.CurrPosInString].ToString());
int digitForGaps = int.Parse(Text[info.CurrPosInString + 1].ToString());
bool[] linesArray = Lines[digitForLines];
bool[] gapsArray = Lines[digitForGaps];
for (int idx = 0; idx < 5; ++idx)
{
RenderBar(info, linesArray[idx]);
RenderGap(info, gapsArray[idx]);
}
info.CurrPosInString += 2;
}
/// <summary>
/// Checks the code to be convertible into an interleaved 2 of 5 bar code.
/// </summary>
/// <param name="text">The code to be checked.</param>
protected override void CheckCode(string text)
{
#if true_
if (text == null)
throw new ArgumentNullException("text");
if (text == "")
throw new ArgumentException(BcgSR.Invalid2Of5Code(text));
if (text.Length % 2 != 0)
throw new ArgumentException(BcgSR.Invalid2Of5Code(text));
foreach (char ch in text)
{
if (!Char.IsDigit(ch))
throw new ArgumentException(BcgSR.Invalid2Of5Code(text));
}
#endif
}
}
}
| 36.597938 | 105 | 0.580423 | [
"MIT"
] | Balaboom-zq/PDFSharp | Didstopia.PDFSharp/Drawing.BarCodes/Code2of5Interleaved.cs | 7,100 | C# |
namespace mini_ITS.Core.Options
{
public class DatabaseOptions
{
public string DataSource { get; set; }
public string InitialCatalog { get; set; }
public bool PersistSecurityInfo { get; set; }
public bool IntegratedSecurity { get; set; }
public string UserId { get; set; }
public string Password { get; set; }
public int ConnectTimeout { get; set; }
}
}
| 30.214286 | 53 | 0.619385 | [
"MIT"
] | tc-soft/mini-ITS | mini-ITS.Core/Options/DatabaseOptions.cs | 425 | C# |
using System.IO;
using UAlbion.Api;
namespace UAlbion.Formats.MapEvents
{
public class ChangeIconEvent : IEvent
{
public static EventNode Load(BinaryReader br, int id, MapEventType type)
{
return new EventNode(id, new ChangeIconEvent
{
X = br.ReadSByte(), // 1
Y = br.ReadSByte(), // 2
Permanent = br.ReadByte(), // 3
ChangeType = (IconChangeType) br.ReadByte(), // 4
Unk5 = br.ReadByte(), // 5
Value = br.ReadUInt16(), // 6
Unk8 = br.ReadUInt16(),
});
}
public enum IconChangeType : byte
{
ChangeUnderlay = 0,
ChangeOverlay = 1,
ChangeWall = 2,
ChangeFloor = 3,
ChangeCeiling = 4,
ChangeNpcMovementType = 5,
ChangeNpcSprite = 6,
ChangeTileEventChain = 7,
PlaceTilemapObjectOverwrite = 8, // Objects are in BLKLIST#.XLD
PlaceTilemapObjectNoOverwrite = 9, // Objects are in BLKLIST#.XLD
ChangeTileEventTrigger = 0xA, // ???? Might not be 0xA
}
public sbyte X { get; private set; }
public sbyte Y { get; private set; }
public byte Permanent { get; private set; }
public IconChangeType ChangeType { get; private set; }
public byte Unk5 { get; private set; }
public ushort Value { get; private set; }
public ushort Unk8 { get; set; }
public override string ToString() => $"change_icon <{X}, {Y}> {(Permanent != 0 ? "Perm" : "Temp")} {ChangeType} {Value} ({Unk5} {Unk8})";
}
}
| 35.744681 | 145 | 0.535119 | [
"MIT"
] | mrwillbarnz/ualbion | Formats/MapEvents/ChangeIconEvent.cs | 1,682 | C# |
using StarryEyes.Anomaly.TwitterApi.DataModels;
using StarryEyes.Views;
namespace StarryEyes.Models.Backstages.TwitterEvents
{
public sealed class RetweetedEvent : TwitterEventBase
{
public RetweetedEvent(TwitterUser source, TwitterStatus target)
: base(source, target) { }
public override string Title
{
get { return "RT"; }
}
public override string Detail
{
get { return Source.ScreenName + ": " + TargetStatus; }
}
public override System.Windows.Media.Color Background
{
get
{
return MetroColors.Emerald;
}
}
}
}
| 23.366667 | 71 | 0.573466 | [
"MIT"
] | Grabacr07/StarryEyes | StarryEyes/Models/Backstages/TwitterEvents/RetweetedEvent.cs | 703 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Exchange_Variable_Values")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Exchange_Variable_Values")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9ad7eb79-c4cb-4489-b150-69447612cb8d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.27027 | 84 | 0.752119 | [
"MIT"
] | stepan82/Programming-Fundamentals-September-2017 | Data-Type-Variables/Exchange_Variable_Values/Properties/AssemblyInfo.cs | 1,419 | C# |
namespace InControl
{
// @cond nodoc
[AutoDiscover]
public class DroidBoxPS3AndroidProfile : UnityInputDeviceProfile
{
// https://www.amazon.com/DroidBOX-Gamepad-Handheld-Touchscreen-Mali-T764-Linux/dp/B01B4ESXT0
// https://droidbox.co.uk/gpd-xd-droidbox-playon-best-mini-handheld-games-tablet-console-android.html
// This controller is capable of switching between PS3 and Xbox modes.
public DroidBoxPS3AndroidProfile()
{
Name = "DroidBOX GPD XD PlayON - PS3 Mode";
Meta = "DroidBOX GPD XD PlayON - PS3 Mode on Android";
DeviceClass = InputDeviceClass.Controller;
IncludePlatforms = new[] {
"Android"
};
JoystickNames = new[] {
"PLAYSTATION(R)3",
};
ButtonMappings = new[] {
new InputControlMapping {
Handle = "Cross",
Target = InputControlType.Action1,
Source = Button0
},
new InputControlMapping {
Handle = "Circle",
Target = InputControlType.Action2,
Source = Button1
},
new InputControlMapping {
Handle = "Square",
Target = InputControlType.Action3,
Source = Button2
},
new InputControlMapping {
Handle = "Triangle",
Target = InputControlType.Action4,
Source = Button3
},
new InputControlMapping {
Handle = "Start",
Target = InputControlType.Start,
Source = Button10
},
new InputControlMapping {
Handle = "Select",
Target = InputControlType.Select,
Source = Button11
},
new InputControlMapping {
Handle = "L1",
Target = InputControlType.LeftBumper,
Source = Button4
},
new InputControlMapping {
Handle = "L2",
Target = InputControlType.LeftTrigger,
Source = Button6
},
new InputControlMapping {
Handle = "L3",
Target = InputControlType.LeftStickButton,
Source = Button8
},
new InputControlMapping {
Handle = "R1",
Target = InputControlType.RightBumper,
Source = Button5
},
new InputControlMapping {
Handle = "R2",
Target = InputControlType.RightTrigger,
Source = Button7
},
new InputControlMapping {
Handle = "R3",
Target = InputControlType.RightStickButton,
Source = Button9
},
};
AnalogMappings = new[] {
LeftStickLeftMapping( Analog0 ),
LeftStickRightMapping( Analog0 ),
LeftStickUpMapping( Analog1 ),
LeftStickDownMapping( Analog1 ),
RightStickLeftMapping( Analog2 ),
RightStickRightMapping( Analog2 ),
RightStickUpMapping( Analog3 ),
RightStickDownMapping( Analog3 ),
DPadLeftMapping( Analog4 ),
DPadRightMapping( Analog4 ),
DPadUpMapping( Analog5 ),
DPadDownMapping( Analog5 ),
};
}
}
// @endcond
}
| 24.779817 | 103 | 0.654943 | [
"MIT"
] | BattlerockStudios/GGJ2019 | Assets/InControl/Source/Unity/DeviceProfiles/DroidBoxPS3AndroidProfile.cs | 2,701 | C# |
using System;
using System.Linq;
using PKISharp.WACS.Services;
namespace PKISharp.WACS.Extensions
{
public static class TargetExtensions
{
public static bool IsCommonNameValid(this Target target, ILogService failureLogService = null)
{
var cn = target.CommonName;
var isValid = cn == null || target.AlternativeNames.Contains(cn, StringComparer.InvariantCultureIgnoreCase);
if (failureLogService != null && !isValid) failureLogService.Error($"The supplied common name '{target.CommonName}' is none of this target's alternative names.");
return isValid;
}
public static void AskForCommonNameChoice(this Target target, IInputService inputService)
{
if (target.AlternativeNames.Count < 2) return;
var sanChoices = target.AlternativeNames.OrderBy(x => x).Select(san => Choice.Create<string>(san)).ToList();
target.CommonName = inputService.ChooseFromList("Choose a domain name to be the certificate's common name", sanChoices, false);
}
}
}
| 44.24 | 175 | 0.669078 | [
"Apache-2.0"
] | helixge/win-acme | letsencrypt-win-simple/Extensions/TargetExtensions.cs | 1,108 | C# |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Management.Automation;
using System.Management.Automation.Runspaces;
namespace Microsoft.PowerShell
{
/// <summary>
/// This class provides an entry point which is called by minishell's main
/// to transfer control to Msh console host implementation.
/// </summary>
public static
class ConsoleShell
{
#if CORECLR
/// <summary>Entry point in to ConsoleShell. This method is called by main of minishell.</summary>
/// <param name="bannerText">Banner text to be displayed by ConsoleHost</param>
/// <param name="helpText">Help text for minishell. This is displayed on 'minishell -?'.</param>
/// <param name="args">Commandline parameters specified by user.</param>
/// <returns>An integer value which should be used as exit code for the process.</returns>
public static int Start(string bannerText, string helpText, string[] args)
{
return Start(null, bannerText, helpText, null, args);
}
#else
/// <summary>Entry point in to ConsoleShell. This method is called by main of minishell.</summary>
/// <param name="configuration">Configuration information which is used to create Runspace.</param>
/// <param name="bannerText">Banner text to be displayed by ConsoleHost</param>
/// <param name="helpText">Help text for minishell. This is displayed on 'minishell -?'.</param>
/// <param name="args">Commandline parameters specified by user.</param>
/// <returns>An integer value which should be used as exit code for the process.</returns>
public static int Start(RunspaceConfiguration configuration, string bannerText, string helpText, string[] args)
{
return Start(configuration, bannerText, helpText, null, args);
}
#endif
/// <summary>
///
/// Entry point in to ConsoleShell. This method is called from the native or managed exe host application
///
/// </summary>
/// <param name="configuration">
/// Configuration information which is used to create Runspace.
/// </param>
///
/// <param name="bannerText">
/// Banner text to be displayed by ConsoleHost
/// </param>
///
/// <param name="helpText">
/// Help text for minishell. This is displayed on 'minishell -?'.
/// </param>
///
/// <param name="preStartWarning">
/// Warning occurred prior to this point, for example, a snap-in fails to load beforehand.
/// This string will be printed out.
/// </param>
///
/// <param name="args">
/// Commandline parameters specified by user.
/// </param>
///
/// <returns>
/// An integer value which should be used as exit code for the
/// process.
/// </returns>
internal static
int
Start(RunspaceConfiguration configuration,
string bannerText,
string helpText,
string preStartWarning,
string[] args)
{
if (args == null)
{
throw PSTraceSource.NewArgumentNullException("args");
}
// The default font face used for Powershell Console is Lucida Console.
// However certain CJK locales dont support Lucida Console font. Hence for such
// locales the console font is updated to Raster dynamically.
// For NanoServer:
// 1. There is no GetCurrentConsoleFontEx / SetCurrentConsoleFontEx on NanoServer;
// 2. We don't handle CJK locales on NanoServer due to lack of win32 API supports on NanoServer.
#if !CORECLR
ConsoleControl.UpdateLocaleSpecificFont();
#endif
return ConsoleHost.Start(configuration, bannerText, helpText, preStartWarning, args);
}
}
}
| 41.049505 | 119 | 0.592619 | [
"Apache-2.0",
"MIT"
] | adbertram/PowerShell | src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleShell.cs | 4,146 | C# |
using System;
using System.IO;
using AudioMog.Application.AudioFileRebuilder;
using AudioMog.Core;
using AudioMog.Core.Audio;
using VGAudio.Containers.Hca;
using VGAudio.Containers.Wave;
using VGAudio.Formats;
namespace AudioMog.Application.Codecs
{
public class HcaACodec : ACodec
{
private static readonly byte[] HcaEncryptionKey = new byte[0x100]
{
0x3A, 0x32, 0x32, 0x32, 0x03, 0x7E, 0x12, 0xF7, 0xB2, 0xE2, 0xA2, 0x67, 0x32, 0x32, 0x22, 0x32, // 00-0F
0x32, 0x52, 0x16, 0x1B, 0x3C, 0xA1, 0x54, 0x7B, 0x1B, 0x97, 0xA6, 0x93, 0x1A, 0x4B, 0xAA, 0xA6, // 10-1F
0x7A, 0x7B, 0x1B, 0x97, 0xA6, 0xF7, 0x02, 0xBB, 0xAA, 0xA6, 0xBB, 0xF7, 0x2A, 0x51, 0xBE, 0x03, // 20-2F
0xF4, 0x2A, 0x51, 0xBE, 0x03, 0xF4, 0x2A, 0x51, 0xBE, 0x12, 0x06, 0x56, 0x27, 0x32, 0x32, 0x36, // 30-3F
0x32, 0xB2, 0x1A, 0x3B, 0xBC, 0x91, 0xD4, 0x7B, 0x58, 0xFC, 0x0B, 0x55, 0x2A, 0x15, 0xBC, 0x40, // 40-4F
0x92, 0x0B, 0x5B, 0x7C, 0x0A, 0x95, 0x12, 0x35, 0xB8, 0x63, 0xD2, 0x0B, 0x3B, 0xF0, 0xC7, 0x14, // 50-5F
0x51, 0x5C, 0x94, 0x86, 0x94, 0x59, 0x5C, 0xFC, 0x1B, 0x17, 0x3A, 0x3F, 0x6B, 0x37, 0x32, 0x32, // 60-6F
0x30, 0x32, 0x72, 0x7A, 0x13, 0xB7, 0x26, 0x60, 0x7A, 0x13, 0xB7, 0x26, 0x50, 0xBA, 0x13, 0xB4, // 70-7F
0x2A, 0x50, 0xBA, 0x13, 0xB5, 0x2E, 0x40, 0xFA, 0x13, 0x95, 0xAE, 0x40, 0x38, 0x18, 0x9A, 0x92, // 80-8F
0xB0, 0x38, 0x00, 0xFA, 0x12, 0xB1, 0x7E, 0x00, 0xDB, 0x96, 0xA1, 0x7C, 0x08, 0xDB, 0x9A, 0x91, // 90-9F
0xBC, 0x08, 0xD8, 0x1A, 0x86, 0xE2, 0x70, 0x39, 0x1F, 0x86, 0xE0, 0x78, 0x7E, 0x03, 0xE7, 0x64, // A0-AF
0x51, 0x9C, 0x8F, 0x34, 0x6F, 0x4E, 0x41, 0xFC, 0x0B, 0xD5, 0xAE, 0x41, 0xFC, 0x0B, 0xD5, 0xAE, // B0-BF
0x41, 0xFC, 0x3B, 0x70, 0x71, 0x64, 0x33, 0x32, 0x12, 0x32, 0x32, 0x36, 0x70, 0x34, 0x2B, 0x56, // C0-CF
0x22, 0x70, 0x3A, 0x13, 0xB7, 0x26, 0x60, 0xBA, 0x1B, 0x94, 0xAA, 0x40, 0x38, 0x00, 0xFA, 0xB2, // D0-DF
0xE2, 0xA2, 0x67, 0x32, 0x32, 0x12, 0x32, 0xB2, 0x32, 0x32, 0x32, 0x32, 0x75, 0xA3, 0x26, 0x7B, // E0-EF
0x83, 0x26, 0xF9, 0x83, 0x2E, 0xFF, 0xE3, 0x16, 0x7D, 0xC0, 0x1E, 0x63, 0x21, 0x07, 0xE3, 0x01, // F0-FF
};
public override string FileFormat => ".hca";
public override void ExtractOriginal(IApplicationLogger logger, MaterialSection.MaterialEntry entry, byte[] fullFileBytes, string outputPath)
{
var rawContentBytes = fullFileBytes.SubArray(entry.InnerStreamStartPosition, entry.InnerStreamSize);
BinaryReader fullBinaryReader = new BinaryReader(new MemoryStream(fullFileBytes));
var encryption = fullBinaryReader.ReadByteAt(entry.ExtraDataOffset + 0x0d);
if (encryption == 1)
DecryptHCA(entry, rawContentBytes, fullBinaryReader);
var rawPath = ExtensionMethods.ChangeExtension(outputPath, FileFormat);
File.WriteAllBytes(rawPath, rawContentBytes);
logger.Log($"Created hca audio track at: {rawPath}");
}
public override void ExtractAsWav(IApplicationLogger logger, MaterialSection.MaterialEntry entry, byte[] fullFileBytes, string wavPath)
{
var rawContentBytes = fullFileBytes.SubArray(entry.InnerStreamStartPosition, entry.InnerStreamSize);
AudioData audioData = null;
HcaReader reader = new HcaReader();
BinaryReader fullBinaryReader = new BinaryReader(new MemoryStream(fullFileBytes));
var encryption = fullBinaryReader.ReadByteAt(entry.ExtraDataOffset + 0x0d);
if (encryption == 1)
DecryptHCA(entry, rawContentBytes, fullBinaryReader);
audioData = reader.Read(rawContentBytes);
WaveWriter writer = new WaveWriter();
var wavBytes = writer.GetFile(audioData);
File.WriteAllBytes(wavPath, wavBytes);
logger.Log($"Created wav audio track at: {wavPath}");
}
private static void DecryptHCA(MaterialSection.MaterialEntry entry, byte[] hcaFileBytes, BinaryReader fullBinaryReader)
{
var extraDataId = entry.ExtraDataId;
var key_start = extraDataId & 0xff;
var header_size = fullBinaryReader.ReadUInt16At(entry.ExtraDataOffset + 0x02);
var start = header_size;
var offset = 0;
for (int byteIndex = 0; byteIndex < hcaFileBytes.Length; byteIndex++)
{
var hcaByte = hcaFileBytes[byteIndex];
bool canSwap = byteIndex >= start + offset;
if (!canSwap)
continue;
var encryptionIndex = key_start + offset + byteIndex - start;
var wrappedEncryptionIndex = encryptionIndex % HcaEncryptionKey.Length;
hcaByte ^= HcaEncryptionKey[wrappedEncryptionIndex];
hcaFileBytes[byteIndex] = hcaByte;
}
}
public override void FixHeader(TemporaryTrack track)
{
ExposedHcaReader reader = new ExposedHcaReader();
var data = reader.GetStructure(track.RawPortion);
if (track.OriginalEntry.Codec != track.CurrentCodec)
{
var tempMaterialData = track.HeaderPortion.SubArray(0, 32);
WriteByte(tempMaterialData, 0x05, (byte)MaterialCodecType.HCA);
var tempHCAData = new byte[16];
WriteByte(tempHCAData, 0x00, 1);
WriteByte(tempHCAData, 0x01, 16); //extraDataSize
WriteUshort(tempHCAData, 0x02, (ushort)data.HeaderSize);
WriteUshort(tempHCAData, 0x04, (ushort)data.Hca.FrameSize);
WriteUshort(tempHCAData, 0x06, (ushort)data.Hca.LoopStartFrame);
WriteUshort(tempHCAData, 0x08, (ushort)data.Hca.LoopEndFrame);
WriteUshort(tempHCAData, 0x0a, (ushort)data.Hca.InsertedSamples);
WriteByte(tempHCAData, 0x0c, 0); //remove mixer flag!
WriteByte(tempHCAData, 0x0d, 0); //remove encryption flag!
WriteUshort(tempHCAData, 0x0e, 0); //clean reserves!
var tempMerged = new byte[48];
tempMaterialData.CopyTo(tempMerged,0);
tempHCAData.CopyTo(tempMerged, 32);
track.HeaderPortion = tempMerged;
}
int loopStart = 0;
int loopEnd = 0;
if (data.Hca.Looping)
{
loopStart = data.Hca.LoopStartSample;
loopEnd = data.Hca.LoopEndSample;
}
var hcaHeaderSize = data.HeaderSize;
var newExtraDataSize = 16 + hcaHeaderSize;
var streamSize = track.RawPortion.Length - hcaHeaderSize;
var headerBytes = track.HeaderPortion;
WriteByte(headerBytes, 0x04, (byte)data.Hca.ChannelCount);
WriteUint(headerBytes, 0x08, (uint)data.Hca.SampleRate);
WriteUint(headerBytes, 0x0c, (uint)loopStart);
WriteUint(headerBytes, 0x10, (uint)loopEnd);
WriteUint(headerBytes, 0x14, (uint)newExtraDataSize);
WriteUint(headerBytes, 0x18, (uint)streamSize);
var extraData = 0x20;
WriteByte(headerBytes, extraData + 0x00, 1);
//WriteByte(headerBytes, extraData + 0x01, 16); //extraDataSize
WriteUshort(headerBytes, extraData + 0x02, (ushort)data.HeaderSize);
WriteUshort(headerBytes, extraData + 0x04, (ushort)data.Hca.FrameSize);
WriteUshort(headerBytes, extraData + 0x06, (ushort)data.Hca.LoopStartFrame);
WriteUshort(headerBytes, extraData + 0x08, (ushort)data.Hca.LoopEndFrame);
WriteUshort(headerBytes, extraData + 0x0a, (ushort)data.Hca.InsertedSamples);
// 0x0c: "use mixer" flag
WriteByte(headerBytes, extraData + 0x0d, 0); //remove encryption flag!
// 0x0e: reserved x2
}
}
} | 45.084416 | 143 | 0.712228 | [
"MIT"
] | Yoraiz0r/AudioMog | AudioMogApplication/Codecs/HcaCodec.cs | 6,945 | C# |
// -----------------------------------------------------------------------
// <copyright file="EntityHashExtensions.cs" company="Hybrid开源团队">
// Copyright (c) 2014-2018 Hybrid. All rights reserved.
// </copyright>
// <site>https://www.lxking.cn</site>
// <last-editor>ArcherTrister</last-editor>
// <last-date>2018-08-12 10:09</last-date>
// -----------------------------------------------------------------------
using Hybrid.Collections;
using Hybrid.Core.Data;
using Hybrid.Core.Systems;
using Hybrid.Extensions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Hybrid.Entity
{
/// <summary>
/// 实体Hash扩展方法
/// </summary>
public static class EntityHashExtensions
{
/// <summary>
/// 检查指定实体的Hash值,决定是否需要进行数据库同步
/// </summary>
public static bool CheckSyncByHash(this IEnumerable<IEntityHash> entityHashes, IServiceProvider provider, ILogger logger)
{
IEntityHash[] hashes = entityHashes as IEntityHash[] ?? entityHashes.ToArray();
if (hashes.Length == 0)
{
return false;
}
string hash = hashes.Select(m => m.GetHash()).ExpandAndToString().ToMd5Hash();
IKeyValueStore store = provider.GetService<IKeyValueStore>();
string entityType = hashes[0].GetType().FullName;
string key = $"Hybrid.Initialize.SyncToDatabaseHash-{entityType}";
IKeyValue keyValue = store.GetKeyValue(key);
if (keyValue != null && keyValue.Value?.ToString() == hash)
{
logger.LogInformation($"{hashes.Length}条基础数据“{entityType}”的内容签名 {hash} 与上次相同,取消数据库同步");
return false;
}
store.CreateOrUpdateKeyValue(key, hash).GetAwaiter().GetResult();
logger.LogInformation($"{hashes.Length}条基础数据“{entityType}”的内容签名 {hash} 与上次 {keyValue?.Value} 不同,将进行数据库同步");
return true;
}
/// <summary>
/// 获取指定实体的Hash值
/// </summary>
/// <param name="entity">实体对象</param>
public static string GetHash(this IEntityHash entity)
{
Type type = entity.GetType();
StringBuilder sb = new StringBuilder();
foreach (PropertyInfo property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(m => m.CanWrite && m.Name != "Id"))
{
sb.Append(property.GetValue(entity));
}
return sb.ToString().ToMd5Hash();
}
}
} | 37.222222 | 151 | 0.58097 | [
"Apache-2.0"
] | ArcherTrister/ESoftor | src/Hybrid/Entity/EntityHashExtensions.cs | 2,872 | C# |
// Copyright (c) 2015 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;
namespace SharpYaml.Serialization
{
/// <summary>
/// A factory of <see cref="IYamlSerializable"/>
/// </summary>
public interface IYamlSerializableFactory
{
/// <summary>
/// Try to create a <see cref="IYamlSerializable"/> or return null if not supported for a particular .NET typeDescriptor.
/// </summary>
/// <param name="context"></param>
/// <param name="typeDescriptor">The typeDescriptor.</param>
/// <returns>If supported, return an instance of <see cref="IYamlSerializable"/> else return <c>null</c>.</returns>
IYamlSerializable TryCreate(SerializerContext context, ITypeDescriptor typeDescriptor);
}
} | 51.793651 | 129 | 0.700276 | [
"MIT"
] | Cinchoo/SharpYaml | src/SharpYaml/Serialization/IYamlSerializableFactory.cs | 3,263 | C# |
namespace FightingArena
{
using System.Collections.Generic;
using System.Linq;
public class Arena
{
private List<Gladiator> gladiators;
public string Name { get; set; }
public int Count => this.gladiators.Count();
public Arena(string name)
{
this.Name = name;
gladiators = new List<Gladiator>();
}
public void Add(Gladiator gladiator)
{
gladiators.Add(gladiator);
}
public void Remove(string name)
{
gladiators = gladiators.Where(x => x.Name != name).ToList();
}
public Gladiator GetGladitorWithHighestStatPower()
{
return gladiators.OrderByDescending(x => x.GetStatPower()).First();
}
public Gladiator GetGladitorWithHighestWeaponPower()
{
return gladiators.OrderByDescending(x => x.GetWeaponPower()).First();
}
public Gladiator GetGladitorWithHighestTotalPower()
{
return gladiators.OrderByDescending(x => x.GetTotalPower()).First();
}
public override string ToString()
{
return $"{this.Name} - {gladiators.Count} gladiators are participating.";
}
}
}
| 27.387755 | 86 | 0.543219 | [
"MIT"
] | q2kPetrov/SoftUni | C#Advanced/ExamPreparation/16_April_2019/03_FightingArena/Arena.cs | 1,344 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RailNomenclature
{
public class AndSwitch : Switch
{
private Switch _s1, _s2;
public AndSwitch(Switch s1, Switch s2): base(null, 0, 0, 0, 0)
{
_s1 = s1;
_s2 = s2;
}
public override string Name()
{
return "AND Switch";
}
public override bool IsActivated()
{
return _s1.IsActivated() && _s2.IsActivated();
}
public override void Draw(Camera c)
{
throw new NotImplementedException();
}
}
}
| 20.529412 | 71 | 0.508596 | [
"MIT"
] | BenMakesGames/RailNomenclature | RailNomenclature/Model/World/Things/Switches/AndSwitch.cs | 700 | C# |
#if !NETSTANDARD13
/*
* 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 appmesh-2019-01-25.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Threading;
using System.Threading.Tasks;
using Amazon.Runtime;
namespace Amazon.AppMesh.Model
{
/// <summary>
/// Base class for ListVirtualGateways paginators.
/// </summary>
internal sealed partial class ListVirtualGatewaysPaginator : IPaginator<ListVirtualGatewaysResponse>, IListVirtualGatewaysPaginator
{
private readonly IAmazonAppMesh _client;
private readonly ListVirtualGatewaysRequest _request;
private int _isPaginatorInUse = 0;
/// <summary>
/// Enumerable containing all full responses for the operation
/// </summary>
public IPaginatedEnumerable<ListVirtualGatewaysResponse> Responses => new PaginatedResponse<ListVirtualGatewaysResponse>(this);
/// <summary>
/// Enumerable containing all of the VirtualGateways
/// </summary>
public IPaginatedEnumerable<VirtualGatewayRef> VirtualGateways =>
new PaginatedResultKeyResponse<ListVirtualGatewaysResponse, VirtualGatewayRef>(this, (i) => i.VirtualGateways);
internal ListVirtualGatewaysPaginator(IAmazonAppMesh client, ListVirtualGatewaysRequest request)
{
this._client = client;
this._request = request;
}
#if BCL
IEnumerable<ListVirtualGatewaysResponse> IPaginator<ListVirtualGatewaysResponse>.Paginate()
{
if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0)
{
throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance.");
}
PaginatorUtils.SetUserAgentAdditionOnRequest(_request);
var nextToken = _request.NextToken;
ListVirtualGatewaysResponse response;
do
{
_request.NextToken = nextToken;
response = _client.ListVirtualGateways(_request);
nextToken = response.NextToken;
yield return response;
}
while (!string.IsNullOrEmpty(nextToken));
}
#endif
#if AWS_ASYNC_ENUMERABLES_API
async IAsyncEnumerable<ListVirtualGatewaysResponse> IPaginator<ListVirtualGatewaysResponse>.PaginateAsync(CancellationToken cancellationToken = default)
{
if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0)
{
throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance.");
}
PaginatorUtils.SetUserAgentAdditionOnRequest(_request);
var nextToken = _request.NextToken;
ListVirtualGatewaysResponse response;
do
{
_request.NextToken = nextToken;
response = await _client.ListVirtualGatewaysAsync(_request, cancellationToken).ConfigureAwait(false);
nextToken = response.NextToken;
cancellationToken.ThrowIfCancellationRequested();
yield return response;
}
while (!string.IsNullOrEmpty(nextToken));
}
#endif
}
}
#endif | 41.030303 | 160 | 0.659527 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/AppMesh/Generated/Model/_bcl45+netstandard/ListVirtualGatewaysPaginator.cs | 4,062 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
namespace Microsoft.WingetCreateCore
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.Deployment.WindowsInstaller.Linq;
using Microsoft.Msix.Utils;
using Microsoft.Msix.Utils.AppxPackaging;
using Microsoft.Msix.Utils.AppxPackagingInterop;
using Microsoft.WingetCreateCore.Common;
using Microsoft.WingetCreateCore.Common.Exceptions;
using Microsoft.WingetCreateCore.Models;
using Microsoft.WingetCreateCore.Models.DefaultLocale;
using Microsoft.WingetCreateCore.Models.Installer;
using Microsoft.WingetCreateCore.Models.Version;
using Newtonsoft.Json;
using Vestris.ResourceLib;
/// <summary>
/// Provides functionality for a parsing and extracting relevant metadata from a given package.
/// </summary>
public static class PackageParser
{
/// <summary>
/// Representation of an installer's architectures detected from the url and binary.
/// </summary>
public record DetectedArch(string Url, InstallerArchitecture? UrlArch, InstallerArchitecture BinaryArch);
/// <summary>
/// The default path where downloaded installers are stored.
/// </summary>
public static readonly string DefaultInstallerDownloadPath = Path.Combine(Path.GetTempPath(), Constants.ProgramName);
private const string InvalidCharacters = "©|®";
private static readonly string[] KnownInstallerResourceNames = new[]
{
"inno",
"nullsoft",
};
private static HttpClient httpClient = new HttpClient();
private enum MachineType
{
X86 = 0x014c,
X64 = 0x8664,
}
/// <summary>
/// Gets or sets the path in the %TEMP% directory where installers are downloaded to.
/// </summary>
public static string InstallerDownloadPath { get; set; } = DefaultInstallerDownloadPath;
/// <summary>
/// Sets the HttpMessageHandler used for the static HttpClient.
/// </summary>
/// <param name="httpMessageHandler">Optional HttpMessageHandler to override default HttpClient behavior.</param>
public static void SetHttpMessageHandler(HttpMessageHandler httpMessageHandler)
{
httpClient.Dispose();
httpClient = httpMessageHandler != null ? new HttpClient(httpMessageHandler) : new HttpClient();
}
/// <summary>
/// Parses packages for available metadata including Version, Publisher, Name, Descripion, License, etc.
/// </summary>
/// <param name="paths">Path(s) to package files. </param>
/// <param name="urls">Installer urls. </param>
/// <param name="manifests">Wrapper object for manifest object models.</param>
/// <param name="detectedArchOfInstallers">List of DetectedArch objects that represent each installers detected architectures.</param>
public static void ParsePackages(
IEnumerable<string> paths,
IEnumerable<string> urls,
Manifests manifests,
out List<DetectedArch> detectedArchOfInstallers)
{
detectedArchOfInstallers = new List<DetectedArch>();
VersionManifest versionManifest = manifests.VersionManifest = new VersionManifest();
// TODO: Remove once default is set in schema
versionManifest.DefaultLocale = "en-US";
InstallerManifest installerManifest = manifests.InstallerManifest = new InstallerManifest();
DefaultLocaleManifest defaultLocaleManifest = manifests.DefaultLocaleManifest = new DefaultLocaleManifest();
List<string> parseFailedInstallerUrls = new List<string>();
foreach (var package in paths.Zip(urls, (path, url) => (path, url)))
{
if (!ParsePackage(package.path, package.url, manifests, ref detectedArchOfInstallers))
{
parseFailedInstallerUrls.Add(package.url);
}
}
if (parseFailedInstallerUrls.Any())
{
throw new ParsePackageException(parseFailedInstallerUrls);
}
}
/// <summary>
/// Download file at specified URL to temp directory, unless it's already present.
/// </summary>
/// <param name="url">The URL of the file to be downloaded.</param>
/// <param name="maxDownloadSize">The maximum file size in bytes to download.</param>
/// <returns>Path of downloaded, or previously downloaded, file.</returns>
public static async Task<string> DownloadFileAsync(string url, long? maxDownloadSize = null)
{
var response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
int redirectCount = 0;
while (response.StatusCode == System.Net.HttpStatusCode.Redirect && redirectCount < 2)
{
var redirectUri = response.Headers.Location;
response = await httpClient.GetAsync(redirectUri, HttpCompletionOption.ResponseHeadersRead);
redirectCount++;
}
if (!response.IsSuccessStatusCode)
{
string message = await response.Content.ReadAsStringAsync();
throw new HttpRequestException(message, null, response.StatusCode);
}
string urlFile = Path.GetFileName(url.Split('?').Last());
string contentDispositionFile = response.Content.Headers.ContentDisposition?.FileName?.Trim('"');
if (!Directory.Exists(InstallerDownloadPath))
{
Directory.CreateDirectory(InstallerDownloadPath);
}
string targetFile = Path.Combine(InstallerDownloadPath, contentDispositionFile ?? urlFile);
long? downloadSize = response.Content.Headers.ContentLength;
if (downloadSize > maxDownloadSize)
{
throw new DownloadSizeExceededException(maxDownloadSize.Value);
}
if (!File.Exists(targetFile) || new FileInfo(targetFile).Length != downloadSize)
{
File.Delete(targetFile);
using var targetFileStream = File.OpenWrite(targetFile);
var contentStream = await response.Content.ReadAsStreamAsync();
await contentStream.CopyToAsync(targetFileStream);
}
return targetFile;
}
/// <summary>
/// Computes the SHA256 hash of a file given its file path.
/// </summary>
/// <param name="path">Path to file to be hashed.</param>
/// <returns>The computed SHA256 hash string.</returns>
public static string GetFileHash(string path)
{
using Stream stream = File.OpenRead(path);
using var hasher = SHA256.Create();
return BitConverter.ToString(hasher.ComputeHash(stream)).Remove("-");
}
/// <summary>
/// Update InstallerManifest's Installer nodes based on specified package file paths.
/// </summary>
/// <param name="installerManifest"><see cref="InstallerManifest"/> to update.</param>
/// <param name="installerUrls">InstallerUrls where installers can be downloaded.</param>
/// <param name="paths">Paths to packages to extract metadata from.</param>
/// <param name="detectedArchOfInstallers">List of DetectedArch objects that represent each installers detected architectures.</param>
/// <param name="newInstallers">List of newly parsed installer nodes.</param>
public static void UpdateInstallerNodesAsync(
InstallerManifest installerManifest,
IEnumerable<string> installerUrls,
IEnumerable<string> paths,
out List<DetectedArch> detectedArchOfInstallers,
out List<Installer> newInstallers)
{
var newPackages = paths.Zip(installerUrls, (path, url) => (path, url)).ToList();
newInstallers = new List<Installer>();
detectedArchOfInstallers = new List<DetectedArch>();
var existingInstallers = new List<Installer>(installerManifest.Installers);
List<Installer> unmatchedInstallers = new List<Installer>();
List<Installer> multipleMatchedInstallers = new List<Installer>();
List<string> parseFailedInstallerUrls = new List<string>();
foreach (var (path, url) in newPackages)
{
if (!ParsePackageAndGenerateInstallerNodes(path, url, newInstallers, null, ref detectedArchOfInstallers))
{
parseFailedInstallerUrls.Add(url);
}
}
// We only allow updating manifests with the same package count
if (newInstallers.Count != existingInstallers.Count)
{
throw new InvalidOperationException();
}
if (parseFailedInstallerUrls.Any())
{
throw new ParsePackageException(parseFailedInstallerUrls);
}
Dictionary<Installer, Installer> installerMatchDict = new Dictionary<Installer, Installer>();
// Update previous installers with parsed data from downloaded packages
foreach (var newInstaller in newInstallers)
{
DetectedArch detectedArch = detectedArchOfInstallers.Find(
i => i.Url == newInstaller.InstallerUrl &&
(i.UrlArch == newInstaller.Architecture || i.BinaryArch == newInstaller.Architecture));
var urlMatch = existingInstallers.Where(
i => (i.InstallerType ?? installerManifest.InstallerType) == newInstaller.InstallerType &&
i.Architecture == detectedArch.UrlArch);
var archAndTypeMatch = existingInstallers.Where(
i => (i.InstallerType ?? installerManifest.InstallerType) == newInstaller.InstallerType &&
i.Architecture == detectedArch.BinaryArch);
int numOfUrlMatches = urlMatch.Count();
int numOfArchAndTypeMatches = archAndTypeMatch.Count();
// Count > 1 indicates multiple matches were found. Count == 0 indicates no matches were found.
// Since string matching isn't always reliable, failing to find a match is okay.
// We only want to show an error if a string match finds multiple matches.
// If string matching fails to find a match, show all errors that may occur from ArchAndTypeMatches.
if (numOfUrlMatches > 1)
{
multipleMatchedInstallers.Add(newInstaller);
continue;
}
else if (numOfUrlMatches == 0)
{
if (numOfArchAndTypeMatches == 0)
{
unmatchedInstallers.Add(newInstaller);
}
else if (numOfArchAndTypeMatches > 1)
{
multipleMatchedInstallers.Add(newInstaller);
}
}
var matchingExistingInstaller = numOfUrlMatches == 1 ? urlMatch.Single() : numOfArchAndTypeMatches == 1 ? archAndTypeMatch.Single() : null;
// If we can't find a match in the remaining existing packages, there must be a mismatch between the old manifest and the URLs provided
if (matchingExistingInstaller == null)
{
continue;
}
else
{
installerMatchDict.Add(matchingExistingInstaller, newInstaller); // add the match to the map.
existingInstallers.Remove(matchingExistingInstaller);
}
}
if (unmatchedInstallers.Any() || multipleMatchedInstallers.Any())
{
throw new InstallerMatchException(multipleMatchedInstallers, unmatchedInstallers);
}
else
{
foreach (var existingInstaller in installerMatchDict.Keys)
{
UpdateInstallerMetadata(existingInstaller, installerMatchDict[existingInstaller]);
}
}
}
/// <summary>
/// Parses the package for relevant metadata and and updates the metadata of the provided installer node.
/// </summary>
/// <param name="installer">Installer node.</param>
/// <param name="path">Path to package file.</param>
/// <param name="url">Installer url.</param>
/// <returns>Boolean indicating whether the package parse was successful.</returns>
public static bool ParsePackageAndUpdateInstallerNode(Installer installer, string path, string url)
{
List<Installer> newInstallers = new List<Installer>();
bool parseResult = ParseExeInstallerType(path, installer, newInstallers) ||
ParseMsix(path, installer, null, newInstallers) ||
ParseMsi(path, installer, null, newInstallers);
if (!parseResult || !newInstallers.Any())
{
return false;
}
Installer newInstaller = newInstallers.First();
if (newInstallers.Count > 1)
{
// For multiple installers in an AppxBundle, use the existing architecture to avoid matching conflicts.
newInstaller.Architecture = installer.Architecture;
}
else
{
// For a single installer, detect the architecture. If no architecture is detected, default to architecture from existing manifest.
newInstaller.Architecture = GetArchFromUrl(url) ?? GetMachineType(path)?.ToString().ToEnumOrDefault<InstallerArchitecture>() ?? installer.Architecture;
}
newInstaller.InstallerUrl = url;
newInstaller.InstallerSha256 = GetFileHash(path);
UpdateInstallerMetadata(installer, newInstallers.First());
return true;
}
/// <summary>
/// Creates a new Installer object that is a copy of the provided Installer.
/// </summary>
/// <param name="installer">Installer object to be cloned.</param>
/// <returns>A new cloned Installer object.</returns>
public static Installer CloneInstaller(Installer installer)
{
string json = JsonConvert.SerializeObject(installer);
return JsonConvert.DeserializeObject<Installer>(json);
}
/// <summary>
/// Updates the metadata from an existing installer node with the metadata from a new installer node.
/// </summary>
/// <param name="existingInstaller">Existing installer node.</param>
/// <param name="newInstaller">New installer node.</param>
private static void UpdateInstallerMetadata(Installer existingInstaller, Installer newInstaller)
{
existingInstaller.Architecture = newInstaller.Architecture;
existingInstaller.InstallerUrl = newInstaller.InstallerUrl;
existingInstaller.InstallerSha256 = newInstaller.InstallerSha256;
existingInstaller.SignatureSha256 = newInstaller.SignatureSha256;
existingInstaller.ProductCode = newInstaller.ProductCode;
existingInstaller.MinimumOSVersion = newInstaller.MinimumOSVersion;
existingInstaller.PackageFamilyName = newInstaller.PackageFamilyName;
existingInstaller.Platform = newInstaller.Platform;
}
/// <summary>
/// Parses a package for available metadata including Version, Publisher, Name, Descripion, License, etc.
/// </summary>
/// <param name="path">Path to package file. </param>
/// <param name="url">Installer url. </param>
/// <param name="manifests">Wrapper object for manifest object models.</param>
/// <param name="detectedArchOfInstallers">List of DetectedArch objects that represent each installers detected architectures.</param>
/// <returns>True if package was successfully parsed and metadata extracted, false otherwise.</returns>
private static bool ParsePackage(
string path,
string url,
Manifests manifests,
ref List<DetectedArch> detectedArchOfInstallers)
{
VersionManifest versionManifest = manifests.VersionManifest;
InstallerManifest installerManifest = manifests.InstallerManifest;
DefaultLocaleManifest defaultLocaleManifest = manifests.DefaultLocaleManifest;
var versionInfo = FileVersionInfo.GetVersionInfo(path);
defaultLocaleManifest.PackageVersion ??= versionInfo.FileVersion?.Trim() ?? versionInfo.ProductVersion?.Trim();
defaultLocaleManifest.Publisher ??= versionInfo.CompanyName?.Trim();
defaultLocaleManifest.PackageName ??= versionInfo.ProductName?.Trim();
defaultLocaleManifest.ShortDescription ??= versionInfo.FileDescription?.Trim();
defaultLocaleManifest.License ??= versionInfo.LegalCopyright?.Trim();
if (ParsePackageAndGenerateInstallerNodes(path, url, installerManifest.Installers, manifests, ref detectedArchOfInstallers))
{
if (!string.IsNullOrEmpty(defaultLocaleManifest.PackageVersion))
{
versionManifest.PackageVersion = installerManifest.PackageVersion = RemoveInvalidCharsFromString(defaultLocaleManifest.PackageVersion);
}
string packageIdPublisher = defaultLocaleManifest.Publisher?.Remove(" ").Trim('.') ?? $"<{nameof(defaultLocaleManifest.Publisher)}>";
string packageIdName = defaultLocaleManifest.PackageName?.Remove(" ").Trim('.') ?? $"<{nameof(defaultLocaleManifest.PackageName)}>";
versionManifest.PackageIdentifier ??= $"{RemoveInvalidCharsFromString(packageIdPublisher)}.{RemoveInvalidCharsFromString(packageIdName)}";
installerManifest.PackageIdentifier = defaultLocaleManifest.PackageIdentifier = versionManifest.PackageIdentifier;
return true;
}
else
{
return false;
}
}
/// <summary>
/// Parses a package for relevant metadata and generates a new installer node for each installer file (MSIX can have multiple installers).
/// </summary>
/// <param name="path">Path to package file.</param>
/// <param name="url">Installer url.</param>
/// <param name="newInstallers">List of new installers.</param>
/// <param name="manifests">Manifests object model.</param>
/// <param name="detectedArchOfInstallers">List of DetectedArch objects representing detected architecture of each installer.</param>
/// <returns>Boolean value indicating whether the function was successful or not.</returns>
private static bool ParsePackageAndGenerateInstallerNodes(
string path,
string url,
List<Installer> newInstallers,
Manifests manifests,
ref List<DetectedArch> detectedArchOfInstallers)
{
var installer = new Installer();
installer.InstallerUrl = url;
installer.InstallerSha256 = GetFileHash(path);
installer.Architecture = GetMachineType(path)?.ToString().ToEnumOrDefault<InstallerArchitecture>() ?? InstallerArchitecture.Neutral;
bool parseMsixResult = false;
bool parseResult = ParseExeInstallerType(path, installer, newInstallers) ||
(parseMsixResult = ParseMsix(path, installer, manifests, newInstallers)) ||
ParseMsi(path, installer, manifests, newInstallers);
if (parseMsixResult)
{
// Skip architecture override for msix installers as there can be more than one installer in a bundle
detectedArchOfInstallers.AddRange(newInstallers
.Where(i => i.InstallerUrl == url)
.Select(i => new DetectedArch(i.InstallerUrl, i.Architecture, i.Architecture)));
}
else
{
var archGuess = GetArchFromUrl(installer.InstallerUrl);
detectedArchOfInstallers.Add(new DetectedArch(installer.InstallerUrl, archGuess, installer.Architecture));
if (archGuess.HasValue)
{
installer.Architecture = archGuess.Value;
}
}
return parseResult;
}
/// <summary>
/// Performs a regex match to determine the installer architecture based on the url string.
/// </summary>
/// <param name="url">Installer url string.</param>
/// <returns>Installer architecture enum.</returns>
private static InstallerArchitecture? GetArchFromUrl(string url)
{
List<InstallerArchitecture> archMatches = new List<InstallerArchitecture>();
// Arm must only be checked if arm64 check fails, otherwise it'll match for arm64 too
if (Regex.Match(url, "arm64|aarch64", RegexOptions.IgnoreCase).Success)
{
archMatches.Add(InstallerArchitecture.Arm64);
}
else if (Regex.Match(url, @"\barm\b", RegexOptions.IgnoreCase).Success)
{
archMatches.Add(InstallerArchitecture.Arm);
}
if (Regex.Match(url, "x64|win64|_64", RegexOptions.IgnoreCase).Success)
{
archMatches.Add(InstallerArchitecture.X64);
}
if (Regex.Match(url, "x86|win32|ia32|_86", RegexOptions.IgnoreCase).Success)
{
archMatches.Add(InstallerArchitecture.X86);
}
return archMatches.Count == 1 ? archMatches.Single() : null;
}
/// <summary>
/// Computes the SHA256 hash value for the specified byte array.
/// </summary>
/// <param name="buffer">The input to compute the hash code for.</param>
/// <returns>The computed SHA256 hash string.</returns>
private static string HashBytes(byte[] buffer)
{
using var hasher = SHA256.Create();
return BitConverter.ToString(hasher.ComputeHash(buffer)).Remove("-");
}
private static string HashAppxFile(IAppxFile signatureFile)
{
var signatureBytes = StreamUtils.ReadStreamToByteArray(signatureFile.GetStream());
return HashBytes(signatureBytes);
}
private static MachineType? GetMachineType(string binary)
{
using (FileStream stream = File.OpenRead(binary))
using (BinaryReader bw = new BinaryReader(stream))
{
const ushort executableMagicNumber = 0x5a4d;
const int peMagicNumber = 0x00004550; // "PE\0\0"
stream.Seek(0, SeekOrigin.Begin);
int magicNumber = bw.ReadUInt16();
bool isExecutable = magicNumber == executableMagicNumber;
if (isExecutable)
{
stream.Seek(60, SeekOrigin.Begin);
int headerOffset = bw.ReadInt32();
stream.Seek(headerOffset, SeekOrigin.Begin);
int signature = bw.ReadInt32();
bool isPortableExecutable = signature == peMagicNumber;
if (isPortableExecutable)
{
MachineType machineType = (MachineType)bw.ReadUInt16();
return machineType;
}
}
}
return null;
}
private static bool ParseExeInstallerType(string path, Installer baseInstaller, List<Installer> newInstallers)
{
try
{
ManifestResource rc = new ManifestResource();
rc.LoadFrom(path);
string installerType = rc.Manifest.DocumentElement
.GetElementsByTagName("description")
.Cast<XmlNode>()
.FirstOrDefault()?
.InnerText?
.Split(' ').First()
.ToLowerInvariant();
if (installerType.EqualsIC("wix"))
{
// See https://github.com/microsoft/winget-create/issues/26, a Burn installer is an exe-installer produced by the WiX toolset.
baseInstaller.InstallerType = InstallerType.Burn;
}
else if (KnownInstallerResourceNames.Contains(installerType))
{
// If it's a known exe installer type, set as appropriately
baseInstaller.InstallerType = installerType.ToEnumOrDefault<InstallerType>();
}
else
{
baseInstaller.InstallerType = InstallerType.Exe;
}
newInstallers.Add(baseInstaller);
return true;
}
catch (Win32Exception)
{
// Installer doesn't have a resource header
return false;
}
}
private static bool ParseMsi(string path, Installer baseInstaller, Manifests manifests, List<Installer> newInstallers)
{
DefaultLocaleManifest defaultLocaleManifest = manifests?.DefaultLocaleManifest;
try
{
using (var database = new QDatabase(path, Deployment.WindowsInstaller.DatabaseOpenMode.ReadOnly))
{
baseInstaller.InstallerType = InstallerType.Msi;
var properties = database.Properties.ToList();
if (defaultLocaleManifest != null)
{
defaultLocaleManifest.PackageVersion ??= properties.FirstOrDefault(p => p.Property == "ProductVersion")?.Value;
defaultLocaleManifest.PackageName ??= properties.FirstOrDefault(p => p.Property == "ProductName")?.Value;
defaultLocaleManifest.Publisher ??= properties.FirstOrDefault(p => p.Property == "Manufacturer")?.Value;
}
baseInstaller.ProductCode = properties.FirstOrDefault(p => p.Property == "ProductCode")?.Value;
string archString = database.SummaryInfo.Template.Split(';').First();
archString = archString.EqualsIC("Intel") ? "x86" :
archString.EqualsIC("Intel64") ? "x64" :
archString.EqualsIC("Arm64") ? "Arm64" :
archString.EqualsIC("Arm") ? "Arm" : archString;
baseInstaller.Architecture = archString.ToEnumOrDefault<InstallerArchitecture>() ?? InstallerArchitecture.Neutral;
if (baseInstaller.InstallerLocale == null)
{
string languageString = properties.FirstOrDefault(p => p.Property == "ProductLanguage")?.Value;
if (int.TryParse(languageString, out int lcid))
{
try
{
baseInstaller.InstallerLocale = new CultureInfo(lcid).Name;
}
catch (Exception ex) when (ex is ArgumentOutOfRangeException || ex is CultureNotFoundException)
{
// If the lcid value is invalid, do nothing.
}
}
}
}
newInstallers?.Add(baseInstaller);
return true;
}
catch (Deployment.WindowsInstaller.InstallerException)
{
// Binary wasn't an MSI, skip
return false;
}
}
private static bool ParseMsix(string path, Installer baseInstaller, Manifests manifests, List<Installer> newInstallers)
{
InstallerManifest installerManifest = manifests?.InstallerManifest;
DefaultLocaleManifest defaultLocaleManifest = manifests?.DefaultLocaleManifest;
AppxMetadata metadata = GetAppxMetadataAndSetInstallerProperties(path, installerManifest, baseInstaller, newInstallers);
if (metadata == null)
{
// Binary wasn't an MSIX, skip
return false;
}
if (defaultLocaleManifest != null)
{
defaultLocaleManifest.PackageVersion ??= metadata.Version?.ToString();
defaultLocaleManifest.PackageName ??= metadata.DisplayName;
defaultLocaleManifest.Publisher ??= metadata.PublisherDisplayName;
defaultLocaleManifest.ShortDescription ??= GetApplicationProperty(metadata, "Description");
}
return true;
}
private static string GetApplicationProperty(AppxMetadata appxMetadata, string propertyName)
{
IAppxManifestApplicationsEnumerator enumerator = appxMetadata.AppxReader.GetManifest().GetApplications();
while (enumerator.GetHasCurrent())
{
IAppxManifestApplication application = enumerator.GetCurrent();
try
{
application.GetStringValue(propertyName, out string value);
return value;
}
catch (ArgumentException)
{
// Property not found on this node, continue
}
enumerator.MoveNext();
}
return null;
}
private static void SetInstallerPropertiesFromAppxMetadata(AppxMetadata appxMetadata, Installer installer, InstallerManifest installerManifest)
{
installer.Architecture = appxMetadata.Architecture.ToEnumOrDefault<InstallerArchitecture>() ?? InstallerArchitecture.Neutral;
installer.MinimumOSVersion = SetInstallerStringPropertyIfNeeded(installerManifest?.MinimumOSVersion, appxMetadata.MinOSVersion?.ToString());
installer.PackageFamilyName = SetInstallerStringPropertyIfNeeded(installerManifest?.PackageFamilyName, appxMetadata.PackageFamilyName);
// We have to fixup the Platform string first, and then remove anything that fails to parse.
var platformValues = appxMetadata.TargetDeviceFamiliesMinVersions.Keys
.Select(k => k.Replace('.', '_').ToEnumOrDefault<Platform>())
.Where(p => p != null)
.Select(p => p.Value)
.ToList();
installer.Platform = SetInstallerListPropertyIfNeeded(installerManifest?.Platform, platformValues);
}
private static string SetInstallerStringPropertyIfNeeded(string rootProperty, string valueToSet)
{
return valueToSet == rootProperty ? null : valueToSet;
}
private static List<T> SetInstallerListPropertyIfNeeded<T>(List<T> rootProperty, List<T> valueToSet)
{
return rootProperty != null && new HashSet<T>(rootProperty).SetEquals(valueToSet) ? null : valueToSet;
}
private static AppxMetadata GetAppxMetadataAndSetInstallerProperties(string path, InstallerManifest installerManifest, Installer baseInstaller, List<Installer> installers)
{
try
{
var appxMetadatas = new List<AppxMetadata>();
string signatureSha256;
try
{
// Check if package is an MsixBundle
var bundle = new AppxBundleMetadata(path);
IAppxFile signatureFile = bundle.AppxBundleReader.GetFootprintFile(APPX_BUNDLE_FOOTPRINT_FILE_TYPE.APPX_BUNDLE_FOOTPRINT_FILE_TYPE_SIGNATURE);
signatureSha256 = HashAppxFile(signatureFile);
// Only create installer nodes for non-resource packages
foreach (var childPackage in bundle.ChildAppxPackages.Where(p => p.PackageType == PackageType.Application))
{
var appxFile = bundle.AppxBundleReader.GetPayloadPackage(childPackage.RelativeFilePath);
appxMetadatas.Add(new AppxMetadata(appxFile.GetStream()));
}
}
catch (COMException)
{
// Check if package is an Msix
var appxMetadata = new AppxMetadata(path);
appxMetadatas.Add(appxMetadata);
IAppxFile signatureFile = appxMetadata.AppxReader.GetFootprintFile(APPX_FOOTPRINT_FILE_TYPE.APPX_FOOTPRINT_FILE_TYPE_SIGNATURE);
signatureSha256 = HashAppxFile(signatureFile);
}
baseInstaller.SignatureSha256 = signatureSha256;
baseInstaller.InstallerType = InstallerType.Msix;
// Add installer nodes for MSIX installers
foreach (var appxMetadata in appxMetadatas)
{
var msixInstaller = CloneInstaller(baseInstaller);
installers.Add(msixInstaller);
SetInstallerPropertiesFromAppxMetadata(appxMetadata, msixInstaller, installerManifest);
}
return appxMetadatas.First();
}
catch (COMException)
{
// Binary wasn't an MSIX
return null;
}
}
private static string RemoveInvalidCharsFromString(string value)
{
return Regex.Replace(value, InvalidCharacters, string.Empty);
}
}
}
| 45.661397 | 179 | 0.601841 | [
"MIT"
] | jedieaston/winget-create | src/WingetCreateCore/Common/PackageParser.cs | 34,661 | C# |
using System;
using Newtonsoft.Json;
using System.Xml.Serialization;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// AlipayDataDataserviceShoppingmallrecVoucherQueryModel Data Structure.
/// </summary>
[Serializable]
public class AlipayDataDataserviceShoppingmallrecVoucherQueryModel : AlipayObject
{
/// <summary>
/// 纬度;注:高德坐标系。经纬度是门店搜索和活动推荐的重要参数,录入时请确保经纬度参数准确。高德经纬度查询:http://lbs.amap.com/console/show/picker
/// </summary>
[JsonProperty("latitude")]
[XmlElement("latitude")]
public string Latitude { get; set; }
/// <summary>
/// 经度;注:高德坐标系。经纬度是门店搜索和活动推荐的重要参数,录入时请确保经纬度参数准确。高德经纬度查询:http://lbs.amap.com/console/show/picker
/// </summary>
[JsonProperty("longitude")]
[XmlElement("longitude")]
public string Longitude { get; set; }
/// <summary>
/// 系统内商场的唯一标识id
/// </summary>
[JsonProperty("mall_id")]
[XmlElement("mall_id")]
public string MallId { get; set; }
/// <summary>
/// 本次请求的全局唯一标识, 支持英文字母和数字, 由开发者自行定义
/// </summary>
[JsonProperty("request_id")]
[XmlElement("request_id")]
public string RequestId { get; set; }
/// <summary>
/// 系统内支付宝用户唯一标识id. 支付宝用户号是以2088开头的纯数字组成
/// </summary>
[JsonProperty("user_id")]
[XmlElement("user_id")]
public string UserId { get; set; }
}
}
| 30.204082 | 103 | 0.601351 | [
"MIT"
] | Aosir/Payment | src/Essensoft.AspNetCore.Payment.Alipay/Domain/AlipayDataDataserviceShoppingmallrecVoucherQueryModel.cs | 1,820 | C# |
// SPDX-License-Identifier: Apache-2.0
// Licensed to the Ed-Fi Alliance under one or more agreements.
// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0.
// See the LICENSE and NOTICES files in the project root for more information.
using System;
namespace EdFi.Ods.WebApi.CompositeSpecFlowTests.Dtos
{
public class StudentAssessmentKeyInformation
{
public Guid Id { get; set; }
public string StudentAssessmentIdentifier { get; set; }
public string AssessmentIdentifier { get; set; }
public string Namespace { get; set; }
public string StudentUniqueId { get; set; }
}
}
| 28.869565 | 86 | 0.704819 | [
"Apache-2.0"
] | AxelMarquez/Ed-Fi-ODS | tests/EdFi.Ods.WebApi.CompositeSpecFlowTests/Dtos/StudentAssessmentKeyInformation.cs | 664 | C# |
namespace Presentacion.Core.Cliente
{
partial class _00003_Clientes
{
/// <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.btnCtaCte = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.error)).BeginInit();
this.SuspendLayout();
//
// btnCtaCte
//
this.btnCtaCte.BackColor = System.Drawing.Color.SteelBlue;
this.btnCtaCte.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
this.btnCtaCte.ForeColor = System.Drawing.Color.White;
this.btnCtaCte.ImageAlign = System.Drawing.ContentAlignment.BottomCenter;
this.btnCtaCte.Location = new System.Drawing.Point(273, 2);
this.btnCtaCte.Name = "btnCtaCte";
this.btnCtaCte.Size = new System.Drawing.Size(65, 52);
this.btnCtaCte.TabIndex = 10;
this.btnCtaCte.Text = "Cuentas Corrientes";
this.btnCtaCte.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this.btnCtaCte.UseVisualStyleBackColor = false;
this.btnCtaCte.Click += new System.EventHandler(this.btnCtaCte_Click);
//
// _00003_Clientes
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(780, 557);
this.Controls.Add(this.btnCtaCte);
this.Name = "_00003_Clientes";
this.Text = "Clientes";
this.Controls.SetChildIndex(this.btnCtaCte, 0);
((System.ComponentModel.ISupportInitialize)(this.error)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnCtaCte;
}
} | 39.608696 | 107 | 0.597512 | [
"MIT"
] | RamonChauqui/SubeCodigo | Presentacion.Core/02-Cliente/_00003_Clientes.Designer.cs | 2,735 | C# |
using System;
namespace Veldrid.MetalBindings
{
public struct MTLDepthStencilState
{
public readonly IntPtr NativePtr;
}
} | 15.888889 | 41 | 0.706294 | [
"MIT"
] | BSG-75/veldrid | src/Veldrid.MetalBindings/MTLDepthStencilState.cs | 143 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/d3d10misc.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop
{
public enum D3D10_DRIVER_TYPE
{
D3D10_DRIVER_TYPE_HARDWARE = 0,
D3D10_DRIVER_TYPE_REFERENCE = 1,
D3D10_DRIVER_TYPE_NULL = 2,
D3D10_DRIVER_TYPE_SOFTWARE = 3,
D3D10_DRIVER_TYPE_WARP = 5,
}
}
| 32.764706 | 145 | 0.718133 | [
"MIT"
] | Perksey/terrafx.interop.windows | sources/Interop/Windows/um/d3d10misc/D3D10_DRIVER_TYPE.cs | 559 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _04.Exam_Shopping
{
class Program
{
static void Main(string[] args)
{
var input = Console.ReadLine();
var shop = new Dictionary<string, int>();
while (input != "shopping time")
{
var itemQuantity = input.Split(' ');
if (shop.ContainsKey(itemQuantity[1]))
shop[itemQuantity[1]] += int.Parse(itemQuantity[2]);
else
shop.Add(itemQuantity[1], int.Parse(itemQuantity[2]));
input = Console.ReadLine();
}
input = Console.ReadLine();
while (input != "exam time")
{
var itemQuantity = input.Split(' ');
if (shop.ContainsKey(itemQuantity[1]))
{
if (shop[itemQuantity[1]] > 0)
shop[itemQuantity[1]] -= int.Parse(itemQuantity[2]);
else
Console.WriteLine($"{itemQuantity[1]} out of stock");
}
else if (!shop.ContainsKey(itemQuantity[1]))
{
Console.WriteLine($"{itemQuantity[1]} doesn't exist");
}
input = Console.ReadLine();
}
foreach (var kv in shop)
{
if (kv.Value > 0)
Console.WriteLine($"{kv.Key} -> {kv.Value}");
}
}
}
}
| 30.769231 | 77 | 0.4575 | [
"MIT"
] | spiderbait90/Step-By-Step-In-C-Sharp | Programming Fundamentals/Dictionaries/04. Exam Shopping/Program.cs | 1,602 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UT.CoreV20;
namespace UT.WechatV22
{
public class WechatHelper : ISendable
{
public void Send(string message)
{
Console.WriteLine("Frome wechat: " + message);
}
}
}
| 18.058824 | 58 | 0.641694 | [
"Apache-2.0"
] | densen2014/RookieProject | IOCDemo/UT.WechatV22/WechatHelper.cs | 309 | 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 Version = Lucene.Net.Util.Version;
namespace Lucene.Net.Analysis
{
/// <summary> Filters <see cref="LetterTokenizer" /> with <see cref="LowerCaseFilter" /> and
/// <see cref="StopFilter" />.
///
/// <a name="version"/>
/// <p/>
/// You must specify the required <see cref="Version" /> compatibility when creating
/// StopAnalyzer:
/// <list type="bullet">
/// <item>As of 2.9, position increments are preserved</item>
/// </list>
/// </summary>
public sealed class StopAnalyzer:Analyzer
{
private ISet<string> stopWords;
private bool enablePositionIncrements;
/// <summary>An unmodifiable set containing some common English words that are not usually useful
/// for searching.
/// </summary>
public static ISet<string> ENGLISH_STOP_WORDS_SET;
/// <summary> Builds an analyzer which removes words in ENGLISH_STOP_WORDS.</summary>
public StopAnalyzer(Version matchVersion)
{
stopWords = ENGLISH_STOP_WORDS_SET;
enablePositionIncrements = StopFilter.GetEnablePositionIncrementsVersionDefault(matchVersion);
}
/// <summary>Builds an analyzer with the stop words from the given set.</summary>
public StopAnalyzer(Version matchVersion, ISet<string> stopWords)
{
this.stopWords = stopWords;
enablePositionIncrements = StopFilter.GetEnablePositionIncrementsVersionDefault(matchVersion);
}
/// <summary> Builds an analyzer with the stop words from the given file.
///
/// </summary>
/// <seealso cref="WordlistLoader.GetWordSet(System.IO.FileInfo)">
/// </seealso>
/// <param name="matchVersion">See <a href="#version">above</a>
/// </param>
/// <param name="stopwordsFile">File to load stop words from
/// </param>
public StopAnalyzer(Version matchVersion, System.IO.FileInfo stopwordsFile)
{
stopWords = WordlistLoader.GetWordSet(stopwordsFile);
this.enablePositionIncrements = StopFilter.GetEnablePositionIncrementsVersionDefault(matchVersion);
}
/// <summary>Builds an analyzer with the stop words from the given reader. </summary>
/// <seealso cref="WordlistLoader.GetWordSet(System.IO.TextReader)">
/// </seealso>
/// <param name="matchVersion">See <a href="#Version">above</a>
/// </param>
/// <param name="stopwords">Reader to load stop words from
/// </param>
public StopAnalyzer(Version matchVersion, System.IO.TextReader stopwords)
{
stopWords = WordlistLoader.GetWordSet(stopwords);
this.enablePositionIncrements = StopFilter.GetEnablePositionIncrementsVersionDefault(matchVersion);
}
/// <summary>Filters LowerCaseTokenizer with StopFilter. </summary>
public override TokenStream TokenStream(System.String fieldName, System.IO.TextReader reader)
{
return new StopFilter(enablePositionIncrements, new LowerCaseTokenizer(reader), stopWords);
}
/// <summary>Filters LowerCaseTokenizer with StopFilter. </summary>
private class SavedStreams
{
public SavedStreams(StopAnalyzer enclosingInstance)
{
InitBlock(enclosingInstance);
}
private void InitBlock(StopAnalyzer enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private StopAnalyzer enclosingInstance;
public StopAnalyzer Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
internal Tokenizer source;
internal TokenStream result;
}
public override TokenStream ReusableTokenStream(System.String fieldName, System.IO.TextReader reader)
{
SavedStreams streams = (SavedStreams) PreviousTokenStream;
if (streams == null)
{
streams = new SavedStreams(this);
streams.source = new LowerCaseTokenizer(reader);
streams.result = new StopFilter(enablePositionIncrements, streams.source, stopWords);
PreviousTokenStream = streams;
}
else
streams.source.Reset(reader);
return streams.result;
}
static StopAnalyzer()
{
{
System.String[] stopWords = new System.String[]{"a", "an", "and", "are", "as", "at", "be", "but", "by", "for", "if", "in", "into", "is", "it", "no", "not", "of", "on", "or", "such", "that", "the", "their", "then", "there", "these", "they", "this", "to", "was", "will", "with"};
CharArraySet stopSet = new CharArraySet(stopWords.Length, false);
stopSet.AddAll(stopWords);
ENGLISH_STOP_WORDS_SET = CharArraySet.UnmodifiableSet(stopSet);
}
}
}
} | 36.783217 | 281 | 0.705513 | [
"Apache-2.0"
] | dineshkummarc/lucene.net | src/core/Analysis/StopAnalyzer.cs | 5,260 | C# |
using System;
using System.Threading.Tasks;
namespace FluentStateMachine
{
public class FsmConfig<TState, TEvent>
{
internal FsmBuilder<TState, TEvent> Root;
public FsmStateConfig<TState, TEvent> State(TState state)
=> Root.State(state);
public IStateMachine<TState, TEvent> Build()
=> Root.Build();
}
public class FsmStateConfig<TState, TEvent> : FsmConfig<TState, TEvent>
{
internal FsmStateModel<TState, TEvent> Model;
public FsmEventConfig<TState, TEvent> On(TEvent e)
{
var eventModel = new FsmEventModel<TState, TEvent>();
if (Model.Events.ContainsKey(e))
Model.Events[e] = eventModel;
else
Model.Events.Add(e, eventModel);
return new FsmEventConfig<TState, TEvent>
{
Model = eventModel,
Root = Root,
Parent = this,
};
}
public FsmStateConfig<TState, TEvent> OnEnter(Func<FsmEnterArgs<TState, TEvent>, Task> action)
{
Model.OnEnter = action;
return this;
}
public FsmStateConfig<TState, TEvent> OnExit(Func<FsmExitArgs<TState, TEvent>, Task> action)
{
Model.OnExit = action;
return this;
}
public FsmStateConfig<TState, TEvent> Enable(Func<FsmEnterArgs<TState, TEvent>, Task<bool>> fn)
{
Model.Enable = fn;
return this;
}
}
public class FsmEventConfig<TState, TEvent> : FsmConfig<TState, TEvent>
{
internal FsmEventModel<TState, TEvent> Model;
internal FsmStateConfig<TState, TEvent> Parent;
public FsmEventConfig<TState, TEvent> On(TEvent e) => Parent?.On(e) ?? Root.On(e);
public FsmEventConfig<TState, TEvent> Execute(Func<FsmTriggerArgs<TState, TEvent>, Task<object>> fn)
{
Model.Execute = fn;
return this;
}
public FsmEventConfig<TState, TEvent> Enable(Func<FsmTriggerArgs<TState, TEvent>, Task<bool>> fn)
{
Model.Enable = fn;
return this;
}
public FsmEventConfig<TState, TEvent> JumpTo(Func<FsmTriggerArgs<TState, TEvent>, Task<TState>> fn)
{
Model.JumpTo = fn;
return this;
}
}
}
| 28.452381 | 108 | 0.571548 | [
"MIT"
] | mustaddon/StateMachine | FluentStateMachine/FsmConfig.cs | 2,392 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace RelhaxModpack
{
public partial class AddPicturesZip : RelhaxForum
{
private string[] AcceptableImageExtensions = new string[] { "*.bmp;", "*.jpg;", "*.jpeg;", "*.png;", "*.gif;" };
private string[] AcceptableSelectionExtensions = new string[] { "*.xml;" };
public string AppStartupPath { get; set; }
public AddPicturesZip()
{
InitializeComponent();
}
private void AddSelectons_Click(object sender, EventArgs e)
{
SelectionPictureDialog.DefaultExt = ".xml";
SelectionPictureDialog.Filter = @" *.xml|*.xml";
SelectionPictureDialog.InitialDirectory = Path.Combine(AppStartupPath, "RelHaxUserConfigs");
SelectionPictureDialog.Title = "Select selection file(s) to include";
if (SelectionPictureDialog.ShowDialog() == DialogResult.Cancel)
return;
foreach (string s in SelectionPictureDialog.FileNames)
listBox1.Items.Add(s);
}
private void AddPictures_Click(object sender, EventArgs e)
{
SelectionPictureDialog.DefaultExt = "";
string allPictureTypes = @" Picture files|";
foreach(string s in AcceptableImageExtensions)
{
allPictureTypes = allPictureTypes + s.ToLower();
allPictureTypes = allPictureTypes + s.ToUpper();
}
SelectionPictureDialog.Filter = allPictureTypes;
SelectionPictureDialog.InitialDirectory = Path.Combine(AppStartupPath, "RelHaxUserConfigs");
SelectionPictureDialog.Title = "Select Picture(s) to include";
if (SelectionPictureDialog.ShowDialog() == DialogResult.Cancel)
return;
foreach (string s in SelectionPictureDialog.FileNames)
listBox1.Items.Add(s);
}
private void RemoveElements_Click(object sender, EventArgs e)
{
for(int i = 0; i < listBox1.SelectedItems.Count; i++)
{
listBox1.Items.Remove(listBox1.SelectedItems[i]);
i--;
}
}
private void Continue_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
}
//https://stackoverflow.com/questions/21706747/drag-and-drop-files-into-my-listbox
private void listBox1_DragDrop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string file in files)
{
string extension = Path.GetExtension(file);
if(IsAcceptableExtantion(extension) && !(listBox1.Items.Contains(file)))
listBox1.Items.Add(file);
}
}
private void listBox1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
}
private bool IsAcceptableExtantion(string extension)
{
extension = extension.ToLower();
foreach (string s in AcceptableSelectionExtensions)
{
string ext = s.Substring(1, s.Length - 2);
if (ext.ToLower().Equals(extension))
return true;
}
foreach (string s in AcceptableImageExtensions)
{
//"*.bmp;"
string ext = s.Substring(1, s.Length - 2);
if (ext.ToLower().Equals(extension))
return true;
}
return false;
}
}
}
| 36.327103 | 120 | 0.580911 | [
"Apache-2.0"
] | Arkhorse/RelhaxModpack | RelhaxLegacy/RelicModManager/Forms/AddPicturesZip.cs | 3,889 | C# |
using Demo.Domain.MessageOutbox;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Demo.Infrastructure.Persistence.Configuration
{
public class MessageOutboxEntityTypeConfiguration : IEntityTypeConfiguration<MessageOutbox>
{
public void Configure(EntityTypeBuilder<MessageOutbox> builder)
{
builder.ToTable(nameof(MessageOutbox))
.HasKey(x => x.Id);
builder.HasIndex(x => x.IsSent);
builder.HasIndex(x => x.LockedUntil);
builder.Property(x => x.Type)
.IsRequired();
builder.Property(x => x.Message);
builder.Property(x => x.LockedUntil);
builder.Property(x => x.LockToken)
.IsConcurrencyToken();
builder.Property(x => x.IsSent)
.HasDefaultValue(false);
builder.Property(x => x.Timestamp)
.IsRowVersion();
}
}
}
| 33.033333 | 95 | 0.608476 | [
"MIT"
] | nvdvlies/aspnet-core-api-demo | src/Demo.Infrastructure/Persistence/Configuration/MessageOutboxEntityTypeConfiguration.cs | 993 | C# |
// Copyright (c) .NET Foundation and Gerard Gunnewijk. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
//
// Changes:
// - Changed namespace to seperate this project from the original https://github.com/aspnet/Proxy
// - Added logging
// - Added support for multiple servers and upstream servers
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace Synercoding.ReverseProxy
{
public class ProxyMiddleware
{
private const int DefaultWebSocketBufferSize = 4096;
private readonly RequestDelegate _next;
private readonly ProxyOptions _options;
private readonly ILogger _logger;
private static readonly string[] NotForwardedWebSocketHeaders = new[] { "Connection", "Host", "Upgrade", "Sec-WebSocket-Key", "Sec-WebSocket-Version" };
public ProxyMiddleware(RequestDelegate next, IOptions<ProxyOptions> options, ILogger<ProxyMiddleware> logger)
{
if (next == null)
{
throw new ArgumentNullException(nameof(next));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (options.Value.Servers.Any(s => s.Host == null))
{
throw new ArgumentException("Options servers must all specify hosts.", nameof(options));
}
if (options.Value.Servers.Any(s => !s.UpstreamServers.Any()))
{
throw new ArgumentException("Options server must have atleast one upstream server.", nameof(options));
}
if (options.Value.Servers.Any(s => s.UpstreamServers.Any(u => u.Scheme == null)))
{
throw new ArgumentException("Options server upstream servers must all specify schemes.", nameof(options));
}
if (options.Value.Servers.Any(s => s.UpstreamServers.Any(u => u.Host == null)))
{
throw new ArgumentException("Options server upstream servers must all specify hosts.", nameof(options));
}
if(logger == null)
{
throw new ArgumentNullException(nameof(logger));
}
_next = next;
_options = options.Value;
_logger = logger;
}
public Task Invoke(HttpContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var server = _options.Servers.FirstOrDefault(s => context.Request.Host.Host == s.Host && (s.Port.HasValue ? context.Request.Host.Port == s.Port : true));
if (server == null)
{
_logger.LogDebug($"No server found with host {context.Request.Host.Host} and port {context.Request.Host.Port}");
return _next(context);
}
_logger.LogDebug($"Found server: {server.Host}{(server.Port.HasValue ? (":" + server.Port) : "")} with {server.UpstreamServers.Count()} upstream servers.");
var selectedServer = RandomGen.Next(server.UpstreamServers.Length);
var upstreamServer = server.UpstreamServers.ElementAt(selectedServer);
_logger.LogDebug($"Selected upstream server: {selectedServer}");
var builder = new UriBuilder(context.Request.GetEncodedUrl());
builder.Scheme = upstreamServer.Scheme;
builder.Host = upstreamServer.Host;
builder.Port = upstreamServer.Port ?? (upstreamServer.Scheme.Contains("https") ? 443 : 80);
_logger.LogDebug($"Forwarded request to {builder.Uri.ToString()}");
return context.ProxyRequest(builder.Uri);
}
}
}
| 41.6875 | 168 | 0.61944 | [
"Apache-2.0"
] | synercoder/Synercoding.ReverseProxy | Synercoding.ReverseProxy/ProxyMiddleware.cs | 4,004 | 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 WindowHiding.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class 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 ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WindowHiding.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;
}
}
}
}
| 33.791667 | 163 | 0.689684 | [
"MIT"
] | 21pages/WPF-Samples | Windows/WindowHiding/Properties/Resources.Designer.cs | 2,435 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pathfinding : MonoBehaviour {
AstarGrid GridReference;//For referencing the grid class
// public Transform StartPosition;//Starting position to pathfind from
// public Transform TargetPosition;//Starting position to pathfind to
[HideInInspector]
public Vector3 StartPosition;//Starting position to pathfind from
[HideInInspector]
public Vector3 TargetPosition;//Starting position to pathfind to
private void Awake()//When the program starts
{
GridReference = GetComponent<AstarGrid>();//Get a reference to the game manager
}
private void Update()//Every frame
{
//Debug.Log("Start Position" + StartPosition);
//Debug.Log("Target Position" + TargetPosition);
FindPath(StartPosition, TargetPosition);//Find a path to the goal
}
public void FindPath(Vector3 a_StartPos, Vector3 a_TargetPos)
{
Node StartNode = GridReference.NodeFromWorldPoint(a_StartPos);//Gets the node closest to the starting position
Node TargetNode = GridReference.NodeFromWorldPoint(a_TargetPos);//Gets the node closest to the target position
List<Node> OpenList = new List<Node>();//List of nodes for the open list
HashSet<Node> ClosedList = new HashSet<Node>();//Hashset of nodes for the closed list
OpenList.Add(StartNode);//Add the starting node to the open list to begin the program
while(OpenList.Count > 0)//Whilst there is something in the open list
{
Node CurrentNode = OpenList[0];//Create a node and set it to the first item in the open list
for(int i = 1; i < OpenList.Count; i++)//Loop through the open list starting from the second object
{
if (OpenList[i].FCost < CurrentNode.FCost || OpenList[i].FCost == CurrentNode.FCost && OpenList[i].ihCost < CurrentNode.ihCost)//If the f cost of that object is less than or equal to the f cost of the current node
{
CurrentNode = OpenList[i];//Set the current node to that object
}
}
OpenList.Remove(CurrentNode);//Remove that from the open list
ClosedList.Add(CurrentNode);//And add it to the closed list
if (CurrentNode == TargetNode)//If the current node is the same as the target node
{
GetFinalPath(StartNode, TargetNode);//Calculate the final path
}
foreach (Node NeighborNode in GridReference.GetNeighboringNodes(CurrentNode))//Loop through each neighbor of the current node
{
if (!NeighborNode.bIsWall || ClosedList.Contains(NeighborNode))//If the neighbor is a wall or has already been checked
{
continue;//Skip it
}
int MoveCost = CurrentNode.igCost + GetManhattenDistance(CurrentNode, NeighborNode);//Get the F cost of that neighbor
if (MoveCost < NeighborNode.igCost || !OpenList.Contains(NeighborNode))//If the f cost is greater than the g cost or it is not in the open list
{
NeighborNode.igCost = MoveCost;//Set the g cost to the f cost
NeighborNode.ihCost = GetManhattenDistance(NeighborNode, TargetNode);//Set the h cost
NeighborNode.ParentNode = CurrentNode;//Set the parent of the node for retracing steps
if(!OpenList.Contains(NeighborNode))//If the neighbor is not in the openlist
{
OpenList.Add(NeighborNode);//Add it to the list
}
}
}
}
}
void GetFinalPath(Node a_StartingNode, Node a_EndNode)
{
List<Node> FinalPath = new List<Node>();//List to hold the path sequentially
Node CurrentNode = a_EndNode;//Node to store the current node being checked
while(CurrentNode != a_StartingNode)//While loop to work through each node going through the parents to the beginning of the path
{
FinalPath.Add(CurrentNode);//Add that node to the final path
CurrentNode = CurrentNode.ParentNode;//Move onto its parent node
}
FinalPath.Reverse();//Reverse the path to get the correct order
GridReference.FinalPath = FinalPath;//Set the final path
}
int GetManhattenDistance(Node a_nodeA, Node a_nodeB)
{
int ix = Mathf.Abs(a_nodeA.iGridX - a_nodeB.iGridX);//x1-x2
int iy = Mathf.Abs(a_nodeA.iGridY - a_nodeB.iGridY);//y1-y2
return ix + iy;//Return the sum
}
}
| 45.311321 | 230 | 0.62919 | [
"MIT"
] | rgferrari/Bomberman-3D | Bomberman-3D/Assets/Scripts/Astar/Pathfinding.cs | 4,805 | C# |
using Android.App;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
namespace EuroVisionQuiz.Droid
{
[Activity(Label = "EuroQuizion", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Xamarin.Forms.Forms.SetFlags("Expander_Experimental");
Android.Gms.Ads.MobileAds.Initialize(ApplicationContext, "ca-app-pub-7647345657299803~1251499855");
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
} | 41.176471 | 186 | 0.712143 | [
"MIT"
] | Ownie/EuroVisionQuiz | EuroVisionQuiz.Android/MainActivity.cs | 1,402 | C# |
using Newtonsoft.Json;
namespace WiseOldManConnector.Models.API.Responses;
internal class SnapshotsResponse : BaseResponse {
[JsonProperty("day")]
public List<WOMSnapshot> Day { get; set; }
[JsonProperty("week")]
public List<WOMSnapshot> Week { get; set; }
[JsonProperty("month")]
public List<WOMSnapshot> Month { get; set; }
[JsonProperty("year")]
public List<WOMSnapshot> Year { get; set; }
}
| 24.055556 | 51 | 0.681293 | [
"MIT"
] | MathieuDR/orsr-discord-automator | WiseOldManConnector/Models/API/Responses/SnapshotsResponse.cs | 435 | C# |
/***********************************************************************
* Project: CoreCms
* ProjectName: 核心内容管理系统
* Web: https://www.corecms.net
* Author: 大灰灰
* Email: [email protected]
* CreateTime: 2021/1/31 21:45:10
* Description: 暂无
***********************************************************************/
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using CoreCms.Net.Configuration;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.Model.Entities.Expression;
using CoreCms.Net.Model.FromBody;
using CoreCms.Net.Model.ViewModels.UI;
using CoreCms.Net.Filter;
using CoreCms.Net.Loging;
using CoreCms.Net.IServices;
using CoreCms.Net.Utility.Helper;
using CoreCms.Net.Utility.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using NPOI.HSSF.UserModel;
using SqlSugar;
namespace CoreCms.Net.Web.Admin.Controllers
{
/// <summary>
/// 操作日志表
///</summary>
[Description("操作日志表")]
[Route("api/[controller]/[action]")]
[ApiController]
[RequiredErrorForAdmin]
[Authorize]
public class SysOperRecordController : Controller
{
private readonly IWebHostEnvironment _webHostEnvironment;
private readonly ISysOperRecordServices _SysOperRecordServices;
/// <summary>
/// 构造函数
///</summary>
public SysOperRecordController(IWebHostEnvironment webHostEnvironment
,ISysOperRecordServices SysOperRecordServices
)
{
_webHostEnvironment = webHostEnvironment;
_SysOperRecordServices = SysOperRecordServices;
}
#region 获取列表============================================================
// POST: Api/SysOperRecord/GetPageList
/// <summary>
/// 获取列表
/// </summary>
/// <returns></returns>
[HttpPost]
[Description("获取列表")]
public async Task<JsonResult> GetPageList()
{
var jm = new AdminUiCallBack();
var pageCurrent = Request.Form["page"].FirstOrDefault().ObjectToInt(1);
var pageSize = Request.Form["limit"].FirstOrDefault().ObjectToInt(30);
var where = PredicateBuilder.True<SysOperRecord>();
//获取排序字段
var orderField = Request.Form["orderField"].FirstOrDefault();
Expression<Func<SysOperRecord, object>> orderEx = orderField switch
{
"id" => p => p.id,"userId" => p => p.userId,"userName" => p => p.userName,"model" => p => p.model,"description" => p => p.description,"url" => p => p.url,"requestMethod" => p => p.requestMethod,"operMethod" => p => p.operMethod,"param" => p => p.param,"result" => p => p.result,"ip" => p => p.ip,"spendTime" => p => p.spendTime,"state" => p => p.state,"createTime" => p => p.createTime,
_ => p => p.id
};
//设置排序方式
var orderDirection = Request.Form["orderDirection"].FirstOrDefault();
var orderBy = orderDirection switch
{
"asc" => OrderByType.Asc,
"desc" => OrderByType.Desc,
_ => OrderByType.Desc
};
//查询筛选
//主键 int
var id = Request.Form["id"].FirstOrDefault().ObjectToInt(0);
if (id > 0)
{
where = where.And(p => p.id == id);
}
//用户id int
var userId = Request.Form["userId"].FirstOrDefault().ObjectToInt(0);
if (userId > 0)
{
where = where.And(p => p.userId == userId);
}
//用户名 nvarchar
var userName = Request.Form["userName"].FirstOrDefault();
if (!string.IsNullOrEmpty(userName))
{
where = where.And(p => p.userName.Contains(userName));
}
//操作模块 nvarchar
var model = Request.Form["model"].FirstOrDefault();
if (!string.IsNullOrEmpty(model))
{
where = where.And(p => p.model.Contains(model));
}
//操作方法 nvarchar
var description = Request.Form["description"].FirstOrDefault();
if (!string.IsNullOrEmpty(description))
{
where = where.And(p => p.description.Contains(description));
}
//请求地址 nvarchar
var url = Request.Form["url"].FirstOrDefault();
if (!string.IsNullOrEmpty(url))
{
where = where.And(p => p.url.Contains(url));
}
//请求方式 nvarchar
var requestMethod = Request.Form["requestMethod"].FirstOrDefault();
if (!string.IsNullOrEmpty(requestMethod))
{
where = where.And(p => p.requestMethod.Contains(requestMethod));
}
//调用方法 nvarchar
var operMethod = Request.Form["operMethod"].FirstOrDefault();
if (!string.IsNullOrEmpty(operMethod))
{
where = where.And(p => p.operMethod.Contains(operMethod));
}
//请求参数 nvarchar
var param = Request.Form["param"].FirstOrDefault();
if (!string.IsNullOrEmpty(param))
{
where = where.And(p => p.param.Contains(param));
}
//返回结果 nvarchar
var result = Request.Form["result"].FirstOrDefault();
if (!string.IsNullOrEmpty(result))
{
where = where.And(p => p.result.Contains(result));
}
//ip地址 nvarchar
var ip = Request.Form["ip"].FirstOrDefault();
if (!string.IsNullOrEmpty(ip))
{
where = where.And(p => p.ip.Contains(ip));
}
//请求耗时,单位毫秒 nvarchar
var spendTime = Request.Form["spendTime"].FirstOrDefault();
if (!string.IsNullOrEmpty(spendTime))
{
where = where.And(p => p.spendTime.Contains(spendTime));
}
//状态,0成功,1异常 int
var state = Request.Form["state"].FirstOrDefault().ObjectToInt(0);
if (state > 0)
{
where = where.And(p => p.state == state);
}
//登录时间 datetime
var createTime = Request.Form["createTime"].FirstOrDefault();
if (!string.IsNullOrEmpty(createTime))
{
if (createTime.Contains("到"))
{
var dts = createTime.Split("到");
var dtStart = dts[0].Trim().ObjectToDate();
where = where.And(p => p.createTime > dtStart);
var dtEnd = dts[1].Trim().ObjectToDate();
where = where.And(p => p.createTime < dtEnd);
}
else
{
var dt = createTime.ObjectToDate();
where = where.And(p => p.createTime > dt);
}
}
//获取数据
var list = await _SysOperRecordServices.QueryPageAsync(where, orderEx, orderBy, pageCurrent, pageSize, true);
//返回数据
jm.data = list;
jm.code = 0;
jm.count = list.TotalCount;
jm.msg = "数据调用成功!";
return Json(jm);
}
#endregion
#region 首页数据============================================================
// POST: Api/SysOperRecord/GetIndex
/// <summary>
/// 首页数据
/// </summary>
/// <returns></returns>
[HttpPost]
[Description("首页数据")]
public JsonResult GetIndex()
{
//返回数据
var jm = new AdminUiCallBack { code = 0 };
return Json(jm);
}
#endregion
#region 创建数据============================================================
// POST: Api/SysOperRecord/GetCreate
/// <summary>
/// 创建数据
/// </summary>
/// <returns></returns>
[HttpPost]
[Description("创建数据")]
public JsonResult GetCreate()
{
//返回数据
var jm = new AdminUiCallBack { code = 0 };
return Json(jm);
}
#endregion
#region 创建提交============================================================
// POST: Api/SysOperRecord/DoCreate
/// <summary>
/// 创建提交
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
[HttpPost]
[Description("创建提交")]
public async Task<JsonResult> DoCreate([FromBody]SysOperRecord entity)
{
var jm = await _SysOperRecordServices.InsertAsync(entity);
return Json(jm);
}
#endregion
#region 编辑数据============================================================
// POST: Api/SysOperRecord/GetEdit
/// <summary>
/// 编辑数据
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
[HttpPost]
[Description("编辑数据")]
public async Task<JsonResult> GetEdit([FromBody]FMIntId entity)
{
var jm = new AdminUiCallBack();
var model = await _SysOperRecordServices.QueryByIdAsync(entity.id, false);
if (model == null)
{
jm.msg = "不存在此信息";
return Json(jm);
}
jm.code = 0;
jm.data = model;
return Json(jm);
}
#endregion
#region 编辑提交============================================================
// POST: Api/SysOperRecord/Edit
/// <summary>
/// 编辑提交
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
[HttpPost]
[Description("编辑提交")]
public async Task<JsonResult> DoEdit([FromBody]SysOperRecord entity)
{
var jm = await _SysOperRecordServices.UpdateAsync(entity);
return Json(jm);
}
#endregion
#region 批量删除============================================================
// POST: Api/SysOperRecord/DoBatchDelete/10,11,20
/// <summary>
/// 批量删除
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
[HttpPost]
[Description("批量删除")]
public async Task<JsonResult> DoBatchDelete([FromBody]FMArrayIntIds entity)
{
var jm = await _SysOperRecordServices.DeleteByIdsAsync(entity.id);
return Json(jm);
}
#endregion
#region 预览数据============================================================
// POST: Api/SysOperRecord/GetDetails/10
/// <summary>
/// 预览数据
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
[HttpPost]
[Description("预览数据")]
public async Task<JsonResult> GetDetails([FromBody]FMIntId entity)
{
var jm = new AdminUiCallBack();
var model = await _SysOperRecordServices.QueryByIdAsync(entity.id, false);
if (model == null)
{
jm.msg = "不存在此信息";
return Json(jm);
}
jm.code = 0;
jm.data = model;
return Json(jm);
}
#endregion
#region 选择导出============================================================
// POST: Api/SysOperRecord/SelectExportExcel/10
/// <summary>
/// 选择导出
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
[HttpPost]
[Description("选择导出")]
public async Task<JsonResult> SelectExportExcel([FromBody]FMArrayIntIds entity)
{
var jm = new AdminUiCallBack();
//创建Excel文件的对象
var book = new HSSFWorkbook();
//添加一个sheet
var mySheet = book.CreateSheet("Sheet1");
//获取list数据
var listModel = await _SysOperRecordServices.QueryListByClauseAsync(p => entity.id.Contains(p.id), p => p.id, OrderByType.Asc, true);
//给sheet1添加第一行的头部标题
var headerRow = mySheet.CreateRow(0);
var headerStyle = ExcelHelper.GetHeaderStyle(book);
var cell0 = headerRow.CreateCell(0);
cell0.SetCellValue("主键");
cell0.CellStyle = headerStyle;
mySheet.SetColumnWidth(0, 10 * 256);
var cell1 = headerRow.CreateCell(1);
cell1.SetCellValue("用户id");
cell1.CellStyle = headerStyle;
mySheet.SetColumnWidth(1, 10 * 256);
var cell2 = headerRow.CreateCell(2);
cell2.SetCellValue("用户名");
cell2.CellStyle = headerStyle;
mySheet.SetColumnWidth(2, 10 * 256);
var cell3 = headerRow.CreateCell(3);
cell3.SetCellValue("操作模块");
cell3.CellStyle = headerStyle;
mySheet.SetColumnWidth(3, 10 * 256);
var cell4 = headerRow.CreateCell(4);
cell4.SetCellValue("操作方法");
cell4.CellStyle = headerStyle;
mySheet.SetColumnWidth(4, 10 * 256);
var cell5 = headerRow.CreateCell(5);
cell5.SetCellValue("请求地址");
cell5.CellStyle = headerStyle;
mySheet.SetColumnWidth(5, 10 * 256);
var cell6 = headerRow.CreateCell(6);
cell6.SetCellValue("请求方式");
cell6.CellStyle = headerStyle;
mySheet.SetColumnWidth(6, 10 * 256);
var cell7 = headerRow.CreateCell(7);
cell7.SetCellValue("调用方法");
cell7.CellStyle = headerStyle;
mySheet.SetColumnWidth(7, 10 * 256);
var cell8 = headerRow.CreateCell(8);
cell8.SetCellValue("请求参数");
cell8.CellStyle = headerStyle;
mySheet.SetColumnWidth(8, 10 * 256);
var cell9 = headerRow.CreateCell(9);
cell9.SetCellValue("返回结果");
cell9.CellStyle = headerStyle;
mySheet.SetColumnWidth(9, 10 * 256);
var cell10 = headerRow.CreateCell(10);
cell10.SetCellValue("ip地址");
cell10.CellStyle = headerStyle;
mySheet.SetColumnWidth(10, 10 * 256);
var cell11 = headerRow.CreateCell(11);
cell11.SetCellValue("请求耗时,单位毫秒");
cell11.CellStyle = headerStyle;
mySheet.SetColumnWidth(11, 10 * 256);
var cell12 = headerRow.CreateCell(12);
cell12.SetCellValue("状态,0成功,1异常");
cell12.CellStyle = headerStyle;
mySheet.SetColumnWidth(12, 10 * 256);
var cell13 = headerRow.CreateCell(13);
cell13.SetCellValue("登录时间");
cell13.CellStyle = headerStyle;
mySheet.SetColumnWidth(13, 10 * 256);
headerRow.Height = 30 * 20;
var commonCellStyle = ExcelHelper.GetCommonStyle(book);
//将数据逐步写入sheet1各个行
for (var i = 0; i < listModel.Count; i++)
{
var rowTemp = mySheet.CreateRow(i + 1);
var rowTemp0 = rowTemp.CreateCell(0);
rowTemp0.SetCellValue(listModel[i].id.ToString());
rowTemp0.CellStyle = commonCellStyle;
var rowTemp1 = rowTemp.CreateCell(1);
rowTemp1.SetCellValue(listModel[i].userId.ToString());
rowTemp1.CellStyle = commonCellStyle;
var rowTemp2 = rowTemp.CreateCell(2);
rowTemp2.SetCellValue(listModel[i].userName.ToString());
rowTemp2.CellStyle = commonCellStyle;
var rowTemp3 = rowTemp.CreateCell(3);
rowTemp3.SetCellValue(listModel[i].model.ToString());
rowTemp3.CellStyle = commonCellStyle;
var rowTemp4 = rowTemp.CreateCell(4);
rowTemp4.SetCellValue(listModel[i].description.ToString());
rowTemp4.CellStyle = commonCellStyle;
var rowTemp5 = rowTemp.CreateCell(5);
rowTemp5.SetCellValue(listModel[i].url.ToString());
rowTemp5.CellStyle = commonCellStyle;
var rowTemp6 = rowTemp.CreateCell(6);
rowTemp6.SetCellValue(listModel[i].requestMethod.ToString());
rowTemp6.CellStyle = commonCellStyle;
var rowTemp7 = rowTemp.CreateCell(7);
rowTemp7.SetCellValue(listModel[i].operMethod.ToString());
rowTemp7.CellStyle = commonCellStyle;
var rowTemp8 = rowTemp.CreateCell(8);
rowTemp8.SetCellValue(listModel[i].param.ToString());
rowTemp8.CellStyle = commonCellStyle;
var rowTemp9 = rowTemp.CreateCell(9);
rowTemp9.SetCellValue(listModel[i].result.ToString());
rowTemp9.CellStyle = commonCellStyle;
var rowTemp10 = rowTemp.CreateCell(10);
rowTemp10.SetCellValue(listModel[i].ip.ToString());
rowTemp10.CellStyle = commonCellStyle;
var rowTemp11 = rowTemp.CreateCell(11);
rowTemp11.SetCellValue(listModel[i].spendTime.ToString());
rowTemp11.CellStyle = commonCellStyle;
var rowTemp12 = rowTemp.CreateCell(12);
rowTemp12.SetCellValue(listModel[i].state.ToString());
rowTemp12.CellStyle = commonCellStyle;
var rowTemp13 = rowTemp.CreateCell(13);
rowTemp13.SetCellValue(listModel[i].createTime.ToString());
rowTemp13.CellStyle = commonCellStyle;
}
// 导出excel
string webRootPath = _webHostEnvironment.WebRootPath;
string tpath = "/files/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "-SysOperRecord导出(选择结果).xls";
string filePath = webRootPath + tpath;
DirectoryInfo di = new DirectoryInfo(filePath);
if (!di.Exists)
{
di.Create();
}
FileStream fileHssf = new FileStream(filePath + fileName, FileMode.Create);
book.Write(fileHssf);
fileHssf.Close();
jm.code = 0;
jm.msg = GlobalConstVars.ExcelExportSuccess;
jm.data = tpath + fileName;
return Json(jm);
}
#endregion
#region 查询导出============================================================
// POST: Api/SysOperRecord/QueryExportExcel/10
/// <summary>
/// 查询导出
/// </summary>
/// <returns></returns>
[HttpPost]
[Description("查询导出")]
public async Task<JsonResult> QueryExportExcel()
{
var jm = new AdminUiCallBack();
var where = PredicateBuilder.True<SysOperRecord>();
//查询筛选
//主键 int
var id = Request.Form["id"].FirstOrDefault().ObjectToInt(0);
if (id > 0)
{
where = where.And(p => p.id == id);
}
//用户id int
var userId = Request.Form["userId"].FirstOrDefault().ObjectToInt(0);
if (userId > 0)
{
where = where.And(p => p.userId == userId);
}
//用户名 nvarchar
var userName = Request.Form["userName"].FirstOrDefault();
if (!string.IsNullOrEmpty(userName))
{
where = where.And(p => p.userName.Contains(userName));
}
//操作模块 nvarchar
var model = Request.Form["model"].FirstOrDefault();
if (!string.IsNullOrEmpty(model))
{
where = where.And(p => p.model.Contains(model));
}
//操作方法 nvarchar
var description = Request.Form["description"].FirstOrDefault();
if (!string.IsNullOrEmpty(description))
{
where = where.And(p => p.description.Contains(description));
}
//请求地址 nvarchar
var url = Request.Form["url"].FirstOrDefault();
if (!string.IsNullOrEmpty(url))
{
where = where.And(p => p.url.Contains(url));
}
//请求方式 nvarchar
var requestMethod = Request.Form["requestMethod"].FirstOrDefault();
if (!string.IsNullOrEmpty(requestMethod))
{
where = where.And(p => p.requestMethod.Contains(requestMethod));
}
//调用方法 nvarchar
var operMethod = Request.Form["operMethod"].FirstOrDefault();
if (!string.IsNullOrEmpty(operMethod))
{
where = where.And(p => p.operMethod.Contains(operMethod));
}
//请求参数 nvarchar
var param = Request.Form["param"].FirstOrDefault();
if (!string.IsNullOrEmpty(param))
{
where = where.And(p => p.param.Contains(param));
}
//返回结果 nvarchar
var result = Request.Form["result"].FirstOrDefault();
if (!string.IsNullOrEmpty(result))
{
where = where.And(p => p.result.Contains(result));
}
//ip地址 nvarchar
var ip = Request.Form["ip"].FirstOrDefault();
if (!string.IsNullOrEmpty(ip))
{
where = where.And(p => p.ip.Contains(ip));
}
//请求耗时,单位毫秒 nvarchar
var spendTime = Request.Form["spendTime"].FirstOrDefault();
if (!string.IsNullOrEmpty(spendTime))
{
where = where.And(p => p.spendTime.Contains(spendTime));
}
//状态,0成功,1异常 int
var state = Request.Form["state"].FirstOrDefault().ObjectToInt(0);
if (state > 0)
{
where = where.And(p => p.state == state);
}
//登录时间 datetime
var createTime = Request.Form["createTime"].FirstOrDefault();
if (!string.IsNullOrEmpty(createTime))
{
var dt = createTime.ObjectToDate();
where = where.And(p => p.createTime > dt);
}
//获取数据
//创建Excel文件的对象
var book = new HSSFWorkbook();
//添加一个sheet
var mySheet = book.CreateSheet("Sheet1");
//获取list数据
var listModel = await _SysOperRecordServices.QueryListByClauseAsync(where, p => p.id, OrderByType.Asc, true);
//给sheet1添加第一行的头部标题
var headerRow = mySheet.CreateRow(0);
var headerStyle = ExcelHelper.GetHeaderStyle(book);
var cell0 = headerRow.CreateCell(0);
cell0.SetCellValue("主键");
cell0.CellStyle = headerStyle;
mySheet.SetColumnWidth(0, 10 * 256);
var cell1 = headerRow.CreateCell(1);
cell1.SetCellValue("用户id");
cell1.CellStyle = headerStyle;
mySheet.SetColumnWidth(1, 10 * 256);
var cell2 = headerRow.CreateCell(2);
cell2.SetCellValue("用户名");
cell2.CellStyle = headerStyle;
mySheet.SetColumnWidth(2, 10 * 256);
var cell3 = headerRow.CreateCell(3);
cell3.SetCellValue("操作模块");
cell3.CellStyle = headerStyle;
mySheet.SetColumnWidth(3, 10 * 256);
var cell4 = headerRow.CreateCell(4);
cell4.SetCellValue("操作方法");
cell4.CellStyle = headerStyle;
mySheet.SetColumnWidth(4, 10 * 256);
var cell5 = headerRow.CreateCell(5);
cell5.SetCellValue("请求地址");
cell5.CellStyle = headerStyle;
mySheet.SetColumnWidth(5, 10 * 256);
var cell6 = headerRow.CreateCell(6);
cell6.SetCellValue("请求方式");
cell6.CellStyle = headerStyle;
mySheet.SetColumnWidth(6, 10 * 256);
var cell7 = headerRow.CreateCell(7);
cell7.SetCellValue("调用方法");
cell7.CellStyle = headerStyle;
mySheet.SetColumnWidth(7, 10 * 256);
var cell8 = headerRow.CreateCell(8);
cell8.SetCellValue("请求参数");
cell8.CellStyle = headerStyle;
mySheet.SetColumnWidth(8, 10 * 256);
var cell9 = headerRow.CreateCell(9);
cell9.SetCellValue("返回结果");
cell9.CellStyle = headerStyle;
mySheet.SetColumnWidth(9, 10 * 256);
var cell10 = headerRow.CreateCell(10);
cell10.SetCellValue("ip地址");
cell10.CellStyle = headerStyle;
mySheet.SetColumnWidth(10, 10 * 256);
var cell11 = headerRow.CreateCell(11);
cell11.SetCellValue("请求耗时,单位毫秒");
cell11.CellStyle = headerStyle;
mySheet.SetColumnWidth(11, 10 * 256);
var cell12 = headerRow.CreateCell(12);
cell12.SetCellValue("状态,0成功,1异常");
cell12.CellStyle = headerStyle;
mySheet.SetColumnWidth(12, 10 * 256);
var cell13 = headerRow.CreateCell(13);
cell13.SetCellValue("登录时间");
cell13.CellStyle = headerStyle;
mySheet.SetColumnWidth(13, 10 * 256);
headerRow.Height = 30 * 20;
var commonCellStyle = ExcelHelper.GetCommonStyle(book);
//将数据逐步写入sheet1各个行
for (var i = 0; i < listModel.Count; i++)
{
var rowTemp = mySheet.CreateRow(i + 1);
var rowTemp0 = rowTemp.CreateCell(0);
rowTemp0.SetCellValue(listModel[i].id.ToString());
rowTemp0.CellStyle = commonCellStyle;
var rowTemp1 = rowTemp.CreateCell(1);
rowTemp1.SetCellValue(listModel[i].userId.ToString());
rowTemp1.CellStyle = commonCellStyle;
var rowTemp2 = rowTemp.CreateCell(2);
rowTemp2.SetCellValue(listModel[i].userName.ToString());
rowTemp2.CellStyle = commonCellStyle;
var rowTemp3 = rowTemp.CreateCell(3);
rowTemp3.SetCellValue(listModel[i].model.ToString());
rowTemp3.CellStyle = commonCellStyle;
var rowTemp4 = rowTemp.CreateCell(4);
rowTemp4.SetCellValue(listModel[i].description.ToString());
rowTemp4.CellStyle = commonCellStyle;
var rowTemp5 = rowTemp.CreateCell(5);
rowTemp5.SetCellValue(listModel[i].url.ToString());
rowTemp5.CellStyle = commonCellStyle;
var rowTemp6 = rowTemp.CreateCell(6);
rowTemp6.SetCellValue(listModel[i].requestMethod.ToString());
rowTemp6.CellStyle = commonCellStyle;
var rowTemp7 = rowTemp.CreateCell(7);
rowTemp7.SetCellValue(listModel[i].operMethod.ToString());
rowTemp7.CellStyle = commonCellStyle;
var rowTemp8 = rowTemp.CreateCell(8);
rowTemp8.SetCellValue(listModel[i].param.ToString());
rowTemp8.CellStyle = commonCellStyle;
var rowTemp9 = rowTemp.CreateCell(9);
rowTemp9.SetCellValue(listModel[i].result.ToString());
rowTemp9.CellStyle = commonCellStyle;
var rowTemp10 = rowTemp.CreateCell(10);
rowTemp10.SetCellValue(listModel[i].ip.ToString());
rowTemp10.CellStyle = commonCellStyle;
var rowTemp11 = rowTemp.CreateCell(11);
rowTemp11.SetCellValue(listModel[i].spendTime.ToString());
rowTemp11.CellStyle = commonCellStyle;
var rowTemp12 = rowTemp.CreateCell(12);
rowTemp12.SetCellValue(listModel[i].state.ToString());
rowTemp12.CellStyle = commonCellStyle;
var rowTemp13 = rowTemp.CreateCell(13);
rowTemp13.SetCellValue(listModel[i].createTime.ToString());
rowTemp13.CellStyle = commonCellStyle;
}
// 写入到excel
string webRootPath = _webHostEnvironment.WebRootPath;
string tpath = "/files/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "-SysOperRecord导出(查询结果).xls";
string filePath = webRootPath + tpath;
DirectoryInfo di = new DirectoryInfo(filePath);
if (!di.Exists)
{
di.Create();
}
FileStream fileHssf = new FileStream(filePath + fileName, FileMode.Create);
book.Write(fileHssf);
fileHssf.Close();
jm.code = 0;
jm.msg = GlobalConstVars.ExcelExportSuccess;
jm.data = tpath + fileName;
return Json(jm);
}
#endregion
}
}
| 35.746617 | 402 | 0.522985 | [
"Apache-2.0"
] | toolgood/CoreShop | CoreCms.Net.Web.Admin/Controllers/System/SysOperRecordController.cs | 30,094 | C# |
using EventStore.ClientAPI;
using EventStore.ClientAPI.ClientOperations;
using EventStore.ClientAPI.Exceptions;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace EventStore.Core.Tests.ClientAPI {
[Category("LongRunning"), Category("ClientAPI")]
[TestFixture(typeof(LogFormat.V2), typeof(string))]
[TestFixture(typeof(LogFormat.V3), typeof(uint))]
public class connect_to_non_existing_persistent_subscription_with_permissions_async<TLogFormat, TStreamId> : SpecificationWithMiniNode<TLogFormat, TStreamId> {
private Exception _innerEx;
protected override async Task When() {
_innerEx = await AssertEx.ThrowsAsync<ArgumentException>(() => _conn.ConnectToPersistentSubscriptionAsync(
"nonexisting2",
"foo",
(sub, e) => {
Console.Write("appeared");
return Task.CompletedTask;
},
(sub, reason, ex) => { }, DefaultData.AdminCredentials));
}
[Test]
public void the_subscription_fails_to_connect_with_argument_exception() {
Assert.IsInstanceOf<ArgumentException>(_innerEx);
}
}
[Category("LongRunning")]
[TestFixture(typeof(LogFormat.V2), typeof(string))]
[TestFixture(typeof(LogFormat.V3), typeof(uint))]
public class connect_to_existing_persistent_subscription_with_permissions_async<TLogFormat, TStreamId> : SpecificationWithMiniNode<TLogFormat, TStreamId> {
private EventStorePersistentSubscriptionBase _sub;
private readonly string _stream = Guid.NewGuid().ToString();
private readonly PersistentSubscriptionSettings _settings = PersistentSubscriptionSettings.Create()
.DoNotResolveLinkTos()
.StartFromCurrent();
protected override async Task When() {
await _conn.CreatePersistentSubscriptionAsync(_stream, "agroupname17", _settings, DefaultData.AdminCredentials)
;
_sub = await _conn.ConnectToPersistentSubscriptionAsync(_stream,
"agroupname17",
(sub, e) => {
Console.Write("appeared");
return Task.CompletedTask;
},
(sub, reason, ex) => { }, DefaultData.AdminCredentials);
}
[Test]
public void the_subscription_succeeds() {
Assert.IsNotNull(_sub);
}
}
[Category("LongRunning")]
[TestFixture(typeof(LogFormat.V2), typeof(string))]
[TestFixture(typeof(LogFormat.V3), typeof(uint))]
public class connect_to_existing_persistent_subscription_without_permissions_async<TLogFormat, TStreamId> : SpecificationWithMiniNode<TLogFormat, TStreamId> {
private readonly string _stream = "$" + Guid.NewGuid();
private readonly PersistentSubscriptionSettings _settings = PersistentSubscriptionSettings.Create()
.DoNotResolveLinkTos()
.StartFromCurrent();
private Exception _innerEx;
protected override async Task When() {
await _conn.CreatePersistentSubscriptionAsync(_stream, "agroupname55", _settings,
DefaultData.AdminCredentials);
_innerEx = await AssertEx.ThrowsAsync<AccessDeniedException>(() => _conn.ConnectToPersistentSubscriptionAsync(
_stream,
"agroupname55",
(sub, e) => {
Console.Write("appeared");
return Task.CompletedTask;
},
(sub, reason, ex) => Console.WriteLine("dropped.")));
}
[Test]
public void the_subscription_fails_to_connect_with_access_denied_exception() {
Assert.IsInstanceOf<AccessDeniedException>(_innerEx);
}
}
[Category("LongRunning")]
[TestFixture(typeof(LogFormat.V2), typeof(string))]
[TestFixture(typeof(LogFormat.V3), typeof(uint))]
public class connect_to_existing_persistent_subscription_with_max_one_client_async<TLogFormat, TStreamId> : SpecificationWithMiniNode<TLogFormat, TStreamId> {
private readonly string _stream = "$" + Guid.NewGuid();
private readonly PersistentSubscriptionSettings _settings = PersistentSubscriptionSettings.Create()
.DoNotResolveLinkTos()
.StartFromCurrent()
.WithMaxSubscriberCountOf(1);
private Exception _innerEx;
private const string _group = "startinbeginning1";
private EventStorePersistentSubscriptionBase _firstConn;
protected override async Task Given() {
await base.Given();
await _conn.CreatePersistentSubscriptionAsync(_stream, _group, _settings,
DefaultData.AdminCredentials);
// First connection
_firstConn = await _conn.ConnectToPersistentSubscriptionAsync(
_stream,
_group,
(s, e) => {
s.Acknowledge(e);
return Task.CompletedTask;
},
(sub, reason, ex) => { },
DefaultData.AdminCredentials);
}
protected override async Task When() {
_innerEx = await AssertEx.ThrowsAsync<MaximumSubscribersReachedException>(() =>
// Second connection
_conn.ConnectToPersistentSubscriptionAsync(
_stream,
_group,
(s, e) => {
s.Acknowledge(e);
return Task.CompletedTask;
},
(sub, reason, ex) => { },
DefaultData.AdminCredentials));
}
[Test]
public void the_first_subscription_connects_successfully() {
Assert.IsNotNull(_firstConn);
}
[Test]
public void the_second_subscription_throws_maximum_subscribers_reached_exception() {
Assert.IsInstanceOf<MaximumSubscribersReachedException>(_innerEx);
}
}
[Category("LongRunning")]
[TestFixture(typeof(LogFormat.V2), typeof(string))]
[TestFixture(typeof(LogFormat.V3), typeof(uint))]
public class
connect_to_existing_persistent_subscription_with_start_from_beginning_and_no_stream_async<TLogFormat, TStreamId> :
SpecificationWithMiniNode<TLogFormat, TStreamId> {
private readonly string _stream = "$" + Guid.NewGuid();
private readonly PersistentSubscriptionSettings _settings = PersistentSubscriptionSettings.Create()
.DoNotResolveLinkTos()
.StartFromBeginning();
private readonly AutoResetEvent _resetEvent = new AutoResetEvent(false);
private ResolvedEvent _firstEvent;
private readonly Guid _id = Guid.NewGuid();
private bool _set = false;
private const string _group = "startinbeginning1";
protected override async Task Given() {
await _conn.CreatePersistentSubscriptionAsync(_stream, _group, _settings,
DefaultData.AdminCredentials);
await _conn.ConnectToPersistentSubscriptionAsync(
_stream,
_group,
HandleEvent,
(sub, reason, ex) => { },
DefaultData.AdminCredentials);
}
protected override Task When() {
return _conn.AppendToStreamAsync(_stream, ExpectedVersion.Any, DefaultData.AdminCredentials,
new EventData(_id, "test", true, Encoding.UTF8.GetBytes("{'foo' : 'bar'}"), new byte[0]));
}
private Task HandleEvent(EventStorePersistentSubscriptionBase sub, ResolvedEvent resolvedEvent) {
if (_set)
return Task.CompletedTask;
_set = true;
_firstEvent = resolvedEvent;
_resetEvent.Set();
return Task.CompletedTask;
}
[Test]
public void the_subscription_gets_event_zero_as_its_first_event() {
Assert.IsTrue(_resetEvent.WaitOne(TimeSpan.FromSeconds(10)));
Assert.AreEqual(0, _firstEvent.Event.EventNumber);
Assert.AreEqual(_id, _firstEvent.Event.EventId);
}
}
[Category("LongRunning")]
[TestFixture(typeof(LogFormat.V2), typeof(string))]
[TestFixture(typeof(LogFormat.V3), typeof(uint))]
public class
connect_to_existing_persistent_subscription_with_start_from_two_and_no_stream_async<TLogFormat, TStreamId> :
SpecificationWithMiniNode<TLogFormat, TStreamId> {
private readonly string _stream = "$" + Guid.NewGuid();
private readonly PersistentSubscriptionSettings _settings = PersistentSubscriptionSettings.Create()
.DoNotResolveLinkTos()
.StartFrom(2);
private readonly AutoResetEvent _resetEvent = new AutoResetEvent(false);
private ResolvedEvent _firstEvent;
private readonly Guid _id = Guid.NewGuid();
private bool _set = false;
private const string _group = "startinbeginning1";
protected override async Task Given() {
await _conn.CreatePersistentSubscriptionAsync(_stream, _group, _settings,
DefaultData.AdminCredentials);
await _conn.ConnectToPersistentSubscriptionAsync(
_stream,
_group,
HandleEvent,
(sub, reason, ex) => { },
DefaultData.AdminCredentials);
}
protected override async Task When() {
await _conn.AppendToStreamAsync(_stream, ExpectedVersion.Any, DefaultData.AdminCredentials,
new EventData(Guid.NewGuid(), "test", true, Encoding.UTF8.GetBytes("{'foo' : 'bar'}"), new byte[0]));
await _conn.AppendToStreamAsync(_stream, ExpectedVersion.Any, DefaultData.AdminCredentials,
new EventData(Guid.NewGuid(), "test", true, Encoding.UTF8.GetBytes("{'foo' : 'bar'}"), new byte[0]));
await _conn.AppendToStreamAsync(_stream, ExpectedVersion.Any, DefaultData.AdminCredentials,
new EventData(_id, "test", true, Encoding.UTF8.GetBytes("{'foo' : 'bar'}"), new byte[0]));
}
private Task HandleEvent(EventStorePersistentSubscriptionBase sub, ResolvedEvent resolvedEvent) {
if (_set)
return Task.CompletedTask;
_set = true;
_firstEvent = resolvedEvent;
_resetEvent.Set();
return Task.CompletedTask;
}
[Test]
public void the_subscription_gets_event_two_as_its_first_event() {
Assert.IsTrue(_resetEvent.WaitOne(TimeSpan.FromSeconds(10)));
Assert.AreEqual(2, _firstEvent.Event.EventNumber);
Assert.AreEqual(_id, _firstEvent.Event.EventId);
}
}
[Category("LongRunning")]
[TestFixture(typeof(LogFormat.V2), typeof(string))]
[TestFixture(typeof(LogFormat.V3), typeof(uint))]
public class
connect_to_existing_persistent_subscription_with_start_from_beginning_and_events_in_it_async<TLogFormat, TStreamId> :
SpecificationWithMiniNode<TLogFormat, TStreamId> {
private readonly string _stream = "$" + Guid.NewGuid();
private readonly PersistentSubscriptionSettings _settings = PersistentSubscriptionSettings.Create()
.DoNotResolveLinkTos()
.StartFromBeginning();
private readonly AutoResetEvent _resetEvent = new AutoResetEvent(false);
private ResolvedEvent _firstEvent;
private List<Guid> _ids = new List<Guid>();
private bool _set = false;
private const string _group = "startinbeginning1";
protected override async Task Given() {
await WriteEvents(_conn);
await _conn.CreatePersistentSubscriptionAsync(_stream, _group, _settings,
DefaultData.AdminCredentials);
}
private async Task WriteEvents(IEventStoreConnection connection) {
for (int i = 0; i < 10; i++) {
_ids.Add(Guid.NewGuid());
await connection.AppendToStreamAsync(_stream, ExpectedVersion.Any, DefaultData.AdminCredentials,
new EventData(_ids[i], "test", true, Encoding.UTF8.GetBytes("{'foo' : 'bar'}"), new byte[0]));
}
}
protected override Task When() {
return _conn.ConnectToPersistentSubscriptionAsync(
_stream,
_group,
HandleEvent,
(sub, reason, ex) => { },
DefaultData.AdminCredentials);
}
private Task HandleEvent(EventStorePersistentSubscriptionBase sub, ResolvedEvent resolvedEvent) {
if (!_set) {
_set = true;
_firstEvent = resolvedEvent;
_resetEvent.Set();
}
return Task.CompletedTask;
}
[Test]
public void the_subscription_gets_event_zero_as_its_first_event() {
Assert.IsTrue(_resetEvent.WaitOne(TimeSpan.FromSeconds(10)));
Assert.AreEqual(0, _firstEvent.Event.EventNumber);
Assert.AreEqual(_ids[0], _firstEvent.Event.EventId);
}
}
[Category("LongRunning")]
[TestFixture(typeof(LogFormat.V2), typeof(string))]
[TestFixture(typeof(LogFormat.V3), typeof(uint))]
public class
connect_to_existing_persistent_subscription_with_start_from_beginning_not_set_and_events_in_it_async<TLogFormat, TStreamId> :
SpecificationWithMiniNode<TLogFormat, TStreamId> {
private readonly string _stream = "$" + Guid.NewGuid();
private readonly PersistentSubscriptionSettings _settings = PersistentSubscriptionSettings.Create()
.DoNotResolveLinkTos()
.StartFromCurrent();
private readonly AutoResetEvent _resetEvent = new AutoResetEvent(false);
private const string _group = "startinbeginning1";
protected override async Task Given() {
await WriteEvents(_conn);
await _conn.CreatePersistentSubscriptionAsync(_stream, _group, _settings,
DefaultData.AdminCredentials);
}
private async Task WriteEvents(IEventStoreConnection connection) {
for (int i = 0; i < 10; i++) {
await connection.AppendToStreamAsync(_stream, ExpectedVersion.Any, DefaultData.AdminCredentials,
new EventData(Guid.NewGuid(), "test", true, Encoding.UTF8.GetBytes("{'foo' : 'bar'}"),
new byte[0]));
}
}
protected override Task When() {
return _conn.ConnectToPersistentSubscriptionAsync(
_stream,
_group,
HandleEvent,
(sub, reason, ex) => { },
DefaultData.AdminCredentials);
}
private Task HandleEvent(EventStorePersistentSubscriptionBase sub, ResolvedEvent resolvedEvent) {
_resetEvent.Set();
return Task.CompletedTask;
}
[Test]
public void the_subscription_gets_no_events() {
Assert.IsFalse(_resetEvent.WaitOne(TimeSpan.FromSeconds(1)));
}
}
}
| 34.609164 | 160 | 0.752025 | [
"Apache-2.0",
"CC0-1.0"
] | BearerPipelineTest/EventStore | src/EventStore.Core.Tests/ClientAPI/connecting_to_a_persistent_subscription_async.cs | 12,842 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("01.RSSToJSON")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("01.RSSToJSON")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f21acf5b-984a-44b0-a5ed-8bb65b69b49c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.756757 | 84 | 0.743737 | [
"MIT"
] | TsvetanKT/TelerikHomeworks | Databases/16.ProcessingJSON/01.RSSToJSON/Properties/AssemblyInfo.cs | 1,400 | C# |
using System;
using Microsoft.Extensions.Configuration;
using System.IO;
namespace Oogi2.AspNetCore.Identity.Tests.Fixtures
{
public class DocumentDbFixture : IDisposable
{
public Connection Connection { get; }
public DocumentDbFixture()
{
var appSettings = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddUserSecrets("oogi2")
.AddEnvironmentVariables()
.Build();
Connection = new Connection(appSettings["endpoint"], appSettings["authorizationKey"], appSettings["database"], appSettings["collection"]);
CreateTestDatabase();
}
void CreateTestDatabase()
{
Connection.CreateCollection();
}
void CleanupTestDatabase()
{
Connection.DeleteCollection();
}
public void Dispose()
{
CleanupTestDatabase();
}
}
} | 26 | 150 | 0.582692 | [
"MIT"
] | goto10hq/Oogi2.AspNetCore.Identity | Oogi2.AspNetCore.Identity.Tests/Fixtures/DocumentDbFixture.cs | 1,042 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("_04.Variable_in_Hex_Format")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("_04.Variable_in_Hex_Format")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2d73ed42-ef34-49b9-82e5-67749aa66b46")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.513514 | 84 | 0.748772 | [
"MIT"
] | spzvtbg/02-Tech-modul | Fundamental task solutions/05.Data Types and Variables - Exercises/04. Variable in Hex Format/Properties/AssemblyInfo.cs | 1,428 | C# |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
namespace Tizen.NUI
{
internal static partial class Interop
{
internal static partial class RendererParameters
{
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_new_RendererParameters_0")]
public static extern global::System.IntPtr NewRendererParameters();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_text_set")]
public static extern void TextSet(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_text_get")]
public static extern string TextGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_horizontalAlignment_set")]
public static extern void HorizontalAlignmentSet(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_horizontalAlignment_get")]
public static extern string HorizontalAlignmentGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_verticalAlignment_set")]
public static extern void VerticalAlignmentSet(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_verticalAlignment_get")]
public static extern string VerticalAlignmentGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_fontFamily_set")]
public static extern void FontFamilySet(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_fontFamily_get")]
public static extern string FontFamilyGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_fontWeight_set")]
public static extern void FontWeightSet(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_fontWeight_get")]
public static extern string FontWeightGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_fontWidth_set")]
public static extern void FontWidthSet(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_fontWidth_get")]
public static extern string FontWidthGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_fontSlant_set")]
public static extern void FontSlantSet(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_fontSlant_get")]
public static extern string FontSlantGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_layout_set")]
public static extern void LayoutSet(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_layout_get")]
public static extern string LayoutGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_circularAlignment_set")]
public static extern void CircularAlignmentSet(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_circularAlignment_get")]
public static extern string CircularAlignmentGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_textColor_set")]
public static extern void TextColorSet(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_textColor_get")]
public static extern global::System.IntPtr TextColorGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_fontSize_set")]
public static extern void FontSizeSet(global::System.Runtime.InteropServices.HandleRef jarg1, float jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_fontSize_get")]
public static extern float FontSizeGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_textWidth_set")]
public static extern void TextWidthSet(global::System.Runtime.InteropServices.HandleRef jarg1, uint jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_textWidth_get")]
public static extern uint TextWidthGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_textHeight_set")]
public static extern void TextHeightSet(global::System.Runtime.InteropServices.HandleRef jarg1, uint jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_textHeight_get")]
public static extern uint TextHeightGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_radius_set")]
public static extern void RadiusSet(global::System.Runtime.InteropServices.HandleRef jarg1, uint jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_radius_get")]
public static extern uint RadiusGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_beginAngle_set")]
public static extern void BeginAngleSet(global::System.Runtime.InteropServices.HandleRef jarg1, float jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_beginAngle_get")]
public static extern float BeginAngleGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_incrementAngle_set")]
public static extern void IncrementAngleSet(global::System.Runtime.InteropServices.HandleRef jarg1, float jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_incrementAngle_get")]
public static extern float IncrementAngleGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_ellipsisEnabled_set")]
public static extern void EllipsisEnabledSet(global::System.Runtime.InteropServices.HandleRef jarg1, bool jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_ellipsisEnabled_get")]
public static extern bool EllipsisEnabledGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_markupEnabled_set")]
public static extern void MarkupEnabledSet(global::System.Runtime.InteropServices.HandleRef jarg1, bool jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_markupEnabled_get")]
public static extern bool MarkupEnabledGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_isTextColorSet_set")]
public static extern void IsTextColorSetSet(global::System.Runtime.InteropServices.HandleRef jarg1, bool jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_isTextColorSet_get")]
public static extern bool IsTextColorSetGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_minLineSize_set")]
public static extern void MinLineSizeSet(global::System.Runtime.InteropServices.HandleRef jarg1, float jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_minLineSize_get")]
public static extern float MinLineSizeGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_padding_set")]
public static extern void PaddingSet(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_RendererParameters_padding_get")]
public static extern global::System.IntPtr PaddingGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_delete_RendererParameters")]
public static extern void DeleteRendererParameters(global::System.Runtime.InteropServices.HandleRef jarg1);
}
internal static partial class EmbeddedItemInfo
{
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_new_EmbeddedItemInfo_0")]
public static extern global::System.IntPtr NewEmbeddedItemInfo();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_delete_EmbeddedItemInfo")]
public static extern void DeleteEmbeddedItemInfo(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_EmbeddedItemInfo_characterIndex_set")]
public static extern void CharacterIndexSet(global::System.Runtime.InteropServices.HandleRef jarg1, uint jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_EmbeddedItemInfo_characterIndex_get")]
public static extern uint CharacterIndexGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_EmbeddedItemInfo_glyphIndex_set")]
public static extern void GlyphIndexSet(global::System.Runtime.InteropServices.HandleRef jarg1, uint jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_EmbeddedItemInfo_glyphIndex_get")]
public static extern uint GlyphIndexGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_EmbeddedItemInfo_position_set")]
public static extern void PositionSet(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_EmbeddedItemInfo_position_get")]
public static extern global::System.IntPtr PositionGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_EmbeddedItemInfo_size_set")]
public static extern void SizeSet(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_EmbeddedItemInfo_size_get")]
public static extern global::System.IntPtr SizeGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_EmbeddedItemInfo_rotatedSize_set")]
public static extern void RotatedSizeSet(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_EmbeddedItemInfo_rotatedSize_get")]
public static extern global::System.IntPtr RotatedSizeGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_EmbeddedItemInfo_angle_set")]
public static extern void AngleSet(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_EmbeddedItemInfo_angle_get")]
public static extern global::System.IntPtr AngleGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_EmbeddedItemInfo_colorBlendingMode_set")]
public static extern void ColorBlendingModeSet(global::System.Runtime.InteropServices.HandleRef jarg1, Tizen.NUI.ColorBlendingMode jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_EmbeddedItemInfo_colorBlendingMode_get")]
public static extern Tizen.NUI.ColorBlendingMode ColorBlendingModeGet(global::System.Runtime.InteropServices.HandleRef jarg1);
}
internal static partial class ShadowParameters
{
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_new_ShadowParameters_0")]
public static extern global::System.IntPtr NewShadowParameters();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_delete_ShadowParameters")]
public static extern void DeleteShadowParameters(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_ShadowParameters_input_set")]
public static extern void InputSet(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_ShadowParameters_input_get")]
public static extern global::System.IntPtr InputGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_ShadowParameters_textColor_set")]
public static extern void TextColorSet(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_ShadowParameters_textColor_get")]
public static extern global::System.IntPtr TextColorGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_ShadowParameters_color_set")]
public static extern void ColorSet(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_ShadowParameters_color_get")]
public static extern global::System.IntPtr ColorGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_ShadowParameters_offset_set")]
public static extern void OffsetSet(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_ShadowParameters_offset_get")]
public static extern global::System.IntPtr OffsetGet(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_ShadowParameters_blendShadow_set")]
public static extern void BlendShadowSet(global::System.Runtime.InteropServices.HandleRef jarg1, bool jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_ShadowParameters_blendShadow_get")]
public static extern bool BlendShadowGet(global::System.Runtime.InteropServices.HandleRef jarg1);
}
internal static partial class TextUtils
{
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_TextUtils_Render")]
public static extern global::System.IntPtr Render(global::System.Runtime.InteropServices.HandleRef jarg1, ref global::System.IntPtr jarg2, ref int count, ref int length);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_TextUtils_CreateShadow")]
public static extern global::System.IntPtr CreateShadow(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_TextUtils_ConvertToRgba8888")]
public static extern global::System.IntPtr ConvertToRgba8888(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2, bool jarg3);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_TextUtils_UpdateBuffer")]
public static extern void UpdateBuffer(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2, uint jarg3, uint jarg4, bool jarg5);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_TextUtils_GetLastCharacterIndex")]
public static extern global::System.IntPtr GetLastCharacterIndex(global::System.Runtime.InteropServices.HandleRef jarg1);
}
}
}
| 83.219608 | 199 | 0.77395 | [
"Apache-2.0",
"MIT"
] | bshsqa/TizenFX | src/Tizen.NUI/src/internal/Interop/Interop.TextUtils.cs | 21,223 | C# |
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
// 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.CodeBuild")]
#if BCL35
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS CodeBuild. AWS CodeBuild is a fully-managed build service in the cloud. AWS CodeBuild compiles your source code, runs unit tests, and produces artifacts that are ready to deploy.")]
#elif BCL45
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - AWS CodeBuild. AWS CodeBuild is a fully-managed build service in the cloud. AWS CodeBuild compiles your source code, runs unit tests, and produces artifacts that are ready to deploy.")]
#elif NETSTANDARD20
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - AWS CodeBuild. AWS CodeBuild is a fully-managed build service in the cloud. AWS CodeBuild compiles your source code, runs unit tests, and produces artifacts that are ready to deploy.")]
#elif NETCOREAPP3_1
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - AWS CodeBuild. AWS CodeBuild is a fully-managed build service in the cloud. AWS CodeBuild compiles your source code, runs unit tests, and produces artifacts that are ready to deploy.")]
#else
#error Unknown platform constant - unable to set correct AssemblyDescription
#endif
[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.2.6")]
[assembly: System.CLSCompliant(true)]
#if BCL
[assembly: System.Security.AllowPartiallyTrustedCallers]
#endif | 52.019608 | 274 | 0.768564 | [
"Apache-2.0"
] | QPC-database/aws-sdk-net | sdk/src/Services/CodeBuild/Properties/AssemblyInfo.cs | 2,653 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace FontSizes.UWP
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Xamarin.Forms.Platform.UWP.WindowsPage
{
public MainPage()
{
this.InitializeComponent();
LoadApplication(new FontSizes.App());
}
}
}
| 27.454545 | 106 | 0.722958 | [
"Apache-2.0"
] | DLozanoNavas/xamarin-forms-book-samples | Chapter05/FS/FontSizes/FontSizes/FontSizes.UWP/MainPage.xaml.cs | 906 | C# |
// ====================================================
// More Templates: https://www.ebenmonney.com/templates
// Email: [email protected]
// ====================================================
using DAL.Models;
using System;
using System.Collections.Generic;
using System.Linq;
namespace DAL.Repositories.Interfaces
{
public interface IProductRepository : IRepository<Product>
{
}
}
| 22.611111 | 62 | 0.545455 | [
"MIT"
] | AivazovskiiRoman/QuickApp | src/DAL/Repositories/Interfaces/IProductRepository.cs | 409 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using EcsRx.Entities;
using EcsRx.Extensions;
using EcsRx.Groups.Observable;
using EcsRx.MicroRx.Extensions;
using EcsRx.Tests.Models;
using EcsRx.Tests.Plugins.Computeds.Models;
using NSubstitute;
using Xunit;
namespace EcsRx.Tests.Plugins.Computeds
{
public class ComputedCollectionFromGroupTests
{
[Fact]
public void should_populate_on_creation()
{
var fakeEntity1 = Substitute.For<IEntity>();
fakeEntity1.Id.Returns(1);
fakeEntity1.HasComponent<TestComponentThree>().Returns(false);
var fakeEntity2 = Substitute.For<IEntity>();
fakeEntity2.Id.Returns(2);
fakeEntity2.HasComponent<TestComponentThree>().Returns(true);
var fakeEntity3 = Substitute.For<IEntity>();
fakeEntity2.Id.Returns(3);
fakeEntity3.HasComponent<TestComponentThree>().Returns(true);
var expectedData = new List<IEntity> {fakeEntity2, fakeEntity3}
.Select(x => x.GetHashCode())
.OrderBy(x => x);
var fakeEntities = new List<IEntity> {fakeEntity1, fakeEntity2, fakeEntity3};
var mockObservableGroup = Substitute.For<IObservableGroup>();
mockObservableGroup.OnEntityAdded.Returns(Observable.Empty<IEntity>());
mockObservableGroup.OnEntityRemoving.Returns(Observable.Empty<IEntity>());
mockObservableGroup.GetEnumerator().Returns(x => fakeEntities.GetEnumerator());
var computedGroupData = new TestComputedCollectionFromGroup(mockObservableGroup);
Assert.Equal(expectedData, computedGroupData.Value);
}
[Fact]
public void should_refresh_when_entities_added_and_value_requested()
{
var fakeEntity1 = Substitute.For<IEntity>();
fakeEntity1.Id.Returns(1);
fakeEntity1.HasComponent<TestComponentThree>().Returns(false);
var fakeEntity2 = Substitute.For<IEntity>();
fakeEntity2.Id.Returns(2);
fakeEntity2.HasComponent<TestComponentThree>().Returns(true);
var fakeEntity3 = Substitute.For<IEntity>();
fakeEntity2.Id.Returns(3);
fakeEntity3.HasComponent<TestComponentThree>().Returns(true);
var expectedData = new List<IEntity> {fakeEntity2, fakeEntity3}
.Select(x => x.GetHashCode())
.OrderBy(x => x);
var fakeEntities = new List<IEntity> {fakeEntity1, fakeEntity2};
var mockObservableGroup = Substitute.For<IObservableGroup>();
var addedEvent = new Subject<IEntity>();
mockObservableGroup.OnEntityAdded.Returns(addedEvent);
mockObservableGroup.OnEntityRemoving.Returns(Observable.Empty<IEntity>());
mockObservableGroup.GetEnumerator().Returns(x => fakeEntities.GetEnumerator());
var computedGroupData = new TestComputedCollectionFromGroup(mockObservableGroup);
fakeEntities.Add(fakeEntity3);
addedEvent.OnNext(null);
var actualData = computedGroupData.Value;
Assert.Equal(expectedData, actualData);
}
[Fact]
public void should_refresh_when_entities_removed_and_value_requested()
{
var fakeEntity1 = Substitute.For<IEntity>();
fakeEntity1.Id.Returns(1);
fakeEntity1.HasComponent<TestComponentThree>().Returns(false);
var fakeEntity2 = Substitute.For<IEntity>();
fakeEntity2.Id.Returns(2);
fakeEntity2.HasComponent<TestComponentThree>().Returns(true);
var fakeEntity3 = Substitute.For<IEntity>();
fakeEntity2.Id.Returns(3);
fakeEntity3.HasComponent<TestComponentThree>().Returns(true);
var expectedData = new[] {fakeEntity2.GetHashCode()};
var fakeEntities = new List<IEntity> {fakeEntity1, fakeEntity2};
var mockObservableGroup = Substitute.For<IObservableGroup>();
var removingEntity = new Subject<IEntity>();
mockObservableGroup.OnEntityAdded.Returns(Observable.Empty<IEntity>());
mockObservableGroup.OnEntityRemoving.Returns(removingEntity);
mockObservableGroup.GetEnumerator().Returns(x => fakeEntities.GetEnumerator());
var computedGroupData = new TestComputedCollectionFromGroup(mockObservableGroup);
fakeEntities.Remove(fakeEntity3);
removingEntity.OnNext(fakeEntity3);
var actualData = computedGroupData.Value;
Assert.Equal(expectedData, actualData);
}
[Fact]
public void should_refresh_on_trigger_and_value_requested()
{
var fakeEntity1 = Substitute.For<IEntity>();
fakeEntity1.Id.Returns(1);
fakeEntity1.HasComponent<TestComponentThree>().Returns(false);
var fakeEntity2 = Substitute.For<IEntity>();
fakeEntity2.Id.Returns(2);
fakeEntity2.HasComponent<TestComponentThree>().Returns(true);
var fakeEntity3 = Substitute.For<IEntity>();
fakeEntity2.Id.Returns(3);
fakeEntity3.HasComponent<TestComponentThree>().Returns(true);
var expectedData = new List<IEntity> {fakeEntity2, fakeEntity3}
.Select(x => x.GetHashCode())
.OrderBy(x => x);
var fakeEntities = new List<IEntity> {fakeEntity1, fakeEntity2};
var mockObservableGroup = Substitute.For<IObservableGroup>();
var addedEvent = new Subject<IEntity>();
mockObservableGroup.OnEntityAdded.Returns(addedEvent);
mockObservableGroup.OnEntityRemoving.Returns(Observable.Empty<IEntity>());
mockObservableGroup.GetEnumerator().Returns(x => fakeEntities.GetEnumerator());
var computedGroupData = new TestComputedCollectionFromGroup(mockObservableGroup);
fakeEntities.Add(fakeEntity3);
computedGroupData.ManuallyRefresh.OnNext(true);
var actualData = computedGroupData.Value;
Assert.Equal(expectedData, actualData);
}
[Fact]
public void should_not_refresh_value_with_no_subs_events_or_triggers_and_value_requested()
{
var fakeEntity1 = Substitute.For<IEntity>();
fakeEntity1.Id.Returns(1);
fakeEntity1.HasComponent<TestComponentThree>().Returns(false);
var fakeEntity2 = Substitute.For<IEntity>();
fakeEntity2.Id.Returns(2);
fakeEntity2.HasComponent<TestComponentThree>().Returns(true);
var fakeEntity3 = Substitute.For<IEntity>();
fakeEntity2.Id.Returns(3);
fakeEntity3.HasComponent<TestComponentThree>().Returns(true);
var expectedData = new List<IEntity> {fakeEntity2, fakeEntity3}
.Select(x => x.GetHashCode())
.OrderBy(x => x);
var fakeEntities = new List<IEntity> {fakeEntity1, fakeEntity2, fakeEntity3};
var mockObservableGroup = Substitute.For<IObservableGroup>();
mockObservableGroup.OnEntityAdded.Returns(Observable.Empty<IEntity>());
mockObservableGroup.OnEntityRemoving.Returns(Observable.Empty<IEntity>());
mockObservableGroup.GetEnumerator().Returns(x => fakeEntities.GetEnumerator());
var computedGroupData = new TestComputedCollectionFromGroup(mockObservableGroup);
fakeEntities.Remove(fakeEntity2);
var actualData = computedGroupData.Value;
Assert.Equal(expectedData, actualData);
}
[Fact]
public void should_not_refresh_cached_data_when_change_notified_but_no_value_request()
{
var fakeEntity1 = Substitute.For<IEntity>();
fakeEntity1.Id.Returns(1);
fakeEntity1.HasComponent<TestComponentThree>().Returns(false);
var fakeEntity2 = Substitute.For<IEntity>();
fakeEntity2.Id.Returns(2);
fakeEntity2.HasComponent<TestComponentThree>().Returns(true);
var fakeEntity3 = Substitute.For<IEntity>();
fakeEntity2.Id.Returns(3);
fakeEntity3.HasComponent<TestComponentThree>().Returns(true);
var fakeEntities = new List<IEntity> {fakeEntity1, fakeEntity2, fakeEntity3};
var mockObservableGroup = Substitute.For<IObservableGroup>();
var addingSubject = new Subject<IEntity>();
mockObservableGroup.OnEntityAdded.Returns(addingSubject);
var removingSubject = new Subject<IEntity>();
mockObservableGroup.OnEntityRemoving.Returns(removingSubject);
mockObservableGroup.GetEnumerator().Returns(x => fakeEntities.GetEnumerator());
var computedGroupData = new TestComputedFromGroup(mockObservableGroup);
var expectedOutput = computedGroupData.CachedData;
addingSubject.OnNext(null);
computedGroupData.ManuallyRefresh.OnNext(true);
Assert.Equal(expectedOutput, computedGroupData.CachedData);
}
[Fact]
public void should_refresh_cached_data_when_change_notified_with_subs_but_no_value_requested()
{
var fakeEntity1 = Substitute.For<IEntity>();
fakeEntity1.Id.Returns(1);
fakeEntity1.HasComponent<TestComponentThree>().Returns(false);
var fakeEntity2 = Substitute.For<IEntity>();
fakeEntity2.Id.Returns(2);
fakeEntity2.HasComponent<TestComponentThree>().Returns(true);
var fakeEntity3 = Substitute.For<IEntity>();
fakeEntity2.Id.Returns(3);
fakeEntity3.HasComponent<TestComponentThree>().Returns(true);
var expectedData = new List<IEntity> {fakeEntity2, fakeEntity3}
.Select(x => x.GetHashCode())
.OrderBy(x => x);
var fakeEntities = new List<IEntity> {fakeEntity1, fakeEntity2, fakeEntity3};
var mockObservableGroup = Substitute.For<IObservableGroup>();
var addingSubject = new Subject<IEntity>();
mockObservableGroup.OnEntityAdded.Returns(addingSubject);
var removingSubject = new Subject<IEntity>();
mockObservableGroup.OnEntityRemoving.Returns(removingSubject);
mockObservableGroup.GetEnumerator().Returns(x => fakeEntities.GetEnumerator());
var computedGroupData = new TestComputedCollectionFromGroup(mockObservableGroup);
computedGroupData.Subscribe(x => {});
fakeEntities.Remove(fakeEntity2);
removingSubject.OnNext(fakeEntity2);
Assert.False(expectedData.SequenceEqual(computedGroupData.Value));
fakeEntities.Add(fakeEntity2);
addingSubject.OnNext(fakeEntity2);
Assert.True(expectedData.SequenceEqual(computedGroupData.Value));
fakeEntities.Remove(fakeEntity2);
computedGroupData.ManuallyRefresh.OnNext(true);
Assert.False(expectedData.SequenceEqual(computedGroupData.Value));
}
}
} | 41.729537 | 102 | 0.628347 | [
"MIT"
] | Fijo/ecsrx | src/EcsRx.Tests/Plugins/Computeds/ComputedCollectionFromGroupTests.cs | 11,726 | C# |
using MetaDslx.CodeAnalysis;
using Microsoft.CodeAnalysis;
using Roslyn.Utilities;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace MetaDslx.CodeAnalysis
{
/// <summary>
/// A diagnostic (such as a compiler error or a warning), along with the location where it occurred.
/// </summary>
[DebuggerDisplay("{GetDebuggerDisplay(), nq}")]
public class LanguageDiagnostic : Diagnostic
{
private readonly LanguageDiagnosticInfo _info;
private readonly Location _location;
private readonly bool _isSuppressed;
internal LanguageDiagnostic(LanguageDiagnosticInfo info, Location location, bool isSuppressed = false)
{
Debug.Assert(info != null);
Debug.Assert(location != null);
_info = info;
_location = location;
_isSuppressed = isSuppressed;
}
/// <summary>
/// Creates a <see cref="Diagnostic"/> instance.
/// </summary>
/// <param name="descriptor">A <see cref="DiagnosticDescriptor"/> describing the diagnostic</param>
/// <param name="location">An optional primary location of the diagnostic. If null, <see cref="Location"/> will return <see cref="Location.None"/>.</param>
/// <param name="messageArgs">Arguments to the message of the diagnostic</param>
/// <returns>The <see cref="Diagnostic"/> instance.</returns>
public static Diagnostic Create(
ErrorCode errorCode,
Location location,
params object[] messageArgs)
{
return Create(errorCode.DiagnosticDescriptor, location, null, null, messageArgs);
}
/// <summary>
/// Creates a <see cref="Diagnostic"/> instance.
/// </summary>
/// <param name="descriptor">A <see cref="DiagnosticDescriptor"/> describing the diagnostic.</param>
/// <param name="location">An optional primary location of the diagnostic. If null, <see cref="Location"/> will return <see cref="Location.None"/>.</param>
/// <param name="properties">
/// An optional set of name-value pairs by means of which the analyzer that creates the diagnostic
/// can convey more detailed information to the fixer. If null, <see cref="Properties"/> will return
/// <see cref="ImmutableDictionary{TKey, TValue}.Empty"/>.
/// </param>
/// <param name="messageArgs">Arguments to the message of the diagnostic.</param>
/// <returns>The <see cref="Diagnostic"/> instance.</returns>
public static Diagnostic Create(
ErrorCode errorCode,
Location location,
ImmutableDictionary<string, string> properties,
params object[] messageArgs)
{
return Create(errorCode.DiagnosticDescriptor, location, null, properties, messageArgs);
}
/// <summary>
/// Creates a <see cref="Diagnostic"/> instance.
/// </summary>
/// <param name="descriptor">A <see cref="DiagnosticDescriptor"/> describing the diagnostic.</param>
/// <param name="location">An optional primary location of the diagnostic. If null, <see cref="Location"/> will return <see cref="Location.None"/>.</param>
/// <param name="additionalLocations">
/// An optional set of additional locations related to the diagnostic.
/// Typically, these are locations of other items referenced in the message.
/// If null, <see cref="AdditionalLocations"/> will return an empty list.
/// </param>
/// <param name="messageArgs">Arguments to the message of the diagnostic.</param>
/// <returns>The <see cref="Diagnostic"/> instance.</returns>
public static Diagnostic Create(
ErrorCode errorCode,
Location location,
IEnumerable<Location> additionalLocations,
params object[] messageArgs)
{
return Create(errorCode.DiagnosticDescriptor, location, additionalLocations, properties: null, messageArgs: messageArgs);
}
/// <summary>
/// Creates a <see cref="Diagnostic"/> instance.
/// </summary>
/// <param name="descriptor">A <see cref="DiagnosticDescriptor"/> describing the diagnostic.</param>
/// <param name="location">An optional primary location of the diagnostic. If null, <see cref="Location"/> will return <see cref="Location.None"/>.</param>
/// <param name="additionalLocations">
/// An optional set of additional locations related to the diagnostic.
/// Typically, these are locations of other items referenced in the message.
/// If null, <see cref="AdditionalLocations"/> will return an empty list.
/// </param>
/// <param name="properties">
/// An optional set of name-value pairs by means of which the analyzer that creates the diagnostic
/// can convey more detailed information to the fixer. If null, <see cref="Properties"/> will return
/// <see cref="ImmutableDictionary{TKey, TValue}.Empty"/>.
/// </param>
/// <param name="messageArgs">Arguments to the message of the diagnostic.</param>
/// <returns>The <see cref="Diagnostic"/> instance.</returns>
public static Diagnostic Create(
ErrorCode errorCode,
Location location,
IEnumerable<Location> additionalLocations,
ImmutableDictionary<string, string> properties,
params object[] messageArgs)
{
return Create(errorCode.DiagnosticDescriptor, location, effectiveSeverity: errorCode.DefaultSeverity, additionalLocations, properties, messageArgs);
}
/// <summary>
/// Creates a <see cref="Diagnostic"/> instance.
/// </summary>
/// <param name="descriptor">A <see cref="DiagnosticDescriptor"/> describing the diagnostic.</param>
/// <param name="location">An optional primary location of the diagnostic. If null, <see cref="Location"/> will return <see cref="Location.None"/>.</param>
/// <param name="effectiveSeverity">Effective severity of the diagnostic.</param>
/// <param name="additionalLocations">
/// An optional set of additional locations related to the diagnostic.
/// Typically, these are locations of other items referenced in the message.
/// If null, <see cref="AdditionalLocations"/> will return an empty list.
/// </param>
/// <param name="properties">
/// An optional set of name-value pairs by means of which the analyzer that creates the diagnostic
/// can convey more detailed information to the fixer. If null, <see cref="Properties"/> will return
/// <see cref="ImmutableDictionary{TKey, TValue}.Empty"/>.
/// </param>
/// <param name="messageArgs">Arguments to the message of the diagnostic.</param>
/// <returns>The <see cref="Diagnostic"/> instance.</returns>
public static Diagnostic Create(
ErrorCode errorCode,
Location location,
DiagnosticSeverity effectiveSeverity,
IEnumerable<Location> additionalLocations,
ImmutableDictionary<string, string> properties,
params object[] messageArgs)
{
return Create(errorCode.DiagnosticDescriptor, location, effectiveSeverity, additionalLocations, properties, messageArgs);
}
public static Diagnostic Create(ErrorCode errorCode)
{
return Create(new LanguageDiagnosticInfo(errorCode));
}
public static Diagnostic Create(ErrorCode errorCode, params object[] arguments)
{
return Create(new LanguageDiagnosticInfo(errorCode, arguments));
}
public static Diagnostic Create(LanguageDiagnosticInfo info)
{
return new DiagnosticWithInfo(info, Location.None);
}
public override Location Location
{
get { return _location; }
}
public override IReadOnlyList<Location> AdditionalLocations
{
get { return this.Info.AdditionalLocations; }
}
internal override IReadOnlyList<string> CustomTags
{
get
{
return this.Info.CustomTags;
}
}
public override DiagnosticDescriptor Descriptor
{
get
{
return this.Info.ErrorCode.DiagnosticDescriptor;
}
}
public override string Id
{
get { return this.Info.MessageIdentifier; }
}
internal override string Category
{
get { return this.Info.Category; }
}
internal sealed override int Code
{
get { return this.Info.Code; }
}
public sealed override DiagnosticSeverity Severity
{
get { return this.Info.Severity; }
}
public sealed override DiagnosticSeverity DefaultSeverity
{
get { return this.Info.DefaultSeverity; }
}
internal sealed override bool IsEnabledByDefault
{
// All compiler errors and warnings are enabled by default.
get { return true; }
}
public override bool IsSuppressed
{
get { return _isSuppressed; }
}
public sealed override int WarningLevel
{
get { return this.Info.WarningLevel; }
}
public override string GetMessage(IFormatProvider formatProvider = null)
{
return this.Info.GetMessage(formatProvider);
}
internal override IReadOnlyList<object> Arguments
{
get { return this.Info.Arguments; }
}
/// <summary>
/// Get the information about the diagnostic: the code, severity, message, etc.
/// </summary>
public LanguageDiagnosticInfo Info
{
get
{
if (_info.Severity == InternalDiagnosticSeverity.Unknown)
{
return (LanguageDiagnosticInfo)_info.GetResolvedInfo();
}
return _info;
}
}
/// <summary>
/// True if the LanguageDiagnosticInfo for this diagnostic requires (or required - this property
/// is immutable) resolution.
/// </summary>
internal bool HasLazyInfo
{
get
{
return _info.Severity == InternalDiagnosticSeverity.Unknown ||
_info.Severity == InternalDiagnosticSeverity.Void;
}
}
public override int GetHashCode()
{
return Hash.Combine(this.Location.GetHashCode(), this.Info.GetHashCode());
}
public override bool Equals(object obj)
{
return Equals(obj as Diagnostic);
}
public override bool Equals(Diagnostic obj)
{
if (this == obj)
{
return true;
}
var other = obj as LanguageDiagnostic;
if (other == null || this.GetType() != other.GetType())
{
return false;
}
return
this.Location.Equals(other._location) &&
this.Info.Equals(other.Info) &&
this.AdditionalLocations.SequenceEqual(other.AdditionalLocations);
}
private string GetDebuggerDisplay()
{
switch (_info.Severity)
{
case InternalDiagnosticSeverity.Unknown:
// If we called ToString before the diagnostic was resolved,
// we would risk infinite recursion (e.g. if we were still computing
// member lists).
return "Unresolved diagnostic at " + this.Location;
case InternalDiagnosticSeverity.Void:
// If we called ToString on a void diagnostic, the MessageProvider
// would complain about the code.
return "Void diagnostic at " + this.Location;
default:
return ToString();
}
}
internal override Diagnostic WithLocation(Location location)
{
if (location == null)
{
throw new ArgumentNullException(nameof(location));
}
if (location != _location)
{
return new LanguageDiagnostic(_info, location, _isSuppressed);
}
return this;
}
internal override Diagnostic WithSeverity(DiagnosticSeverity severity)
{
if (this.Severity != severity)
{
return new LanguageDiagnostic((LanguageDiagnosticInfo)this.Info.GetInstanceWithSeverity(severity), _location, _isSuppressed);
}
return this;
}
internal override Diagnostic WithIsSuppressed(bool isSuppressed)
{
if (this.IsSuppressed != isSuppressed)
{
return new LanguageDiagnostic(this.Info, _location, isSuppressed);
}
return this;
}
internal sealed override bool IsNotConfigurable()
{
return this.Info.IsNotConfigurable();
}
}
}
| 38.174157 | 163 | 0.593304 | [
"Apache-2.0"
] | balazssimon/meta-cs | src/Main/MetaDslx.CodeAnalysis.Meta/CodeAnalysis/Diagnostic/LanguageDiagnostic.cs | 13,590 | C# |
using Gwen.Net.Skin;
namespace Gwen.Net.Control
{
/// <summary>
/// Image container.
/// </summary>
public class ImagePanel : ControlBase
{
private readonly Texture m_Texture;
private readonly float[] m_uv;
private Size m_ImageSize;
/// <summary>
/// Initializes a new instance of the <see cref="ImagePanel" /> class.
/// </summary>
/// <param name="parent">Parent control.</param>
public ImagePanel(ControlBase parent)
: base(parent)
{
m_uv = new float[4];
m_Texture = new Texture(Skin.Renderer);
m_ImageSize = Size.Zero;
SetUV(u1: 0, v1: 0, u2: 1, v2: 1);
MouseInputEnabled = true;
ImageColor = Color.White;
}
/// <summary>
/// Texture name.
/// </summary>
public string ImageName
{
get => m_Texture.Name;
set => m_Texture.Load(value);
}
/// <summary>
/// Gets or sets the size of the image.
/// </summary>
public Size ImageSize
{
get => m_ImageSize;
set
{
if (value == m_ImageSize)
{
return;
}
m_ImageSize = value;
Invalidate();
}
}
/// <summary>
/// Gets or sets the texture coordinates of the image in pixels.
/// </summary>
public Rectangle TextureRect
{
get
{
if (m_Texture == null)
{
return Rectangle.Empty;
}
var x1 = (int) (m_uv[0] * m_Texture.Width);
var y1 = (int) (m_uv[1] * m_Texture.Height);
int x2 = Util.Ceil(m_uv[2] * m_Texture.Width);
int y2 = Util.Ceil(m_uv[3] * m_Texture.Height);
return new Rectangle(x1, y1, x2 - x1, y2 - y1);
}
set
{
if (m_Texture == null)
{
return;
}
m_uv[0] = value.X / (float) m_Texture.Width;
m_uv[1] = value.Y / (float) m_Texture.Height;
m_uv[2] = m_uv[0] + (value.Width / (float) m_Texture.Width);
m_uv[3] = m_uv[1] + (value.Height / (float) m_Texture.Height);
}
}
/// <summary>
/// Gets or sets the color of the image.
/// </summary>
public Color ImageColor { get; set; }
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public override void Dispose()
{
m_Texture.Dispose();
base.Dispose();
}
/// <summary>
/// Sets the texture coordinates of the image in uv-coordinates.
/// </summary>
public virtual void SetUV(float u1, float v1, float u2, float v2)
{
m_uv[0] = u1;
m_uv[1] = v1;
m_uv[2] = u2;
m_uv[3] = v2;
}
/// <summary>
/// Renders the control using specified skin.
/// </summary>
/// <param name="skin">Skin to use.</param>
protected override void Render(SkinBase skin)
{
base.Render(skin);
skin.Renderer.DrawColor = ImageColor;
skin.Renderer.DrawTexturedRect(m_Texture, RenderBounds, m_uv[0], m_uv[1], m_uv[2], m_uv[3]);
}
/// <summary>
/// Control has been clicked - invoked by input system. Windows use it to propagate activation.
/// </summary>
public override void Touch()
{
base.Touch();
}
protected override Size Measure(Size availableSize)
{
if (m_Texture == null)
{
return Size.Zero;
}
float scale = Scale;
Size size = m_ImageSize;
if (size.Width == 0)
{
size.Width = m_Texture.Width;
}
if (size.Height == 0)
{
size.Height = m_Texture.Height;
}
return new Size(Util.Ceil(size.Width * scale), Util.Ceil(size.Height * scale));
}
protected override Size Arrange(Size finalSize)
{
return finalSize;
}
/// <summary>
/// Handler for Space keyboard event.
/// </summary>
/// <param name="down">Indicates whether the key was pressed or released.</param>
/// <returns>
/// True if handled.
/// </returns>
protected override bool OnKeySpace(bool down)
{
if (down)
{
base.OnMouseClickedLeft(x: 0, y: 0, down: true);
}
return true;
}
}
}
| 28.088889 | 120 | 0.458465 | [
"MIT"
] | pershingthesecond/Gwen.Net | Gwen.Net/Control/ImagePanel.cs | 5,058 | C# |
// SPDX-License-Identifier: BSD-3-Clause
//
// Copyright 2020 Raritan Inc. All rights reserved.
//
// This file was generated by IdlC from Ade.idl.
using System;
using System.Linq;
using LightJson;
using Com.Raritan.Idl;
using Com.Raritan.JsonRpc;
using Com.Raritan.Util;
#pragma warning disable 0108, 0219, 0414, 1591
namespace Com.Raritan.Idl.pdumodel {
public class Ade : ObjectProxy {
static public readonly new TypeInfo typeInfo = new TypeInfo("pdumodel.Ade:1.0.0", null);
public Ade(Agent agent, string rid, TypeInfo ti) : base(agent, rid, ti) {}
public Ade(Agent agent, string rid) : this(agent, rid, typeInfo) {}
public static new Ade StaticCast(ObjectProxy proxy) {
return proxy == null ? null : new Ade(proxy.Agent, proxy.Rid, proxy.StaticTypeInfo);
}
public class MetaData : ICloneable {
public object Clone() {
MetaData copy = new MetaData();
copy.adeType = this.adeType;
copy.channels = this.channels;
copy.currentDivider = this.currentDivider;
copy.voltageDivider = this.voltageDivider;
copy.energyDivider = this.energyDivider;
return copy;
}
public LightJson.JsonObject Encode() {
LightJson.JsonObject json = new LightJson.JsonObject();
json["adeType"] = this.adeType;
json["channels"] = this.channels;
json["currentDivider"] = this.currentDivider;
json["voltageDivider"] = this.voltageDivider;
json["energyDivider"] = this.energyDivider;
return json;
}
public static MetaData Decode(LightJson.JsonObject json, Agent agent) {
MetaData inst = new MetaData();
inst.adeType = (string)json["adeType"];
inst.channels = (int)json["channels"];
inst.currentDivider = (double)json["currentDivider"];
inst.voltageDivider = (double)json["voltageDivider"];
inst.energyDivider = (double)json["energyDivider"];
return inst;
}
public string adeType = "";
public int channels = 0;
public double currentDivider = 0.0;
public double voltageDivider = 0.0;
public double energyDivider = 0.0;
}
public class Sample : ICloneable {
public object Clone() {
Sample copy = new Sample();
copy.vrms = this.vrms;
copy.irms = this.irms;
copy.watt = this.watt;
copy.va = this.va;
copy.wh = this.wh;
copy.vah = this.vah;
return copy;
}
public LightJson.JsonObject Encode() {
LightJson.JsonObject json = new LightJson.JsonObject();
json["vrms"] = this.vrms;
json["irms"] = this.irms;
json["watt"] = this.watt;
json["va"] = this.va;
json["wh"] = this.wh;
json["vah"] = this.vah;
return json;
}
public static Sample Decode(LightJson.JsonObject json, Agent agent) {
Sample inst = new Sample();
inst.vrms = (long)json["vrms"];
inst.irms = (long)json["irms"];
inst.watt = (long)json["watt"];
inst.va = (long)json["va"];
inst.wh = (long)json["wh"];
inst.vah = (long)json["vah"];
return inst;
}
public long vrms = 0;
public long irms = 0;
public long watt = 0;
public long va = 0;
public long wh = 0;
public long vah = 0;
}
public class GetMetaDataResult {
public Com.Raritan.Idl.pdumodel.Ade.MetaData _ret_;
}
public GetMetaDataResult getMetaData() {
JsonObject _parameters = null;
var _result = RpcCall("getMetaData", _parameters);
var _ret = new GetMetaDataResult();
_ret._ret_ = Com.Raritan.Idl.pdumodel.Ade.MetaData.Decode(_result["_ret_"], agent);
return _ret;
}
public AsyncRequest getMetaData(AsyncRpcResponse<GetMetaDataResult>.SuccessHandler rsp, AsyncRpcResponse.FailureHandler fail) {
return getMetaData(rsp, fail, RpcCtrl.Default);
}
public AsyncRequest getMetaData(AsyncRpcResponse<GetMetaDataResult>.SuccessHandler rsp, AsyncRpcResponse.FailureHandler fail, RpcCtrl rpcCtrl) {
JsonObject _parameters = null;
return RpcCall("getMetaData", _parameters,
_result => {
try {
var _ret = new GetMetaDataResult();
_ret._ret_ = Com.Raritan.Idl.pdumodel.Ade.MetaData.Decode(_result["_ret_"], agent);
rsp(_ret);
} catch (Exception e) {
if (fail != null) fail(e);
}
}, fail, rpcCtrl);
}
public class GetLatestSampleResult {
public System.Collections.Generic.IEnumerable<Com.Raritan.Idl.pdumodel.Ade.Sample> _ret_;
}
public GetLatestSampleResult getLatestSample() {
JsonObject _parameters = null;
var _result = RpcCall("getLatestSample", _parameters);
var _ret = new GetLatestSampleResult();
_ret._ret_ = new System.Collections.Generic.List<Com.Raritan.Idl.pdumodel.Ade.Sample>(_result["_ret_"].AsJsonArray.Select(
_value => Com.Raritan.Idl.pdumodel.Ade.Sample.Decode(_value, agent)));
return _ret;
}
public AsyncRequest getLatestSample(AsyncRpcResponse<GetLatestSampleResult>.SuccessHandler rsp, AsyncRpcResponse.FailureHandler fail) {
return getLatestSample(rsp, fail, RpcCtrl.Default);
}
public AsyncRequest getLatestSample(AsyncRpcResponse<GetLatestSampleResult>.SuccessHandler rsp, AsyncRpcResponse.FailureHandler fail, RpcCtrl rpcCtrl) {
JsonObject _parameters = null;
return RpcCall("getLatestSample", _parameters,
_result => {
try {
var _ret = new GetLatestSampleResult();
_ret._ret_ = new System.Collections.Generic.List<Com.Raritan.Idl.pdumodel.Ade.Sample>(_result["_ret_"].AsJsonArray.Select(
_value => Com.Raritan.Idl.pdumodel.Ade.Sample.Decode(_value, agent)));
rsp(_ret);
} catch (Exception e) {
if (fail != null) fail(e);
}
}, fail, rpcCtrl);
}
public class GetCalibrationDataResult {
public System.Collections.Generic.IDictionary<string, long> _ret_;
}
public GetCalibrationDataResult getCalibrationData() {
JsonObject _parameters = null;
var _result = RpcCall("getCalibrationData", _parameters);
var _ret = new GetCalibrationDataResult();
_ret._ret_ = DictionaryHelper.Create(_result["_ret_"].AsJsonArray.Select(
_value => new System.Collections.Generic.KeyValuePair<string, long>(_value["key"], (long)_value["value"])));
return _ret;
}
public AsyncRequest getCalibrationData(AsyncRpcResponse<GetCalibrationDataResult>.SuccessHandler rsp, AsyncRpcResponse.FailureHandler fail) {
return getCalibrationData(rsp, fail, RpcCtrl.Default);
}
public AsyncRequest getCalibrationData(AsyncRpcResponse<GetCalibrationDataResult>.SuccessHandler rsp, AsyncRpcResponse.FailureHandler fail, RpcCtrl rpcCtrl) {
JsonObject _parameters = null;
return RpcCall("getCalibrationData", _parameters,
_result => {
try {
var _ret = new GetCalibrationDataResult();
_ret._ret_ = DictionaryHelper.Create(_result["_ret_"].AsJsonArray.Select(
_value => new System.Collections.Generic.KeyValuePair<string, long>(_value["key"], (long)_value["value"])));
rsp(_ret);
} catch (Exception e) {
if (fail != null) fail(e);
}
}, fail, rpcCtrl);
}
public class SetCalibrationDataResult {
public int _ret_;
}
public SetCalibrationDataResult setCalibrationData(System.Collections.Generic.IDictionary<string, long> regs) {
var _parameters = new LightJson.JsonObject();
_parameters["regs"] = new JsonArray(regs.Select(_entry => (JsonValue) new JsonObject(new System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<string, LightJson.JsonValue>> {
new System.Collections.Generic.KeyValuePair<string, JsonValue>("key", _entry.Key),
new System.Collections.Generic.KeyValuePair<string, JsonValue>("value", _entry.Value)
})));
var _result = RpcCall("setCalibrationData", _parameters);
var _ret = new SetCalibrationDataResult();
_ret._ret_ = (int)_result["_ret_"];
return _ret;
}
public AsyncRequest setCalibrationData(System.Collections.Generic.IDictionary<string, long> regs, AsyncRpcResponse<SetCalibrationDataResult>.SuccessHandler rsp, AsyncRpcResponse.FailureHandler fail) {
return setCalibrationData(regs, rsp, fail, RpcCtrl.Default);
}
public AsyncRequest setCalibrationData(System.Collections.Generic.IDictionary<string, long> regs, AsyncRpcResponse<SetCalibrationDataResult>.SuccessHandler rsp, AsyncRpcResponse.FailureHandler fail, RpcCtrl rpcCtrl) {
var _parameters = new LightJson.JsonObject();
try {
_parameters["regs"] = new JsonArray(regs.Select(_entry => (JsonValue) new JsonObject(new System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<string, LightJson.JsonValue>> {
new System.Collections.Generic.KeyValuePair<string, JsonValue>("key", _entry.Key),
new System.Collections.Generic.KeyValuePair<string, JsonValue>("value", _entry.Value)
})));
} catch (Exception e) {
if (fail != null) fail(e);
}
return RpcCall("setCalibrationData", _parameters,
_result => {
try {
var _ret = new SetCalibrationDataResult();
_ret._ret_ = (int)_result["_ret_"];
rsp(_ret);
} catch (Exception e) {
if (fail != null) fail(e);
}
}, fail, rpcCtrl);
}
}
}
| 38.955645 | 221 | 0.656247 | [
"BSD-3-Clause"
] | gregoa/raritan-pdu-json-rpc-sdk | pdu-dotnet-api/_idlc_gen/dotnet/Com/Raritan/Idl/pdumodel/Ade.cs | 9,661 | C# |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** File: RemotingAttributes.cs
**
** Purpose: Custom attributes for modifying remoting interactions.
**
** Date: Oct 5, 2000
**
===========================================================*/
namespace System.Runtime.Remoting.Metadata
{
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Metadata;
using System.Reflection;
using System.Threading;
// This is the data we store in MemberInfo.CachedData, mainly to cache custom
// attributes.
internal class RemotingCachedData
{
protected Object RI; // reflection structure on which this data structure is stored
private SoapAttribute _soapAttr = null; // Soap related attributes derive from SoapAttribute
internal RemotingCachedData(Object ri)
{
RI = ri;
} // RemotingCachedData
// Retrieve SOAP attribute info for _mi (or create for caching if not specified)
internal SoapAttribute GetSoapAttribute()
{
if (_soapAttr == null)
{
lock (this)
{
if (_soapAttr == null)
{
SoapAttribute tempSoapAttr = null;
ICustomAttributeProvider cap = (ICustomAttributeProvider)RI;
if (RI is Type)
{
Object[] attrs = cap.GetCustomAttributes(typeof(SoapTypeAttribute), true);
if ((attrs != null) && (attrs.Length != 0))
tempSoapAttr = (SoapAttribute)attrs[0];
else
tempSoapAttr = new SoapTypeAttribute();
}
else
if (RI is MethodBase)
{
Object[] attrs = cap.GetCustomAttributes(typeof(SoapMethodAttribute), true);
if ((attrs != null) && (attrs.Length != 0))
tempSoapAttr = (SoapAttribute)attrs[0];
else
tempSoapAttr = new SoapMethodAttribute();
}
else
if (RI is FieldInfo)
{
Object[] attrs = cap.GetCustomAttributes(typeof(SoapFieldAttribute), false);
if ((attrs != null) && (attrs.Length != 0))
tempSoapAttr = (SoapAttribute)attrs[0];
else
tempSoapAttr = new SoapFieldAttribute();
}
else
if (RI is ParameterInfo)
{
Object[] attrs = cap.GetCustomAttributes(typeof(SoapParameterAttribute), true);
if ((attrs != null) && (attrs.Length != 0))
tempSoapAttr = (SoapParameterAttribute)attrs[0];
else
tempSoapAttr = new SoapParameterAttribute();
}
// IMPORTANT: This has to be done for certain values to be automatically
// generated in the attribute.
tempSoapAttr.SetReflectInfo(RI);
_soapAttr = tempSoapAttr;
} // if (_soapAttr == null)
} // lock (this)
}
return _soapAttr;
} // GetSoapAttribute
} // class RemotingCachedData
internal class RemotingTypeCachedData : RemotingCachedData
{
private class LastCalledMethodClass
{
public String methodName;
public MethodBase MB;
}
private LastCalledMethodClass _lastMethodCalled; // cache for last method that was called
private TypeInfo _typeInfo; // type info to be used for ObjRef's of this type
private String _qualifiedTypeName;
private String _simpleAssemblyName; // (no strong name, version, etc.)
internal RemotingTypeCachedData(Object ri) : base(ri)
{
_lastMethodCalled = null;
}
internal MethodBase GetLastCalledMethod(String newMeth)
{
LastCalledMethodClass lastMeth = _lastMethodCalled;
if (lastMeth == null)
return null;
String methodName = lastMeth.methodName;
MethodBase mbToReturn = lastMeth.MB;
if (mbToReturn==null || methodName==null)
return null;
if (methodName.Equals(newMeth))
return mbToReturn;
return null;
} // GetLastCalledMethod
internal void SetLastCalledMethod(String newMethName, MethodBase newMB)
{
LastCalledMethodClass lastMeth = new LastCalledMethodClass();
lastMeth.methodName = newMethName;
lastMeth.MB = newMB;
_lastMethodCalled = lastMeth;
} // SetLastCalledMethod
// Retrieve TypeInfo object to be used in ObjRef.
internal TypeInfo TypeInfo
{
get
{
if (_typeInfo == null)
_typeInfo = new TypeInfo((Type)RI);
return _typeInfo;
}
} // TypeInfo
internal String QualifiedTypeName
{
get
{
if (_qualifiedTypeName == null)
_qualifiedTypeName = RemotingServices.DetermineDefaultQualifiedTypeName((Type)RI);
return _qualifiedTypeName;
}
} // QualifiedTypeName
internal String SimpleAssemblyName
{
get
{
if (_simpleAssemblyName == null)
_simpleAssemblyName = ((Type)RI).Module.Assembly.nGetSimpleName();
return _simpleAssemblyName;
}
} // SimpleAssemblyName
} // class RemotingTypeCachedData
internal class RemotingMethodCachedData : RemotingCachedData
{
ParameterInfo[] _parameters = null; // list of parameters (cached because reflection always
// generates a new copy of this array)
[Flags, Serializable]
private enum MethodCacheFlags
{
None = 0x00,
CheckedOneWay = 0x01, // Have we checked for OneWay attribute?
IsOneWay = 0x02, // Is the OneWay attribute present?
CheckedOverloaded = 0x04, // Have we checked to see if this method is overloaded
IsOverloaded = 0x08, // Is the method overloaded?
CheckedForAsync = 0x10, // Have we looked for async versions of this method?
CheckedForReturnType = 0x20, // Have we looked for the return type?
}
MethodCacheFlags flags;
// Names
String _typeAndAssemblyName = null;
String _methodName = null;
Type _returnType = null; // null if return type is void or .ctor
// parameter maps
int[] _inRefArgMap = null; // parameter map of input and ref parameters
int[] _outRefArgMap = null; // parameter map of output and ref parameters
int[] _outOnlyArgMap = null; // parameter map of only output parameters
int[] _nonRefOutArgMap = null; // parameter map of non byref parameters marked with [In, Out] (or [Out])
int[] _marshalRequestMap = null; // map of parameters that should be marshaled in
int[] _marshalResponseMap = null; // map of parameters that should be marshaled out
RemotingAsyncMethodCachedData _asyncMethodData = null; // information about async method versions
internal RemotingMethodCachedData(Object ri) : base(ri)
{
}
internal String TypeAndAssemblyName
{
get
{
if (_typeAndAssemblyName == null)
UpdateNames();
return _typeAndAssemblyName;
}
} // TypeAndAssemblyName
internal String MethodName
{
get
{
if (_methodName == null)
UpdateNames();
return _methodName;
}
} // MethodName
private void UpdateNames()
{
MethodBase mb = (MethodBase)RI;
_methodName = mb.Name;
_typeAndAssemblyName = RemotingServices.GetDefaultQualifiedTypeName(mb.DeclaringType);
} // UpdateNames
internal ParameterInfo[] Parameters
{
get
{
if (_parameters == null)
_parameters = ((MethodBase)RI).GetParameters();
return _parameters;
}
} // Parameters
// contains index of all normal parameters and parameters marked as ref
internal int[] InRefArgMap
{
get
{
if (_inRefArgMap == null)
GetArgMaps();
return _inRefArgMap;
}
} // InRefArgMap
// contains index of all parameters marked as out or ref
internal int[] OutRefArgMap
{
get
{
if (_outRefArgMap == null)
GetArgMaps();
return _outRefArgMap;
}
} // OutRefArgMap
// contains index of parameters marked as out
internal int[] OutOnlyArgMap
{
get
{
if (_outOnlyArgMap == null)
GetArgMaps();
return _outOnlyArgMap;
}
} // OutOnlyArgMap
// contains index of non byref parameters marked with [In, Out]
internal int[] NonRefOutArgMap
{
get
{
if (_nonRefOutArgMap == null)
GetArgMaps();
return _nonRefOutArgMap;
}
} // NonRefOutArgMap
// contains index of parameters that should be marshalled for a request
internal int[] MarshalRequestArgMap
{
get
{
if (_marshalRequestMap == null)
GetArgMaps();
return _marshalRequestMap;
}
} // MarshalRequestMap
// contains index of parameters that should be marshalled for a response
internal int[] MarshalResponseArgMap
{
get
{
if (_marshalResponseMap == null)
GetArgMaps();
return _marshalResponseMap;
}
} // MarshalResponseArgMap
private void GetArgMaps()
{
lock (this)
{
if (_inRefArgMap == null)
{
ArgMapper.GetParameterMaps(Parameters,
out _inRefArgMap, out _outRefArgMap, out _outOnlyArgMap,
out _nonRefOutArgMap,
out _marshalRequestMap, out _marshalResponseMap);
}
}
} // GetArgMaps
internal bool IsOneWayMethod()
{
// We are not protecting against a race
// If there is a race while setting flags
// we will have to compute the result again,
// but we will always return the correct result
//
if ((flags & MethodCacheFlags.CheckedOneWay) == 0)
{
MethodCacheFlags isOneWay = MethodCacheFlags.CheckedOneWay;
Object[] attrs =
((ICustomAttributeProvider)RI).GetCustomAttributes(typeof(OneWayAttribute), true);
if ((attrs != null) && (attrs.Length > 0))
isOneWay |= MethodCacheFlags.IsOneWay;
flags |= isOneWay;
return (isOneWay & MethodCacheFlags.IsOneWay) != 0;
}
return (flags & MethodCacheFlags.IsOneWay) != 0;
} // IsOneWayMethod
internal bool IsOverloaded()
{
// We are not protecting against a race
// If there is a race while setting flags
// we will have to compute the result again,
// but we will always return the correct result
//
if ((flags & MethodCacheFlags.CheckedOverloaded) == 0)
{
MethodCacheFlags isOverloaded = MethodCacheFlags.CheckedOverloaded;
MethodBase mb = (MethodBase)RI;
if (mb.IsOverloaded)
isOverloaded |= MethodCacheFlags.IsOverloaded;
flags |= isOverloaded;
return (isOverloaded & MethodCacheFlags.IsOverloaded) != 0;
}
return (flags & MethodCacheFlags.IsOverloaded) != 0;
} // IsOverloaded
// This will return the return type of the method, or null
// if the return type is void or this is a .ctor.
internal Type ReturnType
{
get
{
if ((flags & MethodCacheFlags.CheckedForReturnType) == 0)
{
MethodInfo mi = RI as MethodInfo;
if (mi != null)
{
Type returnType = mi.ReturnType;
if (returnType != typeof(void))
_returnType = returnType;
}
flags |= MethodCacheFlags.CheckedForReturnType;
}
return _returnType;
} // get
} // ReturnType
internal bool GetAsyncMethodVersion(out MethodInfo begin, out MethodInfo end)
{
// synchronization doesn't matter (methods always return same value)
if ((flags & MethodCacheFlags.CheckedForAsync) == 0)
{
// look for async versions of this method
// FUTURE: In V.Next, there should be an attribute to indicate that
// async processing is desired.
if (RemotingServices.FindAsyncMethodVersion((MethodInfo)RI, out begin, out end))
{
RemotingAsyncMethodCachedData async = new RemotingAsyncMethodCachedData();
async.BeginMethodInfo = begin;
async.EndMethodInfo = end;
_asyncMethodData = async;
}
else
{
_asyncMethodData = null;
}
flags |= MethodCacheFlags.CheckedForAsync;
}
if (_asyncMethodData != null)
{
begin = _asyncMethodData.BeginMethodInfo;
end = _asyncMethodData.EndMethodInfo;
return true;
}
else
{
// there are no async versions of this method
begin = null;
end = null;
return false;
}
} // GetAsyncMethodVersion
//
// STORAGE CLASSES
//
// possibly created by RemotingMethodCachedData if a method has special information
// correlating it to its async versions.
private class RemotingAsyncMethodCachedData
{
public MethodInfo BeginMethodInfo;
public MethodInfo EndMethodInfo;
} // class RemotingAsyncMethodCachedData
} // class RemotingMethodCachedData
//
// SOAP ATTRIBUTES
//
// Options for use with SoapOptionAttribute (combine with OR to get any combination)
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapOption"]/*' />
[Flags, Serializable]
public enum SoapOption
{
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapOption.None"]/*' />
None = 0x0,
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapOption.AlwaysIncludeTypes"]/*' />
AlwaysIncludeTypes = 0x1, // xsi:type always included on SOAP elements
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapOption.XsdString"]/*' />
XsdString = 0x2, // xsi:type always included on SOAP elements
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapOption.EmbedAll"]/*' />
EmbedAll = 0x4, // Soap will be generated without references
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapOption.Option1"]/*' />
/// <internalonly/>
Option1 = 0x8, // Option for temporary interop conditions, the use will change over time
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapOption.Option2"]/*' />
/// <internalonly/>
Option2 = 0x10, // Option for temporary interop conditions, the use will change over time
} // SoapOption
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="XmlFieldOrderOption"]/*' />
/// <internalonly/>
[Serializable]
public enum XmlFieldOrderOption
{
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="XmlFieldOrderOption.All"]/*' />
All,
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="XmlFieldOrderOption.Sequence"]/*' />
Sequence,
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="XmlFieldOrderOption.Choice"]/*' />
Choice
} // XmlFieldOrderOption
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapTypeAttribute"]/*' />
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Enum)]
public sealed class SoapTypeAttribute : SoapAttribute
{
// Used to track which values have been explicitly set. Information needed
// by SoapServices.
[Flags, Serializable]
private enum ExplicitlySet
{
None = 0x0,
XmlElementName = 0x1,
XmlNamespace = 0x2,
XmlTypeName = 0x4,
XmlTypeNamespace = 0x8
}
private ExplicitlySet _explicitlySet = ExplicitlySet.None;
private SoapOption _SoapOptions = SoapOption.None;
private String _XmlElementName = null;
private String _XmlTypeName = null;
private String _XmlTypeNamespace = null;
private XmlFieldOrderOption _XmlFieldOrder = XmlFieldOrderOption.All;
// Returns true if this attribute specifies interop xml element values.
internal bool IsInteropXmlElement()
{
return (_explicitlySet & (ExplicitlySet.XmlElementName | ExplicitlySet.XmlNamespace)) != 0;
} // IsInteropXmlElement
internal bool IsInteropXmlType()
{
return (_explicitlySet & (ExplicitlySet.XmlTypeName | ExplicitlySet.XmlTypeNamespace)) != 0;
} // IsInteropXmlType
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapTypeAttribute.SoapOptions"]/*' />
public SoapOption SoapOptions
{
get { return _SoapOptions; }
set { _SoapOptions = value; }
} // SoapOptions
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapTypeAttribute.XmlElementName"]/*' />
public String XmlElementName
{
get
{
// generate this if it hasn't been set yet
if ((_XmlElementName == null) && (ReflectInfo != null))
_XmlElementName = ((Type)ReflectInfo).Name;
return _XmlElementName;
}
set
{
_XmlElementName = value;
_explicitlySet |= ExplicitlySet.XmlElementName;
}
} // XmlElementName
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapTypeAttribute.XmlNamespace"]/*' />
public override String XmlNamespace
{
get
{
// generate this if it hasn't been set
if ((ProtXmlNamespace == null) && (ReflectInfo != null))
{
ProtXmlNamespace = XmlTypeNamespace;
}
return ProtXmlNamespace;
}
set
{
ProtXmlNamespace = value;
_explicitlySet |= ExplicitlySet.XmlNamespace;
}
} // XmlNamespace
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapTypeAttribute.XmlTypeName"]/*' />
public String XmlTypeName // value for xml type name (this should always be valid)
{
get
{
// generate this if it hasn't been set yet
if ((_XmlTypeName == null) && (ReflectInfo != null))
_XmlTypeName = ((Type)ReflectInfo).Name;
return _XmlTypeName;
}
set
{
_XmlTypeName = value;
_explicitlySet |= ExplicitlySet.XmlTypeName;
}
} // XmlTypeName
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapTypeAttribute.XmlTypeNamespace"]/*' />
public String XmlTypeNamespace // value for xml type namespace (this should always be valid)
{
get
{
// generate this if it hasn't been set yet
if ((_XmlTypeNamespace == null) && (ReflectInfo != null))
{
_XmlTypeNamespace =
XmlNamespaceEncoder.GetXmlNamespaceForTypeNamespace((Type)ReflectInfo, null);
}
return _XmlTypeNamespace;
}
set
{
_XmlTypeNamespace = value;
_explicitlySet |= ExplicitlySet.XmlTypeNamespace;
}
} // XmlTypeNamespace
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapTypeAttribute.XmlFieldOrder"]/*' />
/// <internalonly/>
public XmlFieldOrderOption XmlFieldOrder
{
get { return _XmlFieldOrder; }
set { _XmlFieldOrder = value; }
} // XmlFieldOrder
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapTypeAttribute.UseAttribute"]/*' />
public override bool UseAttribute
{
get { return false; }
set { throw new RemotingException(
Environment.GetResourceString("Remoting_Attribute_UseAttributeNotsettable")); }
} // UseAttribute
} // class SoapTypeAttribute
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapMethodAttribute"]/*' />
[AttributeUsage(AttributeTargets.Method)]
public sealed class SoapMethodAttribute : SoapAttribute
{
private String _SoapAction = null;
private String _responseXmlElementName = null;
private String _responseXmlNamespace = null;
private String _returnXmlElementName = null;
private bool _bSoapActionExplicitySet = false; // Needed by SoapServices to determine if
// SoapAction was actually set (otherwise,
// accessing it will return a generated
// value)
internal bool SoapActionExplicitySet { get { return _bSoapActionExplicitySet; } }
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapMethodAttribute.SoapAction"]/*' />
public String SoapAction // SoapAction value to place in protocol headers.
{
get
{
// generate this if it hasn't been set
if (_SoapAction == null)
{
_SoapAction = XmlTypeNamespaceOfDeclaringType + "#" +
((MemberInfo)ReflectInfo).Name; // This will be the method name.
}
return _SoapAction;
}
set
{
_SoapAction = value;
_bSoapActionExplicitySet = true;
}
}
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapMethodAttribute.UseAttribute"]/*' />
public override bool UseAttribute
{
get { return false; }
set { throw new RemotingException(
Environment.GetResourceString("Remoting_Attribute_UseAttributeNotsettable")); }
}
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapMethodAttribute.XmlNamespace"]/*' />
public override String XmlNamespace
{
get
{
// generate this if it hasn't been set
if (ProtXmlNamespace == null)
{
ProtXmlNamespace = XmlTypeNamespaceOfDeclaringType;
}
return ProtXmlNamespace;
}
set { ProtXmlNamespace = value; }
} // XmlNamespace
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapMethodAttribute.ResponseXmlElementName"]/*' />
public String ResponseXmlElementName
{
get
{
// generate this if it hasn't been set yet
if ((_responseXmlElementName == null) && (ReflectInfo != null))
_responseXmlElementName = ((MemberInfo)ReflectInfo).Name + "Response";
return _responseXmlElementName;
}
set { _responseXmlElementName = value; }
} // ResponseXmlElementName
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapMethodAttribute.ResponseXmlNamespace"]/*' />
public String ResponseXmlNamespace
{
get
{
// generate this if it hasn't been set
if (_responseXmlNamespace == null)
_responseXmlNamespace = XmlNamespace;
return _responseXmlNamespace;
}
set { _responseXmlNamespace = value; }
} // ResponseXmlNamespace
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapMethodAttribute.ReturnXmlElementName"]/*' />
public String ReturnXmlElementName
{
get
{
// generate this if it hasn't been set yet
if (_returnXmlElementName == null)
_returnXmlElementName = "return";
return _returnXmlElementName;
}
set { _returnXmlElementName = value; }
} // ReturnXmlElementName
private String XmlTypeNamespaceOfDeclaringType
{
get
{
if (ReflectInfo != null)
{
Type declaringType = ((MemberInfo)ReflectInfo).DeclaringType;
return XmlNamespaceEncoder.GetXmlNamespaceForType(declaringType, null);
}
else
return null;
}
} // XmlTypeNamespaceOfDeclaringType
} // class SoapMethodAttribute
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapFieldAttribute"]/*' />
[AttributeUsage(AttributeTargets.Field)]
public sealed class SoapFieldAttribute : SoapAttribute
{
// Used to track which values have been explicitly set. Information needed
// by SoapServices.
[Flags, Serializable]
private enum ExplicitlySet
{
None = 0x0,
XmlElementName = 0x1
}
private ExplicitlySet _explicitlySet = ExplicitlySet.None;
private String _xmlElementName = null;
private int _order; // order in which fields should be serialized
// (if Sequence is specified on containing type's SoapTypeAttribute
// Returns true if this attribute specifies interop xml element values.
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapFieldAttribute.IsInteropXmlElement"]/*' />
public bool IsInteropXmlElement()
{
return (_explicitlySet & ExplicitlySet.XmlElementName) != 0;
} // GetInteropXmlElement
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapFieldAttribute.XmlElementName"]/*' />
public String XmlElementName
{
get
{
// generate this if it hasn't been set yet
if ((_xmlElementName == null) && (ReflectInfo != null))
_xmlElementName = ((FieldInfo)ReflectInfo).Name;
return _xmlElementName;
}
set
{
_xmlElementName = value;
_explicitlySet |= ExplicitlySet.XmlElementName;
}
} // XmlElementName
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapFieldAttribute.Order"]/*' />
/// <internalonly/>
public int Order
{
get { return _order; }
set { _order = value; }
}
} // class SoapFieldAttribute
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapParameterAttribute"]/*' />
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class SoapParameterAttribute : SoapAttribute
{
} // SoapParameterAttribute
// Not actually used as an attribute (just the base for the rest of them)
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapAttribute"]/*' />
public class SoapAttribute : Attribute
{
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapAttribute.ProtXmlNamespace"]/*' />
/// <internalonly/>
protected String ProtXmlNamespace = null;
private bool _bUseAttribute = false;
private bool _bEmbedded = false;
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapAttribute.ReflectInfo"]/*' />
/// <internalonly/>
protected Object ReflectInfo = null; // Reflection structure on which this attribute was defined
// IMPORTANT: The caching mechanism is required to set this value before
// handing back a SoapAttribute, so that certain values can be automatically
// generated.
internal void SetReflectInfo(Object info)
{
ReflectInfo = info;
}
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapAttribute.XmlNamespace"]/*' />
public virtual String XmlNamespace // If this returns null, then this shouldn't be namespace qualified.
{
get { return ProtXmlNamespace; }
set { ProtXmlNamespace = value; }
}
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapAttribute.UseAttribute"]/*' />
public virtual bool UseAttribute
{
get { return _bUseAttribute; }
set { _bUseAttribute = value; }
}
/// <include file='doc\RemotingAttributes.uex' path='docs/doc[@for="SoapAttribute.Embedded"]/*' />
public virtual bool Embedded // Determines if type should be nested when serializing for SOAP.
{
get { return _bEmbedded; }
set { _bEmbedded = value; }
}
} // class SoapAttribute
//
// END OF SOAP ATTRIBUTES
//
} // namespace System.Runtime.Remoting
| 37.363938 | 127 | 0.51538 | [
"Unlicense"
] | bestbat/Windows-Server | com/netfx/src/clr/bcl/system/runtime/remoting/remotingattributes.cs | 33,777 | 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 System.Linq;
using System.Threading.Tasks;
namespace SessionSample.Models
{
public class ErrorViewModel
{
}
}
| 34.821429 | 75 | 0.758974 | [
"Apache-2.0"
] | Nordix/geode-native | netcore/asp-netcore-session-sample/Models/ErrorViewModel.cs | 977 | C# |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Input;
using System.Windows.Navigation;
using TRGE.Coord;
using TRGE.View.Model;
using TRGE.View.Updates;
using TRGE.View.Utils;
namespace TRGE.View.Windows
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, IRecentFolderOpener
{
#region Dependency Properties
public static readonly DependencyProperty IsEditorActiveProperty = DependencyProperty.Register
(
"IsEditorActive", typeof(bool), typeof(MainWindow)
);
public static readonly DependencyProperty IsEditorDirtyProperty = DependencyProperty.Register
(
"IsEditorDirty", typeof(bool), typeof(MainWindow)
);
public static readonly DependencyProperty EditorCanExportProperty = DependencyProperty.Register
(
"EditorCanExport", typeof(bool), typeof(MainWindow)
);
public static readonly DependencyProperty CanEmptyRecentFoldersProperty = DependencyProperty.Register
(
"CanEmptyRecentFolders", typeof(bool), typeof(MainWindow)
);
public static readonly DependencyProperty FolderControlVisibilityProperty = DependencyProperty.Register
(
"FolderControlVisibility", typeof(Visibility), typeof(MainWindow)
);
public static readonly DependencyProperty EditorControlVisibilityProperty = DependencyProperty.Register
(
"EditorControlVisibility", typeof(Visibility), typeof(MainWindow)
);
public static readonly DependencyProperty EditorStatusVisibilityProperty = DependencyProperty.Register
(
"EditorStatusVisibility", typeof(Visibility), typeof(MainWindow)
);
public static readonly DependencyProperty EditorSavedStatusVisibilityProperty = DependencyProperty.Register
(
"EditorSavedStatusVisibility", typeof(Visibility), typeof(MainWindow)
);
public static readonly DependencyProperty EditorUnsavedStatusVisibilityProperty = DependencyProperty.Register
(
"EditorUnsavedStatusVisibility", typeof(Visibility), typeof(MainWindow)
);
public static readonly DependencyProperty RecentFoldersProperty = DependencyProperty.Register
(
"RecentFolders", typeof(RecentFolderList), typeof(MainWindow)
);
public static readonly DependencyProperty HasRecentFoldersProperty = DependencyProperty.Register
(
"HasRecentFolders", typeof(bool), typeof(MainWindow)
);
public bool IsEditorActive
{
get => (bool)GetValue(IsEditorActiveProperty);
set
{
SetValue(IsEditorActiveProperty, value);
FolderControlVisibility = value ? Visibility.Collapsed : Visibility.Visible;
EditorControlVisibility = value ? Visibility.Visible : Visibility.Collapsed;
EditorStatusVisibility = value ? Visibility.Visible : Visibility.Hidden;
CanEmptyRecentFolders = !value;
}
}
public bool IsEditorDirty
{
get => (bool)GetValue(IsEditorDirtyProperty);
set
{
SetValue(IsEditorDirtyProperty, value);
EditorSavedStatusVisibility = !value ? Visibility.Visible : Visibility.Collapsed;
EditorUnsavedStatusVisibility = value ? Visibility.Visible : Visibility.Collapsed;
}
}
public bool EditorCanExport
{
get => (bool)GetValue(EditorCanExportProperty);
set => SetValue(EditorCanExportProperty, value);
}
public Visibility EditorControlVisibility
{
get => (Visibility)GetValue(EditorControlVisibilityProperty);
set => SetValue(EditorControlVisibilityProperty, value);
}
public Visibility EditorStatusVisibility
{
get => (Visibility)GetValue(EditorStatusVisibilityProperty);
set => SetValue(EditorStatusVisibilityProperty, value);
}
public Visibility EditorSavedStatusVisibility
{
get => (Visibility)GetValue(EditorSavedStatusVisibilityProperty);
set => SetValue(EditorSavedStatusVisibilityProperty, value);
}
public Visibility EditorUnsavedStatusVisibility
{
get => (Visibility)GetValue(EditorUnsavedStatusVisibilityProperty);
set => SetValue(EditorUnsavedStatusVisibilityProperty, value);
}
public bool CanEmptyRecentFolders
{
get => (bool)GetValue(CanEmptyRecentFoldersProperty);
set => SetValue(CanEmptyRecentFoldersProperty, HasRecentFolders && value);
}
public Visibility FolderControlVisibility
{
get => (Visibility)GetValue(FolderControlVisibilityProperty);
set => SetValue(FolderControlVisibilityProperty, value);
}
public RecentFolderList RecentFolders
{
get => (RecentFolderList)GetValue(RecentFoldersProperty);
set
{
SetValue(RecentFoldersProperty, value);
HasRecentFolders = !RecentFolders.IsEmpty;
_folderControl.RecentFolders = RecentFolders;
}
}
public bool HasRecentFolders
{
get => (bool)GetValue(HasRecentFoldersProperty);
set => SetValue(HasRecentFoldersProperty, value);
}
#endregion
public MainWindow()
{
InitializeComponent();
DataContext = this;
TRCoord.Instance.HistoryAdded += TRCoord_HistoryAdded;
TRCoord.Instance.HistoryChanged += TRCoord_HistoryChanged;
_folderControl.DataFolderOpened += FolderControl_DataFolderOpened;
_editorControl.EditorStateChanged += EditorControl_EditorStateChanged;
RefreshHistoryMenu();
_editionStatusText.DataContext = _folderStatusText.DataContext = _editorControl;
IsEditorActive = false;
UpdateChecker.Instance.UpdateAvailable += UpdateChecker_UpdateAvailable;
MinHeight = Height;
MinWidth = Width;
}
#region History Updates
private void TRCoord_HistoryChanged(object sender, EventArgs e)
{
RefreshHistoryMenu();
}
private void TRCoord_HistoryAdded(object sender, TRHistoryEventArgs e)
{
RefreshHistoryMenu();
}
private void RefreshHistoryMenu()
{
if (Dispatcher.CheckAccess())
{
RecentFolders = new RecentFolderList(this);
}
else
{
Dispatcher.Invoke(RefreshHistoryMenu);
}
}
public void OpenDataFolder(RecentFolder folder)
{
if (ConfirmEditorSaveState())
{
_folderControl.OpenDataFolder(folder);
}
}
private void EmptyRecentFoldersMenuItem_Click(object sender, RoutedEventArgs e)
{
_folderControl.EmptyRecentFolders();
}
#endregion
#region Open/Save/Close
private void OpenCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
if (ConfirmEditorSaveState())
{
_folderControl.OpenDataFolder();
}
}
private void SaveCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
_editorControl.Save();
}
private void CloseCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
if (ConfirmEditorSaveState())
{
_editorControl.Unload();
IsEditorActive = false;
}
}
private void FolderControl_DataFolderOpened(object sender, DataFolderEventArgs e)
{
_editorControl.Load(e);
IsEditorActive = true;
}
private void EditorControl_EditorStateChanged(object sender, EditorEventArgs e)
{
IsEditorDirty = e.IsDirty;
EditorCanExport = e.CanExport;
if (e.ReloadRequested)
{
_editorControl.Unload();
IsEditorActive = false;
_folderControl.OpenDataFolder(_editorControl.DataFolder);
}
}
#endregion
#region Edit Options
private void ShowBackupMenuItem_Click(object sender, RoutedEventArgs e)
{
_editorControl.OpenBackupFolder();
}
private void RestoreDefaultsMenuItem_Click(object sender, RoutedEventArgs e)
{
_editorControl.RestoreDefaults();
}
private void ImportMenuItem_Click(object sender, RoutedEventArgs e)
{
_editorControl.ImportSettings();
}
private void ExportMenuItem_Click(object sender, RoutedEventArgs e)
{
if (ConfirmEditorSaveState())
{
_editorControl.ExportSettings();
}
}
private void EditorFolder_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
Process.Start(e.Uri.AbsoluteUri);
e.Handled = true;
}
#endregion
#region Help Options
private void HelpCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
Process.Start("https://github.com/lahm86/TRGameflowEditor");
}
private void DiscordMenuItem_Click(object sender, RoutedEventArgs e)
{
Process.Start("https://discord.com/channels/183942718630658048/738175962033684510");
}
private void UpdatesMenuItem_Click(object sender, RoutedEventArgs e)
{
try
{
if (UpdateChecker.Instance.CheckForUpdates())
{
ShowUpdateWindow();
}
else
{
MessageWindow.ShowMessage("The current version of TRGE is up to date.");
}
}
catch (Exception ex)
{
MessageWindow.ShowError(ex.Message);
}
}
private void UpdateChecker_UpdateAvailable(object sender, UpdateEventArgs e)
{
if (!Dispatcher.CheckAccess())
{
Dispatcher.Invoke(() => UpdateChecker_UpdateAvailable(sender, e));
}
else
{
_updateAvailableMenu.Visibility = Visibility.Visible;
}
}
private void UpdateAvailableMenuItem_Click(object sender, RoutedEventArgs e)
{
ShowUpdateWindow();
}
private void ShowUpdateWindow()
{
new UpdateAvailableWindow().ShowDialog();
}
private void AboutMenuItem_Click(object sender, RoutedEventArgs e)
{
new AboutWindow().ShowDialog();
}
#endregion
#region Exiting
private void ExitMenuItem_Click(object sender, RoutedEventArgs e)
{
if (ConfirmEditorSaveState())
{
Application.Current.Shutdown();
}
}
private void Window_Closing(object sender, CancelEventArgs e)
{
if (!ConfirmEditorSaveState())
{
e.Cancel = true;
}
}
private bool ConfirmEditorSaveState()
{
if (IsEditorDirty)
{
switch (MessageWindow.ShowConfirmCancel("Do you want to save the changes you have made?"))
{
case MessageBoxResult.Yes:
return _editorControl.Save();
case MessageBoxResult.Cancel:
return false;
}
}
return true;
}
#endregion
}
} | 32.123037 | 117 | 0.594899 | [
"MIT"
] | lahm86/TRGameflowEditor | TRGE.View/Windows/MainWindow.xaml.cs | 12,273 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.DataFactory.Latest.Inputs
{
/// <summary>
/// The Azure MySQL database dataset.
/// </summary>
public sealed class AzureMySqlTableDatasetArgs : Pulumi.ResourceArgs
{
[Input("annotations")]
private InputList<object>? _annotations;
/// <summary>
/// List of tags that can be used for describing the Dataset.
/// </summary>
public InputList<object> Annotations
{
get => _annotations ?? (_annotations = new InputList<object>());
set => _annotations = value;
}
/// <summary>
/// Dataset description.
/// </summary>
[Input("description")]
public Input<string>? Description { get; set; }
/// <summary>
/// The folder that this Dataset is in. If not specified, Dataset will appear at the root level.
/// </summary>
[Input("folder")]
public Input<Inputs.DatasetFolderArgs>? Folder { get; set; }
/// <summary>
/// Linked service reference.
/// </summary>
[Input("linkedServiceName", required: true)]
public Input<Inputs.LinkedServiceReferenceArgs> LinkedServiceName { get; set; } = null!;
[Input("parameters")]
private InputMap<Inputs.ParameterSpecificationArgs>? _parameters;
/// <summary>
/// Parameters for dataset.
/// </summary>
public InputMap<Inputs.ParameterSpecificationArgs> Parameters
{
get => _parameters ?? (_parameters = new InputMap<Inputs.ParameterSpecificationArgs>());
set => _parameters = value;
}
/// <summary>
/// Columns that define the physical type schema of the dataset. Type: array (or Expression with resultType array), itemType: DatasetSchemaDataElement.
/// </summary>
[Input("schema")]
public Input<object>? Schema { get; set; }
/// <summary>
/// Columns that define the structure of the dataset. Type: array (or Expression with resultType array), itemType: DatasetDataElement.
/// </summary>
[Input("structure")]
public Input<object>? Structure { get; set; }
/// <summary>
/// The name of Azure MySQL database table. Type: string (or Expression with resultType string).
/// </summary>
[Input("table")]
public Input<object>? Table { get; set; }
/// <summary>
/// The Azure MySQL database table name. Type: string (or Expression with resultType string).
/// </summary>
[Input("tableName")]
public Input<object>? TableName { get; set; }
/// <summary>
/// Type of dataset.
/// </summary>
[Input("type", required: true)]
public Input<string> Type { get; set; } = null!;
public AzureMySqlTableDatasetArgs()
{
}
}
}
| 33.852632 | 159 | 0.594838 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/DataFactory/Latest/Inputs/AzureMySqlTableDatasetArgs.cs | 3,216 | C# |
// Copyright (c) ZHAW, Marco Bertschi, Patrick Stadler. All rights reserved.
namespace Watra.Client.Desktop
{
using System.Windows;
using Watra.Api.Data.ApiClient;
using Watra.Client.Desktop.ViewModel;
/// <summary>
/// Interaction logic for EditHoseConnectorsWindow.xaml.
/// </summary>
public partial class EditHoseConnectorsWindow : Window
{
private readonly CrudViewModel<HoseConnector> viewModel;
/// <summary>
/// Initializes a new instance of the <see cref="EditHoseConnectorsWindow"/> class.
/// </summary>
public EditHoseConnectorsWindow()
{
this.InitializeComponent();
}
/// <summary>
/// Initializes a new instance of the <see cref="EditHoseConnectorsWindow"/> class.
/// </summary>
public EditHoseConnectorsWindow(CrudViewModel<HoseConnector> viewModel)
: this()
{
this.DataContext = viewModel;
this.viewModel = viewModel;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.viewModel.UpdateAsync();
}
}
}
| 29.15 | 91 | 0.617496 | [
"MIT"
] | OpenWatra/OpenWatra-Core | src/Watra.Client.Desktop/EditHoseConnectorsWindow.xaml.cs | 1,168 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using OSharp.Extensions;
using OSharp.Filter;
namespace OSharp.Collections
{
/// <summary>
/// Enumerable集合扩展方法
/// </summary>
public static class EnumerableExtensions
{
/// <summary>
/// 打乱一个集合的项顺序
/// </summary>
public static IEnumerable<TSource> Shuffle<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
return source.OrderBy(m => Guid.NewGuid());
}
/// <summary>
/// 将集合展开并分别转换成字符串,再以指定的分隔符衔接,拼成一个字符串返回。默认分隔符为逗号
/// </summary>
/// <param name="collection"> 要处理的集合 </param>
/// <param name="separator"> 分隔符,默认为逗号 </param>
/// <returns> 拼接后的字符串 </returns>
public static string ExpandAndToString<T>(this IEnumerable<T> collection, string separator = ",")
{
return collection.ExpandAndToString(t => t?.ToString(), separator);
}
/// <summary>
/// 循环集合的每一项,调用委托生成字符串,返回合并后的字符串。默认分隔符为逗号
/// </summary>
/// <param name="collection">待处理的集合</param>
/// <param name="itemFormatFunc">单个集合项的转换委托</param>
/// <param name="separator">分隔符,默认为逗号</param>
/// <typeparam name="T">泛型类型</typeparam>
/// <returns></returns>
public static string ExpandAndToString<T>(this IEnumerable<T> collection, Func<T, string> itemFormatFunc, string separator = ",")
{
collection = collection as IList<T> ?? collection.ToList();
itemFormatFunc.CheckNotNull("itemFormatFunc");
if (!collection.Any())
{
return string.Empty;
}
StringBuilder sb = new StringBuilder();
int i = 0;
int count = collection.Count();
foreach (T t in collection)
{
if (i == count - 1)
{
sb.Append(itemFormatFunc(t));
}
else
{
sb.Append(itemFormatFunc(t) + separator);
}
i++;
}
return sb.ToString();
}
/// <summary>
/// 集合是否为空
/// </summary>
/// <param name="collection"> 要处理的集合 </param>
/// <typeparam name="T"> 动态类型 </typeparam>
/// <returns> 为空返回True,不为空返回False </returns>
public static bool IsEmpty<T>(this IEnumerable<T> collection)
{
collection = collection as IList<T> ?? collection.ToList();
return !collection.Any();
}
/// <summary>
/// 根据第三方条件是否为真来决定是否执行指定条件的查询
/// </summary>
/// <param name="source"> 要查询的源 </param>
/// <param name="predicate"> 查询条件 </param>
/// <param name="condition"> 第三方条件 </param>
/// <typeparam name="T"> 动态类型 </typeparam>
/// <returns> 查询的结果 </returns>
public static IEnumerable<T> WhereIf<T>(this IEnumerable<T> source, Func<T, bool> predicate, bool condition)
{
predicate.CheckNotNull("predicate");
source = source as IList<T> ?? source.ToList();
return condition ? source.Where(predicate) : source;
}
/// <summary>
/// 将字符串集合按指定前缀排序
/// </summary>
public static IEnumerable<T> OrderByPrefixes<T>(this IEnumerable<T> source, Func<T, string> keySelector, params string[] prefixes)
{
List<T> all = source.OrderBy(keySelector).ToList();
List<T> result = new List<T>();
foreach (string prefix in prefixes)
{
List<T> tmpList = all.Where(m => keySelector(m).StartsWith(prefix)).OrderBy(keySelector).ToList();
all = all.Except(tmpList).ToList();
result.AddRange(tmpList);
}
result.AddRange(all);
return result;
}
/// <summary>
/// 根据指定条件返回集合中不重复的元素
/// </summary>
/// <typeparam name="T">动态类型</typeparam>
/// <typeparam name="TKey">动态筛选条件类型</typeparam>
/// <param name="source">要操作的源</param>
/// <param name="keySelector">重复数据筛选条件</param>
/// <returns>不重复元素的集合</returns>
public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector)
{
keySelector.CheckNotNull("keySelector");
source = source as IList<T> ?? source.ToList();
return source.GroupBy(keySelector).Select(group => group.First());
}
/// <summary>
/// 把<see cref="IEnumerable{T}"/>集合按指定字段与排序方式进行排序
/// </summary>
/// <typeparam name="T">集合项类型</typeparam>
/// <param name="source">要排序的数据集</param>
/// <param name="propertyName">排序属性名</param>
/// <param name="sortDirection">排序方向</param>
/// <returns>排序后的数据集</returns>
public static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> source,
string propertyName,
ListSortDirection sortDirection = ListSortDirection.Ascending)
{
propertyName.CheckNotNullOrEmpty("propertyName");
return CollectionPropertySorter<T>.OrderBy(source, propertyName, sortDirection);
}
/// <summary>
/// 把<see cref="IEnumerable{T}"/>集合按指定字段排序条件进行排序
/// </summary>
/// <typeparam name="T">动态类型</typeparam>
/// <param name="source">要排序的数据集</param>
/// <param name="sortCondition">列表字段排序条件</param>
/// <returns></returns>
public static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> source, SortCondition sortCondition)
{
sortCondition.CheckNotNull("sortCondition");
return source.OrderBy(sortCondition.SortField, sortCondition.ListSortDirection);
}
/// <summary>
/// 把<see cref="IEnumerable{T}"/>集合按指定字段排序条件进行排序
/// </summary>
/// <typeparam name="T">动态类型</typeparam>
/// <param name="source">要排序的数据集</param>
/// <param name="sortCondition">列表字段排序条件</param>
/// <returns></returns>
public static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> source, SortCondition<T> sortCondition)
{
sortCondition.CheckNotNull("sortCondition");
return source.OrderBy(sortCondition.SortField, sortCondition.ListSortDirection);
}
/// <summary>
/// 把<see cref="IOrderedQueryable{T}"/>集合继续按指定字段排序方式进行排序
/// </summary>
/// <typeparam name="T">动态类型</typeparam>
/// <param name="source">要排序的数据集</param>
/// <param name="propertyName">排序属性名</param>
/// <param name="sortDirection">排序方向</param>
/// <returns></returns>
public static IOrderedEnumerable<T> ThenBy<T>(this IOrderedEnumerable<T> source,
string propertyName,
ListSortDirection sortDirection = ListSortDirection.Ascending)
{
propertyName.CheckNotNullOrEmpty("propertyName");
return CollectionPropertySorter<T>.ThenBy(source, propertyName, sortDirection);
}
/// <summary>
/// 把<see cref="IOrderedEnumerable{T}"/>集合继续指定字段排序方式进行排序
/// </summary>
/// <typeparam name="T">动态类型</typeparam>
/// <param name="source">要排序的数据集</param>
/// <param name="sortCondition">列表字段排序条件</param>
/// <returns></returns>
public static IOrderedEnumerable<T> ThenBy<T>(this IOrderedEnumerable<T> source, SortCondition sortCondition)
{
sortCondition.CheckNotNull("sortCondition");
return source.ThenBy(sortCondition.SortField, sortCondition.ListSortDirection);
}
}
}
| 37.004673 | 138 | 0.566359 | [
"Apache-2.0"
] | 188867052/osharp-master | src/OSharp/Collections/EnumerableExtensions.cs | 8,869 | C# |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using PureCloudPlatform.Client.V2.Client;
namespace PureCloudPlatform.Client.V2.Model
{
/// <summary>
/// NumberPlan
/// </summary>
[DataContract]
public partial class NumberPlan : IEquatable<NumberPlan>
{
/// <summary>
/// Indicates if the resource is active, inactive, or deleted.
/// </summary>
/// <value>Indicates if the resource is active, inactive, or deleted.</value>
[JsonConverter(typeof(UpgradeSdkEnumConverter))]
public enum StateEnum
{
/// <summary>
/// Your SDK version is out of date and an unknown enum value was encountered.
/// Please upgrade the SDK using the command "Upgrade-Package PureCloudApiSdk"
/// in the Package Manager Console
/// </summary>
[EnumMember(Value = "OUTDATED_SDK_VERSION")]
OutdatedSdkVersion,
/// <summary>
/// Enum Active for "active"
/// </summary>
[EnumMember(Value = "active")]
Active,
/// <summary>
/// Enum Inactive for "inactive"
/// </summary>
[EnumMember(Value = "inactive")]
Inactive,
/// <summary>
/// Enum Deleted for "deleted"
/// </summary>
[EnumMember(Value = "deleted")]
Deleted
}
/// <summary>
/// Indicates if the resource is active, inactive, or deleted.
/// </summary>
/// <value>Indicates if the resource is active, inactive, or deleted.</value>
[DataMember(Name="state", EmitDefaultValue=false)]
public StateEnum? State { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="NumberPlan" /> class.
/// </summary>
[JsonConstructorAttribute]
protected NumberPlan() { }
/// <summary>
/// Initializes a new instance of the <see cref="NumberPlan" /> class.
/// </summary>
/// <param name="Name">The name of the entity. (required).</param>
/// <param name="Description">The resource's description..</param>
/// <param name="Version">The current version of the resource..</param>
/// <param name="DateCreated">The date the resource was created. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z.</param>
/// <param name="DateModified">The date of the last modification to the resource. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z.</param>
/// <param name="ModifiedBy">The ID of the user that last modified the resource..</param>
/// <param name="CreatedBy">The ID of the user that created the resource..</param>
/// <param name="ModifiedByApp">The application that last modified the resource..</param>
/// <param name="CreatedByApp">The application that created the resource..</param>
/// <param name="Match">Match.</param>
/// <param name="NormalizedFormat">NormalizedFormat.</param>
/// <param name="Priority">Priority.</param>
/// <param name="Numbers">Numbers.</param>
/// <param name="DigitLength">DigitLength.</param>
/// <param name="Classification">Classification.</param>
/// <param name="MatchType">MatchType.</param>
public NumberPlan(string Name = null, string Description = null, int? Version = null, DateTime? DateCreated = null, DateTime? DateModified = null, string ModifiedBy = null, string CreatedBy = null, string ModifiedByApp = null, string CreatedByApp = null, string Match = null, string NormalizedFormat = null, int? Priority = null, List<double?> Numbers = null, DigitLength DigitLength = null, string Classification = null, string MatchType = null)
{
this.Name = Name;
this.Description = Description;
this.Version = Version;
this.DateCreated = DateCreated;
this.DateModified = DateModified;
this.ModifiedBy = ModifiedBy;
this.CreatedBy = CreatedBy;
this.ModifiedByApp = ModifiedByApp;
this.CreatedByApp = CreatedByApp;
this.Match = Match;
this.NormalizedFormat = NormalizedFormat;
this.Priority = Priority;
this.Numbers = Numbers;
this.DigitLength = DigitLength;
this.Classification = Classification;
this.MatchType = MatchType;
}
/// <summary>
/// The globally unique identifier for the object.
/// </summary>
/// <value>The globally unique identifier for the object.</value>
[DataMember(Name="id", EmitDefaultValue=false)]
public string Id { get; private set; }
/// <summary>
/// The name of the entity.
/// </summary>
/// <value>The name of the entity.</value>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// The resource's description.
/// </summary>
/// <value>The resource's description.</value>
[DataMember(Name="description", EmitDefaultValue=false)]
public string Description { get; set; }
/// <summary>
/// The current version of the resource.
/// </summary>
/// <value>The current version of the resource.</value>
[DataMember(Name="version", EmitDefaultValue=false)]
public int? Version { get; set; }
/// <summary>
/// The date the resource was created. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z
/// </summary>
/// <value>The date the resource was created. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z</value>
[DataMember(Name="dateCreated", EmitDefaultValue=false)]
public DateTime? DateCreated { get; set; }
/// <summary>
/// The date of the last modification to the resource. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z
/// </summary>
/// <value>The date of the last modification to the resource. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z</value>
[DataMember(Name="dateModified", EmitDefaultValue=false)]
public DateTime? DateModified { get; set; }
/// <summary>
/// The ID of the user that last modified the resource.
/// </summary>
/// <value>The ID of the user that last modified the resource.</value>
[DataMember(Name="modifiedBy", EmitDefaultValue=false)]
public string ModifiedBy { get; set; }
/// <summary>
/// The ID of the user that created the resource.
/// </summary>
/// <value>The ID of the user that created the resource.</value>
[DataMember(Name="createdBy", EmitDefaultValue=false)]
public string CreatedBy { get; set; }
/// <summary>
/// The application that last modified the resource.
/// </summary>
/// <value>The application that last modified the resource.</value>
[DataMember(Name="modifiedByApp", EmitDefaultValue=false)]
public string ModifiedByApp { get; set; }
/// <summary>
/// The application that created the resource.
/// </summary>
/// <value>The application that created the resource.</value>
[DataMember(Name="createdByApp", EmitDefaultValue=false)]
public string CreatedByApp { get; set; }
/// <summary>
/// Gets or Sets Match
/// </summary>
[DataMember(Name="match", EmitDefaultValue=false)]
public string Match { get; set; }
/// <summary>
/// Gets or Sets NormalizedFormat
/// </summary>
[DataMember(Name="normalizedFormat", EmitDefaultValue=false)]
public string NormalizedFormat { get; set; }
/// <summary>
/// Gets or Sets Priority
/// </summary>
[DataMember(Name="priority", EmitDefaultValue=false)]
public int? Priority { get; set; }
/// <summary>
/// Gets or Sets Numbers
/// </summary>
[DataMember(Name="numbers", EmitDefaultValue=false)]
public List<double?> Numbers { get; set; }
/// <summary>
/// Gets or Sets DigitLength
/// </summary>
[DataMember(Name="digitLength", EmitDefaultValue=false)]
public DigitLength DigitLength { get; set; }
/// <summary>
/// Gets or Sets Classification
/// </summary>
[DataMember(Name="classification", EmitDefaultValue=false)]
public string Classification { get; set; }
/// <summary>
/// Gets or Sets MatchType
/// </summary>
[DataMember(Name="matchType", EmitDefaultValue=false)]
public string MatchType { get; set; }
/// <summary>
/// The URI for this object
/// </summary>
/// <value>The URI for this object</value>
[DataMember(Name="selfUri", EmitDefaultValue=false)]
public string SelfUri { get; private set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class NumberPlan {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Description: ").Append(Description).Append("\n");
sb.Append(" Version: ").Append(Version).Append("\n");
sb.Append(" DateCreated: ").Append(DateCreated).Append("\n");
sb.Append(" DateModified: ").Append(DateModified).Append("\n");
sb.Append(" ModifiedBy: ").Append(ModifiedBy).Append("\n");
sb.Append(" CreatedBy: ").Append(CreatedBy).Append("\n");
sb.Append(" State: ").Append(State).Append("\n");
sb.Append(" ModifiedByApp: ").Append(ModifiedByApp).Append("\n");
sb.Append(" CreatedByApp: ").Append(CreatedByApp).Append("\n");
sb.Append(" Match: ").Append(Match).Append("\n");
sb.Append(" NormalizedFormat: ").Append(NormalizedFormat).Append("\n");
sb.Append(" Priority: ").Append(Priority).Append("\n");
sb.Append(" Numbers: ").Append(Numbers).Append("\n");
sb.Append(" DigitLength: ").Append(DigitLength).Append("\n");
sb.Append(" Classification: ").Append(Classification).Append("\n");
sb.Append(" MatchType: ").Append(MatchType).Append("\n");
sb.Append(" SelfUri: ").Append(SelfUri).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
Formatting = Formatting.Indented
});
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as NumberPlan);
}
/// <summary>
/// Returns true if NumberPlan instances are equal
/// </summary>
/// <param name="other">Instance of NumberPlan to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(NumberPlan other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return true &&
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.Description == other.Description ||
this.Description != null &&
this.Description.Equals(other.Description)
) &&
(
this.Version == other.Version ||
this.Version != null &&
this.Version.Equals(other.Version)
) &&
(
this.DateCreated == other.DateCreated ||
this.DateCreated != null &&
this.DateCreated.Equals(other.DateCreated)
) &&
(
this.DateModified == other.DateModified ||
this.DateModified != null &&
this.DateModified.Equals(other.DateModified)
) &&
(
this.ModifiedBy == other.ModifiedBy ||
this.ModifiedBy != null &&
this.ModifiedBy.Equals(other.ModifiedBy)
) &&
(
this.CreatedBy == other.CreatedBy ||
this.CreatedBy != null &&
this.CreatedBy.Equals(other.CreatedBy)
) &&
(
this.State == other.State ||
this.State != null &&
this.State.Equals(other.State)
) &&
(
this.ModifiedByApp == other.ModifiedByApp ||
this.ModifiedByApp != null &&
this.ModifiedByApp.Equals(other.ModifiedByApp)
) &&
(
this.CreatedByApp == other.CreatedByApp ||
this.CreatedByApp != null &&
this.CreatedByApp.Equals(other.CreatedByApp)
) &&
(
this.Match == other.Match ||
this.Match != null &&
this.Match.Equals(other.Match)
) &&
(
this.NormalizedFormat == other.NormalizedFormat ||
this.NormalizedFormat != null &&
this.NormalizedFormat.Equals(other.NormalizedFormat)
) &&
(
this.Priority == other.Priority ||
this.Priority != null &&
this.Priority.Equals(other.Priority)
) &&
(
this.Numbers == other.Numbers ||
this.Numbers != null &&
this.Numbers.SequenceEqual(other.Numbers)
) &&
(
this.DigitLength == other.DigitLength ||
this.DigitLength != null &&
this.DigitLength.Equals(other.DigitLength)
) &&
(
this.Classification == other.Classification ||
this.Classification != null &&
this.Classification.Equals(other.Classification)
) &&
(
this.MatchType == other.MatchType ||
this.MatchType != null &&
this.MatchType.Equals(other.MatchType)
) &&
(
this.SelfUri == other.SelfUri ||
this.SelfUri != null &&
this.SelfUri.Equals(other.SelfUri)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.Name != null)
hash = hash * 59 + this.Name.GetHashCode();
if (this.Description != null)
hash = hash * 59 + this.Description.GetHashCode();
if (this.Version != null)
hash = hash * 59 + this.Version.GetHashCode();
if (this.DateCreated != null)
hash = hash * 59 + this.DateCreated.GetHashCode();
if (this.DateModified != null)
hash = hash * 59 + this.DateModified.GetHashCode();
if (this.ModifiedBy != null)
hash = hash * 59 + this.ModifiedBy.GetHashCode();
if (this.CreatedBy != null)
hash = hash * 59 + this.CreatedBy.GetHashCode();
if (this.State != null)
hash = hash * 59 + this.State.GetHashCode();
if (this.ModifiedByApp != null)
hash = hash * 59 + this.ModifiedByApp.GetHashCode();
if (this.CreatedByApp != null)
hash = hash * 59 + this.CreatedByApp.GetHashCode();
if (this.Match != null)
hash = hash * 59 + this.Match.GetHashCode();
if (this.NormalizedFormat != null)
hash = hash * 59 + this.NormalizedFormat.GetHashCode();
if (this.Priority != null)
hash = hash * 59 + this.Priority.GetHashCode();
if (this.Numbers != null)
hash = hash * 59 + this.Numbers.GetHashCode();
if (this.DigitLength != null)
hash = hash * 59 + this.DigitLength.GetHashCode();
if (this.Classification != null)
hash = hash * 59 + this.Classification.GetHashCode();
if (this.MatchType != null)
hash = hash * 59 + this.MatchType.GetHashCode();
if (this.SelfUri != null)
hash = hash * 59 + this.SelfUri.GetHashCode();
return hash;
}
}
}
}
| 34.453642 | 454 | 0.482941 | [
"MIT"
] | F-V-L/platform-client-sdk-dotnet | build/src/PureCloudPlatform.Client.V2/Model/NumberPlan.cs | 20,810 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms.TestUtilities;
using Xunit;
namespace System.Windows.Forms.Tests
{
public class DataGridViewColumnTests : IClassFixture<ThreadExceptionFixture>
{
[WinFormsFact]
public void DataGridViewColumn_Ctor_Default()
{
using var column = new SubDataGridViewColumn();
Assert.Equal(DataGridViewAutoSizeColumnMode.NotSet, column.AutoSizeMode);
Assert.Null(column.CellTemplate);
Assert.Null(column.CellType);
Assert.Null(column.ContextMenuStrip);
Assert.Null(column.DataGridView);
Assert.Empty(column.DataPropertyName);
Assert.NotNull(column.DefaultCellStyle);
Assert.Same(column.DefaultCellStyle, column.DefaultCellStyle);
Assert.Same(typeof(DataGridViewColumnHeaderCell), column.DefaultHeaderCellType);
Assert.Equal(-1, column.DisplayIndex);
Assert.False(column.Displayed);
Assert.Equal(0, column.DividerWidth);
Assert.Equal(100, column.FillWeight);
Assert.False(column.Frozen);
Assert.True(column.HasDefaultCellStyle);
Assert.IsType<DataGridViewColumnHeaderCell>(column.HeaderCell);
Assert.Same(column.HeaderCell, column.HeaderCell);
Assert.IsType<DataGridViewColumnHeaderCell>(column.HeaderCellCore);
Assert.Same(column.HeaderCellCore, column.HeaderCellCore);
Assert.Empty(column.HeaderText);
Assert.Equal(column.Index, column.Index);
Assert.Equal(DataGridViewAutoSizeColumnMode.NotSet, column.InheritedAutoSizeMode);
Assert.Same(column.DefaultCellStyle, column.InheritedStyle);
Assert.False(column.IsDataBound);
Assert.False(column.IsRow);
Assert.Equal(5, column.MinimumWidth);
Assert.Empty(column.Name);
Assert.False(column.ReadOnly);
Assert.Equal(DataGridViewTriState.NotSet, column.Resizable);
Assert.False(column.Selected);
Assert.Null(column.Site);
Assert.Equal(DataGridViewElementStates.Visible, column.State);
Assert.Equal(DataGridViewColumnSortMode.NotSortable, column.SortMode);
Assert.Null(column.Tag);
Assert.Empty(column.ToolTipText);
Assert.Null(column.ValueType);
Assert.True(column.Visible);
Assert.Equal(100, column.Width);
}
public static IEnumerable<object[]> Ctor_DataGridViewCell_TestData()
{
yield return new object[] { null };
yield return new object[] { new SubDataGridViewCell() };
}
[WinFormsTheory]
[MemberData(nameof(Ctor_DataGridViewCell_TestData))]
public void DataGridViewColumn_Ctor_DataGridViewCell(DataGridViewCell cellTemplate)
{
using var column = new SubDataGridViewColumn(cellTemplate);
Assert.Equal(DataGridViewAutoSizeColumnMode.NotSet, column.AutoSizeMode);
Assert.Same(cellTemplate, column.CellTemplate);
Assert.Equal(cellTemplate?.GetType(), column.CellType);
Assert.Null(column.ContextMenuStrip);
Assert.Null(column.DataGridView);
Assert.Empty(column.DataPropertyName);
Assert.NotNull(column.DefaultCellStyle);
Assert.Same(column.DefaultCellStyle, column.DefaultCellStyle);
Assert.Same(typeof(DataGridViewColumnHeaderCell), column.DefaultHeaderCellType);
Assert.Equal(-1, column.DisplayIndex);
Assert.False(column.Displayed);
Assert.Equal(0, column.DividerWidth);
Assert.Equal(100, column.FillWeight);
Assert.False(column.Frozen);
Assert.True(column.HasDefaultCellStyle);
Assert.Empty(column.HeaderText);
Assert.Equal(-1, column.Index);
Assert.Equal(DataGridViewAutoSizeColumnMode.NotSet, column.InheritedAutoSizeMode);
Assert.Same(column.DefaultCellStyle, column.InheritedStyle);
Assert.False(column.IsDataBound);
Assert.False(column.IsRow);
Assert.Equal(5, column.MinimumWidth);
Assert.Empty(column.Name);
Assert.False(column.ReadOnly);
Assert.Equal(DataGridViewTriState.NotSet, column.Resizable);
Assert.False(column.Selected);
Assert.Null(column.Site);
Assert.Equal(DataGridViewElementStates.Visible, column.State);
Assert.Equal(DataGridViewColumnSortMode.NotSortable, column.SortMode);
Assert.Null(column.Tag);
Assert.Empty(column.ToolTipText);
Assert.Null(column.ValueType);
Assert.True(column.Visible);
Assert.Equal(100, column.Width);
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEnumTypeTheoryData), typeof(DataGridViewAutoSizeColumnMode))]
public void DataGridViewColumn_AutoSizeMode_Set_GetReturnsExpected(DataGridViewAutoSizeColumnMode value)
{
using var column = new DataGridViewColumn
{
AutoSizeMode = value
};
Assert.Equal(value, column.AutoSizeMode);
Assert.Equal(value, column.InheritedAutoSizeMode);
Assert.Equal(100, column.Width);
// Set same.
column.AutoSizeMode = value;
Assert.Equal(value, column.AutoSizeMode);
Assert.Equal(value, column.InheritedAutoSizeMode);
Assert.Equal(100, column.Width);
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEnumTypeTheoryData), typeof(DataGridViewAutoSizeColumnMode))]
public void DataGridViewColumn_AutoSizeMode_SetNotVisible_GetReturnsExpected(DataGridViewAutoSizeColumnMode value)
{
using var column = new DataGridViewColumn
{
AutoSizeMode = value,
Visible = false
};
Assert.Equal(value, column.AutoSizeMode);
Assert.Equal(value, column.InheritedAutoSizeMode);
Assert.Equal(100, column.Width);
// Set same.
column.AutoSizeMode = value;
Assert.Equal(value, column.AutoSizeMode);
Assert.Equal(value, column.InheritedAutoSizeMode);
Assert.Equal(100, column.Width);
}
public static IEnumerable<object[]> AutoSizeMode_SetWithDataGridView_TestData()
{
foreach (DataGridViewAutoSizeColumnsMode dataGridMode in Enum.GetValues(typeof(DataGridViewAutoSizeColumnsMode)))
{
foreach (bool columnHeadersVisible in new bool[] { true, false })
{
if (dataGridMode == DataGridViewAutoSizeColumnsMode.ColumnHeader && !columnHeadersVisible)
{
continue;
}
foreach (bool frozen in new bool[] { true, false })
{
if (dataGridMode == DataGridViewAutoSizeColumnsMode.Fill && frozen)
{
continue;
}
yield return new object[] { dataGridMode, columnHeadersVisible, frozen, DataGridViewAutoSizeColumnMode.AllCells, DataGridViewAutoSizeColumnMode.AllCells };
yield return new object[] { dataGridMode, columnHeadersVisible, frozen, DataGridViewAutoSizeColumnMode.AllCellsExceptHeader, DataGridViewAutoSizeColumnMode.AllCellsExceptHeader };
yield return new object[] { dataGridMode, columnHeadersVisible, frozen, DataGridViewAutoSizeColumnMode.DisplayedCells, DataGridViewAutoSizeColumnMode.DisplayedCells };
yield return new object[] { dataGridMode, columnHeadersVisible, frozen, DataGridViewAutoSizeColumnMode.DisplayedCellsExceptHeader, DataGridViewAutoSizeColumnMode.DisplayedCellsExceptHeader };
yield return new object[] { dataGridMode, columnHeadersVisible, frozen, DataGridViewAutoSizeColumnMode.None, DataGridViewAutoSizeColumnMode.None };
}
yield return new object[] { dataGridMode, columnHeadersVisible, false, DataGridViewAutoSizeColumnMode.Fill, DataGridViewAutoSizeColumnMode.Fill };
}
if (dataGridMode != DataGridViewAutoSizeColumnsMode.Fill)
{
yield return new object[] { dataGridMode, true, true, DataGridViewAutoSizeColumnMode.ColumnHeader, DataGridViewAutoSizeColumnMode.ColumnHeader };
}
yield return new object[] { dataGridMode, true, false, DataGridViewAutoSizeColumnMode.ColumnHeader, DataGridViewAutoSizeColumnMode.ColumnHeader };
}
}
[WinFormsTheory]
[MemberData(nameof(AutoSizeMode_SetWithDataGridView_TestData))]
public void DataGridViewColumn_AutoSizeMode_SetWithDataGridView_GetReturnsExpected(DataGridViewAutoSizeColumnsMode parentMode, bool columnHeadersVisible, bool frozen, DataGridViewAutoSizeColumnMode value, DataGridViewAutoSizeColumnMode expectedInherited)
{
using var control = new DataGridView
{
AutoSizeColumnsMode = parentMode,
ColumnHeadersVisible = columnHeadersVisible
};
using var column = new DataGridViewColumn
{
CellTemplate = new SubDataGridViewCell(),
Frozen = frozen
};
control.Columns.Add(column);
column.AutoSizeMode = value;
Assert.Equal(value, column.AutoSizeMode);
Assert.Equal(expectedInherited, column.InheritedAutoSizeMode);
Assert.Equal(100, column.Width);
// Set same.
column.AutoSizeMode = value;
Assert.Equal(value, column.AutoSizeMode);
Assert.Equal(expectedInherited, column.InheritedAutoSizeMode);
Assert.Equal(100, column.Width);
}
public static IEnumerable<object[]> AutoSizeMode_SetWithDataGridViewNotVisible_TestData()
{
foreach (DataGridViewAutoSizeColumnsMode dataGridMode in Enum.GetValues(typeof(DataGridViewAutoSizeColumnsMode)))
{
foreach (bool columnHeadersVisible in new bool[] { true, false })
{
foreach (bool frozen in new bool[] { true, false })
{
yield return new object[] { dataGridMode, columnHeadersVisible, frozen, DataGridViewAutoSizeColumnMode.AllCells, DataGridViewAutoSizeColumnMode.AllCells };
yield return new object[] { dataGridMode, columnHeadersVisible, frozen, DataGridViewAutoSizeColumnMode.AllCellsExceptHeader, DataGridViewAutoSizeColumnMode.AllCellsExceptHeader };
yield return new object[] { dataGridMode, columnHeadersVisible, frozen, DataGridViewAutoSizeColumnMode.ColumnHeader, DataGridViewAutoSizeColumnMode.ColumnHeader };
yield return new object[] { dataGridMode, columnHeadersVisible, frozen, DataGridViewAutoSizeColumnMode.DisplayedCells, DataGridViewAutoSizeColumnMode.DisplayedCells };
yield return new object[] { dataGridMode, columnHeadersVisible, frozen, DataGridViewAutoSizeColumnMode.DisplayedCellsExceptHeader, DataGridViewAutoSizeColumnMode.DisplayedCellsExceptHeader };
yield return new object[] { dataGridMode, columnHeadersVisible, frozen, DataGridViewAutoSizeColumnMode.Fill, DataGridViewAutoSizeColumnMode.Fill };
yield return new object[] { dataGridMode, columnHeadersVisible, frozen, DataGridViewAutoSizeColumnMode.None, DataGridViewAutoSizeColumnMode.None };
}
}
}
}
[WinFormsTheory]
[MemberData(nameof(AutoSizeMode_SetWithDataGridViewNotVisible_TestData))]
public void DataGridViewColumn_AutoSizeMode_SetWithDataGridViewNotVisible_GetReturnsExpected(DataGridViewAutoSizeColumnsMode parentMode, bool columnHeadersVisible, bool frozen, DataGridViewAutoSizeColumnMode value, DataGridViewAutoSizeColumnMode expectedInherited)
{
using var control = new DataGridView
{
AutoSizeColumnsMode = parentMode,
ColumnHeadersVisible = columnHeadersVisible
};
using var column = new DataGridViewColumn
{
CellTemplate = new SubDataGridViewCell(),
Visible = false,
Frozen = frozen
};
control.Columns.Add(column);
column.AutoSizeMode = value;
Assert.Equal(value, column.AutoSizeMode);
Assert.Equal(expectedInherited, column.InheritedAutoSizeMode);
Assert.Equal(100, column.Width);
// Set same.
column.AutoSizeMode = value;
Assert.Equal(value, column.AutoSizeMode);
Assert.Equal(expectedInherited, column.InheritedAutoSizeMode);
Assert.Equal(100, column.Width);
}
[WinFormsFact]
public void DataGridViewColumn_AutoSizeMode_SetColumnHeaderWithDataGridViewColumnHeadersNotVisible_ThrowsInvalidOperationException()
{
using var control = new DataGridView
{
ColumnHeadersVisible = false
};
using var cellTemplate = new SubDataGridViewCell();
using var column = new DataGridViewColumn
{
CellTemplate = cellTemplate
};
control.Columns.Add(column);
Assert.Throws<InvalidOperationException>(() => column.AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader);
Assert.Equal(DataGridViewAutoSizeColumnMode.NotSet, column.AutoSizeMode);
Assert.Equal(DataGridViewAutoSizeColumnMode.None, column.InheritedAutoSizeMode);
}
[WinFormsFact]
public void DataGridViewColumn_AutoSizeMode_SetNotSetWithDataGridViewColumnHeadersNotVisible_GetReturnsExpected()
{
using var control = new DataGridView
{
ColumnHeadersVisible = false
};
using var column = new DataGridViewColumn
{
AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells,
CellTemplate = new SubDataGridViewCell()
};
control.Columns.Add(column);
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet;
Assert.Equal(DataGridViewAutoSizeColumnMode.NotSet, column.AutoSizeMode);
Assert.Equal(DataGridViewAutoSizeColumnMode.None, column.InheritedAutoSizeMode);
}
[WinFormsFact]
public void DataGridViewColumn_AutoSizeMode_SetNotSetWithDataGridViewColumnHeadersNotVisible_ThrowsInvalidOperationException()
{
using var control = new DataGridView
{
AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader,
ColumnHeadersVisible = false
};
using var column = new DataGridViewColumn
{
AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells,
CellTemplate = new SubDataGridViewCell()
};
control.Columns.Add(column);
Assert.Throws<InvalidOperationException>(() => column.AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet);
Assert.Equal(DataGridViewAutoSizeColumnMode.AllCells, column.AutoSizeMode);
Assert.Equal(DataGridViewAutoSizeColumnMode.AllCells, column.InheritedAutoSizeMode);
}
[WinFormsFact]
public void DataGridViewColumn_AutoSizeMode_SetFillWithDataGridViewFrozen_ThrowsInvalidOperationException()
{
using var control = new DataGridView();
using var column = new DataGridViewColumn
{
CellTemplate = new SubDataGridViewCell(),
Frozen = true
};
control.Columns.Add(column);
Assert.Throws<InvalidOperationException>(() => column.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill);
Assert.Equal(DataGridViewAutoSizeColumnMode.NotSet, column.AutoSizeMode);
Assert.Equal(DataGridViewAutoSizeColumnMode.None, column.InheritedAutoSizeMode);
}
[WinFormsFact]
public void DataGridViewColumn_AutoSizeMode_SetNotSetWithDataGridViewFrozen_GetReturnsExpected()
{
using var control = new DataGridView();
using var column = new DataGridViewColumn
{
AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells,
CellTemplate = new SubDataGridViewCell(),
Frozen = true
};
control.Columns.Add(column);
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet;
Assert.Equal(DataGridViewAutoSizeColumnMode.NotSet, column.AutoSizeMode);
Assert.Equal(DataGridViewAutoSizeColumnMode.None, column.InheritedAutoSizeMode);
}
[WinFormsFact]
public void DataGridViewColumn_AutoSizeMode_SetNotSetWithDataGridViewFrozen_ThrowsInvalidOperationException()
{
using var control = new DataGridView
{
AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
};
using var column = new DataGridViewColumn
{
AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells,
CellTemplate = new SubDataGridViewCell(),
Frozen = true
};
control.Columns.Add(column);
Assert.Throws<InvalidOperationException>(() => column.AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet);
Assert.Equal(DataGridViewAutoSizeColumnMode.AllCells, column.AutoSizeMode);
Assert.Equal(DataGridViewAutoSizeColumnMode.AllCells, column.InheritedAutoSizeMode);
}
public static IEnumerable<object[]> AutoSizeMode_SetWithOldValue_TestData()
{
foreach (DataGridViewAutoSizeColumnMode oldValue in Enum.GetValues(typeof(DataGridViewAutoSizeColumnMode)))
{
foreach (DataGridViewAutoSizeColumnMode value in Enum.GetValues(typeof(DataGridViewAutoSizeColumnMode)))
{
yield return new object[] { oldValue, value };
}
}
}
[WinFormsTheory]
[MemberData(nameof(AutoSizeMode_SetWithOldValue_TestData))]
public void DataGridViewColumn_AutoSizeMode_SetWithOldValue_GetReturnsExpected(DataGridViewAutoSizeColumnMode oldValue, DataGridViewAutoSizeColumnMode value)
{
using var column = new DataGridViewColumn
{
AutoSizeMode = oldValue
};
column.AutoSizeMode = value;
Assert.Equal(value, column.AutoSizeMode);
Assert.Equal(value, column.InheritedAutoSizeMode);
Assert.Equal(100, column.Width);
// Set same.
column.AutoSizeMode = value;
Assert.Equal(value, column.AutoSizeMode);
Assert.Equal(value, column.InheritedAutoSizeMode);
Assert.Equal(100, column.Width);
}
public static IEnumerable<object[]> AutoSizeMode_SetWithWidth_TestData()
{
foreach (DataGridViewAutoSizeColumnMode previous in new DataGridViewAutoSizeColumnMode[] { DataGridViewAutoSizeColumnMode.NotSet, DataGridViewAutoSizeColumnMode.None, DataGridViewAutoSizeColumnMode.Fill })
{
yield return new object[] { previous, DataGridViewAutoSizeColumnMode.AllCells, 20 };
yield return new object[] { previous, DataGridViewAutoSizeColumnMode.AllCellsExceptHeader, 20 };
yield return new object[] { previous, DataGridViewAutoSizeColumnMode.None, 20 };
yield return new object[] { previous, DataGridViewAutoSizeColumnMode.NotSet, 20 };
yield return new object[] { previous, DataGridViewAutoSizeColumnMode.Fill, 20 };
}
yield return new object[] { DataGridViewAutoSizeColumnMode.AllCells, DataGridViewAutoSizeColumnMode.AllCells, 10 };
yield return new object[] { DataGridViewAutoSizeColumnMode.AllCells, DataGridViewAutoSizeColumnMode.AllCellsExceptHeader, 10 };
yield return new object[] { DataGridViewAutoSizeColumnMode.AllCells, DataGridViewAutoSizeColumnMode.None, 20 };
yield return new object[] { DataGridViewAutoSizeColumnMode.AllCells, DataGridViewAutoSizeColumnMode.NotSet, 20 };
yield return new object[] { DataGridViewAutoSizeColumnMode.AllCells, DataGridViewAutoSizeColumnMode.Fill, 20 };
}
[WinFormsTheory]
[MemberData(nameof(AutoSizeMode_SetWithWidth_TestData))]
public void DataGridViewColumn_AutoSizeMode_SetWithWidth_GetReturnsExpected(DataGridViewAutoSizeColumnMode oldValue, DataGridViewAutoSizeColumnMode value, int expectedWidth)
{
using var column = new DataGridViewColumn
{
Width = 10,
AutoSizeMode = oldValue
};
column.Width = 20;
column.AutoSizeMode = value;
Assert.Equal(value, column.AutoSizeMode);
Assert.Equal(value, column.InheritedAutoSizeMode);
Assert.Equal(expectedWidth, column.Width);
// Set same.
column.AutoSizeMode = value;
Assert.Equal(value, column.AutoSizeMode);
Assert.Equal(value, column.InheritedAutoSizeMode);
Assert.Equal(expectedWidth, column.Width);
}
[WinFormsFact]
public void ToolStripItem_AutoSizeMode_SetWithHandler_CallsAutoSizeModeChanged()
{
using var control = new DataGridView
{
AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
};
using var cellTemplate = new SubDataGridViewCell();
using var column = new DataGridViewColumn
{
CellTemplate = cellTemplate
};
control.Columns.Add(column);
int callCount = 0;
object expectedPreviousMode = DataGridViewAutoSizeColumnMode.Fill;
DataGridViewAutoSizeColumnModeEventHandler handler = (sender, e) =>
{
Assert.Same(control, sender);
Assert.Same(column, e.Column);
Assert.Equal(expectedPreviousMode, e.PreviousMode);
callCount++;
};
control.AutoSizeColumnModeChanged += handler;
// Set different.
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
Assert.Equal(DataGridViewAutoSizeColumnMode.AllCells, column.AutoSizeMode);
Assert.Equal(1, callCount);
// Set same.
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
Assert.Equal(DataGridViewAutoSizeColumnMode.AllCells, column.AutoSizeMode);
Assert.Equal(1, callCount);
// Set different.
expectedPreviousMode = DataGridViewAutoSizeColumnMode.AllCells;
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
Assert.Equal(DataGridViewAutoSizeColumnMode.Fill, column.AutoSizeMode);
Assert.Equal(2, callCount);
// Remove handler.
control.AutoSizeColumnModeChanged -= handler;
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
Assert.Equal(DataGridViewAutoSizeColumnMode.AllCells, column.AutoSizeMode);
Assert.Equal(2, callCount);
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEnumTypeTheoryDataInvalid), typeof(DataGridViewAutoSizeColumnMode))]
public void DataGridViewColumn_AutoSizeMode_SetInvalidValue_ThrowsInvalidEnumArgumentException(DataGridViewAutoSizeColumnMode value)
{
using var column = new DataGridViewColumn();
Assert.Throws<InvalidEnumArgumentException>("value", () => column.AutoSizeMode = value);
}
public static IEnumerable<object[]> CellTemplate_Set_TestData()
{
yield return new object[] { null };
yield return new object[] { new SubDataGridViewCell() };
}
[WinFormsTheory]
[MemberData(nameof(CellTemplate_Set_TestData))]
public void DataGridViewColumn_CellTemplate_Set_GetReturnsExpected(DataGridViewCell value)
{
using var column = new SubDataGridViewColumn
{
CellTemplate = value
};
Assert.Same(value, column.CellTemplate);
Assert.Same(value?.GetType(), column.CellType);
// Set same.
column.CellTemplate = value;
Assert.Same(value, column.CellTemplate);
Assert.Same(value?.GetType(), column.CellType);
}
public static IEnumerable<object[]> ContextMenuStrip_Set_TestData()
{
yield return new object[] { null };
yield return new object[] { new ContextMenuStrip() };
}
[WinFormsTheory]
[MemberData(nameof(ContextMenuStrip_Set_TestData))]
public void DataGridViewColumn_ContextMenuStrip_Set_GetReturnsExpected(ContextMenuStrip value)
{
using var column = new DataGridViewColumn
{
ContextMenuStrip = value
};
Assert.Same(value, column.ContextMenuStrip);
// Set same.
column.ContextMenuStrip = value;
Assert.Same(value, column.ContextMenuStrip);
}
[WinFormsTheory]
[MemberData(nameof(ContextMenuStrip_Set_TestData))]
public void DataGridViewColumn_ContextMenuStrip_SetWithCustomOldValue_GetReturnsExpected(ContextMenuStrip value)
{
using var oldValue = new ContextMenuStrip();
using var column = new DataGridViewColumn
{
ContextMenuStrip = oldValue
};
column.ContextMenuStrip = value;
Assert.Same(value, column.ContextMenuStrip);
// Set same.
column.ContextMenuStrip = value;
Assert.Same(value, column.ContextMenuStrip);
}
[WinFormsTheory]
[MemberData(nameof(ContextMenuStrip_Set_TestData))]
public void DataGridViewColumn_ContextMenuStrip_SetWithDataGridView_GetReturnsExpected(ContextMenuStrip value)
{
using var control = new DataGridView();
using var cellTemplate = new SubDataGridViewCell();
using var column = new DataGridViewColumn
{
CellTemplate = cellTemplate
};
control.Columns.Add(column);
column.ContextMenuStrip = value;
Assert.Same(value, column.ContextMenuStrip);
Assert.False(control.IsHandleCreated);
// Set same.
column.ContextMenuStrip = value;
Assert.Same(value, column.ContextMenuStrip);
Assert.False(control.IsHandleCreated);
}
[WinFormsFact]
public void DataGridViewColumn_ContextMenuStrip_SetDisposeNew_RemovesContextMenuStrip()
{
using var menu = new ContextMenuStrip();
using var control = new DataGridViewColumn
{
ContextMenuStrip = menu
};
Assert.Same(menu, control.ContextMenuStrip);
menu.Dispose();
Assert.Null(control.ContextMenuStrip);
}
[WinFormsFact]
public void DataGridViewColumn_ContextMenuStrip_SetDisposeOld_RemovesContextMenuStrip()
{
using var menu1 = new ContextMenuStrip();
using var menu2 = new ContextMenuStrip();
using var control = new DataGridViewColumn
{
ContextMenuStrip = menu1
};
Assert.Same(menu1, control.ContextMenuStrip);
control.ContextMenuStrip = menu2;
Assert.Same(menu2, control.ContextMenuStrip);
menu1.Dispose();
Assert.Same(menu2, control.ContextMenuStrip);
}
[WinFormsFact]
public void DataGridViewColumn_ContextMenuStrip_SetWithHandler_CallsContextMenuStripChanged()
{
using var control = new DataGridView();
using var cellTemplate = new SubDataGridViewCell();
using var column = new DataGridViewColumn
{
CellTemplate = cellTemplate
};
control.Columns.Add(column);
int callCount = 0;
DataGridViewColumnEventHandler handler = (sender, e) =>
{
Assert.Same(control, sender);
Assert.Same(column, e.Column);
callCount++;
};
control.ColumnContextMenuStripChanged += handler;
// Set different.
using var menu1 = new ContextMenuStrip();
column.ContextMenuStrip = menu1;
Assert.Same(menu1, column.ContextMenuStrip);
Assert.Equal(1, callCount);
// Set same.
column.ContextMenuStrip = menu1;
Assert.Same(menu1, column.ContextMenuStrip);
Assert.Equal(1, callCount);
// Set different.
using var menu2 = new ContextMenuStrip();
column.ContextMenuStrip = menu2;
Assert.Same(menu2, column.ContextMenuStrip);
Assert.Equal(2, callCount);
// Set null.
column.ContextMenuStrip = null;
Assert.Null(column.ContextMenuStrip);
Assert.Equal(3, callCount);
// Remove handler.
control.ColumnContextMenuStripChanged -= handler;
column.ContextMenuStrip = menu1;
Assert.Same(menu1, column.ContextMenuStrip);
Assert.Equal(3, callCount);
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetStringNormalizedTheoryData))]
public void DataGridViewColumn_DataPropertyName_SetWithoutDataGridView_GetReturnsExpected(string value, string expected)
{
using var column = new DataGridViewColumn
{
DataPropertyName = value
};
Assert.Equal(expected, column.DataPropertyName);
// Set same.
column.DataPropertyName = value;
Assert.Equal(expected, column.DataPropertyName);
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetStringNormalizedTheoryData))]
public void DataGridViewColumn_DataPropertyName_SetWithDataGridView_GetReturnsExpected(string value, string expected)
{
using var control = new DataGridView();
using var cellTemplate = new SubDataGridViewCell();
using var column = new DataGridViewColumn
{
CellTemplate = cellTemplate
};
control.Columns.Add(column);
column.DataPropertyName = value;
Assert.Equal(expected, column.DataPropertyName);
Assert.False(control.IsHandleCreated);
// Set same.
column.DataPropertyName = value;
Assert.Equal(expected, column.DataPropertyName);
Assert.False(control.IsHandleCreated);
}
[WinFormsFact]
public void DataGridViewColumn_DataPropertyName_SetWithHandler_CallsColumnDataPropertyNameChanged()
{
using var control = new DataGridView();
using var cellTemplate = new SubDataGridViewCell();
using var column = new DataGridViewColumn
{
CellTemplate = cellTemplate
};
control.Columns.Add(column);
int callCount = 0;
DataGridViewColumnEventHandler handler = (sender, e) =>
{
Assert.Same(control, sender);
Assert.Equal(column, e.Column);
callCount++;
};
control.ColumnDataPropertyNameChanged += handler;
// Set different.
column.DataPropertyName = "text";
Assert.Equal("text", column.DataPropertyName);
Assert.Equal(1, callCount);
// Set same.
column.DataPropertyName = "text";
Assert.Equal("text", column.DataPropertyName);
Assert.Equal(1, callCount);
// Set different.
column.DataPropertyName = null;
Assert.Empty(column.DataPropertyName);
Assert.Equal(2, callCount);
// Remove handler.
control.ColumnDataPropertyNameChanged -= handler;
column.DataPropertyName = "text";
Assert.Equal("text", column.DataPropertyName);
Assert.Equal(2, callCount);
}
public static IEnumerable<object[]> DefaultCellStyle_Set_TestData()
{
yield return new object[] { null, new DataGridViewCellStyle() };
var style1 = new DataGridViewCellStyle { Alignment = DataGridViewContentAlignment.MiddleCenter };
var style2 = new DataGridViewCellStyle { Alignment = DataGridViewContentAlignment.BottomLeft };
yield return new object[] { style1, style1 };
yield return new object[] { style2, style2 };
}
[WinFormsTheory]
[MemberData(nameof(DefaultCellStyle_Set_TestData))]
public void DataGridViewColumn_DefaultCellStyle_Set_GetReturnsExpected(DataGridViewCellStyle value, DataGridViewCellStyle expected)
{
using var column = new DataGridViewColumn
{
DefaultCellStyle = value
};
Assert.Equal(expected, column.DefaultCellStyle);
Assert.True(column.HasDefaultCellStyle);
// Set same.
column.DefaultCellStyle = value;
Assert.Equal(expected, column.DefaultCellStyle);
Assert.True(column.HasDefaultCellStyle);
}
[WinFormsTheory]
[MemberData(nameof(DefaultCellStyle_Set_TestData))]
public void DataGridViewColumn_DefaultCellStyle_SetWithNonNullOldValue_GetReturnsExpected(DataGridViewCellStyle value, DataGridViewCellStyle expected)
{
var oldValue = new DataGridViewCellStyle
{
Alignment = DataGridViewContentAlignment.MiddleCenter
};
using var column = new DataGridViewColumn
{
DefaultCellStyle = oldValue
};
column.DefaultCellStyle = value;
Assert.Equal(expected, column.DefaultCellStyle);
Assert.True(column.HasDefaultCellStyle);
// Set same.
column.DefaultCellStyle = value;
Assert.Equal(expected, column.DefaultCellStyle);
Assert.True(column.HasDefaultCellStyle);
}
[WinFormsTheory]
[MemberData(nameof(DefaultCellStyle_Set_TestData))]
public void DataGridViewColumn_DefaultCellStyle_SetWithDataGridView_GetReturnsExpected(DataGridViewCellStyle value, DataGridViewCellStyle expected)
{
using var control = new DataGridView();
using var cellTemplate = new SubDataGridViewCell();
using var column = new DataGridViewColumn
{
CellTemplate = cellTemplate
};
control.Columns.Add(column);
column.DefaultCellStyle = value;
Assert.Equal(expected, column.DefaultCellStyle);
Assert.True(column.HasDefaultCellStyle);
Assert.False(control.IsHandleCreated);
// Set same.
column.DefaultCellStyle = value;
Assert.Equal(expected, column.DefaultCellStyle);
Assert.True(column.HasDefaultCellStyle);
Assert.False(control.IsHandleCreated);
}
[WinFormsTheory]
[MemberData(nameof(DefaultCellStyle_Set_TestData))]
public void DataGridViewColumn_DefaultCellStyle_SetWithDataGridViewWithNonNullOldValue_GetReturnsExpected(DataGridViewCellStyle value, DataGridViewCellStyle expected)
{
var oldValue = new DataGridViewCellStyle
{
Alignment = DataGridViewContentAlignment.MiddleCenter
};
using var control = new DataGridView();
using var cellTemplate = new SubDataGridViewCell();
using var column = new DataGridViewColumn
{
CellTemplate = cellTemplate,
DefaultCellStyle = oldValue
};
control.Columns.Add(column);
column.DefaultCellStyle = value;
Assert.Equal(expected, column.DefaultCellStyle);
Assert.True(column.HasDefaultCellStyle);
Assert.False(control.IsHandleCreated);
// Set same.
column.DefaultCellStyle = value;
Assert.Equal(expected, column.DefaultCellStyle);
Assert.True(column.HasDefaultCellStyle);
Assert.False(control.IsHandleCreated);
}
[WinFormsFact]
public void DataGridViewColumn_DefaultCellStyle_SetWithDataGridView_CallsColumnDefaultCellStyleChanged()
{
using var control = new DataGridView();
using var cellTemplate = new SubDataGridViewCell();
using var column = new DataGridViewColumn
{
CellTemplate = cellTemplate
};
control.Columns.Add(column);
int callCount = 0;
DataGridViewColumnEventHandler handler = (sender, e) =>
{
Assert.Same(control, sender);
Assert.Same(column, e.Column);
callCount++;
};
control.ColumnDefaultCellStyleChanged += handler;
var style1 = new DataGridViewCellStyle
{
Alignment = DataGridViewContentAlignment.MiddleCenter
};
// Set non-null.
column.DefaultCellStyle = style1;
Assert.Equal(style1, column.DefaultCellStyle);
Assert.True(column.HasDefaultCellStyle);
Assert.Equal(1, callCount);
// Set same.
column.DefaultCellStyle = style1;
Assert.Equal(style1, column.DefaultCellStyle);
Assert.True(column.HasDefaultCellStyle);
Assert.Equal(1, callCount);
// Set different.
var style2 = new DataGridViewCellStyle
{
Alignment = DataGridViewContentAlignment.BottomCenter
};
column.DefaultCellStyle = style2;
Assert.Same(style2, column.DefaultCellStyle);
Assert.True(column.HasDefaultCellStyle);
Assert.Equal(2, callCount);
// Set null.
column.DefaultCellStyle = null;
Assert.NotNull(column.DefaultCellStyle);
Assert.True(column.HasDefaultCellStyle);
Assert.Equal(3, callCount);
// Set null again.
column.DefaultCellStyle = null;
Assert.NotNull(column.DefaultCellStyle);
Assert.True(column.HasDefaultCellStyle);
Assert.Equal(4, callCount);
// Set non-null.
column.DefaultCellStyle = style2;
Assert.NotNull(column.DefaultCellStyle);
Assert.True(column.HasDefaultCellStyle);
Assert.Equal(5, callCount);
// Remove handler.
control.ColumnDefaultCellStyleChanged -= handler;
column.DefaultCellStyle = style1;
Assert.Equal(style1, column.DefaultCellStyle);
Assert.True(column.HasDefaultCellStyle);
Assert.Equal(5, callCount);
}
public static IEnumerable<object[]> DefaultHeaderCellType_Set_TestData()
{
yield return new object[] { null, typeof(DataGridViewColumnHeaderCell) };
yield return new object[] { typeof(DataGridViewRowHeaderCell), typeof(DataGridViewRowHeaderCell) };
yield return new object[] { typeof(DataGridViewColumnHeaderCell), typeof(DataGridViewColumnHeaderCell) };
}
[WinFormsTheory]
[MemberData(nameof(DefaultHeaderCellType_Set_TestData))]
public void DataGridViewColumn_DefaultHeaderCellType_Set_GetReturnsExpected(Type value, Type expected)
{
using var column = new DataGridViewColumn
{
DefaultHeaderCellType = value
};
Assert.Equal(expected, column.DefaultHeaderCellType);
// Set same.
column.DefaultHeaderCellType = value;
Assert.Equal(expected, column.DefaultHeaderCellType);
}
[WinFormsTheory]
[InlineData(typeof(DataGridViewRowHeaderCell))]
[InlineData(typeof(DataGridViewColumnHeaderCell))]
[InlineData(typeof(DataGridViewHeaderCell))]
public void DataGridViewColumn_DefaultHeaderCellType_SetWithNonNullOldValue_GetReturnsExpected(Type value)
{
using var column = new SubDataGridViewColumn
{
DefaultHeaderCellType = typeof(DataGridViewRowHeaderCell)
};
column.DefaultHeaderCellType = value;
Assert.Equal(value, column.DefaultHeaderCellType);
// Set same.
column.DefaultHeaderCellType = value;
Assert.Equal(value, column.DefaultHeaderCellType);
}
[WinFormsTheory]
[MemberData(nameof(DefaultHeaderCellType_Set_TestData))]
public void DataGridViewColumn_DefaultHeaderCellType_SetWithDataGridView_GetReturnsExpected(Type value, Type expected)
{
using var control = new DataGridView();
using var cellTemplate = new SubDataGridViewCell();
using var column = new DataGridViewColumn
{
CellTemplate = cellTemplate
};
control.Columns.Add(column);
column.DefaultHeaderCellType = value;
Assert.Equal(expected, column.DefaultHeaderCellType);
// Set same.
column.DefaultHeaderCellType = value;
Assert.Equal(expected, column.DefaultHeaderCellType);
}
[WinFormsTheory]
[InlineData(typeof(DataGridViewRowHeaderCell))]
[InlineData(typeof(DataGridViewColumnHeaderCell))]
[InlineData(typeof(DataGridViewHeaderCell))]
public void DataGridViewColumn_DefaultHeaderCellType_SetWithDataGridViewNonNullOldValue_GetReturnsExpected(Type value)
{
using var control = new DataGridView();
using var cellTemplate = new SubDataGridViewCell();
using var column = new DataGridViewColumn
{
CellTemplate = cellTemplate
};
control.Columns.Add(column);
column.DefaultHeaderCellType = typeof(DataGridViewRowHeaderCell);
column.DefaultHeaderCellType = value;
Assert.Equal(value, column.DefaultHeaderCellType);
// Set same.
column.DefaultHeaderCellType = value;
Assert.Equal(value, column.DefaultHeaderCellType);
}
[WinFormsTheory]
[InlineData(typeof(int))]
public void DataGridViewColumn_DefaultHeaderCellType_SetInvalidWithNullOldValue_GetReturnsExpected(Type value)
{
using var column = new DataGridViewRow();
Assert.Throws<ArgumentException>("value", () => column.DefaultHeaderCellType = value);
}
[WinFormsTheory]
[InlineData(null)]
[InlineData(typeof(int))]
public void DataGridViewColumn_DefaultHeaderCellType_SetInvalidWithNonNullOldValue_GetReturnsExpected(Type value)
{
using var column = new DataGridViewColumn
{
DefaultHeaderCellType = typeof(DataGridViewRowHeaderCell)
};
Assert.Throws<ArgumentException>("value", () => column.DefaultHeaderCellType = value);
}
[WinFormsFact]
public void DataGridViewColumn_Displayed_Get_ReturnsExpected()
{
using var control = new DataGridView();
using var cellTemplate = new SubDataGridViewCell();
using var column = new DataGridViewColumn
{
CellTemplate = cellTemplate
};
control.Columns.Add(column);
Assert.False(column.Displayed);
}
public static IEnumerable<object[]> DividerWidth_Set_TestData()
{
yield return new object[] { 0 };
yield return new object[] { 1 };
yield return new object[] { 65536 };
}
[WinFormsTheory]
[MemberData(nameof(DividerWidth_Set_TestData))]
public void DataGridViewColumn_DividerWidth_Set_GetReturnsExpected(int value)
{
using var column = new DataGridViewColumn
{
DividerWidth = value
};
Assert.Equal(value, column.DividerWidth);
// Set same.
column.DividerWidth = value;
Assert.Equal(value, column.DividerWidth);
}
[WinFormsTheory]
[MemberData(nameof(DividerWidth_Set_TestData))]
public void DataGridViewColumn_DividerWidth_SetWithDataGridView_GetReturnsExpected(int value)
{
using var control = new DataGridView
{
ColumnCount = 1,
RowCount = 1
};
DataGridViewColumn column = control.Columns[0];
column.DividerWidth = value;
Assert.Equal(value, column.DividerWidth);
Assert.False(control.IsHandleCreated);
// Set same.
column.DividerWidth = value;
Assert.Equal(value, column.DividerWidth);
Assert.False(control.IsHandleCreated);
}
[WinFormsFact]
public void DataGridViewColumn_DividerWidth_SetWithDataGridView_CallsColumnDividerWidthChanged()
{
using var control = new DataGridView();
using var cellTemplate = new SubDataGridViewCell();
using var column = new DataGridViewColumn
{
CellTemplate = cellTemplate
};
control.Columns.Add(column);
int callCount = 0;
DataGridViewColumnEventHandler handler = (sender, e) =>
{
callCount++;
Assert.Same(control, sender);
Assert.Same(column, e.Column);
};
control.ColumnDividerWidthChanged += handler;
// Set non-zero.
column.DividerWidth = 4;
Assert.Equal(4, column.DividerWidth);
Assert.Equal(1, callCount);
// Set same.
column.DividerWidth = 4;
Assert.Equal(4, column.DividerWidth);
Assert.Equal(1, callCount);
// Set different.
column.DividerWidth = 3;
Assert.Equal(3, column.DividerWidth);
Assert.Equal(2, callCount);
// Remove handler.
control.ColumnDividerWidthChanged -= handler;
column.DividerWidth = 4;
Assert.Equal(4, column.DividerWidth);
Assert.Equal(2, callCount);
}
[WinFormsTheory]
[InlineData(-1)]
[InlineData(65537)]
public void DataGridViewColumn_DividerWidth_SetInvalid_ThrowsArgumentOutOfRangeException(int value)
{
using var column = new DataGridViewColumn();
Assert.Throws<ArgumentOutOfRangeException>("value", () => column.DividerWidth = value);
}
[WinFormsTheory]
[InlineData(DataGridViewElementStates.None, false)]
[InlineData(DataGridViewElementStates.Frozen, true)]
[InlineData(DataGridViewElementStates.Frozen | DataGridViewElementStates.ReadOnly, true)]
[InlineData(DataGridViewElementStates.Frozen | DataGridViewElementStates.Selected, true)]
public void DataGridViewColumn_Frozen_GetWithCustomState_ReturnsExpected(DataGridViewElementStates state, bool expected)
{
using var row = new CustomStateDataGridViewColumn
{
StateResult = state
};
Assert.Equal(expected, row.Frozen);
}
[WinFormsFact]
public void DataGridViewColumn_Frozen_GetWithDataGridView_ReturnsExpected()
{
using var control = new DataGridView();
using var cellTemplate = new SubDataGridViewCell();
using var column = new DataGridViewColumn
{
CellTemplate = cellTemplate
};
control.Columns.Add(column);
Assert.False(control.Columns[0].Frozen);
}
public static IEnumerable<object[]> Frozen_Set_TestData()
{
foreach (bool visible in new bool[] { true, false })
{
foreach (DataGridViewAutoSizeColumnMode autoSizeMode in Enum.GetValues(typeof(DataGridViewAutoSizeColumnMode)))
{
yield return new object[] { visible, autoSizeMode, true };
yield return new object[] { visible, autoSizeMode, false };
}
}
}
[WinFormsTheory]
[MemberData(nameof(Frozen_Set_TestData))]
public void DataGridViewColumn_Frozen_Set_GetReturnsExpected(bool visible, DataGridViewAutoSizeColumnMode autoSizeMode, bool value)
{
using var column = new DataGridViewColumn
{
Visible = visible,
AutoSizeMode = autoSizeMode,
Frozen = value
};
Assert.Equal(value, column.Frozen);
Assert.Equal(autoSizeMode, column.AutoSizeMode);
// Set same.
column.Frozen = value;
Assert.Equal(value, column.Frozen);
Assert.Equal(autoSizeMode, column.AutoSizeMode);
// Set different.
column.Frozen = !value;
Assert.Equal(!value, column.Frozen);
Assert.Equal(autoSizeMode, column.AutoSizeMode);
}
public static IEnumerable<object[]> Frozen_SetWithDataGridView_TestData()
{
foreach (bool visible in new bool[] { true, false })
{
foreach (DataGridViewAutoSizeColumnMode autoSizeMode in Enum.GetValues(typeof(DataGridViewAutoSizeColumnMode)))
{
if (autoSizeMode == DataGridViewAutoSizeColumnMode.Fill)
{
continue;
}
yield return new object[] { visible, autoSizeMode, true, autoSizeMode, autoSizeMode };
yield return new object[] { visible, autoSizeMode, false, autoSizeMode, autoSizeMode };
}
}
yield return new object[] { true, DataGridViewAutoSizeColumnMode.Fill, true, DataGridViewAutoSizeColumnsMode.None, DataGridViewAutoSizeColumnsMode.None };
yield return new object[] { true, DataGridViewAutoSizeColumnMode.Fill, false, DataGridViewAutoSizeColumnsMode.Fill, DataGridViewAutoSizeColumnsMode.None };
yield return new object[] { false, DataGridViewAutoSizeColumnMode.Fill, true, DataGridViewAutoSizeColumnsMode.Fill, DataGridViewAutoSizeColumnsMode.Fill };
yield return new object[] { false, DataGridViewAutoSizeColumnMode.Fill, false, DataGridViewAutoSizeColumnsMode.Fill, DataGridViewAutoSizeColumnsMode.Fill };
}
[WinFormsTheory]
[MemberData(nameof(Frozen_SetWithDataGridView_TestData))]
public void DataGridViewColumn_Frozen_SetWithDataGridView_GetReturnsExpected(bool visible, DataGridViewAutoSizeColumnMode autoSizeMode, bool value, DataGridViewAutoSizeColumnMode expectedAutoSizeMode1, DataGridViewAutoSizeColumnMode expectedAutoSizeMode2)
{
using var control = new DataGridView
{
AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader
};
using var column = new DataGridViewColumn
{
Visible = visible,
AutoSizeMode = autoSizeMode,
CellTemplate = new SubDataGridViewCell()
};
control.Columns.Add(column);
column.Frozen = value;
Assert.Equal(value, column.Frozen);
Assert.Equal(expectedAutoSizeMode1, column.AutoSizeMode);
// Set same.
column.Frozen = value;
Assert.Equal(value, column.Frozen);
Assert.Equal(expectedAutoSizeMode1, column.AutoSizeMode);
// Set different.
column.Frozen = !value;
Assert.Equal(!value, column.Frozen);
Assert.Equal(expectedAutoSizeMode2, column.AutoSizeMode);
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetBoolTheoryData))]
public void DataGridViewColumn_Frozen_SetWithPreviousColumns_SetsToFrozen(bool previousVisible)
{
using var control = new DataGridView();
using var column1 = new DataGridViewColumn
{
CellTemplate = new SubDataGridViewCell()
};
using var column2 = new DataGridViewColumn
{
CellTemplate = new SubDataGridViewCell(),
Visible = previousVisible
};
using var column3 = new DataGridViewColumn
{
CellTemplate = new SubDataGridViewCell()
};
using var column4 = new DataGridViewColumn
{
CellTemplate = new SubDataGridViewCell()
};
control.Columns.Add(column1);
control.Columns.Add(column2);
control.Columns.Add(column3);
control.Columns.Add(column4);
// Freeze middle.
column3.Frozen = true;
Assert.True(column1.Frozen);
Assert.Equal(previousVisible, column2.Frozen);
Assert.True(column3.Frozen);
Assert.False(column4.Frozen);
// Freeze again.
column3.Frozen = true;
Assert.True(column1.Frozen);
Assert.Equal(previousVisible, column2.Frozen);
Assert.True(column3.Frozen);
Assert.False(column4.Frozen);
// Freeze later.
column4.Frozen = true;
Assert.True(column1.Frozen);
Assert.Equal(previousVisible, column2.Frozen);
Assert.True(column3.Frozen);
Assert.True(column4.Frozen);
// Unfreeze middle.
column3.Frozen = false;
Assert.True(column1.Frozen);
Assert.Equal(previousVisible, column2.Frozen);
Assert.False(column3.Frozen);
Assert.False(column4.Frozen);
// Unfreeze first.
column1.Frozen = false;
Assert.False(column1.Frozen);
Assert.False(column2.Frozen);
Assert.False(column3.Frozen);
Assert.False(column4.Frozen);
}
[WinFormsFact]
public void DataGridViewColumn_Frozen_SetWithDataGridView_CallsColumnStateChanged()
{
using var control = new DataGridView();
using var cellTemplate = new SubDataGridViewCell();
using var column = new DataGridViewColumn
{
CellTemplate = cellTemplate,
Frozen = true
};
control.Columns.Add(column);
int callCount = 0;
DataGridViewColumnStateChangedEventHandler handler = (sender, e) =>
{
callCount++;
Assert.Same(control, sender);
Assert.Same(column, e.Column);
Assert.Equal(DataGridViewElementStates.Frozen, e.StateChanged);
};
control.ColumnStateChanged += handler;
// Set different.
column.Frozen = false;
Assert.False(column.Frozen);
Assert.Equal(1, callCount);
// Set same.
column.Frozen = false;
Assert.False(column.Frozen);
Assert.Equal(1, callCount);
// Set different.
column.Frozen = true;
Assert.True(column.Frozen);
Assert.Equal(2, callCount);
// Remove handler.
control.ColumnStateChanged -= handler;
column.Frozen = false;
Assert.False(column.Frozen);
Assert.Equal(2, callCount);
}
[WinFormsFact]
public void DataGridViewColumn_HeaderCell_Get_ReturnsExpected()
{
using var column = new SubDataGridViewColumn();
Assert.IsType<DataGridViewColumnHeaderCell>(column.HeaderCell);
Assert.Same(column, column.HeaderCell.OwningColumn);
Assert.Null(column.HeaderCell.OwningRow);
Assert.Same(column.HeaderCell, column.HeaderCell);
Assert.Same(column.HeaderCell, column.HeaderCellCore);
Assert.Empty(column.HeaderText);
}
[WinFormsFact]
public void DataGridViewColumn_HeaderCellCore_Get_ReturnsExpected()
{
using var column = new SubDataGridViewColumn();
Assert.IsType<DataGridViewColumnHeaderCell>(column.HeaderCellCore);
Assert.Same(column, column.HeaderCellCore.OwningColumn);
Assert.Null(column.HeaderCellCore.OwningRow);
Assert.Same(column.HeaderCellCore, column.HeaderCellCore);
Assert.Same(column.HeaderCell, column.HeaderCellCore);
Assert.Empty(column.HeaderText);
}
[WinFormsTheory]
[InlineData(DataGridViewAutoSizeColumnsMode.AllCells, DataGridViewAutoSizeColumnMode.AllCells)]
[InlineData(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader, DataGridViewAutoSizeColumnMode.AllCellsExceptHeader)]
[InlineData(DataGridViewAutoSizeColumnsMode.ColumnHeader, DataGridViewAutoSizeColumnMode.ColumnHeader)]
[InlineData(DataGridViewAutoSizeColumnsMode.DisplayedCells, DataGridViewAutoSizeColumnMode.DisplayedCells)]
[InlineData(DataGridViewAutoSizeColumnsMode.DisplayedCellsExceptHeader, DataGridViewAutoSizeColumnMode.DisplayedCellsExceptHeader)]
[InlineData(DataGridViewAutoSizeColumnsMode.Fill, DataGridViewAutoSizeColumnMode.Fill)]
[InlineData(DataGridViewAutoSizeColumnsMode.None, DataGridViewAutoSizeColumnMode.None)]
public void DataGridViewColumn_InheritedAutoSizeMode_GetWithDataGridView_ReturnsExpected(DataGridViewAutoSizeColumnsMode mode, DataGridViewAutoSizeColumnMode expected)
{
using var control = new DataGridView
{
AutoSizeColumnsMode = mode
};
using var cellTemplate = new SubDataGridViewCell();
using var column = new DataGridViewColumn
{
CellTemplate = cellTemplate
};
control.Columns.Add(column);
Assert.Equal(expected, column.InheritedAutoSizeMode);
}
[WinFormsTheory]
[InlineData(DataGridViewElementStates.None, false)]
[InlineData(DataGridViewElementStates.ReadOnly, true)]
[InlineData(DataGridViewElementStates.ReadOnly | DataGridViewElementStates.Visible, true)]
[InlineData(DataGridViewElementStates.ReadOnly | DataGridViewElementStates.Selected, true)]
public void DataGridViewColumn_ReadOnly_GetWithCustomState_ReturnsExpected(DataGridViewElementStates state, bool expected)
{
using var column = new CustomStateDataGridViewColumn
{
StateResult = state
};
Assert.Equal(expected, column.ReadOnly);
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetBoolTheoryData))]
public void DataGridViewRow_ReadOnly_GetWithDataGridView_ReturnsExpected(bool dataGridViewReadOnly)
{
using var control = new DataGridView
{
ReadOnly = dataGridViewReadOnly
};
using var cellTemplate = new SubDataGridViewCell();
using var column = new DataGridViewColumn
{
CellTemplate = cellTemplate
};
control.Columns.Add(column);
Assert.Equal(dataGridViewReadOnly, column.ReadOnly);
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetBoolTheoryData))]
public void DataGridViewColumn_ReadOnly_Set_GetReturnsExpected(bool value)
{
using var column = new DataGridViewColumn
{
ReadOnly = value
};
Assert.Equal(value, column.ReadOnly);
Assert.Equal(value, (column.State & DataGridViewElementStates.ReadOnly) != 0);
// Set same.
column.ReadOnly = value;
Assert.Equal(value, column.ReadOnly);
Assert.Equal(value, (column.State & DataGridViewElementStates.ReadOnly) != 0);
// Set different.
column.ReadOnly = !value;
Assert.Equal(!value, column.ReadOnly);
Assert.Equal(!value, (column.State & DataGridViewElementStates.ReadOnly) != 0);
}
[WinFormsTheory]
[InlineData(true, true)]
[InlineData(true, false)]
[InlineData(false, true)]
[InlineData(false, false)]
public void DataGridViewColumn_ReadOnly_SetWithDataGridView_GetReturnsExpected(bool controlReadOnly, bool value)
{
using var control = new DataGridView();
using var cellTemplate = new SubDataGridViewCell();
using var column = new DataGridViewColumn
{
CellTemplate = cellTemplate
};
control.Columns.Add(column);
control.ReadOnly = controlReadOnly;
column.ReadOnly = value;
Assert.Equal(controlReadOnly || value, column.ReadOnly);
// Set same.
column.ReadOnly = value;
Assert.Equal(controlReadOnly || value, column.ReadOnly);
// Set different.
column.ReadOnly = !value;
Assert.Equal(controlReadOnly || !value, column.ReadOnly);
control.ReadOnly = false;
Assert.Equal(!controlReadOnly && !value, column.ReadOnly);
}
[WinFormsFact]
public void DataGridViewColumn_ReadOnly_SetWithDataGridView_CallsColumnStateChanged()
{
using var control = new DataGridView();
using var cellTemplate = new SubDataGridViewCell();
using var column = new DataGridViewColumn
{
CellTemplate = cellTemplate
};
control.Columns.Add(column);
int callCount = 0;
DataGridViewColumnStateChangedEventHandler handler = (sender, e) =>
{
callCount++;
Assert.Same(control, sender);
Assert.Same(column, e.Column);
Assert.Equal(DataGridViewElementStates.ReadOnly, e.StateChanged);
};
control.ColumnStateChanged += handler;
// Set true.
column.ReadOnly = true;
Assert.True(column.ReadOnly);
Assert.Equal(1, callCount);
// Set same.
column.ReadOnly = true;
Assert.True(column.ReadOnly);
Assert.Equal(1, callCount);
// Set different.
column.ReadOnly = false;
Assert.False(column.ReadOnly);
Assert.Equal(2, callCount);
// Remove handler.
control.ColumnStateChanged -= handler;
column.ReadOnly = true;
Assert.True(column.ReadOnly);
Assert.Equal(2, callCount);
}
[WinFormsTheory]
[InlineData(DataGridViewElementStates.None, false)]
[InlineData(DataGridViewElementStates.Visible, true)]
[InlineData(DataGridViewElementStates.Visible | DataGridViewElementStates.ReadOnly, true)]
[InlineData(DataGridViewElementStates.Visible | DataGridViewElementStates.Selected, true)]
public void DataGridViewColumn_Visible_GetWithCustomState_ReturnsExpected(DataGridViewElementStates state, bool expected)
{
using var row = new CustomStateDataGridViewColumn
{
StateResult = state
};
Assert.Equal(expected, row.Visible);
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetBoolTheoryData))]
public void DataGridViewColumn_Visible_GetWithDataGridView_ReturnsExpected(bool visible)
{
using var control = new DataGridView
{
Visible = visible
};
using var cellTemplate = new SubDataGridViewCell();
using var column = new DataGridViewColumn
{
CellTemplate = cellTemplate
};
control.Columns.Add(column);
Assert.True(control.Columns[0].Visible);
}
public static IEnumerable<object[]> Visible_Set_TestData()
{
foreach (DataGridViewAutoSizeColumnMode autoSizeMode in Enum.GetValues(typeof(DataGridViewAutoSizeColumnMode)))
{
foreach (bool frozen in new bool[] { true, false })
{
yield return new object[] { autoSizeMode, frozen, true };
yield return new object[] { autoSizeMode, frozen, false };
}
}
}
[WinFormsTheory]
[MemberData(nameof(Visible_Set_TestData))]
public void DataGridViewColumn_Visible_Set_GetReturnsExpected(DataGridViewAutoSizeColumnMode autoSizeMode, bool frozen, bool value)
{
using var column = new DataGridViewColumn
{
AutoSizeMode = autoSizeMode,
Frozen = frozen,
Visible = value
};
Assert.Equal(value, column.Visible);
Assert.Equal(autoSizeMode, column.AutoSizeMode);
// Set same.
column.Visible = value;
Assert.Equal(value, column.Visible);
Assert.Equal(autoSizeMode, column.AutoSizeMode);
// Set different.
column.Visible = !value;
Assert.Equal(!value, column.Visible);
Assert.Equal(autoSizeMode, column.AutoSizeMode);
}
public static IEnumerable<object[]> Visible_SetWithDataGridView_TestData()
{
foreach (bool visible in new bool[] { true, false })
{
foreach (bool columnHeadersVisible in new bool[] { true, false })
{
foreach (DataGridViewAutoSizeColumnMode autoSizeMode in Enum.GetValues(typeof(DataGridViewAutoSizeColumnMode)))
{
if (!columnHeadersVisible && autoSizeMode == DataGridViewAutoSizeColumnMode.ColumnHeader)
{
continue;
}
yield return new object[] { visible, columnHeadersVisible, autoSizeMode, true, autoSizeMode, autoSizeMode };
yield return new object[] { visible, columnHeadersVisible, autoSizeMode, false, autoSizeMode, autoSizeMode };
}
}
}
}
[WinFormsTheory]
[MemberData(nameof(Visible_SetWithDataGridView_TestData))]
public void DataGridViewColumn_Visible_SetWithDataGridView_GetReturnsExpected(bool visible, bool columnHeadersVisible, DataGridViewAutoSizeColumnMode autoSizeMode, bool value, DataGridViewAutoSizeColumnMode expectedAutoSizeMode1, DataGridViewAutoSizeColumnMode expectedAutoSizeMode2)
{
using var control = new DataGridView
{
Visible = visible,
ColumnHeadersVisible = columnHeadersVisible,
AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader
};
using var cellTemplate = new SubDataGridViewCell();
using var column = new DataGridViewColumn
{
AutoSizeMode = autoSizeMode,
CellTemplate = cellTemplate
};
control.Columns.Add(column);
column.Visible = value;
Assert.Equal(value, column.Visible);
Assert.Equal(expectedAutoSizeMode1, column.AutoSizeMode);
// Set same.
column.Visible = value;
Assert.Equal(value, column.Visible);
Assert.Equal(expectedAutoSizeMode1, column.AutoSizeMode);
// Set different.
column.Visible = !value;
Assert.Equal(!value, column.Visible);
Assert.Equal(expectedAutoSizeMode2, column.AutoSizeMode);
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetBoolTheoryData))]
public void DataGridViewColumn_Visible_SetWithPreviousColumns_SetsToVisible(bool previousVisible)
{
using var control = new DataGridView();
using var column1 = new DataGridViewColumn
{
CellTemplate = new SubDataGridViewCell()
};
using var column2 = new DataGridViewColumn
{
CellTemplate = new SubDataGridViewCell(),
Visible = previousVisible
};
using var column3 = new DataGridViewColumn
{
CellTemplate = new SubDataGridViewCell()
};
using var column4 = new DataGridViewColumn
{
CellTemplate = new SubDataGridViewCell()
};
control.Columns.Add(column1);
control.Columns.Add(column2);
control.Columns.Add(column3);
control.Columns.Add(column4);
// Freeze middle.
column3.Visible = true;
Assert.True(column1.Visible);
Assert.Equal(previousVisible, column2.Visible);
Assert.True(column3.Visible);
Assert.True(column4.Visible);
// Freeze again.
column3.Visible = true;
Assert.True(column1.Visible);
Assert.Equal(previousVisible, column2.Visible);
Assert.True(column3.Visible);
Assert.True(column4.Visible);
// Freeze later.
column4.Visible = true;
Assert.True(column1.Visible);
Assert.Equal(previousVisible, column2.Visible);
Assert.True(column3.Visible);
Assert.True(column4.Visible);
// Unfreeze middle.
column3.Visible = false;
Assert.True(column1.Visible);
Assert.Equal(previousVisible, column2.Visible);
Assert.False(column3.Visible);
Assert.True(column4.Visible);
// Unfreeze first.
column1.Visible = false;
Assert.False(column1.Visible);
Assert.Equal(previousVisible, column2.Visible);
Assert.False(column3.Visible);
Assert.True(column4.Visible);
}
[WinFormsFact]
public void DataGridViewColumn_Visible_SetWithDataGridView_CallsColumnStateChanged()
{
using var control = new DataGridView();
using var cellTemplate = new SubDataGridViewCell();
using var column = new DataGridViewColumn
{
CellTemplate = cellTemplate,
Visible = true
};
control.Columns.Add(column);
int callCount = 0;
DataGridViewColumnStateChangedEventHandler handler = (sender, e) =>
{
callCount++;
Assert.Same(control, sender);
Assert.Same(column, e.Column);
Assert.Equal(DataGridViewElementStates.Visible, e.StateChanged);
};
control.ColumnStateChanged += handler;
// Set different.
column.Visible = false;
Assert.False(column.Visible);
Assert.Equal(1, callCount);
// Set same.
column.Visible = false;
Assert.False(column.Visible);
Assert.Equal(1, callCount);
// Set different.
column.Visible = true;
Assert.True(column.Visible);
Assert.Equal(2, callCount);
// Remove handler.
control.ColumnStateChanged -= handler;
column.Visible = false;
Assert.False(column.Visible);
Assert.Equal(2, callCount);
}
public static IEnumerable<object[]> GetPreferred_WithoutDataGridView_TestData()
{
foreach (bool fixedHeight in new bool[] { true, false })
{
yield return new object[] { DataGridViewAutoSizeColumnMode.ColumnHeader, fixedHeight };
yield return new object[] { DataGridViewAutoSizeColumnMode.AllCellsExceptHeader, fixedHeight };
yield return new object[] { DataGridViewAutoSizeColumnMode.AllCells, fixedHeight };
yield return new object[] { DataGridViewAutoSizeColumnMode.DisplayedCellsExceptHeader, fixedHeight };
yield return new object[] { DataGridViewAutoSizeColumnMode.DisplayedCells, fixedHeight };
}
}
[WinFormsTheory]
[MemberData(nameof(GetPreferred_WithoutDataGridView_TestData))]
public void DataGridViewColumn_GetPreferredWidth_InvokeWithoutDataGridView_ReturnsExpected(DataGridViewAutoSizeColumnMode autoSizeColumnMode, bool fixedHeight)
{
using var column = new SubDataGridViewColumn();
Assert.Equal(-1, column.GetPreferredWidth(autoSizeColumnMode, fixedHeight));
}
[WinFormsTheory]
[InlineData(DataGridViewAutoSizeColumnMode.NotSet)]
[InlineData(DataGridViewAutoSizeColumnMode.None)]
[InlineData(DataGridViewAutoSizeColumnMode.Fill)]
public void DataGridViewColumn_GetPreferredWidth_NotApplicableAutoSizeColumnMode_ThrowsArgumentException(DataGridViewAutoSizeColumnMode autoSizeColumnMode)
{
using var column = new SubDataGridViewColumn();
Assert.Throws<ArgumentException>(null, () => column.GetPreferredWidth(autoSizeColumnMode, fixedHeight: true));
Assert.Throws<ArgumentException>(null, () => column.GetPreferredWidth(autoSizeColumnMode, fixedHeight: false));
}
[WinFormsTheory]
[CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEnumTypeTheoryDataInvalid), typeof(DataGridViewAutoSizeColumnMode))]
public void DataGridViewColumn_GetPreferredWidth_NotApplicableAutoSizeColumnMode_ThrowsInvalidEnumArgumentException(DataGridViewAutoSizeColumnMode autoSizeColumnMode)
{
using var column = new SubDataGridViewColumn();
Assert.Throws<InvalidEnumArgumentException>("autoSizeColumnMode", () => column.GetPreferredWidth(autoSizeColumnMode, fixedHeight: true));
Assert.Throws<InvalidEnumArgumentException>("autoSizeColumnMode", () => column.GetPreferredWidth(autoSizeColumnMode, fixedHeight: false));
}
[WinFormsFact]
public void DataGridViewColumn_ToString_Invoke_ReturnsExpected()
{
using var column = new DataGridViewColumn();
Assert.Equal("DataGridViewColumn { Name=, Index=-1 }", column.ToString());
}
[WinFormsFact]
public void DataGridViewColumn_ToString_InvokeWithName_ReturnsExpected()
{
using var column = new DataGridViewColumn
{
Name = "name"
};
Assert.Equal("DataGridViewColumn { Name=name, Index=-1 }", column.ToString());
}
private class CustomStateDataGridViewColumn : DataGridViewColumn
{
public DataGridViewElementStates StateResult { get; set; }
public override DataGridViewElementStates State => StateResult;
}
private class SubDataGridViewCell : DataGridViewCell
{
}
private class SubDataGridViewColumn : DataGridViewColumn
{
public SubDataGridViewColumn() : base()
{
}
public SubDataGridViewColumn(DataGridViewCell cellTemplate) : base(cellTemplate)
{
}
public new DataGridViewHeaderCell HeaderCellCore => base.HeaderCellCore;
public new bool IsRow => base.IsRow;
}
}
}
| 42.499455 | 291 | 0.621741 | [
"MIT"
] | abdullah1133/winforms | src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/DataGridViewColumnTests.cs | 77,946 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WastePermits.Model.EarlyBound
{
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "9.0.0.9369")]
public enum ImportFile_FileTypeCode
{
[System.Runtime.Serialization.EnumMemberAttribute()]
Attachment = 2,
[System.Runtime.Serialization.EnumMemberAttribute()]
CSV = 0,
[System.Runtime.Serialization.EnumMemberAttribute()]
XLSX = 3,
[System.Runtime.Serialization.EnumMemberAttribute()]
XMLSpreadsheet2003 = 1,
}
} | 29.3 | 80 | 0.59727 | [
"Unlicense"
] | DEFRA/license-and-permitting-dynamics | Crm/WastePermits/Defra.Lp.WastePermits/Model/EarlyBound/OptionSets/ImportFile_FileTypeCode.cs | 879 | C# |
#region Copyright 2014 Exceptionless
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// http://www.gnu.org/licenses/agpl-3.0.html
#endregion
using System;
using System.Collections.Generic;
using Exceptionless.Core.Caching;
using Exceptionless.Core.Messaging;
using Exceptionless.Models;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.IdGenerators;
using MongoDB.Bson.Serialization.Options;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
namespace Exceptionless.Api.Tests.Repositories.InMemory {
public class MonthStackStatsRepository : MongoRepositoryOwnedByProjectAndStack<MonthStackStats>, IMonthStackStatsRepository {
public MonthStackStatsRepository(MongoDatabase database, ICacheClient cacheClient = null, IMessagePublisher messagePublisher = null)
: base(database, cacheClient, messagePublisher) {
_getIdValue = s => s;
}
public ICollection<MonthStackStats> GetRange(string start, string end) {
var query = Query.And(Query.GTE(FieldNames.Id, start), Query.LTE(FieldNames.Id, end));
return Find<MonthStackStats>(new MultiOptions().WithQuery(query));
}
public long IncrementStats(string id, DateTime localDate) {
var update = Update.Inc(FieldNames.Total, 1)
.Inc(String.Format(FieldNames.DayStats_Format, localDate.Day), 1);
return UpdateAll(new QueryOptions().WithId(id), update);
}
#region Collection Setup
public const string CollectionName = "stack.stats.month";
protected override string GetCollectionName() {
return CollectionName;
}
public static class FieldNames {
public const string DayStats_Format = "day.{0}";
public const string Id = CommonFieldNames.Id;
public const string ProjectId = CommonFieldNames.ProjectId;
public const string StackId = CommonFieldNames.StackId;
public const string Total = "tot";
public const string DayStats = "day";
}
protected override void InitializeCollection(MongoDatabase database) {
base.InitializeCollection(database);
_collection.CreateIndex(IndexKeys.Ascending(FieldNames.ProjectId), IndexOptions.SetBackground(true));
_collection.CreateIndex(IndexKeys.Ascending(FieldNames.StackId), IndexOptions.SetBackground(true));
}
protected override void ConfigureClassMap(BsonClassMap<MonthStackStats> cm) {
cm.AutoMap();
cm.SetIgnoreExtraElements(true);
cm.SetIdMember(cm.GetMemberMap(c => c.Id));
cm.GetMemberMap(c => c.ProjectId).SetElementName(CommonFieldNames.ProjectId).SetRepresentation(BsonType.ObjectId).SetIdGenerator(new StringObjectIdGenerator());
cm.GetMemberMap(c => c.StackId).SetElementName(CommonFieldNames.StackId).SetRepresentation(BsonType.ObjectId).SetIdGenerator(new StringObjectIdGenerator());
cm.GetMemberMap(c => c.Total).SetElementName(FieldNames.Total);
cm.GetMemberMap(c => c.DayStats).SetElementName(FieldNames.DayStats).SetSerializationOptions(DictionarySerializationOptions.Document);
}
#endregion
}
} | 44.455696 | 172 | 0.705296 | [
"Apache-2.0"
] | ToddZhao/Exceptionless | Source/Tests/Repositories/InMemory/MonthStackStatsRepository.cs | 3,514 | C# |
/**
* Copyright (c) 2015, Harry CU 邱允根 ([email protected]).
*
* 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.
*/
namespace SqlGenerater.Test.Model
{
public class UserModel
{
public int Id { get; set; }
public string Name { get; set; }
}
}
| 32.12 | 76 | 0.676214 | [
"Apache-2.0"
] | HarryCU/SqlGenerater | SqlGenerater.Test/Model/UserModel.cs | 811 | C# |
using System;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace ViewDiscovery.Views
{
/// <summary>
/// Interaction logic for ViewA.xaml
/// </summary>
public partial class ViewA : UserControl
{
public ViewA()
{
this.InitializeComponent();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
}
| 18.608696 | 44 | 0.579439 | [
"MIT"
] | AvaloniaCommunity/Prism.Avalonia | samples/ViewDiscovery/Views/ViewA.xaml.cs | 430 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Silverfly.Example.Domain
{
public abstract class Animal
{
public abstract string Description { get; }
}
}
| 18.153846 | 52 | 0.677966 | [
"Apache-2.0"
] | nick-hadfield/silverfly | src/Silverfly.Example/Domain/Animal.cs | 238 | C# |
using System.Collections.Generic;
using Application.Interfaces;
namespace Application.Entities.Catalogs
{
public class CatalogItem : ICatalogItem
{
public static uint Seed = 0;
public uint id { get ; set ; }
public int quantity { get ; set ; }
public decimal price { get ; set ; }
public string descrition { get ; set ; }
public string pictureUri{get;set;}
public bool showPrice{get;set;} = true;
public int idCatalog {get;}
public CatalogItem(){
}
public CatalogItem(decimal price,int quantity){
this.quantity = quantity;
this.price = price;
}
public CatalogItem(int quantity, decimal price, string descrition, int idCatalog,string pictureUri)
{
id =++Seed;
this.quantity = quantity;
this.price = price;
this.descrition = descrition;
this.pictureUri = pictureUri;
this.idCatalog = idCatalog;
}
}
} | 27.5 | 107 | 0.576077 | [
"MIT"
] | natividadejoao/eShopOnWeb | Application/Entities/Catalogs/CatalogItem.cs | 1,045 | C# |
using System;
namespace Recipes.RepoDb.Models
{
public class EmployeeClassificationWithCount : IEmployeeClassificationWithCount
{
public int EmployeeClassificationKey { get; set; }
public string? EmployeeClassificationName { get; set; }
public int EmployeeCount { get; set; }
}
}
| 26.5 | 83 | 0.707547 | [
"Unlicense"
] | TEJA1122/DotNet-ORM-Cookbook | ORM Cookbook/Recipes.RepoDb/Models/EmployeeClassificationWithCount.cs | 320 | C# |
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
namespace StardewValleyMods.CategorizeChests.Framework.Persistence
{
/// <summary>
/// The class responsible for reading saved data and using it to restore
/// the mod state.
/// </summary>
class Loader
{
private readonly IChestDataManager ChestDataManager;
private readonly IChestFinder ChestFinder;
private readonly IItemDataManager ItemDataManager;
public Loader(IChestDataManager chestDataManager, IChestFinder chestFinder, IItemDataManager itemDataManager)
{
ChestDataManager = chestDataManager;
ChestFinder = chestFinder;
ItemDataManager = itemDataManager;
}
/// <summary>
/// Read the given save data and use it to reconstruct the mod state.
/// </summary>
/// <param name="token">The save data.</param>
public void LoadData(JToken token)
{
var serializer = new JsonSerializer();
serializer.Converters.Add(new StringEnumConverter());
var data = token.ToObject<SaveData>(serializer);
foreach (var entry in data.ChestEntries)
{
var chest = ChestFinder.GetChestByAddress(entry.Address);
var chestData = ChestDataManager.GetChestData(chest);
chestData.AcceptedItemKinds = entry.AcceptedItemKinds
.Where(itemKey => ItemDataManager.HasItem(itemKey));
}
}
}
} | 35.044444 | 117 | 0.639822 | [
"MIT"
] | doncollins/StardewValleyMods | CategorizeChests/Framework/Persistence/Loader.cs | 1,579 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
#if WINFORMS_NAMESPACE
using CAPS = System.Windows.Forms.NativeMethods;
#elif DRAWING_NAMESPACE
using CAPS = System.Drawing.SafeNativeMethods;
#elif DRAWINGDESIGN_NAMESPACE
using System.Drawing.Design;
using CAPS = System.Drawing.Design.NativeMethods;
#else
using System.Design;
using CAPS = System.Design.NativeMethods;
#endif
namespace System.Windows.Forms
{
/// <summary>
/// Helper class for scaling coordinates and images according to current DPI scaling set in Windows for the primary screen.
/// </summary>
internal static partial class DpiHelper
{
internal const double LogicalDpi = 96.0;
private static bool isInitialized = false;
private static bool isInitializeDpiHelperForWinforms = false;
/// <summary>
/// The primary screen's (device) current DPI
/// </summary>
private static double deviceDpi = LogicalDpi;
private static double logicalToDeviceUnitsScalingFactor = 0.0;
private static InterpolationMode interpolationMode = InterpolationMode.Invalid;
// Backing field, indicating that we will need to send a PerMonitorV2 query in due course.
private static bool doesNeedQueryForPerMonitorV2Awareness = false;
// Backing field, indicating that either DPI is <> 96 or we are in some PerMonitor HighDpi mode.
private static bool isScalingRequirementMet = false;
private static void Initialize()
{
if (isInitialized)
{
return;
}
IntPtr hDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef);
if (hDC != IntPtr.Zero)
{
deviceDpi = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(null, hDC), CAPS.LOGPIXELSX);
UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, hDC));
}
isInitialized = true;
}
internal static void InitializeDpiHelperForWinforms()
{
if (isInitializeDpiHelperForWinforms)
{
return;
}
// initialize shared fields
Initialize();
// We are in Windows 10/1603 or greater when this API is present.
if (ApiHelper.IsApiAvailable(ExternDll.User32, nameof(CommonUnsafeNativeMethods.GetThreadDpiAwarenessContext)))
{
// We are on Windows 10/1603 or greater all right, but we could still be DpiUnaware or SystemAware, so let's find that out...
NativeMethods.PROCESS_DPI_AWARENESS processDpiAwareness;
var currentProcessId = SafeNativeMethods.GetCurrentProcessId();
IntPtr hProcess = SafeNativeMethods.OpenProcess(SafeNativeMethods.PROCESS_QUERY_INFORMATION, false, currentProcessId);
var result = SafeNativeMethods.GetProcessDpiAwareness(hProcess, out processDpiAwareness);
// Only if we're not, it makes sense to query for PerMonitorV2 awareness from now on, if needed.
if (!(processDpiAwareness == CAPS.PROCESS_DPI_AWARENESS.PROCESS_DPI_UNAWARE ||
processDpiAwareness == CAPS.PROCESS_DPI_AWARENESS.PROCESS_SYSTEM_DPI_AWARE))
{
doesNeedQueryForPerMonitorV2Awareness = true;
}
}
if (IsScalingRequired || doesNeedQueryForPerMonitorV2Awareness)
{
isScalingRequirementMet = true;
}
isInitializeDpiHelperForWinforms = true;
}
/// <summary>
/// Returns a boolean to specify if we should enable processing of WM_DPICHANGED and related messages
/// </summary>
internal static bool IsPerMonitorV2Awareness
{
get
{
InitializeDpiHelperForWinforms();
if (doesNeedQueryForPerMonitorV2Awareness)
{
// We can't cache this value because different top level windows can have different DPI awareness context
// for mixed mode applications.
DpiAwarenessContext dpiAwareness = CommonUnsafeNativeMethods.GetThreadDpiAwarenessContext();
return CommonUnsafeNativeMethods.TryFindDpiAwarenessContextsEqual(dpiAwareness, DpiAwarenessContext.DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
}
else
{
return false;
}
}
}
/// <summary>
/// Indicates, if rescaling becomes necessary, either because we are not 96 DPI or we're PerMonitorV2Aware.
/// </summary>
internal static bool IsScalingRequirementMet
{
get
{
InitializeDpiHelperForWinforms();
return isScalingRequirementMet;
}
}
internal static int DeviceDpi
{
get
{
Initialize();
return (int)deviceDpi;
}
}
private static double LogicalToDeviceUnitsScalingFactor
{
get
{
if (logicalToDeviceUnitsScalingFactor == 0.0)
{
Initialize();
logicalToDeviceUnitsScalingFactor = deviceDpi / LogicalDpi;
}
return logicalToDeviceUnitsScalingFactor;
}
}
private static InterpolationMode InterpolationMode
{
get
{
if (interpolationMode == InterpolationMode.Invalid)
{
int dpiScalePercent = (int)Math.Round(LogicalToDeviceUnitsScalingFactor * 100);
// We will prefer NearestNeighbor algorithm for 200, 300, 400, etc zoom factors, in which each pixel become a 2x2, 3x3, 4x4, etc rectangle.
// This produces sharp edges in the scaled image and doesn't cause distorsions of the original image.
// For any other scale factors we will prefer a high quality resizing algorith. While that introduces fuzziness in the resulting image,
// it will not distort the original (which is extremely important for small zoom factors like 125%, 150%).
// We'll use Bicubic in those cases, except on reducing (zoom < 100, which we shouldn't have anyway), in which case Linear produces better
// results because it uses less neighboring pixels.
if ((dpiScalePercent % 100) == 0)
{
interpolationMode = InterpolationMode.NearestNeighbor;
}
else if (dpiScalePercent < 100)
{
interpolationMode = InterpolationMode.HighQualityBilinear;
}
else
{
interpolationMode = InterpolationMode.HighQualityBicubic;
}
}
return interpolationMode;
}
}
private static Bitmap ScaleBitmapToSize(Bitmap logicalImage, Size deviceImageSize)
{
Bitmap deviceImage;
deviceImage = new Bitmap(deviceImageSize.Width, deviceImageSize.Height, logicalImage.PixelFormat);
using (Graphics graphics = Graphics.FromImage(deviceImage))
{
graphics.InterpolationMode = InterpolationMode;
RectangleF sourceRect = new RectangleF(0, 0, logicalImage.Size.Width, logicalImage.Size.Height);
RectangleF destRect = new RectangleF(0, 0, deviceImageSize.Width, deviceImageSize.Height);
// Specify a source rectangle shifted by half of pixel to account for GDI+ considering the source origin the center of top-left pixel
// Failing to do so will result in the right and bottom of the bitmap lines being interpolated with the graphics' background color,
// and will appear black even if we cleared the background with transparent color.
// The apparition of these artifacts depends on the interpolation mode, on the dpi scaling factor, etc.
// E.g. at 150% DPI, Bicubic produces them and NearestNeighbor is fine, but at 200% DPI NearestNeighbor also shows them.
sourceRect.Offset(-0.5f, -0.5f);
graphics.DrawImage(logicalImage, destRect, sourceRect, GraphicsUnit.Pixel);
}
return deviceImage;
}
private static Bitmap CreateScaledBitmap(Bitmap logicalImage, int deviceDpi = 0)
{
Size deviceImageSize = DpiHelper.LogicalToDeviceUnits(logicalImage.Size, deviceDpi);
return ScaleBitmapToSize(logicalImage, deviceImageSize);
}
/// <summary>
/// Returns whether scaling is required when converting between logical-device units,
/// if the application opted in the automatic scaling in the .config file.
/// </summary>
public static bool IsScalingRequired
{
get
{
Initialize();
return deviceDpi != LogicalDpi;
}
}
/// <summary>
/// Transforms a horizontal or vertical integer coordinate from logical to device units
/// by scaling it up for current DPI and rounding to nearest integer value
/// </summary>
/// <param name="value">value in logical units</param>
/// <returns>value in device units</returns>
public static int LogicalToDeviceUnits(int value, int devicePixels = 0)
{
if (devicePixels == 0)
{
return (int)Math.Round(LogicalToDeviceUnitsScalingFactor * (double)value);
}
double scalingFactor = devicePixels / LogicalDpi;
return (int)Math.Round(scalingFactor * (double)value);
}
/// <summary>
/// Transforms a horizontal integer coordinate from logical to device units
/// by scaling it up for current DPI and rounding to nearest integer value
/// </summary>
/// <param name="value">The horizontal value in logical units</param>
/// <returns>The horizontal value in device units</returns>
public static int LogicalToDeviceUnitsX(int value)
{
return LogicalToDeviceUnits(value, 0);
}
/// <summary>
/// Transforms a vertical integer coordinate from logical to device units
/// by scaling it up for current DPI and rounding to nearest integer value
/// </summary>
/// <param name="value">The vertical value in logical units</param>
/// <returns>The vertical value in device units</returns>
public static int LogicalToDeviceUnitsY(int value)
{
return LogicalToDeviceUnits(value, 0);
}
/// <summary>
/// Returns a new Size with the input's
/// dimensions converted from logical units to device units.
/// </summary>
/// <param name="logicalSize">Size in logical units</param>
/// <returns>Size in device units</returns>
public static Size LogicalToDeviceUnits(Size logicalSize, int deviceDpi = 0)
{
return new Size(LogicalToDeviceUnits(logicalSize.Width, deviceDpi),
LogicalToDeviceUnits(logicalSize.Height, deviceDpi));
}
/// <summary>
/// Create and return a new bitmap scaled to the specified size.
/// </summary>
/// <param name="logicalImage">The image to scale from logical units to device units</param>
/// <param name="targetImageSize">The size to scale image to</param>
public static Bitmap CreateResizedBitmap(Bitmap logicalImage, Size targetImageSize)
{
if (logicalImage == null)
{
return null;
}
return ScaleBitmapToSize(logicalImage, targetImageSize);
}
/// <summary>
/// Create a new bitmap scaled for the device units.
/// When displayed on the device, the scaled image will have same size as the original image would have when displayed at 96dpi.
/// </summary>
/// <param name="logicalBitmap">The image to scale from logical units to device units</param>
public static void ScaleBitmapLogicalToDevice(ref Bitmap logicalBitmap, int deviceDpi = 0)
{
if (logicalBitmap == null)
{
return;
}
Bitmap deviceBitmap = CreateScaledBitmap(logicalBitmap, deviceDpi);
if (deviceBitmap != null)
{
logicalBitmap.Dispose();
logicalBitmap = deviceBitmap;
}
}
// This method is used only in System.Design, thus excluding the rest.
// This is particularly important for System.Drawing, which should not depend
// on System.Windows.Forms assembly, where "Button" type is defined.
#if (!DRAWING_NAMESPACE && !DRAWINGDESIGN_NAMESPACE && !WINFORMS_NAMESPACE)
/// <summary>
/// Create a new button bitmap scaled for the device units.
/// Note: original image might be disposed.
/// </summary>
/// <param name="button">button with an image, image size is defined in logical units</param>
public static void ScaleButtonImageLogicalToDevice(Button button)
{
if (button == null)
{
return;
}
Bitmap buttonBitmap = button.Image as Bitmap;
if (buttonBitmap == null)
{
return;
}
Bitmap deviceBitmap = CreateScaledBitmap(buttonBitmap);
button.Image.Dispose();
button.Image = deviceBitmap;
}
#endif
}
internal enum DpiAwarenessContext
{
DPI_AWARENESS_CONTEXT_UNSPECIFIED = 0,
DPI_AWARENESS_CONTEXT_UNAWARE = -1,
DPI_AWARENESS_CONTEXT_SYSTEM_AWARE = -2,
DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE = -3,
DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 = -4
}
}
| 41.805714 | 164 | 0.604497 | [
"MIT"
] | Liminiens/winforms | src/System.Windows.Forms/src/misc/DpiHelper.cs | 14,634 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Muwesome.MethodDelegate {
/// <summary>Returns an instance for an injected parameter.</summary>
public delegate object ParameterResolver(ParameterInfo parameter);
public static class MethodDelegateHelper {
/// <summary>Gets a class method delegate by type parameter.</summary>
public static Delegate GetMethodDelegate<T>(Type methodClassType, ParameterResolver parameterResolver = null, bool includeNonPublicMethods = false) =>
GetMethodDelegate(methodClassType, typeof(T), parameterResolver, includeNonPublicMethods);
/// <summary>Gets a class method delegate by type.</summary>
public static Delegate GetMethodDelegate(Type methodClassType, Type delegateType, ParameterResolver parameterResolver = null, bool includeNonPublicMethods = false) =>
DefaultBuilder(methodClassType, parameterResolver, includeNonPublicMethods)
.Filter((_, @delegate) => @delegate == delegateType)
.Build()
.FirstOrDefault();
/// <summary>Gets an instance's method delegate by type parameter.</summary>
public static Delegate GetMethodDelegate<T>(object instance, ParameterResolver parameterResolver = null, bool includeNonPublicMethods = false) =>
GetMethodDelegate(instance, typeof(T), parameterResolver, includeNonPublicMethods);
/// <summary>Gets an instance's method delegate by type.</summary>
public static Delegate GetMethodDelegate(object instance, Type delegateType, ParameterResolver parameterResolver = null, bool includeNonPublicMethods = false) =>
DefaultBuilder(instance.GetType(), parameterResolver, includeNonPublicMethods)
.MethodClassInstance(instance)
.AllowMethodBinding(BindingFlags.Instance)
.Filter((_, @delegate) => @delegate == delegateType)
.Build()
.FirstOrDefault();
/// <summary>Gets an instance's method delegates.</summary>
public static IEnumerable<Delegate> GetMethodDelegates(object instance, ParameterResolver parameterResolver = null, bool includeNonPublicMethods = false) =>
DefaultBuilder(instance.GetType(), parameterResolver, includeNonPublicMethods)
.MethodClassInstance(instance)
.AllowMethodBinding(BindingFlags.Instance)
.Build();
/// <summary>Gets the default method delegate builder.</summary>
private static MethodDelegateBuilder DefaultBuilder(Type methodClassType, ParameterResolver parameterResolver, bool includeNonPublicMethods) =>
new MethodDelegateBuilder(methodClassType)
.ParameterResolver(parameterResolver)
.AllowMethodBinding(includeNonPublicMethods ? BindingFlags.NonPublic : 0);
}
} | 56.285714 | 170 | 0.763234 | [
"MIT"
] | darfink/Muwesome | lib/MethodDelegate/MethodDelegateHelper.cs | 2,758 | C# |
namespace EZCoach.Pong {
public enum PlayerDirection {
None = 0,
Up = 1,
Down = -1
}
} | 17 | 33 | 0.487395 | [
"MIT"
] | Pawel-M/EZ-Coach | Unity plugin/Assets/EZ-Coach/Examples/EZ Pong/Scripts/PlayerDirection.cs | 121 | C# |
using System;
using System.Collections.Generic;
namespace _0230
{
/**
* Definition for a binary tree node. */
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
public class Solution
{
public int KthSmallest(TreeNode root, int k)
{
var TreeSize = new Dictionary<TreeNode, int>();
while (k > 0)
{
var leftCount = CountNodes(root.left, TreeSize);
if (leftCount == k - 1)
{
return root.val;
}
else if (k <= leftCount)
{
root = root.left;
}
else
{
k -= (leftCount + 1);
root = root.right;
}
}
return -1;
}
private int CountNodes(TreeNode root, Dictionary<TreeNode, int> TreeSize)
{
if (root == null)
{
return 0;
}
if (TreeSize.ContainsKey(root))
{
return TreeSize[root];
}
var count = CountNodes(root.left, TreeSize) + CountNodes(root.right, TreeSize) + 1;
TreeSize[root] = count;
return count;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
| 22.514286 | 95 | 0.424492 | [
"Apache-2.0"
] | twilightgod/PlayLeetcode | 0230/Program.cs | 1,578 | C# |
using TestWrapper.Workers;
using Unity.Burst;
using Unity.Collections;
using Unity.Mathematics;
namespace TestCase.Basic.Multiplication.Simd.Optimization
{
[BurstCompile]
public struct SimdMultiplicationOptimizationUInt2Job : IJobExt<NativeArray<uint2>, NativeArray<uint2>, NativeArray<uint2>>
{
[ReadOnly] private NativeArray<uint2> _data1;
[ReadOnly] private NativeArray<uint2> _data2;
[WriteOnly] private NativeArray<uint2> _data3;
public int DataSize { get; set; }
public NativeArray<uint2> Data1
{
get => _data1;
set => _data1 = value;
}
public NativeArray<uint2> Data2
{
get => _data2;
set => _data2 = value;
}
public NativeArray<uint2> Data3
{
get => _data3;
set => _data3 = value;
}
public void Execute()
{
for (int i = 0; i < DataSize; i++)
{
_data3[i] = _data1[i] * _data2[i];
}
}
public void CustomSetUp()
{
}
public void CustomCleanUp()
{
}
}
} | 23.156863 | 126 | 0.536833 | [
"MIT"
] | ErikMoczi/Unity.TestRunner.Jobs | Assets/TestCase/Basic/Multiplication/Simd/Optimization/SimdAdditionOptimizationUInt2Job.cs | 1,183 | C# |
using System;
using System.Windows.Automation;
using XiangJiang.Core;
using XiangJiang.Windows.UIA.Core;
namespace XiangJiang.Windows.UIA
{
/// <summary>
/// ComboBox 控件
/// </summary>
// ReSharper disable once InconsistentNaming
public static class ComboBoxHelper
{
/// <summary>
/// 设置选中项
/// </summary>
/// <param name="comboBox">AutomationElement</param>
/// <param name="item">需要选中的文本</param>
/// <exception cref="ArgumentException">
/// Element with AutomationId '{comboBox.Current.AutomationId}' and Name
/// '{comboBox.Current.Name}' ControlType is not ComboBox.
/// </exception>
public static bool SetSelectedItem(this AutomationElement comboBox, string item)
{
Checker.Begin().NotNull(comboBox, nameof(comboBox))
.NotNullOrEmpty(item, nameof(item))
.SupportedType(comboBox, ControlType.ComboBox);
var listBox = comboBox.FindFirst(TreeScope.Children,
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.List));
if (listBox == null) return false;
var listItem = listBox.FindFirst(TreeScope.Children,
new PropertyCondition(AutomationElement.NameProperty, item));
if (listItem == null) return false;
if (!listItem.TryGetCurrentPattern(SelectionItemPatternIdentifiers.Pattern, out var sipCombox))
return false;
var selectionItemPattern = sipCombox as SelectionItemPattern;
selectionItemPattern?.Select();
return true;
}
}
} | 39.093023 | 107 | 0.627603 | [
"Apache-2.0"
] | YanZhiwei/XiangJiang.Infrastructure.Windows.UIA | XiangJiang.Windows.UIA/ComboBoxHelper.cs | 1,711 | C# |
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using Epi;
// Generic assembly settings
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyCompany("Centers for Disease Control and Prevention")]
[assembly: AssemblyProduct("Epi Info�")]
[assembly: AssemblyCopyright("� Centers for Disease Control and Prevention")]
[assembly: AssemblyTrademark("Epi Info is a trademark of CDC")]
[assembly: AssemblyCulture("")]
// For .NET 4.0 upgrade
[assembly: System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)]
//mark the types you want to export to COM with ComVisible(true)
[assembly: ComVisible(false)]
// Allow unsigned assemblies access to Epi Info assemblies
[assembly: AllowPartiallyTrustedCallers]
//define english/us as the neutral language
[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.MainAssembly)]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("7.2.*")]
[assembly: AssemblyFileVersion("7.2.4.0")]
[assembly: AssemblyInformationalVersion("7.2.4.0")]
[assembly: SatelliteContractVersion("7.0.0.0")]
[assembly: Epi.AssemblyReleaseDateAttribute("04/27/2020")]
//
// In order to sign your assembly you must specify a key to use. Refer to the
// Microsoft .NET Framework documentation for more information on assembly signing.
//
// Use the attributes below to control which key is used for signing.
//
// Notes:
// (*) If no key is specified, the assembly is not signed.
// (*) KeyName refers to a key that has been installed in the Crypto Service
// Provider (CSP) on your machine. KeyFile refers to a file which contains
// a key.
// (*) If the KeyFile and the KeyName values are both specified, the
// following processing occurs:
// (1) If the KeyName can be found in the CSP, that key is used.
// (2) If the KeyName does not exist and the KeyFile does exist, the key
// in the KeyFile is installed into the CSP and used.
// When specifying the KeyFile, the location of the KeyFile should be
// %Project Directory%\obj\<configuration>. For example, if your KeyFile is
// located in the project directory, you would specify the AssemblyKeyFile
// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
// documentation for more information on this.
//
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
//[assembly: AssemblyKeyName("")]
| 42.450704 | 93 | 0.71367 | [
"Apache-2.0"
] | keymind/Epi-Info-Community-Edition | SolutionInfo.cs | 3,018 | C# |
using System.Web;
using System.Web.Mvc;
namespace my_aspnetmvc_learning
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
}
| 19.571429 | 80 | 0.667883 | [
"MIT"
] | zhouyongtao/my_aspnetmvc_learning | my_aspnetmvc_learning/App_Start/FilterConfig.cs | 276 | C# |
using Lidgren.Network;
using Robust.Shared.Network;
namespace OpenDreamShared.Network.Messages
{
public sealed class MsgTopic : NetMessage
{
public override MsgGroups MsgGroup => MsgGroups.EntityEvent;
public string Query;
public override void ReadFromBuffer(NetIncomingMessage buffer)
{
Query = buffer.ReadString();
}
public override void WriteToBuffer(NetOutgoingMessage buffer)
{
buffer.Write(Query);
}
}
}
| 22.391304 | 70 | 0.646602 | [
"MIT"
] | DamianX/OpenDream | OpenDreamShared/Network/Messages/MsgTopic.cs | 517 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace BE
{
public class Estado
{
public int IdEstado { get; set; }
public string NomEstado { get; set; }
}
}
| 16.153846 | 45 | 0.633333 | [
"MIT"
] | carloseip/ApiEventos | BE/Estado.cs | 212 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BaseballSimulatorApp
{
using System.Collections.ObjectModel;
class BaseballSimulator
{
private Ball ball = new Ball();
private Pitcher pitcher;
private Fan fan;
public ObservableCollection<string> FanSays { get { return fan.FanSays; } }
public ObservableCollection<string> PitcherSays { get { return pitcher.PitcherSays; } }
public int Trajectory { get; set; }
public int Distance { get; set; }
public BaseballSimulator()
{
pitcher = new Pitcher(ball);
fan = new Fan(ball);
}
public void PlayBall()
{
Bat bat = ball.GetNewBat();
BallEventArgs ballEventArgs =
new BallEventArgs(Trajectory, Distance);
bat.HitTheBall(ballEventArgs);
}
}
}
| 28.055556 | 96 | 0.585149 | [
"MIT"
] | JianGuoWan/third-edition | VS2012/Chapter_15/BaseballSimulatorAppWithCallback/BaseballSimulatorApp/BaseballSimulator.cs | 1,012 | C# |
#if !__MACCATALYST__
using System;
using System.Threading.Tasks;
using Foundation;
namespace VideoSubscriberAccount {
public static partial class VSAccountProviderAuthenticationSchemeExtensions {
// these are less common pattern so it's not automatically generated
public static NSString[] GetConstants (this VSAccountProviderAuthenticationScheme[] self)
{
if (self == null)
throw new ArgumentNullException (nameof (self));
var array = new NSString [self.Length];
for (int n = 0; n < self.Length; n++)
array [n] = self [n].GetConstant ();
return array;
}
public static VSAccountProviderAuthenticationScheme[] GetValues (NSString[] constants)
{
if (constants == null)
throw new ArgumentNullException (nameof (constants));
var array = new VSAccountProviderAuthenticationScheme [constants.Length];
for (int n = 0; n < constants.Length; n++)
array [n] = GetValue (constants [n]);
return array;
}
}
}
#endif // !__MACCATALYST__
| 27.472222 | 91 | 0.717897 | [
"BSD-3-Clause"
] | NormanChiflen/xamarin-all-IOS | src/VideoSubscriberAccount/VSAccountProviderAuthenticationScheme.cs | 989 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ConferenceDTO;
namespace FrontEnd.Services
{
public interface IApiClient
{
Task<List<SessionResponse>> GetSessionsAsync();
Task<SessionResponse> GetSessionAsync(int id);
Task<List<SpeakerResponse>> GetSpeakersAsync();
Task<SpeakerResponse> GetSpeakerAsync(int id);
Task PutSessionAsync(Session session);
Task<bool> AddAttendeeAsync(Attendee attendee);
Task<AttendeeResponse> GetAttendeeAsync(string name);
Task DeleteSessionAsync(int id);
Task<List<SearchResult>> SearchAsync(string query);
}
}
| 29.782609 | 61 | 0.718248 | [
"MIT"
] | alex-coupe/conference-planner | FrontEnd/Services/IApiClient.cs | 687 | C# |
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Novinichka.Data.Common.Repositories;
namespace Novinichka.Data.Repositories
{
public class EfRepository<TEntity> : IRepository<TEntity>
where TEntity : class
{
public EfRepository(ApplicationDbContext context)
{
this.Context = context ?? throw new ArgumentNullException(nameof(context));
this.DbSet = this.Context.Set<TEntity>();
}
protected DbSet<TEntity> DbSet { get; set; }
protected ApplicationDbContext Context { get; set; }
public virtual IQueryable<TEntity> All()
=> this.DbSet;
public virtual IQueryable<TEntity> AllAsNoTracking()
=> this.DbSet.AsNoTracking();
public virtual Task AddAsync(TEntity entity)
=> this.DbSet.AddAsync(entity).AsTask();
public virtual void Update(TEntity entity)
{
var entry = this.Context.Entry(entity);
if (entry.State == EntityState.Detached)
{
this.DbSet.Attach(entity);
}
entry.State = EntityState.Modified;
}
public virtual void Delete(TEntity entity)
=> this.DbSet.Remove(entity);
public Task<int> SaveChangesAsync()
=> this.Context.SaveChangesAsync();
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.Context?.Dispose();
}
}
}
}
| 25.772727 | 87 | 0.580835 | [
"MIT"
] | georgidelchev/novini4ka | Data/Novinichka.Data/Repositories/EfRepository.cs | 1,703 | C# |
// StrawberryShake.CodeGeneration.CSharp.ClientGenerator
#nullable enable
namespace StrawberryShake.CodeGeneration.CSharp.Analyzers.StarWars
{
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")]
public partial class StarWarsClient
{
private readonly GetPeopleQuery _getPeopleQuery;
public StarWarsClient(GetPeopleQuery getPeopleQuery)
{
_getPeopleQuery = getPeopleQuery
?? throw new global::System.ArgumentNullException(nameof(getPeopleQuery));
}
public GetPeopleQuery GetPeopleQuery => _getPeopleQuery;
}
}
| 29.666667 | 91 | 0.717496 | [
"MIT"
] | HonzaBejvl/hotchocolate | src/StrawberryShake/SourceGenerator/test/CodeGeneration.CSharp.Analyzers.Tests/StarWars/Generated/StarWarsClient.StarWarsClient.StrawberryShake.cs | 625 | C# |
namespace SereneApi.Abstractions.Queries
{
/// <summary>
/// Formats objects to strings.
/// </summary>
/// <param name="queryObject">The object to be formatted to a string.</param>
public delegate string ObjectToStringFormatter(object queryObject);
}
| 27.4 | 81 | 0.693431 | [
"MIT"
] | SereneApi/SereneApi | src/SereneApi.Abstractions/Queries/ObjectToStringFormatter.cs | 276 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712
{
using Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.PowerShell;
/// <summary>Slack channel definition</summary>
[System.ComponentModel.TypeConverter(typeof(SlackChannelTypeConverter))]
public partial class SlackChannel
{
/// <summary>
/// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the
/// object before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content);
/// <summary>
/// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content);
/// <summary>
/// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <paramref name="returnNow" /> output
/// parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow);
/// <summary>
/// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <paramref name="returnNow" /> output
/// parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.SlackChannel"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannel" />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannel DeserializeFromDictionary(global::System.Collections.IDictionary content)
{
return new SlackChannel(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.SlackChannel"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannel" />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannel DeserializeFromPSObject(global::System.Management.Automation.PSObject content)
{
return new SlackChannel(content);
}
/// <summary>
/// Creates a new instance of <see cref="SlackChannel" />, deserializing the content from a json string.
/// </summary>
/// <param name="jsonText">a string containing a JSON serialized instance of this model.</param>
/// <returns>an instance of the <see cref="SlackChannel" /> model class.</returns>
public static Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannel FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.Json.JsonNode.Parse(jsonText));
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.SlackChannel"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
internal SlackChannel(global::System.Collections.IDictionary content)
{
bool returnNow = false;
BeforeDeserializeDictionary(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
if (content.Contains("Property"))
{
((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.SlackChannelPropertiesTypeConverter.ConvertFrom);
}
if (content.Contains("Name"))
{
((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.IChannelInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.IChannelInternal)this).Name, global::System.Convert.ToString);
}
if (content.Contains("ClientId"))
{
((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).ClientId = (string) content.GetValueForProperty("ClientId",((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).ClientId, global::System.Convert.ToString);
}
if (content.Contains("ClientSecret"))
{
((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).ClientSecret = (string) content.GetValueForProperty("ClientSecret",((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).ClientSecret, global::System.Convert.ToString);
}
if (content.Contains("VerificationToken"))
{
((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).VerificationToken = (string) content.GetValueForProperty("VerificationToken",((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).VerificationToken, global::System.Convert.ToString);
}
if (content.Contains("LandingPageUrl"))
{
((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).LandingPageUrl = (string) content.GetValueForProperty("LandingPageUrl",((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).LandingPageUrl, global::System.Convert.ToString);
}
if (content.Contains("RedirectAction"))
{
((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).RedirectAction = (string) content.GetValueForProperty("RedirectAction",((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).RedirectAction, global::System.Convert.ToString);
}
if (content.Contains("LastSubmissionId"))
{
((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).LastSubmissionId = (string) content.GetValueForProperty("LastSubmissionId",((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).LastSubmissionId, global::System.Convert.ToString);
}
if (content.Contains("RegisterBeforeOAuthFlow"))
{
((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).RegisterBeforeOAuthFlow = (bool?) content.GetValueForProperty("RegisterBeforeOAuthFlow",((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).RegisterBeforeOAuthFlow, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("IsValidated"))
{
((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).IsValidated = (bool?) content.GetValueForProperty("IsValidated",((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).IsValidated, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("IsEnabled"))
{
((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).IsEnabled = (bool) content.GetValueForProperty("IsEnabled",((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).IsEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
AfterDeserializeDictionary(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.SlackChannel"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
internal SlackChannel(global::System.Management.Automation.PSObject content)
{
bool returnNow = false;
BeforeDeserializePSObject(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
if (content.Contains("Property"))
{
((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.SlackChannelPropertiesTypeConverter.ConvertFrom);
}
if (content.Contains("Name"))
{
((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.IChannelInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.IChannelInternal)this).Name, global::System.Convert.ToString);
}
if (content.Contains("ClientId"))
{
((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).ClientId = (string) content.GetValueForProperty("ClientId",((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).ClientId, global::System.Convert.ToString);
}
if (content.Contains("ClientSecret"))
{
((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).ClientSecret = (string) content.GetValueForProperty("ClientSecret",((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).ClientSecret, global::System.Convert.ToString);
}
if (content.Contains("VerificationToken"))
{
((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).VerificationToken = (string) content.GetValueForProperty("VerificationToken",((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).VerificationToken, global::System.Convert.ToString);
}
if (content.Contains("LandingPageUrl"))
{
((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).LandingPageUrl = (string) content.GetValueForProperty("LandingPageUrl",((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).LandingPageUrl, global::System.Convert.ToString);
}
if (content.Contains("RedirectAction"))
{
((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).RedirectAction = (string) content.GetValueForProperty("RedirectAction",((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).RedirectAction, global::System.Convert.ToString);
}
if (content.Contains("LastSubmissionId"))
{
((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).LastSubmissionId = (string) content.GetValueForProperty("LastSubmissionId",((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).LastSubmissionId, global::System.Convert.ToString);
}
if (content.Contains("RegisterBeforeOAuthFlow"))
{
((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).RegisterBeforeOAuthFlow = (bool?) content.GetValueForProperty("RegisterBeforeOAuthFlow",((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).RegisterBeforeOAuthFlow, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("IsValidated"))
{
((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).IsValidated = (bool?) content.GetValueForProperty("IsValidated",((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).IsValidated, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("IsEnabled"))
{
((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).IsEnabled = (bool) content.GetValueForProperty("IsEnabled",((Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.ISlackChannelInternal)this).IsEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
AfterDeserializePSObject(content);
}
/// <summary>Serializes this instance to a json string.</summary>
/// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns>
public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.SerializationMode.IncludeAll)?.ToString();
}
/// Slack channel definition
[System.ComponentModel.TypeConverter(typeof(SlackChannelTypeConverter))]
public partial interface ISlackChannel
{
}
} | 76.214286 | 472 | 0.700152 | [
"MIT"
] | imadan1996/azure-powershell | src/BotService/generated/api/Models/Api20180712/SlackChannel.PowerShell.cs | 16,849 | C# |
using PddOpenSdk.Models.Request.Logisticsticket;
using PddOpenSdk.Models.Response.Logisticsticket;
using System.Threading.Tasks;
namespace PddOpenSdk.Services.PddApi
{
public class LogisticsticketApi : PddCommonApi
{
/// <summary>
/// 客户与机器人的聊天记录获取接口
/// </summary>
public async Task<GetLogisticsCsHistoryMessageResponseModel> GetLogisticsCsHistoryMessageAsync(GetLogisticsCsHistoryMessageRequestModel getLogisticsCsHistoryMessage)
{
var result = await PostAsync<GetLogisticsCsHistoryMessageRequestModel, GetLogisticsCsHistoryMessageResponseModel>("pdd.logistics.cs.history.message.get", getLogisticsCsHistoryMessage);
return result;
}
/// <summary>
/// 客服给发消息接口
/// </summary>
public async Task<SendLogisticsCsMessageResponseModel> SendLogisticsCsMessageAsync(SendLogisticsCsMessageRequestModel sendLogisticsCsMessage)
{
var result = await PostAsync<SendLogisticsCsMessageRequestModel, SendLogisticsCsMessageResponseModel>("pdd.logistics.cs.message.send", sendLogisticsCsMessage);
return result;
}
/// <summary>
/// 客服关闭会话接口
/// </summary>
public async Task<CloseLogisticsCsSessionResponseModel> CloseLogisticsCsSessionAsync(CloseLogisticsCsSessionRequestModel closeLogisticsCsSession)
{
var result = await PostAsync<CloseLogisticsCsSessionRequestModel, CloseLogisticsCsSessionResponseModel>("pdd.logistics.cs.session.close", closeLogisticsCsSession);
return result;
}
/// <summary>
/// 物流客服系统创建同步会话状态接口
/// </summary>
public async Task<StartLogisticsCsSessionResponseModel> StartLogisticsCsSessionAsync(StartLogisticsCsSessionRequestModel startLogisticsCsSession)
{
var result = await PostAsync<StartLogisticsCsSessionRequestModel, StartLogisticsCsSessionResponseModel>("pdd.logistics.cs.session.start", startLogisticsCsSession);
return result;
}
/// <summary>
/// 快递公司工单查询接口
/// </summary>
public async Task<GetLogisticsTicketResponseModel> GetLogisticsTicketAsync(GetLogisticsTicketRequestModel getLogisticsTicket)
{
var result = await PostAsync<GetLogisticsTicketRequestModel, GetLogisticsTicketResponseModel>("pdd.logistics.ticket.get", getLogisticsTicket);
return result;
}
/// <summary>
/// 工单图片上传接口
/// </summary>
public async Task<UploadLogisticsTicketImageResponseModel> UploadLogisticsTicketImageAsync(UploadLogisticsTicketImageRequestModel uploadLogisticsTicketImage)
{
var result = await PostAsync<UploadLogisticsTicketImageRequestModel, UploadLogisticsTicketImageResponseModel>("pdd.logistics.ticket.image.upload", uploadLogisticsTicketImage);
return result;
}
/// <summary>
/// 快递公司处理结果回调接口
/// </summary>
public async Task<NotifyLogisticsTicketResponseModel> NotifyLogisticsTicketAsync(NotifyLogisticsTicketRequestModel notifyLogisticsTicket)
{
var result = await PostAsync<NotifyLogisticsTicketRequestModel, NotifyLogisticsTicketResponseModel>("pdd.logistics.ticket.notify", notifyLogisticsTicket);
return result;
}
/// <summary>
/// 快递公司工单问题类型列表接口
/// </summary>
public async Task<GetLogisticsTicketProblemTypeResponseModel> GetLogisticsTicketProblemTypeAsync(GetLogisticsTicketProblemTypeRequestModel getLogisticsTicketProblemType)
{
var result = await PostAsync<GetLogisticsTicketProblemTypeRequestModel, GetLogisticsTicketProblemTypeResponseModel>("pdd.logistics.ticket.problem.type.get", getLogisticsTicketProblemType);
return result;
}
}
}
| 51.373333 | 200 | 0.719699 | [
"Apache-2.0"
] | zuhuizou/open-pdd-net-sdk | PddOpenSdk/PddOpenSdk/Services/PddApi/LogisticsticketApi.cs | 4,035 | C# |
using System;
using BEPUphysics.BroadPhaseEntries;
using BEPUphysics.BroadPhaseEntries.MobileCollidables;
using BEPUphysics.CollisionTests.CollisionAlgorithms.GJK;
using BEPUphysics.CollisionTests.Manifolds;
using BEPUphysics.Constraints.Collision;
using BEPUphysics.DataStructures;
using BEPUutilities.DataStructures;
using BEPUphysics.PositionUpdating;
using BEPUphysics.Settings;
using BEPUutilities;
using FixMath.NET;
namespace BEPUphysics.NarrowPhaseSystems.Pairs
{
///<summary>
/// Handles a instanced mesh-convex collision pair.
///</summary>
public abstract class InstancedMeshPairHandler : StandardPairHandler
{
InstancedMesh instancedMesh;
ConvexCollidable convex;
private NonConvexContactManifoldConstraint contactConstraint;
public override Collidable CollidableA
{
get { return convex; }
}
public override Collidable CollidableB
{
get { return instancedMesh; }
}
public override Entities.Entity EntityA
{
get { return convex.entity; }
}
public override Entities.Entity EntityB
{
get { return null; }
}
/// <summary>
/// Gets the contact constraint used by the pair handler.
/// </summary>
public override ContactManifoldConstraint ContactConstraint
{
get { return contactConstraint; }
}
/// <summary>
/// Gets the contact manifold used by the pair handler.
/// </summary>
public override ContactManifold ContactManifold
{
get { return MeshManifold; }
}
protected abstract InstancedMeshContactManifold MeshManifold { get; }
protected InstancedMeshPairHandler()
{
contactConstraint = new NonConvexContactManifoldConstraint(this);
}
///<summary>
/// Initializes the pair handler.
///</summary>
///<param name="entryA">First entry in the pair.</param>
///<param name="entryB">Second entry in the pair.</param>
public override void Initialize(BroadPhaseEntry entryA, BroadPhaseEntry entryB)
{
instancedMesh = entryA as InstancedMesh;
convex = entryB as ConvexCollidable;
if (instancedMesh == null || convex == null)
{
instancedMesh = entryB as InstancedMesh;
convex = entryA as ConvexCollidable;
if (instancedMesh == null || convex == null)
throw new ArgumentException("Inappropriate types used to initialize pair.");
}
//Contact normal goes from A to B.
broadPhaseOverlap.entryA = convex;
broadPhaseOverlap.entryB = instancedMesh;
UpdateMaterialProperties(convex.entity != null ? convex.entity.material : null, instancedMesh.material);
base.Initialize(entryA, entryB);
}
///<summary>
/// Cleans up the pair handler.
///</summary>
public override void CleanUp()
{
base.CleanUp();
instancedMesh = null;
convex = null;
}
///<summary>
/// Updates the time of impact for the pair.
///</summary>
///<param name="requester">Collidable requesting the update.</param>
///<param name="dt">Timestep duration.</param>
public override void UpdateTimeOfImpact(Collidable requester, Fix64 dt)
{
//Notice that we don't test for convex entity null explicitly. The convex.IsActive property does that for us.
if (convex.IsActive && convex.entity.PositionUpdateMode == PositionUpdateMode.Continuous)
{
//TODO: This system could be made more robust by using a similar region-based rejection of edges.
//CCD events are awfully rare under normal circumstances, so this isn't usually an issue.
//Only perform the test if the minimum radii are small enough relative to the size of the velocity.
Vector3 velocity;
Vector3.Multiply(ref convex.entity.linearVelocity, dt, out velocity);
Fix64 velocitySquared = velocity.LengthSquared();
var minimumRadius = convex.Shape.MinimumRadius * MotionSettings.CoreShapeScaling;
timeOfImpact = F64.C1;
if (minimumRadius * minimumRadius < velocitySquared)
{
var triangle = PhysicsThreadResources.GetTriangle();
triangle.collisionMargin = F64.C0;
//Spherecast against all triangles to find the earliest time.
for (int i = 0; i < MeshManifold.overlappedTriangles.Count; i++)
{
MeshBoundingBoxTreeData data = instancedMesh.Shape.TriangleMesh.Data;
int triangleIndex = MeshManifold.overlappedTriangles.Elements[i];
data.GetTriangle(triangleIndex, out triangle.vA, out triangle.vB, out triangle.vC);
AffineTransform.Transform(ref triangle.vA, ref instancedMesh.worldTransform, out triangle.vA);
AffineTransform.Transform(ref triangle.vB, ref instancedMesh.worldTransform, out triangle.vB);
AffineTransform.Transform(ref triangle.vC, ref instancedMesh.worldTransform, out triangle.vC);
//Put the triangle into 'localish' space of the convex.
Vector3.Subtract(ref triangle.vA, ref convex.worldTransform.Position, out triangle.vA);
Vector3.Subtract(ref triangle.vB, ref convex.worldTransform.Position, out triangle.vB);
Vector3.Subtract(ref triangle.vC, ref convex.worldTransform.Position, out triangle.vC);
RayHit rayHit;
if (GJKToolbox.CCDSphereCast(new Ray(Toolbox.ZeroVector, velocity), minimumRadius, triangle, ref Toolbox.RigidIdentity, timeOfImpact, out rayHit) &&
rayHit.T > Toolbox.BigEpsilon)
{
if (instancedMesh.sidedness != TriangleSidedness.DoubleSided)
{
Vector3 AB, AC;
Vector3.Subtract(ref triangle.vB, ref triangle.vA, out AB);
Vector3.Subtract(ref triangle.vC, ref triangle.vA, out AC);
Vector3 normal;
Vector3.Cross(ref AB, ref AC, out normal);
Fix64 dot;
Vector3.Dot(ref normal, ref rayHit.Normal, out dot);
//Only perform sweep if the object is in danger of hitting the object.
//Triangles can be one sided, so check the impact normal against the triangle normal.
if (instancedMesh.sidedness == TriangleSidedness.Counterclockwise && dot < F64.C0 ||
instancedMesh.sidedness == TriangleSidedness.Clockwise && dot > F64.C0)
{
timeOfImpact = rayHit.T;
}
}
else
{
timeOfImpact = rayHit.T;
}
}
}
PhysicsThreadResources.GiveBack(triangle);
}
}
}
protected internal override void GetContactInformation(int index, out ContactInformation info)
{
info.Contact = MeshManifold.contacts.Elements[index];
//Find the contact's normal and friction forces.
info.FrictionImpulse = F64.C0;
info.NormalImpulse = F64.C0;
for (int i = 0; i < contactConstraint.frictionConstraints.Count; i++)
{
if (contactConstraint.frictionConstraints.Elements[i].PenetrationConstraint.contact == info.Contact)
{
info.FrictionImpulse = contactConstraint.frictionConstraints.Elements[i].accumulatedImpulse;
info.NormalImpulse = contactConstraint.frictionConstraints.Elements[i].PenetrationConstraint.accumulatedImpulse;
break;
}
}
//Compute relative velocity
if (convex.entity != null)
{
Vector3 velocity;
Vector3.Subtract(ref info.Contact.Position, ref convex.entity.position, out velocity);
Vector3.Cross(ref convex.entity.angularVelocity, ref velocity, out velocity);
Vector3.Add(ref velocity, ref convex.entity.linearVelocity, out info.RelativeVelocity);
}
else
info.RelativeVelocity = new Vector3();
info.Pair = this;
}
}
}
| 42.242152 | 173 | 0.556688 | [
"MIT"
] | RossNordby/bepuphysics1int | BEPUphysics/NarrowPhaseSystems/Pairs/InstancedMeshPairHandler.cs | 9,422 | C# |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks;
using Elastic.Xunit.Sdk;
using Elastic.Xunit.XunitPlumbing;
using FluentAssertions;
using Nest;
using Tests.Framework;
using Tests.Framework.Integration;
using Tests.Framework.ManagedElasticsearch.Clusters;
using Xunit;
namespace Tests.Document.Multiple.BulkAll
{
public class BulkAllApiTests : SerializationTestBase, IClusterFixture<IntrusiveOperationCluster>, IClassFixture<EndpointUsage>
{
private class SmallObject
{
public int Id { get; set; }
}
private readonly IElasticClient _client;
private static string CreateIndexName() => $"project-copy-{Guid.NewGuid().ToString("N").Substring(8)}";
private IEnumerable<SmallObject> CreateLazyStreamOfDocuments(int count)
{
for (var i = 0; i < count; i++)
yield return new SmallObject() { Id = i };
}
public BulkAllApiTests(IntrusiveOperationCluster cluster, EndpointUsage usage) => this._client = cluster.Client;
[I] public async Task BulkAllAndScrollAll()
{
var index = CreateIndexName();
const int size = 1000, pages = 100, numberOfDocuments = size * pages, numberOfShards = 10;
var documents = this.CreateLazyStreamOfDocuments(numberOfDocuments);
await this.CreateIndexAsync(index, numberOfShards);
this.BulkAll(index, documents, size, pages, numberOfDocuments);
this.ScrollAll(index, numberOfShards, numberOfDocuments);
}
private void ScrollAll(string index, int numberOfShards, int numberOfDocuments)
{
var seenDocuments = 0;
var seenSlices = new ConcurrentBag<int>();
var scrollObserver = this._client.ScrollAll<SmallObject>("1m", numberOfShards, s => s
.MaxDegreeOfParallelism(numberOfShards / 2)
.Search(search => search
.Index(index)
.AllTypes()
.MatchAll()
)
).Wait(TimeSpan.FromMinutes(5), r =>
{
seenSlices.Add(r.Slice);
Interlocked.Add(ref seenDocuments, r.SearchResponse.Hits.Count);
});
seenDocuments.Should().Be(numberOfDocuments);
var groups = seenSlices.GroupBy(s => s).ToList();
groups.Count().Should().Be(numberOfShards);
groups.Should().OnlyContain(g => g.Count() > 1);
}
private void BulkAll(string index, IEnumerable<SmallObject> documents, int size, int pages, int numberOfDocuments)
{
var seenPages = 0;
//first we setup our cold observable
var observableBulk = this._client.BulkAll(documents, f => f
.MaxDegreeOfParallelism(8)
.BackOffTime(TimeSpan.FromSeconds(10))
.BackOffRetries(2)
.Size(size)
.RefreshOnCompleted()
.Index(index)
);
//we set up an observer
var bulkObserver = observableBulk.Wait(TimeSpan.FromMinutes(5), b => Interlocked.Increment(ref seenPages));
seenPages.Should().Be(pages);
var count = this._client.Count<SmallObject>(f => f.Index(index));
count.Count.Should().Be(numberOfDocuments);
bulkObserver.TotalNumberOfFailedBuffers.Should().Be(0);
}
private async Task CreateIndexAsync(string indexName, int numberOfShards)
{
var result = await this._client.CreateIndexAsync(indexName, s => s
.Settings(settings => settings
.NumberOfShards(numberOfShards)
.NumberOfReplicas(0)
)
);
result.Should().NotBeNull();
result.ShouldBeValid();
}
private static void OnError(ref Exception ex, Exception e, EventWaitHandle handle)
{
ex = e;
handle.Set();
throw e;
}
[I, SkipOnTeamCity]
public void DisposingObservableCancelsBulkAll()
{
var index = CreateIndexName();
var handle = new ManualResetEvent(false);
var size = 1000;
var pages = 1000;
var seenPages = 0;
var numberOfDocuments = size * pages;
var documents = this.CreateLazyStreamOfDocuments(numberOfDocuments);
//first we setup our cold observable
var observableBulk = this._client.BulkAll(documents, f => f
.MaxDegreeOfParallelism(8)
.BackOffTime(TimeSpan.FromSeconds(10))
.BackOffRetries(2)
.Size(size)
.RefreshOnCompleted()
.Index(index)
);
//we set up an observer
Exception ex = null;
var bulkObserver = new BulkAllObserver(
onError: (e) => OnError(ref ex, e, handle),
onCompleted: () => handle.Set(),
onNext: (b) => Interlocked.Increment(ref seenPages)
);
//when we subscribe the observable becomes hot
observableBulk.Subscribe(bulkObserver);
//we wait N seconds to see some bulks
handle.WaitOne(TimeSpan.FromSeconds(3));
observableBulk.Dispose();
//we wait N seconds to give in flight request a chance to cancel
handle.WaitOne(TimeSpan.FromSeconds(3));
if (ex != null && !(ex is TaskCanceledException) && !(ex is OperationCanceledException)) throw ex;
seenPages.Should().BeLessThan(pages).And.BeGreaterThan(0);
var count = this._client.Count<SmallObject>(f => f.Index(index));
count.Count.Should().BeLessThan(numberOfDocuments).And.BeGreaterThan(0);
bulkObserver.TotalNumberOfFailedBuffers.Should().Be(0);
}
[I, SkipOnTeamCity]
public void CancelBulkAll()
{
var index = CreateIndexName();
var handle = new ManualResetEvent(false);
var size = 1000;
var pages = 1000;
var seenPages = 0;
var numberOfDocuments = size * pages;
var documents = this.CreateLazyStreamOfDocuments(numberOfDocuments);
//first we setup our cold observable
var tokenSource = new CancellationTokenSource();
var observableBulk = this._client.BulkAll(documents, f => f
.MaxDegreeOfParallelism(8)
.BackOffTime(TimeSpan.FromSeconds(10))
.BackOffRetries(2)
.Size(size)
.RefreshOnCompleted()
.Index(index)
, tokenSource.Token);
//we set up an observer
Exception ex = null;
var bulkObserver = new BulkAllObserver(
onError: (e) => OnError(ref ex, e, handle),
onNext: (b) => Interlocked.Increment(ref seenPages)
);
//when we subscribe the observable becomes hot
observableBulk.Subscribe(bulkObserver);
//we wait Nseconds to see some bulks
handle.WaitOne(TimeSpan.FromSeconds(3));
tokenSource.Cancel();
//we wait Nseconds to give in flight request a chance to cancel
handle.WaitOne(TimeSpan.FromSeconds(3));
if (ex != null && !(ex is TaskCanceledException) && !(ex is OperationCanceledException)) throw ex;
seenPages.Should().BeLessThan(pages).And.BeGreaterThan(0);
var count = this._client.Count<SmallObject>(f => f.Index(index));
count.Count.Should().BeLessThan(numberOfDocuments).And.BeGreaterThan(0);
bulkObserver.TotalNumberOfFailedBuffers.Should().Be(0);
bulkObserver.TotalNumberOfRetries.Should().Be(0);
}
[I] public async Task AwaitBulkAll()
{
var index = CreateIndexName();
var size = 1000;
var pages = 10;
var seenPages = 0;
var numberOfDocuments = size * pages;
var documents = this.CreateLazyStreamOfDocuments(numberOfDocuments);
var tokenSource = new CancellationTokenSource();
var observableBulk = this._client.BulkAll(documents, f => f
.MaxDegreeOfParallelism(8)
.BackOffTime(TimeSpan.FromSeconds(10))
.BackOffRetries(2)
.Size(size)
.RefreshOnCompleted()
.Index(index)
.BufferToBulk((r, buffer) => r.IndexMany(buffer))
, tokenSource.Token);
await observableBulk
.ForEachAsync(x => Interlocked.Increment(ref seenPages), tokenSource.Token);
seenPages.Should().Be(pages);
var count = this._client.Count<SmallObject>(f => f.Index(index));
count.Count.Should().Be(numberOfDocuments);
}
[I] public void WaitBulkAllThrowsAndIsCaught()
{
var index = CreateIndexName();
var size = 1000;
var pages = 10;
var seenPages = 0;
var numberOfDocuments = size * pages;
var documents = this.CreateLazyStreamOfDocuments(numberOfDocuments);
var tokenSource = new CancellationTokenSource();
var observableBulk = this._client.BulkAll(documents, f => f
.MaxDegreeOfParallelism(4)
.BackOffTime(TimeSpan.FromSeconds(10))
.BackOffRetries(2)
.Size(size)
.RefreshOnCompleted()
.Index(index)
.BufferToBulk((r, buffer) => r.IndexMany(buffer))
, tokenSource.Token);
try
{
observableBulk.Wait(TimeSpan.FromSeconds(30), b =>
{
if (seenPages == 8) throw new Exception("boom");
Interlocked.Increment(ref seenPages);
});
}
catch (Exception e)
{
seenPages.Should().Be(8);
e.Message.Should().Be("boom");
}
}
[I] public void ForEachAsyncReleasesProcessedItemsInMemory()
{
WeakReference<SmallObject> deallocReference = null;
SmallObject obj = null;
var lazyCollection = GetLazyCollection(
weakRef => deallocReference = weakRef,
delegate { },//...
delegate { },//Making sure that all of the objects have gone through pipeline
delegate { },//so that the first one can be deallocated
delegate { },//Various GC roots prevent several of previous (2 or 3)
delegate { },//items in the lazy Enumerable from deallocation during forced GC
delegate { },//...
delegate {
GC.Collect(2, GCCollectionMode.Forced, true);
deallocReference.TryGetTarget(out obj);
}
);
var index = CreateIndexName();
var observableBulk = this._client.BulkAll(lazyCollection, f => f
.MaxDegreeOfParallelism(1)
.Size(1)
.Index(index)
.BufferToBulk((r, buffer) => r.IndexMany(buffer)));
observableBulk.Wait(TimeSpan.FromSeconds(30), delegate { });
deallocReference.Should().NotBeNull();
obj.Should().BeNull();
}
private IEnumerable<SmallObject> GetLazyCollection(params Action<WeakReference<SmallObject>>[] getFirstObjectCallBack)
{
var counter = 0;
foreach (var callback in getFirstObjectCallBack)
{
var obj = new SmallObject { Id = ++counter };
callback(new WeakReference<SmallObject>(obj));
yield return obj;
}
}
}
}
| 31.003165 | 127 | 0.703481 | [
"Apache-2.0"
] | Tchami/elasticsearch-net | src/Tests/Document/Multiple/BulkAll/BulkAllApiTests.cs | 9,799 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
namespace MusicCenter.App.Controllers
{
public class BaseController : Controller
{
protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
{
string cultureName = null;
// Attempt to read the culture cookie from Request
HttpCookie cultureCookie = Request.Cookies["_culture"];
if (cultureCookie != null)
cultureName = cultureCookie.Value;
else
cultureName = Request.UserLanguages != null && Request.UserLanguages.Length > 0 ?
Request.UserLanguages[0] : // obtain it from HTTP header AcceptLanguages
null;
// Validate culture name
//cultureName = CultureHelper.GetImplementedCulture(cultureName); // This is safe
// Modify current thread's cultures
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cultureName);
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
return base.BeginExecuteCore(callback, state);
}
public string RenderRazorViewToString(string viewName, object model)
{
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View,
ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
}
} | 43.647059 | 105 | 0.548967 | [
"MIT"
] | lkosciuk/MusicCenter | MusicCenter.App/Controllers/BaseController.cs | 2,228 | C# |
using Amazon.JSII.Runtime.Deputy;
#pragma warning disable CS0672,CS0809,CS1591
namespace aws
{
[JsiiInterface(nativeType: typeof(IWafv2RuleGroupRuleStatementAndStatementStatementNotStatementStatementGeoMatchStatement), fullyQualifiedName: "aws.Wafv2RuleGroupRuleStatementAndStatementStatementNotStatementStatementGeoMatchStatement")]
public interface IWafv2RuleGroupRuleStatementAndStatementStatementNotStatementStatementGeoMatchStatement
{
[JsiiProperty(name: "countryCodes", typeJson: "{\"collection\":{\"elementtype\":{\"primitive\":\"string\"},\"kind\":\"array\"}}")]
string[] CountryCodes
{
get;
}
[JsiiTypeProxy(nativeType: typeof(IWafv2RuleGroupRuleStatementAndStatementStatementNotStatementStatementGeoMatchStatement), fullyQualifiedName: "aws.Wafv2RuleGroupRuleStatementAndStatementStatementNotStatementStatementGeoMatchStatement")]
internal sealed class _Proxy : DeputyBase, aws.IWafv2RuleGroupRuleStatementAndStatementStatementNotStatementStatementGeoMatchStatement
{
private _Proxy(ByRefValue reference): base(reference)
{
}
[JsiiProperty(name: "countryCodes", typeJson: "{\"collection\":{\"elementtype\":{\"primitive\":\"string\"},\"kind\":\"array\"}}")]
public string[] CountryCodes
{
get => GetInstanceProperty<string[]>()!;
}
}
}
}
| 46.580645 | 246 | 0.713989 | [
"MIT"
] | scottenriquez/cdktf-alpha-csharp-testing | resources/.gen/aws/aws/IWafv2RuleGroupRuleStatementAndStatementStatementNotStatementStatementGeoMatchStatement.cs | 1,444 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.