content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Collections;
using Devdog.General;
using UnityEngine;
namespace Devdog.QuestSystemPro
{
public sealed class UseTriggerWaypointAction : MonoBehaviour, IWaypointAction
{
[Required]
public Trigger trigger;
public float useDistance = 1f;
public IEnumerator PerformActionsAtWaypoint(Waypoint waypoint, IWaypointCharacter character)
{
DevdogLogger.LogVerbose("(start) Use trigger waypoint action", character.transform);
character.characterController.SetDestination(trigger.transform.position);
// Wait to reach trigger.
while (character.characterController.distanceToDestination > useDistance)
{
yield return null;
}
DevdogLogger.LogVerbose("(complete) Force use trigger", character.transform);
trigger.ForceUseWithoutStateAndUI(character.transform.gameObject);
}
}
}
| 31.193548 | 100 | 0.679421 | [
"MIT"
] | Alan-love/Quest-System-Pro | Assets/Devdog/QuestSystemPro/Scripts/Waypoint/WaypointActions/UseTriggerWaypointAction.cs | 969 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using Elsa.Attributes;
using Elsa.Serialization.ContractResolvers;
using Newtonsoft.Json;
using NodaTime;
using NodaTime.Serialization.JsonNet;
namespace Elsa.Bookmarks
{
public class BookmarkHasher : IBookmarkHasher
{
public string Hash(IBookmark bookmark)
{
var type = bookmark.GetType();
var whiteListedProperties = FilterProperties(type.GetProperties()).ToList();
var contractResolver = new WhiteListedPropertiesContractResolver(whiteListedProperties);
var serializerSettings = new JsonSerializerSettings
{
ContractResolver = contractResolver
}.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
var json = JsonConvert.SerializeObject(bookmark, serializerSettings);
var hash = Hash(json);
return hash;
}
private static string Hash(string input)
{
using var sha = new SHA256Managed();
return Hash(sha, input);
}
private static string Hash(HashAlgorithm hashAlgorithm, string input)
{
var data = hashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(input));
var builder = new StringBuilder();
foreach (var t in data)
builder.Append(t.ToString("x2"));
return builder.ToString();
}
private static IEnumerable<PropertyInfo> FilterProperties(IEnumerable<PropertyInfo> properties) => properties.Where(property => property.GetCustomAttribute<ExcludeFromHashAttribute>() == null);
}
} | 33.72549 | 201 | 0.666279 | [
"BSD-3-Clause"
] | JohnZhaoXiaoHu/elsa-core | src/core/Elsa.Core/Bookmarks/BookmarkHasher.cs | 1,722 | C# |
using System.Collections.Generic;
using SearchSharp;
namespace SearchSharpIntro
{
/// <summary>
/// The data type.
/// </summary>
public record MyData
{
public string MySearchKey;
public int MyValue;
}
public class Program
{
public static void Main(string[] args)
{
// Create DataSet
List<MyData> myDataSet = new()
{
new() {MySearchKey = "TheFirstNumber", MyValue = 1},
new() {MySearchKey = "TheSecondNumber", MyValue = 2}
};
// Create SearchStorage
SearchStorage<MyData> storage = new();
// Add Items
// foreach (MyData data in myDataSet) storage.Add(data.MySearchKey, data);
// Or
storage.Add(myDataSet, x => x.MySearchKey);
// Search
HashSet<MyData> result = storage.Search("num");
}
}
}
| 24.333333 | 86 | 0.522655 | [
"MIT"
] | Afanyiyu/SearchSharp | samples/SearchSharpIntro/Program.cs | 951 | C# |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: doc.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace NPitaya.Protos {
/// <summary>Holder for reflection information generated from doc.proto</summary>
public static partial class DocReflection {
#region Descriptor
/// <summary>File descriptor for doc.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static DocReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cglkb2MucHJvdG8SBnByb3RvcyISCgNEb2MSCwoDZG9jGAEgASgJYgZwcm90",
"bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.Doc), global::NPitaya.Protos.Doc.Parser, new[]{ "Doc_" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class Doc : pb::IMessage<Doc> {
private static readonly pb::MessageParser<Doc> _parser = new pb::MessageParser<Doc>(() => new Doc());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Doc> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::NPitaya.Protos.DocReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Doc() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Doc(Doc other) : this() {
doc_ = other.doc_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Doc Clone() {
return new Doc(this);
}
/// <summary>Field number for the "doc" field.</summary>
public const int Doc_FieldNumber = 1;
private string doc_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Doc_ {
get { return doc_; }
set {
doc_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Doc);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Doc other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Doc_ != other.Doc_) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Doc_.Length != 0) hash ^= Doc_.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Doc_.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Doc_);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Doc_.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Doc_);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Doc other) {
if (other == null) {
return;
}
if (other.Doc_.Length != 0) {
Doc_ = other.Doc_;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Doc_ = input.ReadString();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| 30.953757 | 147 | 0.656956 | [
"MIT"
] | rodopoulos/pitaya-rs | pitaya-sharp/NPitaya/src/gen/Doc.cs | 5,355 | C# |
using System;
using Newtonsoft.Json;
namespace TdLib
{
/// <summary>
/// Autogenerated TDLib APIs
/// </summary>
public partial class TdApi
{
/// <summary>
/// Checks the 2-step verification recovery email address verification code
/// </summary>
public class CheckRecoveryEmailAddressCode : Function<PasswordState>
{
/// <summary>
/// Data type for serialization
/// </summary>
[JsonProperty("@type")]
public override string DataType { get; set; } = "checkRecoveryEmailAddressCode";
/// <summary>
/// Extra data attached to the message
/// </summary>
[JsonProperty("@extra")]
public override string Extra { get; set; }
/// <summary>
/// Verification code
/// </summary>
[JsonConverter(typeof(Converter))]
[JsonProperty("code")]
public string Code { get; set; }
}
}
} | 28.75 | 92 | 0.525604 | [
"MIT"
] | mostafa8026/tdsharp | TDLib.Api/Functions/CheckRecoveryEmailAddressCode.cs | 1,035 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ytg.BasicModel.DTO
{
/// <summary>
/// 投注时用户信息
/// </summary>
public class BettUserDto
{
public int Id { get; set; }
public double Rebate { get; set; }
public string Code { get; set; }
public int UserType { get; set; }
public int PlayType { get; set; }
/// <summary>
/// 1表示该用户被禁用
/// </summary>
public bool IsDelete { get; set; }
/// <summary>
/// 1表示禁用资金
/// </summary>
public int Status { get; set; }
/**
sy.id,sy.Code,sy.Rebate,sy.UserType,sy.IsDelete,b.Status
*/
}
}
| 19.820513 | 69 | 0.525226 | [
"Apache-2.0"
] | heqinghua/lottery-code-qq-814788821- | YtgProject/Ytg.BasicModel/DTO/BettUserDto.cs | 817 | C# |
// MonoGame - Copyright (C) The MonoGame Team
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
using System;
using System.Collections.Generic;
using System.Diagnostics;
#if WINDOWS_UAP
using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;
#endif
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
namespace Microsoft.Xna.Framework
{
public partial class Game : IDisposable
{
private GameComponentCollection _components;
private GameServiceContainer _services;
private ContentManager _content;
internal GamePlatform Platform;
private SortingFilteringCollection<IDrawable> _drawables =
new SortingFilteringCollection<IDrawable>(
d => d.Visible,
(d, handler) => d.VisibleChanged += handler,
(d, handler) => d.VisibleChanged -= handler,
(d1 ,d2) => Comparer<int>.Default.Compare(d1.DrawOrder, d2.DrawOrder),
(d, handler) => d.DrawOrderChanged += handler,
(d, handler) => d.DrawOrderChanged -= handler);
private SortingFilteringCollection<IUpdateable> _updateables =
new SortingFilteringCollection<IUpdateable>(
u => u.Enabled,
(u, handler) => u.EnabledChanged += handler,
(u, handler) => u.EnabledChanged -= handler,
(u1, u2) => Comparer<int>.Default.Compare(u1.UpdateOrder, u2.UpdateOrder),
(u, handler) => u.UpdateOrderChanged += handler,
(u, handler) => u.UpdateOrderChanged -= handler);
private IGraphicsDeviceManager _graphicsDeviceManager;
private IGraphicsDeviceService _graphicsDeviceService;
private bool _initialized = false;
private bool _isFixedTimeStep = true;
private TimeSpan _targetElapsedTime = TimeSpan.FromTicks(166667); // 60fps
private TimeSpan _inactiveSleepTime = TimeSpan.FromSeconds(0.02);
private TimeSpan _maxElapsedTime = TimeSpan.FromMilliseconds(500);
private bool _shouldExit;
private bool _suppressDraw;
// If set to true, enables Wayland VSync on the SDL game platform.
public bool WaylandVsync
{
get
{
if (Platform is SdlGamePlatform sdlGamePlatform)
return sdlGamePlatform.WaylandVsync;
return false;
}
set
{
if (Platform is SdlGamePlatform sdlGamePlatform)
sdlGamePlatform.WaylandVsync = value;
}
}
partial void PlatformConstruct();
public Game()
{
_instance = this;
LaunchParameters = new LaunchParameters();
_services = new GameServiceContainer();
_components = new GameComponentCollection();
_content = new ContentManager(_services);
Platform = GamePlatform.PlatformCreate(this);
Platform.Activated += OnActivated;
Platform.Deactivated += OnDeactivated;
_services.AddService(typeof(GamePlatform), Platform);
// Calling Update() for first time initializes some systems
FrameworkDispatcher.Update();
// Allow some optional per-platform construction to occur too.
PlatformConstruct();
}
~Game()
{
Dispose(false);
}
[System.Diagnostics.Conditional("DEBUG")]
internal void Log(string Message)
{
if (Platform != null) Platform.Log(Message);
}
#region IDisposable Implementation
private bool _isDisposed;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
EventHelpers.Raise(this, Disposed, EventArgs.Empty);
}
protected virtual void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
{
// Dispose loaded game components
for (int i = 0; i < _components.Count; i++)
{
var disposable = _components[i] as IDisposable;
if (disposable != null)
disposable.Dispose();
}
_components = null;
if (_content != null)
{
_content.Dispose();
_content = null;
}
if (_graphicsDeviceManager != null)
{
(_graphicsDeviceManager as GraphicsDeviceManager).Dispose();
_graphicsDeviceManager = null;
}
if (Platform != null)
{
Platform.Activated -= OnActivated;
Platform.Deactivated -= OnDeactivated;
_services.RemoveService(typeof(GamePlatform));
Platform.Dispose();
Platform = null;
}
ContentTypeReaderManager.ClearTypeCreators();
if (SoundEffect._systemState == SoundEffect.SoundSystemState.Initialized)
SoundEffect.PlatformShutdown();
}
#if ANDROID
Activity = null;
#endif
_isDisposed = true;
_instance = null;
}
}
[System.Diagnostics.DebuggerNonUserCode]
private void AssertNotDisposed()
{
if (_isDisposed)
{
string name = GetType().Name;
throw new ObjectDisposedException(
name, string.Format("The {0} object was used after being Disposed.", name));
}
}
#endregion IDisposable Implementation
#region Properties
#if ANDROID
[CLSCompliant(false)]
public static AndroidGameActivity Activity { get; internal set; }
#endif
private static Game _instance = null;
internal static Game Instance { get { return Game._instance; } }
public LaunchParameters LaunchParameters { get; private set; }
public GameComponentCollection Components
{
get { return _components; }
}
public TimeSpan InactiveSleepTime
{
get { return _inactiveSleepTime; }
set
{
if (value < TimeSpan.Zero)
throw new ArgumentOutOfRangeException("The time must be positive.", default(Exception));
_inactiveSleepTime = value;
}
}
/// <summary>
/// The maximum amount of time we will frameskip over and only perform Update calls with no Draw calls.
/// MonoGame extension.
/// </summary>
public TimeSpan MaxElapsedTime
{
get { return _maxElapsedTime; }
set
{
if (value < TimeSpan.Zero)
throw new ArgumentOutOfRangeException("The time must be positive.", default(Exception));
if (value < _targetElapsedTime)
throw new ArgumentOutOfRangeException("The time must be at least TargetElapsedTime", default(Exception));
_maxElapsedTime = value;
}
}
public bool IsActive
{
get { return Platform.IsActive; }
}
public bool IsMouseVisible
{
get { return Platform.IsMouseVisible; }
set { Platform.IsMouseVisible = value; }
}
public TimeSpan TargetElapsedTime
{
get { return _targetElapsedTime; }
set
{
// Give GamePlatform implementations an opportunity to override
// the new value.
value = Platform.TargetElapsedTimeChanging(value);
if (value <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException(
"The time must be positive and non-zero.", default(Exception));
if (value != _targetElapsedTime)
{
_targetElapsedTime = value;
Platform.TargetElapsedTimeChanged();
}
}
}
public bool IsFixedTimeStep
{
get { return _isFixedTimeStep; }
set { _isFixedTimeStep = value; }
}
public GameServiceContainer Services {
get { return _services; }
}
public ContentManager Content
{
get { return _content; }
set
{
if (value == null)
throw new ArgumentNullException();
_content = value;
}
}
public GraphicsDevice GraphicsDevice
{
get
{
if (_graphicsDeviceService == null)
{
_graphicsDeviceService = (IGraphicsDeviceService)
Services.GetService(typeof(IGraphicsDeviceService));
if (_graphicsDeviceService == null)
throw new InvalidOperationException("No Graphics Device Service");
}
return _graphicsDeviceService.GraphicsDevice;
}
}
[CLSCompliant(false)]
public GameWindow Window
{
get { return Platform.Window; }
}
#endregion Properties
#region Internal Properties
// FIXME: Internal members should be eliminated.
// Currently Game.Initialized is used by the Mac game window class to
// determine whether to raise DeviceResetting and DeviceReset on
// GraphicsDeviceManager.
internal bool Initialized
{
get { return _initialized; }
}
#endregion Internal Properties
#region Events
public event EventHandler<EventArgs> Activated;
public event EventHandler<EventArgs> Deactivated;
public event EventHandler<EventArgs> Disposed;
public event EventHandler<EventArgs> Exiting;
#if WINDOWS_UAP
[CLSCompliant(false)]
public ApplicationExecutionState PreviousExecutionState { get; internal set; }
#endif
#endregion
#region Public Methods
#if IOS
[Obsolete("This platform's policy does not allow programmatically closing.", true)]
#endif
public void Exit()
{
_shouldExit = true;
_suppressDraw = true;
}
public void ResetElapsedTime()
{
Platform.ResetElapsedTime();
_gameTimer.Reset();
_gameTimer.Start();
_accumulatedElapsedTime = TimeSpan.Zero;
_gameTime.ElapsedGameTime = TimeSpan.Zero;
_previousTicks = 0L;
}
public void SuppressDraw()
{
_suppressDraw = true;
}
public void RunOneFrame()
{
if (Platform == null)
return;
if (!Platform.BeforeRun())
return;
if (!_initialized)
{
DoInitialize ();
_gameTimer = Stopwatch.StartNew();
_initialized = true;
}
BeginRun();
//Not quite right..
Tick ();
EndRun ();
}
public void Run()
{
Run(Platform.DefaultRunBehavior);
}
public void Run(GameRunBehavior runBehavior)
{
AssertNotDisposed();
if (!Platform.BeforeRun())
{
BeginRun();
_gameTimer = Stopwatch.StartNew();
return;
}
if (!_initialized) {
DoInitialize ();
_initialized = true;
}
BeginRun();
_gameTimer = Stopwatch.StartNew();
switch (runBehavior)
{
case GameRunBehavior.Asynchronous:
Platform.AsyncRunLoopEnded += Platform_AsyncRunLoopEnded;
Platform.StartRunLoop();
break;
case GameRunBehavior.Synchronous:
// XNA runs one Update even before showing the window
DoUpdate(new GameTime());
Platform.RunLoop();
EndRun();
DoExiting();
break;
default:
throw new ArgumentException(string.Format(
"Handling for the run behavior {0} is not implemented.", runBehavior));
}
}
private TimeSpan _accumulatedElapsedTime;
private readonly GameTime _gameTime = new GameTime();
private Stopwatch _gameTimer;
private long _previousTicks = 0;
private int _updateFrameLag;
#if WINDOWS_UAP
private readonly object _locker = new object();
#endif
public void Tick()
{
// NOTE: This code is very sensitive and can break very badly
// with even what looks like a safe change. Be sure to test
// any change fully in both the fixed and variable timestep
// modes across multiple devices and platforms.
RetryTick:
if (!IsActive && (InactiveSleepTime.TotalMilliseconds >= 1.0))
{
#if WINDOWS_UAP
lock (_locker)
System.Threading.Monitor.Wait(_locker, (int)InactiveSleepTime.TotalMilliseconds);
#else
System.Threading.Thread.Sleep((int)InactiveSleepTime.TotalMilliseconds);
#endif
}
// Advance the accumulated elapsed time.
var currentTicks = _gameTimer.Elapsed.Ticks;
_accumulatedElapsedTime += TimeSpan.FromTicks(currentTicks - _previousTicks);
_previousTicks = currentTicks;
if (IsFixedTimeStep && _accumulatedElapsedTime < TargetElapsedTime)
{
#if WINDOWS
// Sleep for as long as possible without overshooting the update time
var sleepTime = (TargetElapsedTime - _accumulatedElapsedTime).TotalMilliseconds;
MonoGame.Utilities.TimerHelper.SleepForNoMoreThan(sleepTime);
#endif
// Keep looping until it's time to perform the next update
goto RetryTick;
}
// Do not allow any update to take longer than our maximum.
if (_accumulatedElapsedTime > _maxElapsedTime)
_accumulatedElapsedTime = _maxElapsedTime;
if (IsFixedTimeStep)
{
_gameTime.ElapsedGameTime = TargetElapsedTime;
var stepCount = 0;
// Perform as many full fixed length time steps as we can.
while (_accumulatedElapsedTime >= TargetElapsedTime && !_shouldExit)
{
_gameTime.TotalGameTime += TargetElapsedTime;
_accumulatedElapsedTime -= TargetElapsedTime;
++stepCount;
DoUpdate(_gameTime);
}
//Every update after the first accumulates lag
_updateFrameLag += Math.Max(0, stepCount - 1);
//If we think we are running slowly, wait until the lag clears before resetting it
if (_gameTime.IsRunningSlowly)
{
if (_updateFrameLag == 0)
_gameTime.IsRunningSlowly = false;
}
else if (_updateFrameLag >= 5)
{
//If we lag more than 5 frames, start thinking we are running slowly
_gameTime.IsRunningSlowly = true;
}
//Every time we just do one update and one draw, then we are not running slowly, so decrease the lag
if (stepCount == 1 && _updateFrameLag > 0)
_updateFrameLag--;
// Draw needs to know the total elapsed time
// that occured for the fixed length updates.
_gameTime.ElapsedGameTime = TimeSpan.FromTicks(TargetElapsedTime.Ticks * stepCount);
}
else
{
// Perform a single variable length update.
_gameTime.ElapsedGameTime = _accumulatedElapsedTime;
_gameTime.TotalGameTime += _accumulatedElapsedTime;
_accumulatedElapsedTime = TimeSpan.Zero;
DoUpdate(_gameTime);
}
// Draw unless the update suppressed it.
if (_suppressDraw)
_suppressDraw = false;
else
{
DoDraw(_gameTime);
}
if (_shouldExit)
{
Platform.Exit();
_shouldExit = false; //prevents perpetual exiting on platforms supporting resume.
}
}
#endregion
#region Protected Methods
protected virtual bool BeginDraw() { return true; }
protected virtual void EndDraw()
{
Platform.Present();
}
protected virtual void BeginRun() { }
protected virtual void EndRun() { }
protected virtual void LoadContent() { }
protected virtual void UnloadContent() { }
protected virtual void Initialize()
{
// TODO: This should be removed once all platforms use the new GraphicsDeviceManager
#if !(WINDOWS && DIRECTX)
applyChanges(graphicsDeviceManager);
#endif
// According to the information given on MSDN (see link below), all
// GameComponents in Components at the time Initialize() is called
// are initialized.
// http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.initialize.aspx
// Initialize all existing components
InitializeExistingComponents();
_graphicsDeviceService = (IGraphicsDeviceService)
Services.GetService(typeof(IGraphicsDeviceService));
if (_graphicsDeviceService != null &&
_graphicsDeviceService.GraphicsDevice != null)
{
LoadContent();
}
}
private static readonly Action<IDrawable, GameTime> DrawAction =
(drawable, gameTime) => drawable.Draw(gameTime);
protected virtual void Draw(GameTime gameTime)
{
_drawables.ForEachFilteredItem(DrawAction, gameTime);
}
private static readonly Action<IUpdateable, GameTime> UpdateAction =
(updateable, gameTime) => updateable.Update(gameTime);
protected virtual void Update(GameTime gameTime)
{
_updateables.ForEachFilteredItem(UpdateAction, gameTime);
}
protected virtual void OnExiting(object sender, EventArgs args)
{
EventHelpers.Raise(sender, Exiting, args);
}
protected virtual void OnActivated(object sender, EventArgs args)
{
AssertNotDisposed();
EventHelpers.Raise(sender, Activated, args);
}
protected virtual void OnDeactivated(object sender, EventArgs args)
{
AssertNotDisposed();
EventHelpers.Raise(sender, Deactivated, args);
}
#endregion Protected Methods
#region Event Handlers
private void Components_ComponentAdded(
object sender, GameComponentCollectionEventArgs e)
{
// Since we only subscribe to ComponentAdded after the graphics
// devices are set up, it is safe to just blindly call Initialize.
e.GameComponent.Initialize();
CategorizeComponent(e.GameComponent);
}
private void Components_ComponentRemoved(
object sender, GameComponentCollectionEventArgs e)
{
DecategorizeComponent(e.GameComponent);
}
private void Platform_AsyncRunLoopEnded(object sender, EventArgs e)
{
AssertNotDisposed();
var platform = (GamePlatform)sender;
platform.AsyncRunLoopEnded -= Platform_AsyncRunLoopEnded;
EndRun();
DoExiting();
}
#endregion Event Handlers
#region Internal Methods
// FIXME: We should work toward eliminating internal methods. They
// break entirely the possibility that additional platforms could
// be added by third parties without changing MonoGame itself.
#if !(WINDOWS && DIRECTX)
internal void applyChanges(GraphicsDeviceManager manager)
{
Platform.BeginScreenDeviceChange(GraphicsDevice.PresentationParameters.IsFullScreen);
if (GraphicsDevice.PresentationParameters.IsFullScreen)
Platform.EnterFullScreen();
else
Platform.ExitFullScreen();
var viewport = new Viewport(0, 0,
GraphicsDevice.PresentationParameters.BackBufferWidth,
GraphicsDevice.PresentationParameters.BackBufferHeight);
GraphicsDevice.Viewport = viewport;
Platform.EndScreenDeviceChange(string.Empty, viewport.Width, viewport.Height);
}
#endif
internal void DoUpdate(GameTime gameTime)
{
AssertNotDisposed();
if (Platform.BeforeUpdate(gameTime))
{
FrameworkDispatcher.Update();
Update(gameTime);
//The TouchPanel needs to know the time for when touches arrive
TouchPanelState.CurrentTimestamp = gameTime.TotalGameTime;
}
}
internal void DoDraw(GameTime gameTime)
{
AssertNotDisposed();
// Draw and EndDraw should not be called if BeginDraw returns false.
// http://stackoverflow.com/questions/4054936/manual-control-over-when-to-redraw-the-screen/4057180#4057180
// http://stackoverflow.com/questions/4235439/xna-3-1-to-4-0-requires-constant-redraw-or-will-display-a-purple-screen
if (Platform.BeforeDraw(gameTime) && BeginDraw())
{
Draw(gameTime);
EndDraw();
}
}
internal void DoInitialize()
{
AssertNotDisposed();
if (GraphicsDevice == null && graphicsDeviceManager != null)
_graphicsDeviceManager.CreateDevice();
Platform.BeforeInitialize();
Initialize();
// We need to do this after virtual Initialize(...) is called.
// 1. Categorize components into IUpdateable and IDrawable lists.
// 2. Subscribe to Added/Removed events to keep the categorized
// lists synced and to Initialize future components as they are
// added.
CategorizeComponents();
_components.ComponentAdded += Components_ComponentAdded;
_components.ComponentRemoved += Components_ComponentRemoved;
}
internal void DoExiting()
{
OnExiting(this, EventArgs.Empty);
UnloadContent();
}
#endregion Internal Methods
internal GraphicsDeviceManager graphicsDeviceManager
{
get
{
if (_graphicsDeviceManager == null)
{
_graphicsDeviceManager = (IGraphicsDeviceManager)
Services.GetService(typeof(IGraphicsDeviceManager));
}
return (GraphicsDeviceManager)_graphicsDeviceManager;
}
set
{
if (_graphicsDeviceManager != null)
throw new InvalidOperationException("GraphicsDeviceManager already registered for this Game object");
_graphicsDeviceManager = value;
}
}
// NOTE: InitializeExistingComponents really should only be called once.
// Game.Initialize is the only method in a position to guarantee
// that no component will get a duplicate Initialize call.
// Further calls to Initialize occur immediately in response to
// Components.ComponentAdded.
private void InitializeExistingComponents()
{
for(int i = 0; i < Components.Count; ++i)
Components[i].Initialize();
}
private void CategorizeComponents()
{
DecategorizeComponents();
for (int i = 0; i < Components.Count; ++i)
CategorizeComponent(Components[i]);
}
// FIXME: I am open to a better name for this method. It does the
// opposite of CategorizeComponents.
private void DecategorizeComponents()
{
_updateables.Clear();
_drawables.Clear();
}
private void CategorizeComponent(IGameComponent component)
{
if (component is IUpdateable)
_updateables.Add((IUpdateable)component);
if (component is IDrawable)
_drawables.Add((IDrawable)component);
}
// FIXME: I am open to a better name for this method. It does the
// opposite of CategorizeComponent.
private void DecategorizeComponent(IGameComponent component)
{
if (component is IUpdateable)
_updateables.Remove((IUpdateable)component);
if (component is IDrawable)
_drawables.Remove((IDrawable)component);
}
/// <summary>
/// The SortingFilteringCollection class provides efficient, reusable
/// sorting and filtering based on a configurable sort comparer, filter
/// predicate, and associate change events.
/// </summary>
class SortingFilteringCollection<T> : ICollection<T>
{
private readonly List<T> _items;
private readonly List<AddJournalEntry<T>> _addJournal;
private readonly Comparison<AddJournalEntry<T>> _addJournalSortComparison;
private readonly List<int> _removeJournal;
private readonly List<T> _cachedFilteredItems;
private bool _shouldRebuildCache;
private readonly Predicate<T> _filter;
private readonly Comparison<T> _sort;
private readonly Action<T, EventHandler<EventArgs>> _filterChangedSubscriber;
private readonly Action<T, EventHandler<EventArgs>> _filterChangedUnsubscriber;
private readonly Action<T, EventHandler<EventArgs>> _sortChangedSubscriber;
private readonly Action<T, EventHandler<EventArgs>> _sortChangedUnsubscriber;
public SortingFilteringCollection(
Predicate<T> filter,
Action<T, EventHandler<EventArgs>> filterChangedSubscriber,
Action<T, EventHandler<EventArgs>> filterChangedUnsubscriber,
Comparison<T> sort,
Action<T, EventHandler<EventArgs>> sortChangedSubscriber,
Action<T, EventHandler<EventArgs>> sortChangedUnsubscriber)
{
_items = new List<T>();
_addJournal = new List<AddJournalEntry<T>>();
_removeJournal = new List<int>();
_cachedFilteredItems = new List<T>();
_shouldRebuildCache = true;
_filter = filter;
_filterChangedSubscriber = filterChangedSubscriber;
_filterChangedUnsubscriber = filterChangedUnsubscriber;
_sort = sort;
_sortChangedSubscriber = sortChangedSubscriber;
_sortChangedUnsubscriber = sortChangedUnsubscriber;
_addJournalSortComparison = CompareAddJournalEntry;
}
private int CompareAddJournalEntry(AddJournalEntry<T> x, AddJournalEntry<T> y)
{
int result = _sort(x.Item, y.Item);
if (result != 0)
return result;
return x.Order - y.Order;
}
public void ForEachFilteredItem<TUserData>(Action<T, TUserData> action, TUserData userData)
{
if (_shouldRebuildCache)
{
ProcessRemoveJournal();
ProcessAddJournal();
// Rebuild the cache
_cachedFilteredItems.Clear();
for (int i = 0; i < _items.Count; ++i)
if (_filter(_items[i]))
_cachedFilteredItems.Add(_items[i]);
_shouldRebuildCache = false;
}
for (int i = 0; i < _cachedFilteredItems.Count; ++i)
action(_cachedFilteredItems[i], userData);
// If the cache was invalidated as a result of processing items,
// now is a good time to clear it and give the GC (more of) a
// chance to do its thing.
if (_shouldRebuildCache)
_cachedFilteredItems.Clear();
}
public void Add(T item)
{
// NOTE: We subscribe to item events after items in _addJournal
// have been merged.
_addJournal.Add(new AddJournalEntry<T>(_addJournal.Count, item));
InvalidateCache();
}
public bool Remove(T item)
{
if (_addJournal.Remove(AddJournalEntry<T>.CreateKey(item)))
return true;
var index = _items.IndexOf(item);
if (index >= 0)
{
UnsubscribeFromItemEvents(item);
_removeJournal.Add(index);
InvalidateCache();
return true;
}
return false;
}
public void Clear()
{
for (int i = 0; i < _items.Count; ++i)
{
_filterChangedUnsubscriber(_items[i], Item_FilterPropertyChanged);
_sortChangedUnsubscriber(_items[i], Item_SortPropertyChanged);
}
_addJournal.Clear();
_removeJournal.Clear();
_items.Clear();
InvalidateCache();
}
public bool Contains(T item)
{
return _items.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
_items.CopyTo(array, arrayIndex);
}
public int Count
{
get { return _items.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public IEnumerator<T> GetEnumerator()
{
return _items.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return ((System.Collections.IEnumerable)_items).GetEnumerator();
}
private static readonly Comparison<int> RemoveJournalSortComparison =
(x, y) => Comparer<int>.Default.Compare(y, x); // Sort high to low
private void ProcessRemoveJournal()
{
if (_removeJournal.Count == 0)
return;
// Remove items in reverse. (Technically there exist faster
// ways to bulk-remove from a variable-length array, but List<T>
// does not provide such a method.)
_removeJournal.Sort(RemoveJournalSortComparison);
for (int i = 0; i < _removeJournal.Count; ++i)
_items.RemoveAt(_removeJournal[i]);
_removeJournal.Clear();
}
private void ProcessAddJournal()
{
if (_addJournal.Count == 0)
return;
// Prepare the _addJournal to be merge-sorted with _items.
// _items is already sorted (because it is always sorted).
_addJournal.Sort(_addJournalSortComparison);
int iAddJournal = 0;
int iItems = 0;
while (iItems < _items.Count && iAddJournal < _addJournal.Count)
{
var addJournalItem = _addJournal[iAddJournal].Item;
// If addJournalItem is less than (belongs before)
// _items[iItems], insert it.
if (_sort(addJournalItem, _items[iItems]) < 0)
{
SubscribeToItemEvents(addJournalItem);
_items.Insert(iItems, addJournalItem);
++iAddJournal;
}
// Always increment iItems, either because we inserted and
// need to move past the insertion, or because we didn't
// insert and need to consider the next element.
++iItems;
}
// If _addJournal had any "tail" items, append them all now.
for (; iAddJournal < _addJournal.Count; ++iAddJournal)
{
var addJournalItem = _addJournal[iAddJournal].Item;
SubscribeToItemEvents(addJournalItem);
_items.Add(addJournalItem);
}
_addJournal.Clear();
}
private void SubscribeToItemEvents(T item)
{
_filterChangedSubscriber(item, Item_FilterPropertyChanged);
_sortChangedSubscriber(item, Item_SortPropertyChanged);
}
private void UnsubscribeFromItemEvents(T item)
{
_filterChangedUnsubscriber(item, Item_FilterPropertyChanged);
_sortChangedUnsubscriber(item, Item_SortPropertyChanged);
}
private void InvalidateCache()
{
_shouldRebuildCache = true;
}
private void Item_FilterPropertyChanged(object sender, EventArgs e)
{
InvalidateCache();
}
private void Item_SortPropertyChanged(object sender, EventArgs e)
{
var item = (T)sender;
var index = _items.IndexOf(item);
_addJournal.Add(new AddJournalEntry<T>(_addJournal.Count, item));
_removeJournal.Add(index);
// Until the item is back in place, we don't care about its
// events. We will re-subscribe when _addJournal is processed.
UnsubscribeFromItemEvents(item);
InvalidateCache();
}
}
private struct AddJournalEntry<T>
{
public readonly int Order;
public readonly T Item;
public AddJournalEntry(int order, T item)
{
Order = order;
Item = item;
}
public static AddJournalEntry<T> CreateKey(T item)
{
return new AddJournalEntry<T>(-1, item);
}
public override int GetHashCode()
{
return Item.GetHashCode();
}
public override bool Equals(object obj)
{
if (!(obj is AddJournalEntry<T>))
return false;
return object.Equals(Item, ((AddJournalEntry<T>)obj).Item);
}
}
}
}
| 34.191107 | 129 | 0.549225 | [
"MIT"
] | PulsarcGame/MonoGame | MonoGame.Framework/Game.cs | 36,140 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CS451ScrabbleAssignment
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
}
}
| 18.190476 | 37 | 0.693717 | [
"MIT"
] | ajm1014/scrabble | CS451ScrabbleAssignment/Form2.cs | 384 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ICSharpCode.CodeConverter.Shared;
using ICSharpCode.CodeConverter.Util;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Rename;
namespace ICSharpCode.CodeConverter.VB
{
internal static class CaseConflictResolver
{
/// <summary>
/// Renames symbols in a CSharp project so that they don't clash on case within the same named scope, attempting to rename the least public ones first.
/// This is because C# is case sensitive but VB is case insensitive.
/// </summary>
/// <remarks>
/// Cases in different named scopes should be dealt with by <seealso cref="DocumentExtensions.ExpandVbAsync"/>.
/// For names scoped within a type member, see <seealso cref="GetCsLocalSymbolsPerScope"/>.
/// </remarks>
public static async Task<Project> RenameClashingSymbols(Project project)
{
var compilation = await project.GetCompilationAsync();
var memberRenames = compilation.GlobalNamespace.FollowProperty((INamespaceOrTypeSymbol n) => n.GetMembers().OfType<INamespaceOrTypeSymbol>().Where(s => s.IsDefinedInSource()))
.SelectMany(x => GetSymbolsWithNewNames(x, compilation));
return await PerformRenames(project, memberRenames.ToList());
}
private static IEnumerable<(ISymbol Original, string NewName)> GetSymbolsWithNewNames(INamespaceOrTypeSymbol containerSymbol, Compilation compilation)
{
var members = containerSymbol.GetMembers().Where(m => m.Locations.Any(loc => compilation.ContainsSyntaxTree(loc.SourceTree))).ToArray();
var symbolSets = GetLocalSymbolSets(containerSymbol, compilation, members).Concat(members.AsEnumerable().Yield());
return symbolSets.SelectMany(GetUniqueNamesForSymbolSet);
}
public static IEnumerable<IEnumerable<ISymbol>> GetLocalSymbolSets(INamespaceOrTypeSymbol containerSymbol, Compilation compilation, IReadOnlyCollection<ISymbol> members)
{
if (!(containerSymbol is ITypeSymbol)) return Enumerable.Empty<IEnumerable<ISymbol>>();
var semanticModels = containerSymbol.Locations.Select(loc => loc.SourceTree).Distinct()
.Where(sourceTree => compilation.ContainsSyntaxTree(sourceTree))
.Select(sourceTree => compilation.GetSemanticModel(sourceTree, true));
return semanticModels.SelectMany(semanticModel => members.SelectMany(m => semanticModel.GetCsSymbolsPerScope(m)));
}
private static IEnumerable<(ISymbol Original, string NewName)> GetUniqueNamesForSymbolSet(IEnumerable<ISymbol> symbols) {
var membersByCaseInsensitiveName = symbols.ToLookup(m => GetName(m), m => m, StringComparer.OrdinalIgnoreCase);
var names = new HashSet<string>(membersByCaseInsensitiveName.Select(ms => ms.Key),
StringComparer.OrdinalIgnoreCase);
var symbolsWithNewNames = membersByCaseInsensitiveName.Where(ms => ms.Count() > 1)
.SelectMany(symbolGroup => GetSymbolsWithNewNames(symbolGroup.ToArray(), names));
return symbolsWithNewNames;
}
private static string GetName(ISymbol m) {
if (m.CanBeReferencedByName)
return m.Name;
if (m.ExplicitInterfaceImplementations().Any())
return m.Name.Split('.').Last();
return m.Name;
}
private static IEnumerable<(ISymbol Original, string NewName)> GetSymbolsWithNewNames(IReadOnlyCollection<ISymbol> symbolGroup, HashSet<string> names)
{
var canRename = symbolGroup.Where(s => s.IsDefinedInSource() && s.CanBeReferencedByName).ToArray();
var specialSymbolUsingName = canRename.Length < symbolGroup.Count;
var methodSymbols = canRename.OfType<IMethodSymbol>().ToArray();
var canKeepOneNormalMemberName = !specialSymbolUsingName && !methodSymbols.Any();
symbolGroup = canRename.Except(methodSymbols).ToArray();
(ISymbol Original, string NewName)[] methodsWithNewNames = GetMethodSymbolsWithNewNames(methodSymbols.ToArray(), names, specialSymbolUsingName);
return GetSymbolsWithNewNames(symbolGroup, names.Add, canKeepOneNormalMemberName).Concat(methodsWithNewNames);
}
private static (ISymbol Original, string NewName)[] GetMethodSymbolsWithNewNames(IMethodSymbol[] methodSymbols,
HashSet<string> names,
bool specialSymbolUsingName)
{
var methodsByCaseInsensitiveSignature = methodSymbols
.ToLookup(m => m.GetUnqualifiedMethodSignature(false))
.Where(g => g.Count() > 1)
.SelectMany(clashingMethodGroup =>
{
var thisMethodGroupNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var symbolsWithNewNames = GetSymbolsWithNewNames(clashingMethodGroup,
n => !names.Contains(n) && thisMethodGroupNames.Add(n),
!specialSymbolUsingName).ToArray();
return symbolsWithNewNames;
}).ToArray();
foreach (var newMethodNames in methodsByCaseInsensitiveSignature.Select(m => m.NewName))
{
names.Add(newMethodNames);
}
return methodsByCaseInsensitiveSignature;
}
private static IEnumerable<(ISymbol Original, string NewName)> GetSymbolsWithNewNames(
IEnumerable<ISymbol> toRename, Func<string, bool> canUse, bool canKeepOne)
{
var symbolsWithNewNames = toRename.OrderByDescending(x => x.DeclaredAccessibility).ThenByDescending(x => x.Kind == SymbolKind.Parameter || x.Kind == SymbolKind.Property).Skip(canKeepOne ? 1 :0).Select(tr =>
{
string newName = NameGenerator.GenerateUniqueName(GetBaseName(tr), canUse);
return (Original: tr, NewName: newName);
});
return symbolsWithNewNames;
}
private static async Task<Project> PerformRenames(Project project, IReadOnlyCollection<(ISymbol Original, string NewName)> symbolsWithNewNames)
{
var solution = project.Solution;
foreach (var (originalSymbol, newName) in symbolsWithNewNames) {
project = solution.GetProject(project.Id);
var compilation = await project.GetCompilationAsync();
ISymbol currentDeclaration = SymbolFinder.FindSimilarSymbols(originalSymbol, compilation).FirstOrDefault();
if (currentDeclaration == null)
continue; //Must have already renamed this symbol for a different reason
solution = await Renamer.RenameSymbolAsync(solution, currentDeclaration, newName, solution.Workspace.Options);
}
return solution.GetProject(project.Id);
}
private static string GetBaseName(ISymbol declaration)
{
string prefix = declaration.Kind.ToString().ToLowerInvariant()[0] + "_";
string name = GetName(declaration);
return prefix + name.Substring(0, 1).ToUpperInvariant() + name.Substring(1);
}
}
} | 57.037879 | 219 | 0.657325 | [
"MIT"
] | renesugar/CodeConverter | CodeConverter/VB/CaseConflictResolver.cs | 7,400 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace cloudscribe.Core.Storage.EFCore.MySql.Migrations
{
public partial class cscore20190420 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "BrowserKey",
table: "cs_User",
maxLength: 50,
nullable: true);
migrationBuilder.AddColumn<bool>(
name: "SingleBrowserSessions",
table: "cs_Site",
nullable: false,
defaultValue: false);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "BrowserKey",
table: "cs_User");
migrationBuilder.DropColumn(
name: "SingleBrowserSessions",
table: "cs_Site");
}
}
}
| 28.735294 | 71 | 0.551689 | [
"Apache-2.0"
] | MicheleRoma/cloudscribe | src/cloudscribe.Core.Storage.EFCore.MySql/Migrations/20190420184803_cs-core-20190420.cs | 979 | C# |
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(MovementMotor))]
[RequireComponent(typeof(LookController))]
[RequireComponent(typeof(PlayerAnimStateMachineController))]
//[RequireComponent(typeof(PlayerCamController))]
public class PlayerController : MonoBehaviour {
public enum InteractionMode {
Movement = 0,
Painting = 1,
}
private Rigidbody rigBod;
public LookController lookControl;
public MovementMotor motor;
PlayerAnimStateMachineController animationBinder;
public PlayerCamController camController;
public InteractionMode curInteractionMode;
void Awake() {
rigBod = GetComponent<Rigidbody>();
lookControl = GetComponent<LookController>();
motor = GetComponent<MovementMotor>();
animationBinder = GetComponent<PlayerAnimStateMachineController>();
}
void Start () {
}
// Update is called once per frame
void Update () {
HandleInput();
}
private void HandleInput() {
HandleLookInput();
HandleMovementInput();
}
private void HandleLookInput() {
lookControl.SetDeltaAimDirec(new Vector2(Input.GetAxisRaw("Mouse X"),
Input.GetAxisRaw("Mouse Y")));
}
private void HandleMovementInput() {
motor.SetDesiredMoveDirec(new Vector3(Input.GetAxisRaw("Horizontal"),
0.0f,
Input.GetAxisRaw("Vertical")));
}
public void SwitchModes(InteractionMode newMode) {
if (curInteractionMode == newMode) { return; }
switch(newMode) {
case InteractionMode.Movement:
SwitchToMovementModeProtocol();
break;
case InteractionMode.Painting:
SwitchToPaintingModeProtocol();
break;
}
}
private void SwitchToMovementModeProtocol() {
}
private void SwitchToPaintingModeProtocol() {
}
public void KillPlayer() {
rigBod.constraints = RigidbodyConstraints.None;
rigBod.useGravity = true;
rigBod.AddTorque(rigBod.transform.right * 50);
motor.enabled = false;
animationBinder.canAnimate = false;
//lookControl.enabled = false;
//camController.KillPlayerEffects();
}
}
| 21.070707 | 75 | 0.727709 | [
"Apache-2.0"
] | carlsc2/A-Clockwork-Cadmium-Orange | Parody Game Jam/Assets/Scripts/PlayerController.cs | 2,088 | C# |
/*
* Copyright (C) 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS))
using System;
using GooglePlayGames.Native.PInvoke;
using System.Runtime.InteropServices;
using GooglePlayGames.OurUtils;
using System.Collections.Generic;
using GooglePlayGames.Native.Cwrapper;
using C = GooglePlayGames.Native.Cwrapper.ParticipantResults;
using Types = GooglePlayGames.Native.Cwrapper.Types;
using Status = GooglePlayGames.Native.Cwrapper.CommonErrorStatus;
namespace GooglePlayGames.Native.PInvoke {
internal class ParticipantResults : BaseReferenceHolder {
internal ParticipantResults(IntPtr selfPointer) : base(selfPointer) {
}
internal bool HasResultsForParticipant(string participantId) {
return C.ParticipantResults_HasResultsForParticipant(SelfPtr(), participantId);
}
internal uint PlacingForParticipant(string participantId) {
return C.ParticipantResults_PlaceForParticipant(SelfPtr(), participantId);
}
internal Types.MatchResult ResultsForParticipant(string participantId) {
return C.ParticipantResults_MatchResultForParticipant(SelfPtr(), participantId);
}
internal ParticipantResults WithResult(string participantId, uint placing,
Types.MatchResult result) {
return new ParticipantResults(C.ParticipantResults_WithResult(
SelfPtr(), participantId, placing, result));
}
protected override void CallDispose(HandleRef selfPointer) {
C.ParticipantResults_Dispose(selfPointer);
}
}
}
#endif
| 35.322034 | 88 | 0.762956 | [
"MIT"
] | Kaktus606/Fifteen | Assets/GooglePlayGames/Platforms/Native/PInvoke/ParticipantResults.cs | 2,084 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace pitachan.DTOs.Janitors
{
public class LoginDTO
{
[Required(ErrorMessage = "Login_Email_Required_Message")]
[EmailAddress(ErrorMessage = "Login_Email_Format_Error_Message")]
public string Email { get; set; }
[Required(ErrorMessage = "Login_Password_Required_Message")]
[DataType(DataType.Password, ErrorMessage = "Login_Password_Format_Requirement_Message")]
public string Password { get; set; }
}
}
| 30.7 | 97 | 0.73127 | [
"MIT"
] | persamuel/pitachan | pitachan/DTOs/Janitors/LoginDTO.cs | 616 | C# |
using System;
using System.Linq;
using System.Windows.Forms;
using HidLibrary;
namespace TestHarness
{
public partial class Main : Form
{
public Main()
{
InitializeComponent();
}
private HidDevice[] _deviceList;
private HidDevice _selectedDevice;
public delegate void ReadHandlerDelegate(HidReport report);
private void Main_Load(object sender, EventArgs e)
{
RefreshDevices();
}
private void Read_Click(object sender, EventArgs e)
{
if (Devices.SelectedIndex <= -1) return;
var device = _deviceList[Devices.SelectedIndex];
device.OpenDevice();
device.MonitorDeviceEvents = true;
device.ReadReport(ReadProcess);
}
private void Scan_MouseDown(object sender, MouseEventArgs e)
{
var outData = _deviceList[Devices.SelectedIndex].CreateReport();
outData.ReportId = 0x4;
outData.Data[0] = 0x4;
_deviceList[Devices.SelectedIndex].WriteReport(outData);
}
private void Scan_MouseUp(object sender, MouseEventArgs e)
{
var outData = _deviceList[Devices.SelectedIndex].CreateReport();
outData.ReportId = 0x4;
outData.Data[0] = 0x1;
_deviceList[Devices.SelectedIndex].WriteReport(outData);
}
private void ErrorBeep_Click(object sender, EventArgs e)
{
var report = _deviceList[Devices.SelectedIndex].CreateReport();
report.ReportId = 0x4;
report.Data[0] = 0x20;
_deviceList[Devices.SelectedIndex].WriteReport(report);
}
private void SuccessBeep_Click(object sender, EventArgs e)
{
var outData = _deviceList[Devices.SelectedIndex].CreateReport();
outData.ReportId = 0x4;
outData.Data[0] = 0x40;
_deviceList[Devices.SelectedIndex].WriteReport(outData, WriteResult);
}
private void Refresh_Click(object sender, EventArgs e)
{
RefreshDevices();
}
private void Devices_SelectedIndexChanged(object sender, EventArgs e)
{
if ((_selectedDevice != null)) _selectedDevice.CloseDevice();
_selectedDevice = _deviceList[Devices.SelectedIndex];
_selectedDevice.OpenDevice();
_selectedDevice.MonitorDeviceEvents = true;
_selectedDevice.Inserted += Device_Inserted;
_selectedDevice.Removed += Device_Removed;
}
private void Devices_DoubleClick(object sender, EventArgs e)
{
if (Devices.SelectedIndex > -1) MessageBox.Show("Connected: " + _deviceList[Devices.SelectedIndex].IsConnected);
}
private void Device_Inserted()
{
if (InvokeRequired)
{
BeginInvoke(new Action(Device_Inserted));
return;
}
Output.AppendText("Connected\r\n");
}
private void Device_Removed()
{
if (InvokeRequired)
{
BeginInvoke(new Action(Device_Removed));
return;
}
Output.AppendText("Disconnected\r\n");
}
private void ReadProcess(HidReport report)
{
BeginInvoke(new ReadHandlerDelegate(ReadHandler), new object[] { report });
}
private void ReadHandler(HidReport report)
{
Output.Clear();
Output.AppendText(String.Join(" ", report.Data.Select(d => d.ToString("X2"))));
_deviceList[Devices.SelectedIndex].ReadReport(ReadProcess);
}
private static void WriteResult(bool success)
{
MessageBox.Show("Write result: " + success);
}
private void RefreshDevices()
{
_deviceList = HidDevices.Enumerate().ToArray();
//_deviceList = HidDevices.Enumerate(0x536, 0x207, 0x1c7).ToArray();
Devices.DisplayMember = "Name";
Devices.DataSource = _deviceList;
if (_deviceList.Length > 0) _selectedDevice = _deviceList[0];
}
}
}
| 30.611111 | 125 | 0.563521 | [
"MIT"
] | profK/HidLibrary | src/TestHarness/Main.cs | 4,410 | C# |
using LoteriaFacil.Domain.Validations;
namespace LoteriaFacil.Domain.Commands
{
public class RegisterNewTypeLotteryCommand : TypeLotteryCommand
{
public RegisterNewTypeLotteryCommand(string name, int tens_min, decimal bet_min, int hit_min, int hit_max)
{
this.Name = name;
this.Tens_Min = tens_min;
this.Bet_Min = bet_min;
this.Hit_Min = hit_min;
this.Hit_Max = hit_max;
}
public override bool IsValid()
{
ValidationResult = new RegisterNewTypeLotteryCommandValidation().Validate(this);
return ValidationResult.IsValid;
}
}
}
| 29.217391 | 114 | 0.635417 | [
"MIT"
] | DiegoGalante/lotofacil-aspnetcore | LoteriaFacil.Domain/Commands/RegisterNewTypeLotteryCommand.cs | 674 | C# |
using Moq;
using StandardDot.Abstract.Configuration;
using Xunit;
namespace StandardDot.Abstract.IntegrationTests.Configuration
{
public class IConfigurationCacheTests
{
[Fact]
public void Properties()
{
Mock<IConfigurationCache> cacheProxy = new Mock<IConfigurationCache>(MockBehavior.Strict);
cacheProxy.SetupGet(x => x.NumberOfConfigurations).Returns(4);
Assert.Equal(4, cacheProxy.Object.NumberOfConfigurations);
}
[Fact]
public void ResetCacheTest()
{
Mock<IConfigurationCache> cacheProxy = new Mock<IConfigurationCache>(MockBehavior.Strict);
cacheProxy.Setup(x => x.ResetCache());
cacheProxy.Object.ResetCache();
cacheProxy.Verify(x => x.ResetCache());
}
}
} | 27.153846 | 93 | 0.756374 | [
"MIT"
] | mrlunchbox777/StandardDot | src/AbstractIntegrationTests/Configuration/IConfigurationCacheTests.cs | 706 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: IEntityCollectionRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The interface IOnPremisesPublishingProfilePublishedResourcesCollectionRequest.
/// </summary>
public partial interface IOnPremisesPublishingProfilePublishedResourcesCollectionRequest : IBaseRequest
{
/// <summary>
/// Adds the specified PublishedResource to the collection via POST.
/// </summary>
/// <param name="publishedResource">The PublishedResource to add.</param>
/// <returns>The created PublishedResource.</returns>
System.Threading.Tasks.Task<PublishedResource> AddAsync(PublishedResource publishedResource);
/// <summary>
/// Adds the specified PublishedResource to the collection via POST.
/// </summary>
/// <param name="publishedResource">The PublishedResource to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created PublishedResource.</returns>
System.Threading.Tasks.Task<PublishedResource> AddAsync(PublishedResource publishedResource, CancellationToken cancellationToken);
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
System.Threading.Tasks.Task<IOnPremisesPublishingProfilePublishedResourcesCollectionPage> GetAsync();
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
System.Threading.Tasks.Task<IOnPremisesPublishingProfilePublishedResourcesCollectionPage> GetAsync(CancellationToken cancellationToken);
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
IOnPremisesPublishingProfilePublishedResourcesCollectionRequest Expand(string value);
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
IOnPremisesPublishingProfilePublishedResourcesCollectionRequest Expand(Expression<Func<PublishedResource, object>> expandExpression);
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
IOnPremisesPublishingProfilePublishedResourcesCollectionRequest Select(string value);
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
IOnPremisesPublishingProfilePublishedResourcesCollectionRequest Select(Expression<Func<PublishedResource, object>> selectExpression);
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
IOnPremisesPublishingProfilePublishedResourcesCollectionRequest Top(int value);
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
IOnPremisesPublishingProfilePublishedResourcesCollectionRequest Filter(string value);
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
IOnPremisesPublishingProfilePublishedResourcesCollectionRequest Skip(int value);
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
IOnPremisesPublishingProfilePublishedResourcesCollectionRequest OrderBy(string value);
}
}
| 47.5 | 153 | 0.651657 | [
"MIT"
] | GeertVL/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Generated/requests/IOnPremisesPublishingProfilePublishedResourcesCollectionRequest.cs | 5,130 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
namespace Azure.Identity
{
/// <summary>
/// Options used to configure the <see cref="ClientCertificateCredential"/>.
/// </summary>
public class ClientCertificateCredentialOptions : TokenCredentialOptions, ITokenCacheOptions
{
/// <summary>
/// Specifies the <see cref="TokenCachePersistenceOptions"/> to be used by the credential. If not options are specified, the token cache will not be persisted.
/// </summary>
public TokenCachePersistenceOptions TokenCachePersistenceOptions { get; set; }
/// <summary>
/// Will include x5c header in client claims when acquiring a token to enable subject name / issuer based authentication for the <see cref="ClientCertificateCredential"/>.
/// </summary>
public bool SendCertificateChain { get; set; }
}
}
| 42.5 | 179 | 0.691979 | [
"MIT"
] | AME-Redmond/azure-sdk-for-net | sdk/identity/Azure.Identity/src/ClientCertificateCredentialOptions.cs | 937 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using NewLife;
using NewLife.Collections;
namespace XCode
{
/// <summary>表达式基类</summary>
public class Expression
{
#region 属性
/// <summary>文本表达式</summary>
public String Text { get; private set; }
/// <summary>是否为空</summary>
public virtual Boolean IsEmpty => Text.IsNullOrEmpty();
/// <summary>空表达式,一般用于表达式连写</summary>
public static Expression Empty = new Expression();
#endregion
#region 构造
/// <summary>实例化简单表达式</summary>
public Expression() { }
/// <summary>用一段文本实例化简单表达式</summary>
/// <param name="value"></param>
public Expression(String value) => Text = value;
#endregion
#region 方法
/// <summary>用于匹配Or关键字的正则表达式</summary>
internal protected static Regex _regOr = new Regex(@"\bOr\b", RegexOptions.IgnoreCase | RegexOptions.Compiled);
/// <summary>获取表达式的文本表示</summary>
/// <param name="ps">参数字典</param>
/// <returns></returns>
public String GetString(IDictionary<String, Object> ps)
{
var sb = Pool.StringBuilder.Get();
GetString(sb, ps);
return sb.Put(true);
}
/// <summary>获取字符串</summary>
/// <param name="builder">字符串构建器</param>
/// <param name="ps">参数字典</param>
public virtual void GetString(StringBuilder builder, IDictionary<String, Object> ps)
{
var txt = Text;
if (txt.IsNullOrEmpty()) return;
if (_regOr.IsMatch(txt))
builder.AppendFormat("({0})", txt);
else
builder.Append(txt);
}
/// <summary>输出该表达式的字符串形式</summary>
/// <returns></returns>
public override String ToString() => GetString(null);
/// <summary>类型转换</summary>
/// <param name="obj"></param>
/// <returns></returns>
public static implicit operator String(Expression obj) => obj?.ToString();
#endregion
#region 重载运算符
/// <summary>重载运算符实现And操作</summary>
/// <param name="exp"></param>
/// <param name="value">数值</param>
/// <returns></returns>
public static WhereExpression operator &(Expression exp, Expression value) => And(exp, value);
/// <summary>重载运算符实现And操作</summary>
/// <param name="exp"></param>
/// <param name="value">数值</param>
/// <returns></returns>
public static WhereExpression operator &(Expression exp, String value) => And(exp, new Expression(value));
static WhereExpression And(Expression exp, Expression value)
{
// 如果exp为空,主要考虑右边
if (exp == null) return CreateWhere(value);
// 左边构造条件表达式,自己是也好,新建立也好
if (value == null) return CreateWhere(exp);
return new WhereExpression(exp, Operator.And, value);
}
/// <summary>重载运算符实现Or操作</summary>
/// <param name="exp"></param>
/// <param name="value">数值</param>
/// <returns></returns>
public static WhereExpression operator |(Expression exp, Expression value) => Or(exp, value);
/// <summary>重载运算符实现Or操作</summary>
/// <param name="exp"></param>
/// <param name="value">数值</param>
/// <returns></returns>
public static WhereExpression operator |(Expression exp, String value) => Or(exp, new Expression(value));
static WhereExpression Or(Expression exp, Expression value)
{
//// 如果exp为空,主要考虑右边
//if (exp == null) return value;
//// 左边构造条件表达式,自己是也好,新建立也好
////var where = CreateWhere(exp);
//if (value == null) return exp;
// 如果右边为空,创建的表达式将会失败,直接返回左边
//return where.Or(value);
//return new WhereExpression(exp, OperatorExpression.Or, value);
return new WhereExpression(exp, Operator.Or, value);
}
/// <summary>重载运算符实现+操作</summary>
/// <param name="exp"></param>
/// <param name="value">数值</param>
/// <returns></returns>
public static WhereExpression operator +(Expression exp, Expression value)
{
//if (exp == null) return value;
//if (value == null) return exp;
return new WhereExpression(exp, Operator.Space, value);
}
internal static WhereExpression CreateWhere(Expression value)
{
if (value == null) return null;
if (value is WhereExpression where) return where;
return new WhereExpression(value, Operator.Space, null);
}
#endregion
}
} | 34.447552 | 120 | 0.550954 | [
"MIT"
] | WuJiBase/X | XCode/Model/Expression.cs | 5,450 | C# |
/***********************************************************************************************\
* (C) KAL ATM Software GmbH, 2021
* KAL ATM Software GmbH licenses this file to you under the MIT license.
* See the LICENSE file in the project root for more information.
\***********************************************************************************************/
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Text;
using System.Linq;
using XFS4IoT;
using XFS4IoTFramework.CardReader;
using XFS4IoTFramework.Common;
using XFS4IoT.Common.Commands;
using XFS4IoT.Common.Completions;
using XFS4IoT.CardReader.Events;
using XFS4IoT.CardReader.Commands;
using XFS4IoT.CardReader.Completions;
using XFS4IoT.Completions;
using XFS4IoTServer;
namespace KAL.XFS4IoTSP.CardReader.Sample
{
/// <summary>
/// Sample CardReader device class to implement
/// </summary>
public class CardReaderSample : ICardReaderDevice, ICommonDevice
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="Logger"></param>
public CardReaderSample(ILogger Logger)
{
Logger.IsNotNull($"Invalid parameter received in the {nameof(CardReaderSample)} constructor. {nameof(Logger)}");
this.Logger = Logger;
MediaStatus = MediaStatusEnum.NotPresent;
}
//
// CARDREADER interface
//
/// <summary>
/// For motor driven card readers, the card unit checks whether a card has been inserted.
/// All specified tracks are read immediately if the device can read with the low level accept command and store read data in the device specific class and set data on the ReadCardData method call.
/// If reading the chip is requested, the chip will be contacted and reset and the ATR (AnswerTo Reset) data will be read.
/// When this command completes the chip will be in contacted position. This command can also be used for an explicit cold reset of a previously contacted chip.
/// This command should only be used for user cards and should not be used for permanently connected chips.
/// If no card has been inserted, and for all other categories of card readers, the card unit waits for the period of time specified in the call for a card to be either inserted or pulled through.
/// The InsertCardEvent will be generated when there is no card in the cardreader and the device is ready to accept a card.
/// </summary>
public async Task<AcceptCardResult> AcceptCardAsync(IAcceptCardEvents events,
AcceptCardRequest acceptCardInfo,
CancellationToken cancellation)
{
if (acceptCardInfo.DataToRead != ReadCardRequest.CardDataTypesEnum.NoDataRead ||
MediaStatus != MediaStatusEnum.Present)
{
await events.InsertCardEvent();
await Task.Delay(2000, cancellation);
await events.MediaInsertedEvent();
}
MediaStatus = MediaStatusEnum.Present;
return new AcceptCardResult(MessagePayload.CompletionCodeEnum.Success);
}
/// <summary>
/// Read alltracks specified.
/// All specified tracks are read immediately or
/// A security check via a security module(i.e. MM, CIM86) can be requested. If the security check fails however this should not stop valid data beingreturned.
/// The response securityFail will be returned if the command specifies only security data to be read andthe security check could not be executed, in all other cases ok will be returned with the data field of theoutput parameter set to the relevant value including *hardwareError*.
/// For non-motorized Card Readers which read track data on card exit, the invalidData error code is returned whena call to is made to read both track data and chip data.
/// If the card unit is a latched dip unit then the device will latch the card when the chip card will be read,
/// The card will remain latched until a call to EjectCard is made.
/// For contactless chip card readers a collision of two or more card signals may happen.
/// In this case, if the deviceis not able to pick the strongest signal, errorCardCollision will be returned.
/// </summary>
public async Task<ReadCardResult> ReadCardAsync(IReadRawDataEvents events,
ReadCardRequest dataToRead,
CancellationToken cancellation)
{
await Task.Delay(1000, cancellation);
MessagePayload.CompletionCodeEnum completionCode = MessagePayload.CompletionCodeEnum.InvalidData;
Dictionary<ReadCardRequest.CardDataTypesEnum, ReadCardResult.CardData> readData = new();
List<ReadCardResult.CardData> chipATR = new();
if ((dataToRead.DataToRead & ReadCardRequest.CardDataTypesEnum.Track1) == ReadCardRequest.CardDataTypesEnum.Track1||
(dataToRead.DataToRead & ReadCardRequest.CardDataTypesEnum.Track2) == ReadCardRequest.CardDataTypesEnum.Track2||
(dataToRead.DataToRead & ReadCardRequest.CardDataTypesEnum.Track3) == ReadCardRequest.CardDataTypesEnum.Track3 ||
(dataToRead.DataToRead & ReadCardRequest.CardDataTypesEnum.Chip) == ReadCardRequest.CardDataTypesEnum.Chip)
{
if ((dataToRead.DataToRead & ReadCardRequest.CardDataTypesEnum.Track1) == ReadCardRequest.CardDataTypesEnum.Track1)
{
readData.Add(ReadCardRequest.CardDataTypesEnum.Track1,
new ReadCardResult.CardData(ReadCardResult.CardData.DataStatusEnum.Ok,
Encoding.UTF8.GetBytes("B1234567890123456^SMITH/JOHN.MR^020945852301200589800568000000").ToList()));
}
if ((dataToRead.DataToRead & ReadCardRequest.CardDataTypesEnum.Track2) == ReadCardRequest.CardDataTypesEnum.Track2)
{
readData.Add(ReadCardRequest.CardDataTypesEnum.Track2,
new ReadCardResult.CardData(ReadCardResult.CardData.DataStatusEnum.Ok,
Encoding.UTF8.GetBytes("1234567890123456=0209458523012005898").ToList()));
}
if ((dataToRead.DataToRead & ReadCardRequest.CardDataTypesEnum.Track3) == ReadCardRequest.CardDataTypesEnum.Track3)
{
readData.Add(ReadCardRequest.CardDataTypesEnum.Track3,
new ReadCardResult.CardData(ReadCardResult.CardData.DataStatusEnum.Ok,
Encoding.UTF8.GetBytes("011234567890123456==000667788903609640040000006200013010000020000098120209105123==00568000999999").ToList()));
}
if ((dataToRead.DataToRead & ReadCardRequest.CardDataTypesEnum.Chip) == ReadCardRequest.CardDataTypesEnum.Chip)
{
chipATR.Add(new ReadCardResult.CardData(ReadCardResult.CardData.DataStatusEnum.Ok,
new List<byte>() { 0x3b, 0x2a, 0x00, 0x80, 0x65, 0xa2, 0x1, 0x2, 0x1, 0x31, 0x72, 0xd6, 0x43 }));
}
completionCode = MessagePayload.CompletionCodeEnum.Success;
}
return new ReadCardResult(completionCode,
readData,
chipATR);
}
/// <summary>
/// The device is ready to accept a card.
/// The application must pass the magnetic stripe data in ASCII without any sentinels.
/// If the data passed in is too long. The invalidError error code will be returned.
/// This procedure is followed by data verification.
/// If power fails during a write the outcome of the operation will be vendor specific, there is no guarantee that thewrite will have succeeded.
/// </summary>
public async Task<WriteCardResult> WriteCardAsync(IWriteRawDataEvents events,
WriteCardRequest dataToWrite,
CancellationToken cancellation)
{
await Task.Delay(1000, cancellation);
return new WriteCardResult(MessagePayload.CompletionCodeEnum.Success);
}
/// <summary>
/// This command is only applicable to motor driven card readers and latched dip card readers.
/// For motorized card readers the default operation is that the card is driven to the exit slot from where the usercan remove it.
/// The card remains in position for withdrawal until either it is taken or another command is issuedthat moves the card.
/// For latched dip readers, this command causes the card to be unlatched (if not already unlatched), enablingremoval.
/// After successful completion of this command, a CardReader.MediaRemovedEvent is generated to inform the application when the card is taken.
/// </summary>
public async Task<EjectCardResult> EjectCardAsync(EjectCardRequest ejectCardInfo,
CancellationToken cancellation)
{
await Task.Delay(1000, cancellation);
MediaStatus = MediaStatusEnum.Entering;
new Thread(CardTakenThread).IsNotNull().Start();
return new EjectCardResult(MessagePayload.CompletionCodeEnum.Success);
}
/// <summary>
/// Thread for simulate card taken event to be fired
/// </summary>
private void CardTakenThread()
{
Thread.Sleep(5000);
cardTakenSignal.Release();
}
/// <summary>
/// This command is used to communicate with the chip.
/// Transparent data is sent from the application to the chip andthe response of the chip is returned transparently to the application.
/// The identification information e.g. ATR of the chip must be obtained before issuing this command.
/// The identification information for a user card or the Memory Card Identification (when available) must initially be obtained using CardReader.ReadRawData.
/// The identification information for subsequentresets of a user card can be obtained using either CardReader.ReadRawDat or CardReader.ChipPower.
/// The ATR for permanent connected chips is always obtained through CardReader.ChipPower.
/// For contactless chip card readers, applications need to specify which chip to contact with, as part of chipData, if more than one chip has been detected and multiple identification data has been returned by the CardReader.ReadRawData command.
/// For contactless chip card readers a collision of two or more card signals may happen.
/// In this case, if the deviceis not able to pick the strongest signal, the cardCollision error code will be returned.
/// </summary>
public async Task<ChipIOResult> ChipIOAsync(ChipIORequest dataToSend,
CancellationToken cancellation)
{
await Task.Delay(1000, cancellation);
List<byte> chipData = new() { 0x90, 0x00 };
return new ChipIOResult(MessagePayload.CompletionCodeEnum.Success, chipData);
}
/// <summary>
/// This command is used by the application to perform a hardware reset which will attempt to return the card readerdevice to a known good state.
/// This command does not over-ride a lock obtained by another application or service handle.
/// If the device is a user ID card unit, the device will attempt to either retain, eject or will perform no action onany user cards found in the device as specified in the input parameter.
/// It may not always be possible to retain oreject the items as specified because of hardware problems.
/// If a user card is found inside the device the CardReader.MediaInsertedEvent will inform the application where card wasactually moved to.
/// If no action is specified the user card will not be moved even if this means that the devicecannot be recovered.
/// If the device is a permanent chip card unit, this command will power-off the chip.For devices with parking station capability there will be one MediaInsertedEvent for each card found.
/// </summary>
public async Task<ResetDeviceResult> ResetDeviceAsync(IResetEvents events,
ResetDeviceRequest cardAction,
CancellationToken cancellation)
{
await Task.Delay(1000, cancellation);
MediaStatus = MediaStatusEnum.NotPresent;
return new ResetDeviceResult(MessagePayload.CompletionCodeEnum.Success);
}
/// <summary>
/// This command handles the power actions that can be done on the chip.For user chips, this command is only used after the chip has been contacted for the first time using the[CardReader.ReadRawData](#cardreader.readrawdata) command. For contactless user chips, this command may be used todeactivate the contactless card communication.For permanently connected chip cards, this command is the only way to control the chip power.
/// </summary>
public async Task<ChipPowerResult> ChipPowerAsync(IChipPowerEvents events,
ChipPowerRequest action,
CancellationToken cancellation)
{
await Task.Delay(1000, cancellation);
return new ChipPowerResult(MessagePayload.CompletionCodeEnum.Success);
}
/// <summary>
/// This command is used to move a card that is present in the reader to a parking station.
/// A parking station isdefined as an area in the ID card unit, which can be used to temporarily store the card while the device performs operations on another card.
/// This command is also used to move a card from the parking station to the read/write,chip I/O or transport position.
/// When a card is moved from the parking station to the read/write, chip I/O ortransport position parkOut, the read/write, chip I/O or transport position must not be occupied with anothercard, otherwise the error cardPresent will be returned.
/// After moving a card to a parking station, another card can be inserted and read by calling, e.g.,CardReader.ReadRawData.
/// Cards in parking stations will not be affected by any CardReader commands until they are removed from the parkingstation using this command, except for the CardReader.Reset command, which will move thecards in the parking stations as specified in its input as part of the reset action if possible.
/// </summary>
public async Task<ParkCardResult> ParkCardAsync(ParkCardRequest parkCardInfo,
CancellationToken cancellation)
{
await Task.Delay(1000, cancellation);
return new ParkCardResult(MessagePayload.CompletionCodeEnum.Success);
}
/// <summary>
/// This command is used to configure an intelligent contactless card reader before performing a contactlesstransaction.
/// This command sets terminal related data elements, the list of terminal acceptable applications with associated application specific data and any encryption key data required for offline data authentication.
/// This command should be used prior to CardReader.EMVClessPerformTransaction command.
/// It may be calledonce on application start up or when any of the configuration parameters require to be changed.
/// The configurationset by this command is persistent.This command should be called with a complete list of acceptable payment system applications as any previous configurations will be replaced.
/// </summary>
public async Task<EMVContactlessConfigureResult> EMVContactlessConfigureAsync(EMVContactlessConfigureRequest terminalConfig, CancellationToken cancellation)
{
await Task.Delay(1000, cancellation);
return new EMVContactlessConfigureResult(MessagePayload.CompletionCodeEnum.Success) ;
}
/// <summary>
/// This command is used to enable an intelligent contactless card reader.
/// The transaction will start as soon as thecard tap is detected.
/// Based on the configuration of the contactless chip card and the reader device, this command could return dataformatted either as magnetic stripe information or as a set of BER-TLV encoded EMV tags.
/// This command supports magnetic stripe emulation cards and EMV-like contactless cards but cannot be used on storagecontactless cards.
/// The latter must be managed using the CardReader.ReadRawData and CardReader.ChipIO commands.
/// For specific payment system's card profiles an intelligent card reader could return a set of EMV tags along withmagnetic stripe formatted data.
/// In this case, two contactless card data structures will be returned, onecontaining the magnetic stripe like data and one containing BER-TLV encoded tags.
/// If no card has been tapped, the contactless chip card reader waits for the period of time specified in the commandcall for a card to be tapped.
/// For intelligent contactless card readers, any in-built audio/visual feedback such as Beep/LEDs, need to becontrolled directly by the reader.
/// These indications should be implemented based on the EMVCo and payment system'sspecifications.
/// </summary>
public async Task<EMVContactlessPerformTransactionResult> EMVContactlessPerformTransactionAsync(IEMVClessPerformTransactionEvents events,
EMVContactlessPerformTransactionRequest transactionData,
CancellationToken cancellation)
{
await events.EMVClessReadStatusEvent(new EMVClessReadStatusEvent.PayloadData(100, EMVClessReadStatusEvent.PayloadData.StatusEnum.ReadyToRead, 0, EMVClessReadStatusEvent.PayloadData.ValueQualifierEnum.Amount));
await Task.Delay(1000, cancellation);
EMVContactlessTransactionDataOutput txnOutput = new(EMVContactlessTransactionDataOutput.TransactionOutcomeEnum.Approve,
EMVContactlessTransactionDataOutput.CardholderActionEnum.None,
new List<byte>() { 0x9c, 0x1, 0x0, 0x9f, 0x26, 0x08, 0x47, 0x9c, 0x4f, 0x7e, 0xc8, 0x52, 0xd1, 0x6, 0x9f, 0x34, 0x03, 0x1e, 0x00, 0x00 },
new EMVContactlessTransactionDataOutput.EMVContactlessOutcome(EMVContactlessTransactionDataOutput.EMVContactlessOutcome.CvmEnum.OnlinePIN,
EMVContactlessTransactionDataOutput.EMVContactlessOutcome.AlternateInterfaceEnum.Contact,
false,
new EMVContactlessTransactionDataOutput.EMVContactlessOutcome.EMVContactlessUI(3,
EMVContactlessTransactionDataOutput.EMVContactlessOutcome.EMVContactlessUI.StatusEnum.CardReadOk,
0,
EMVContactlessTransactionDataOutput.EMVContactlessOutcome.EMVContactlessUI.ValueQualifierEnum.NotApplicable,
"0",
"EUR",
"EN"),
null,
0,
0,
new List<byte>() { }));
return new EMVContactlessPerformTransactionResult(MessagePayload.CompletionCodeEnum.Success,
new()
{
{
EMVContactlessPerformTransactionResult.DataSourceTypeEnum.Chip,
txnOutput
}
});
}
/// <summary>
/// This command performs the post authorization processing on payment systems contactless cards.
/// Before an online authorized transaction is considered complete, further chip processing may be requested by theissuer.
/// This is only required when the authorization response includes issuer update data either issuer scriptsor issuer authentication data.
/// The command enables the contactless card reader and waits for the customer to re-tap their card.
/// The contactless chip card reader waits for the period of time specified in the command all for a card to be tapped.
/// </summary>
public async Task<EMVContactlessIssuerUpdateResult> EMVContactlessIssuerUpdateAsync(IEMVClessIssuerUpdateEvents events,
EMVContactlessIssuerUpdateRequest transactionData,
CancellationToken cancellation)
{
await Task.Delay(1000, cancellation);
EMVContactlessTransactionDataOutput txnOutput = new (EMVContactlessTransactionDataOutput.TransactionOutcomeEnum.Approve,
EMVContactlessTransactionDataOutput.CardholderActionEnum.None,
new List<byte>() { 0x9c, 0x1, 0x0, 0x9f, 0x26, 0x08, 0x47, 0x9c, 0x4f, 0x7e, 0xc8, 0x52, 0xd1, 0x6, 0x9f, 0x34, 0x03, 0x1e, 0x00, 0x00},
new EMVContactlessTransactionDataOutput.EMVContactlessOutcome(EMVContactlessTransactionDataOutput.EMVContactlessOutcome.CvmEnum.OnlinePIN,
EMVContactlessTransactionDataOutput.EMVContactlessOutcome.AlternateInterfaceEnum.Contact,
false,
new EMVContactlessTransactionDataOutput.EMVContactlessOutcome.EMVContactlessUI(3,
EMVContactlessTransactionDataOutput.EMVContactlessOutcome.EMVContactlessUI.StatusEnum.CardReadOk,
0,
EMVContactlessTransactionDataOutput.EMVContactlessOutcome.EMVContactlessUI.ValueQualifierEnum.NotApplicable,
"0",
"EUR",
"EN"),
null,
0,
0,
new List<byte>() { }));
return new EMVContactlessIssuerUpdateResult(MessagePayload.CompletionCodeEnum.Success, txnOutput);
}
/// <summary>
/// The card is removed from its present position (card inserted into device, card entering, unknown position) and stored in the retain bin;
/// applicable to motor-driven card readers only.
/// The ID card unit sends a CardReader.RetainBinThresholdEvent if the storage capacity of the retainbin is reached.
/// If the storage capacity has already been reached, and the command cannot be executed, an error isreturned and the card remains in its present position.
/// </summary>
public async Task<CaptureCardResult> CaptureCardAsync(IRetainCardEvents events,
CancellationToken cancellation)
{
await Task.Delay(1000, cancellation);
await events.MediaRetainedEvent();
CapturedCount++;
CardReaderServiceProvider cardReaderServiceProvider = SetServiceProvider as CardReaderServiceProvider;
if (CapturedCount >= CpMaxCaptureCount)
{
// Send the threshold event only once when we reached the threshold
if (RetainBinStatus != StatusCompletion.PayloadData.CardReaderClass.RetainBinEnum.High)
{
await cardReaderServiceProvider.IsNotNull().RetainBinThresholdEvent(new RetainBinThresholdEvent.PayloadData(RetainBinThresholdEvent.PayloadData.StateEnum.Full));
}
RetainBinStatus = StatusCompletion.PayloadData.CardReaderClass.RetainBinEnum.Full;
}
else if (CapturedCount >= (int)(((3 * CpMaxCaptureCount) / 4) + 0.5))
{
// Send the threshold event only once when we reached the threshold
if (RetainBinStatus != StatusCompletion.PayloadData.CardReaderClass.RetainBinEnum.High)
{
// unsolic threadhold
await cardReaderServiceProvider.IsNotNull().RetainBinThresholdEvent(new RetainBinThresholdEvent.PayloadData(RetainBinThresholdEvent.PayloadData.StateEnum.High));
}
RetainBinStatus = StatusCompletion.PayloadData.CardReaderClass.RetainBinEnum.High;
}
else
{
RetainBinStatus = StatusCompletion.PayloadData.CardReaderClass.RetainBinEnum.Ok;
}
return new CaptureCardResult(MessagePayload.CompletionCodeEnum.Success,
CapturedCount++,
XFS4IoT.CardReader.Completions.RetainCardCompletion.PayloadData.PositionEnum.Present);
}
/// <summary>
/// This function resets the present value for number of cards retained to zero.
/// The function is possible formotor-driven card readers only.
/// The number of cards retained is controlled by the service.
/// </summary>
public Task<ResetCountResult> ResetBinCountAsync(CancellationToken cancellation)
{
// The device doesn't need to talk to the device and return captured count immediately works as a sync
CapturedCount = 0;
return Task.FromResult(new ResetCountResult(MessagePayload.CompletionCodeEnum.Success));
}
/// <summary>
/// This command is used for setting the DES key that is necessary for operating a CIM86 module.
/// The command must beexecuted before the first read command is issued to the card reader.
/// </summary>
public async Task<SetCIM86KeyResult> SetCIM86KeyAsync(SetCIM86KeyRequest keyInfo,
CancellationToken cancellation)
{
await Task.Delay(1000, cancellation);
return new SetCIM86KeyResult(MessagePayload.CompletionCodeEnum.Success);
}
/// <summary>
/// RunAync
/// Handle unsolic events
/// Here is an example of handling MediaRemovedEvent after card is ejected successfully.
/// </summary>
/// <returns></returns>
public async Task RunAsync()
{
for (; ; )
{
await cardTakenSignal?.WaitAsync();
MediaStatus = MediaStatusEnum.NotPresent;
CardReaderServiceProvider cardReaderServiceProvider = SetServiceProvider as CardReaderServiceProvider;
await cardReaderServiceProvider.IsNotNull().MediaRemovedEvent();
}
}
/// <summary>
/// This command is used to retrieve the complete list of registration authority Interface Module (IFM) identifiers.
/// The primary registration authority is EMVCo but other organizations are also supported for historical or localcountry requirements.
/// New registration authorities may be added in the future so applications should be able to handle the return of new(as yet undefined) IFM identifiers.
/// </summary>
public QueryIFMIdentifierResult QueryIFMIdentifier()
{
return new QueryIFMIdentifierResult(MessagePayload.CompletionCodeEnum.Success,
new List<IFMIdentifierInfo>()
{
new IFMIdentifierInfo(XFS4IoT.CardReader.Completions.QueryIFMIdentifierCompletion.PayloadData.IfmAuthorityEnum.Emv, new List<byte>() { 0x1, 0x2, 0x3, 0x4 } )
});
}
/// <summary>
/// This command is used to retrieve the supported payment system applications available within an intelligentcontactless card unit.
/// The payment system application can either be identified by an AID or by the AID incombination with a Kernel Identifier.
/// The Kernel Identifier has been introduced by the EMVCo specifications; seeReference [3].
/// </summary>
public QueryEMVApplicationResult EMVContactlessQueryApplications()
{
List<EMVApplication> AIDList = new()
{
new EMVApplication(Encoding.UTF8.GetBytes("A0000000031010").ToList(), null),
new EMVApplication(Encoding.UTF8.GetBytes("A0000000041010").ToList(), null)
};
return new QueryEMVApplicationResult(MessagePayload.CompletionCodeEnum.Success, AIDList);
}
/// COMMON interface
public StatusCompletion.PayloadData Status()
{
StatusCompletion.PayloadData.CommonClass common = new(
StatusCompletion.PayloadData.CommonClass.DeviceEnum.Online,
new List<string>(),
new StatusCompletion.PayloadData.CommonClass.GuideLightsClass(
StatusCompletion.PayloadData.CommonClass.GuideLightsClass.FlashRateEnum.Off,
StatusCompletion.PayloadData.CommonClass.GuideLightsClass.ColorEnum.Green,
StatusCompletion.PayloadData.CommonClass.GuideLightsClass.DirectionEnum.Off),
StatusCompletion.PayloadData.CommonClass.DevicePositionEnum.Inposition,
0,
StatusCompletion.PayloadData.CommonClass.AntiFraudModuleEnum.Ok);
StatusCompletion.PayloadData.CardReaderClass cardReader = new(
MediaStatus switch
{
MediaStatusEnum.Entering => StatusCompletion.PayloadData.CardReaderClass.MediaEnum.Entering,
MediaStatusEnum.Jammed => StatusCompletion.PayloadData.CardReaderClass.MediaEnum.Jammed,
MediaStatusEnum.Latched => StatusCompletion.PayloadData.CardReaderClass.MediaEnum.Latched,
MediaStatusEnum.NotPresent => StatusCompletion.PayloadData.CardReaderClass.MediaEnum.NotPresent,
MediaStatusEnum.NotSupported => StatusCompletion.PayloadData.CardReaderClass.MediaEnum.NotSupported,
MediaStatusEnum.Present => StatusCompletion.PayloadData.CardReaderClass.MediaEnum.Present,
MediaStatusEnum.Unknown => StatusCompletion.PayloadData.CardReaderClass.MediaEnum.Unknown,
_ => null
},
StatusCompletion.PayloadData.CardReaderClass.RetainBinEnum.Ok,
StatusCompletion.PayloadData.CardReaderClass.SecurityEnum.NotSupported,
CapturedCount,
StatusCompletion.PayloadData.CardReaderClass.ChipPowerEnum.PoweredOff,
StatusCompletion.PayloadData.CardReaderClass.ChipModuleEnum.Ok,
StatusCompletion.PayloadData.CardReaderClass.MagWriteModuleEnum.Ok,
StatusCompletion.PayloadData.CardReaderClass.FrontImageModuleEnum.Ok,
StatusCompletion.PayloadData.CardReaderClass.BackImageModuleEnum.Ok,
new List<string>());
return new StatusCompletion.PayloadData(MessagePayload.CompletionCodeEnum.Success,
null,
common,
cardReader);
}
public CapabilitiesCompletion.PayloadData Capabilities()
{
CapabilitiesCompletion.PayloadData.CommonClass.GuideLightsClass guideLights = new(
new CapabilitiesCompletion.PayloadData.CommonClass.GuideLightsClass.FlashRateClass(true, true, true, true),
new CapabilitiesCompletion.PayloadData.CommonClass.GuideLightsClass.ColorClass(true, true, true, true, true, true, true),
new CapabilitiesCompletion.PayloadData.CommonClass.GuideLightsClass.DirectionClass(false, false));
CapabilitiesCompletion.PayloadData.CommonClass common = new(
"1.0",
new CapabilitiesCompletion.PayloadData.CommonClass.DeviceInformationClass(
"Simulator",
"123456-78900001",
"1.0",
"KAL simualtor",
new CapabilitiesCompletion.PayloadData.CommonClass.DeviceInformationClass.FirmwareClass(
"XFS4 SP",
"1.0",
"1.0"),
new CapabilitiesCompletion.PayloadData.CommonClass.DeviceInformationClass.SoftwareClass(
"XFS4 SP",
"1.0")),
new CapabilitiesCompletion.PayloadData.CommonClass.VendorModeIformationClass(
true,
new List<string>()
{
"CardReader.ReadRawData",
"CardReader.EjectCard"
}),
new List<string>(),
guideLights,
false,
false,
new List<string>(),
false,
false,
false);
CapabilitiesCompletion.PayloadData.CardReaderClass cardReader = new(
DeviceType switch
{
DeviceTypeEnum.Motor => CapabilitiesCompletion.PayloadData.CardReaderClass.TypeEnum.Motor,
DeviceTypeEnum.Dip => CapabilitiesCompletion.PayloadData.CardReaderClass.TypeEnum.Dip,
DeviceTypeEnum.LatchedDip => CapabilitiesCompletion.PayloadData.CardReaderClass.TypeEnum.LatchedDip,
DeviceTypeEnum.Swipe => CapabilitiesCompletion.PayloadData.CardReaderClass.TypeEnum.Swipe,
DeviceTypeEnum.Contactless => CapabilitiesCompletion.PayloadData.CardReaderClass.TypeEnum.Contactless,
DeviceTypeEnum.IntelligentContactless => CapabilitiesCompletion.PayloadData.CardReaderClass.TypeEnum.IntelligentContactless,
DeviceTypeEnum.Permanent => CapabilitiesCompletion.PayloadData.CardReaderClass.TypeEnum.Permanent,
_ => null
},
new CapabilitiesCompletion.PayloadData.CardReaderClass.ReadTracksClass(true, true, true, false, false, false, false, false, false, false),
new CapabilitiesCompletion.PayloadData.CardReaderClass.WriteTracksClass(true, true, true, false, false, false),
new CapabilitiesCompletion.PayloadData.CardReaderClass.ChipProtocolsClass(true, true, false, false, false, false, false),
CpMaxCaptureCount,
CapabilitiesCompletion.PayloadData.CardReaderClass.SecurityTypeEnum.NotSupported,
CapabilitiesCompletion.PayloadData.CardReaderClass.PowerOnOptionEnum.NoAction,
CapabilitiesCompletion.PayloadData.CardReaderClass.PowerOffOptionEnum.NoAction,
false, false,
new CapabilitiesCompletion.PayloadData.CardReaderClass.WriteModeClass(false, true, false, true),
new CapabilitiesCompletion.PayloadData.CardReaderClass.ChipPowerClass(false, true, true, true),
new CapabilitiesCompletion.PayloadData.CardReaderClass.MemoryChipProtocolsClass(false, false),
new CapabilitiesCompletion.PayloadData.CardReaderClass.EjectPositionClass(true, false),
0);
List<CapabilitiesCompletion.PayloadData.InterfacesClass> interfaces = new()
{
new CapabilitiesCompletion.PayloadData.InterfacesClass(
CapabilitiesCompletion.PayloadData.InterfacesClass.NameEnum.Common,
new List<string>()
{
"Common.Status",
"Common.Capabilities"
},
new List<string>(),
1000,
new List<string>()),
new CapabilitiesCompletion.PayloadData.InterfacesClass(
CapabilitiesCompletion.PayloadData.InterfacesClass.NameEnum.CardReader,
new List<string>
{
"CardReader.ReadRawData",
"CardReader.EjectCard",
"CardReader.Reset",
"CardReader.WriteRawData",
"CardReader.ChipIO",
"CardReader.ChipPower",
"CardReader.EMVClessConfigure",
"CardReader.EMVClessIssuerUpdate",
"CardReader.EMVClessPerformTransaction",
"CardReader.EMVClessQueryApplications",
"CardReader.ParkCard",
"CardReader.QueryIFMIdentifier",
"CardReader.ResetCount",
"CardReader.RetainCard",
"CardReader.SetKey"
},
new List<string>
{
"CardReader.MediaDetectedEvent",
"CardReader.MediaInsertedEvent",
"CardReader.MediaRemovedEvent",
"CardReader.MediaRetainedEvent",
"CardReader.InvalidMediaEvent",
"CardReader.EMVClessReadStatusEvent"
},
1000,
new List<string>())
};
return new CapabilitiesCompletion.PayloadData(MessagePayload.CompletionCodeEnum.Success,
null,
interfaces,
common,
cardReader);
}
public Task<PowerSaveControlCompletion.PayloadData> PowerSaveControl(PowerSaveControlCommand.PayloadData payload) => throw new System.NotImplementedException();
public Task<SynchronizeCommandCompletion.PayloadData> SynchronizeCommand(SynchronizeCommandCommand.PayloadData payload) => throw new System.NotImplementedException();
public Task<SetTransactionStateCompletion.PayloadData> SetTransactionState(SetTransactionStateCommand.PayloadData payload) => throw new System.NotImplementedException();
public GetTransactionStateCompletion.PayloadData GetTransactionState() => throw new System.NotImplementedException();
public Task<GetCommandRandomNumberResult> GetCommandRandomNumber() => throw new System.NotImplementedException();
/// <summary>
/// Specify the type of cardreader
/// </summary>
public DeviceTypeEnum DeviceType { get; private set; } = DeviceTypeEnum.Motor;
/// <summary>
/// Specify the current status of media after card is accepted.
/// </summary>
public MediaStatusEnum MediaStatus { get; private set; } = MediaStatusEnum.Unknown;
public XFS4IoTServer.IServiceProvider SetServiceProvider { get; set; } = null;
/// Internal variables
///
private int CapturedCount = 0;
private int CpMaxCaptureCount = 100;
private StatusCompletion.PayloadData.CardReaderClass.RetainBinEnum RetainBinStatus = StatusCompletion.PayloadData.CardReaderClass.RetainBinEnum.Ok;
private ILogger Logger { get; }
private readonly SemaphoreSlim cardTakenSignal = new(0, 1);
}
} | 69.605304 | 437 | 0.572607 | [
"MIT"
] | KitPatterson/KAL_XFS4IoT_SP-Dev | Devices/SampleCardReader/CardReaderSample.cs | 44,619 | 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("Alcohol Market")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Alcohol Market")]
[assembly: AssemblyCopyright("Copyright © Microsoft 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("bbd670e0-f123-4dbd-a08a-7c0a6972d139")]
// 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.351351 | 84 | 0.74771 | [
"MIT"
] | StefanDimitrov97/SoftUni-Basic | Exams/7 may/Alcohol Market/Alcohol Market/Alcohol Market/Properties/AssemblyInfo.cs | 1,422 | C# |
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using System.IO;
using System;
using System.Collections;
public class ExternalPackageManager
{
public static ExportPackageOptions exportOptions = ExportPackageOptions.IncludeDependencies | ExportPackageOptions.Recurse;
protected static PackagesJson packagesJson;
private static string externalAssetDirectory = Path.Combine("Assets", "External");
private static string externalAssetDirectoryPath = Path.Combine(Application.dataPath, "External");
private static Queue<String> downloadQueue = null;
private static int totalDownloads = 0;
private static int downloadCount = 0;
private static Action<Boolean> DownloadsComplete;
private delegate void HandlePackageComplete(Boolean error);
[MenuItem("Assets/External Package Manager/Export All")]
static void ExportAll()
{
Debug.Log("EPM: ExportAll");
parsePackagesJson();
try
{
// Make sure build folder exists at project root (inferred from assets folder)
string buildFolderPath =
Path.Combine(Application.dataPath, Path.Combine("..", packagesJson.buildFolder));
if (!Directory.Exists(buildFolderPath))
{
Directory.CreateDirectory(buildFolderPath);
}
// Export a package per export directory defined in packages.json
foreach (string packageFolder in packagesJson.exports)
{
string packageFolderPath = Path.Combine(externalAssetDirectoryPath, packageFolder);
ArrayList exportedPackages = new ArrayList();
if (Directory.Exists(packageFolderPath))
{
string packageBuildName = packageFolder + "-v" + packagesJson.version + ".unitypackage";
string packageBuildPath = Path.GetFullPath(Path.Combine(buildFolderPath, packageBuildName));
Debug.Log("EPM: Exporting assets from " + externalAssetDirectoryPath + " to package " + packageBuildPath);
AssetDatabase.ExportPackage(externalAssetDirectory, packageBuildPath, exportOptions);
exportedPackages.Add(packageBuildPath);
}
else
{
EditorUtility.DisplayDialog("External Package Manager",
"Unable to find package folder (" + packageFolderPath + ") for export.",
"OK");
}
if (exportedPackages.Count > 0)
{
EditorUtility.DisplayDialog("External Package Manager",
"Exported the following packages: " +
string.Join("," + System.Environment.NewLine,
(string[])exportedPackages.ToArray(Type.GetType("System.String"))),
"OK");
}
}
}
catch (Exception ex)
{
Debug.LogException(ex);
}
}
[MenuItem("Assets/External Package Manager/Import All")]
static void ImportAll()
{
// Download and import all packages from package.json
Debug.Log("EPM: ImportAll");
parsePackagesJson();
downloadQueue = new Queue<string>();
// Init queue
packagesJson.dependencies.ForEach(downloadQueue.Enqueue);
totalDownloads = downloadQueue.Count;
downloadCount = 0;
double startTime = EditorApplication.timeSinceStartup;
DownloadsComplete = (error) =>
{
if (!error)
{
// Time it
double totalTime = EditorApplication.timeSinceStartup - startTime;
// Display complete dialog with elapsed time and downloaded bytes
EditorUtility.DisplayDialog("External Package Manager",
"Imported " + totalDownloads + " packages in " + Math.Floor(totalTime) + " seconds.",
"OK");
}
DownloadsComplete = null;
};
// Kick off
ImportPackage();
}
static void ImportPackage()
{
if (downloadQueue.Count > 0)
{
String url = downloadQueue.Dequeue();
string tempFile = FileUtil.GetUniqueTempPathInProject();
string dialogMessage = "Downloading " + Path.GetFileName(url) + " (" + (downloadCount + 1) + " of " + totalDownloads + ")";
DownloadPackage(url, dialogMessage, tempFile, (Boolean error) =>
{
if (!error)
{
// Import package
AssetDatabase.ImportPackage(tempFile, false);
FileUtil.DeleteFileOrDirectory(tempFile);
downloadCount++;
// Try to import the next package
ImportPackage();
}
else
{
downloadQueue.Clear();
DownloadsComplete(true);
}
});
}
else
{
DownloadsComplete(false);
}
}
private static void DownloadPackage(string dependencyUrl, string dialogMessage, string destFile, HandlePackageComplete callback)
{
Debug.Log("EPM: " + dialogMessage);
float lastProgress = 0.0f;
WWW www = new WWW(dependencyUrl);
EditorApplication.CallbackFunction checkDownload = null;
checkDownload = () =>
{
if (!www.isDone)
{
// Only update if this is the first update or we have made progress
if (lastProgress < 0.01f || (www.progress - lastProgress > 0.01f))
{
lastProgress = www.progress;
if (EditorUtility.DisplayCancelableProgressBar("External Package Manager", dialogMessage, www.progress))
{
Debug.Log("EPM: ImportAll cancelled by user.");
www.Dispose();
EditorUtility.ClearProgressBar();
EditorApplication.update -= checkDownload;
callback(true);
}
}
}
else
{
EditorUtility.ClearProgressBar();
if (!String.IsNullOrEmpty(www.error))
{
EditorUtility.DisplayDialog("External Package Manager",
"Unable to download " + dependencyUrl + ": " + System.Environment.NewLine + www.error,
"OK");
// Remove ourselves
EditorApplication.update -= checkDownload;
callback(true);
}
else
{
// Save package
File.WriteAllBytes(destFile, www.bytes);
// Remove ourselves
EditorApplication.update -= checkDownload;
callback(false);
}
}
};
// Check download each update cycle
EditorApplication.update += checkDownload;
}
private static void parsePackagesJson()
{
string packagesPath = Path.Combine(Application.dataPath, "packages.json");
Debug.Log("EPM: Loading packages file: " + packagesPath);
try
{
if (File.Exists(packagesPath))
{
string dataAsJson = File.ReadAllText(packagesPath);
packagesJson = JsonUtility.FromJson<PackagesJson>(dataAsJson);
}
else
{
EditorUtility.DisplayDialog("External Package Manager",
"Unable to find " + packagesPath,
"OK");
}
}
catch (Exception ex)
{
Debug.LogException(ex);
}
}
protected class PackagesJson
{
public string version;
public string buildFolder = Path.Combine("Builds", "Packages"); // relative to project root
public List<string> exports = new List<string>();
public List<string> dependencies = new List<string>();
}
} | 35.668085 | 135 | 0.538774 | [
"MIT"
] | TimeWalkOrg/TimeWalk | Assets/Editor/ExternalPackageManager.cs | 8,382 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the lakeformation-2017-03-31.normal.json service model.
*/
using System;
using Amazon.Runtime;
namespace Amazon.LakeFormation
{
/// <summary>
/// Constants used for properties of type ComparisonOperator.
/// </summary>
public class ComparisonOperator : ConstantClass
{
/// <summary>
/// Constant BEGINS_WITH for ComparisonOperator
/// </summary>
public static readonly ComparisonOperator BEGINS_WITH = new ComparisonOperator("BEGINS_WITH");
/// <summary>
/// Constant BETWEEN for ComparisonOperator
/// </summary>
public static readonly ComparisonOperator BETWEEN = new ComparisonOperator("BETWEEN");
/// <summary>
/// Constant CONTAINS for ComparisonOperator
/// </summary>
public static readonly ComparisonOperator CONTAINS = new ComparisonOperator("CONTAINS");
/// <summary>
/// Constant EQ for ComparisonOperator
/// </summary>
public static readonly ComparisonOperator EQ = new ComparisonOperator("EQ");
/// <summary>
/// Constant GE for ComparisonOperator
/// </summary>
public static readonly ComparisonOperator GE = new ComparisonOperator("GE");
/// <summary>
/// Constant GT for ComparisonOperator
/// </summary>
public static readonly ComparisonOperator GT = new ComparisonOperator("GT");
/// <summary>
/// Constant IN for ComparisonOperator
/// </summary>
public static readonly ComparisonOperator IN = new ComparisonOperator("IN");
/// <summary>
/// Constant LE for ComparisonOperator
/// </summary>
public static readonly ComparisonOperator LE = new ComparisonOperator("LE");
/// <summary>
/// Constant LT for ComparisonOperator
/// </summary>
public static readonly ComparisonOperator LT = new ComparisonOperator("LT");
/// <summary>
/// Constant NE for ComparisonOperator
/// </summary>
public static readonly ComparisonOperator NE = new ComparisonOperator("NE");
/// <summary>
/// Constant NOT_CONTAINS for ComparisonOperator
/// </summary>
public static readonly ComparisonOperator NOT_CONTAINS = new ComparisonOperator("NOT_CONTAINS");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public ComparisonOperator(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ComparisonOperator FindValue(string value)
{
return FindValue<ComparisonOperator>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ComparisonOperator(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type DataLakeResourceType.
/// </summary>
public class DataLakeResourceType : ConstantClass
{
/// <summary>
/// Constant CATALOG for DataLakeResourceType
/// </summary>
public static readonly DataLakeResourceType CATALOG = new DataLakeResourceType("CATALOG");
/// <summary>
/// Constant DATA_LOCATION for DataLakeResourceType
/// </summary>
public static readonly DataLakeResourceType DATA_LOCATION = new DataLakeResourceType("DATA_LOCATION");
/// <summary>
/// Constant DATABASE for DataLakeResourceType
/// </summary>
public static readonly DataLakeResourceType DATABASE = new DataLakeResourceType("DATABASE");
/// <summary>
/// Constant LF_TAG for DataLakeResourceType
/// </summary>
public static readonly DataLakeResourceType LF_TAG = new DataLakeResourceType("LF_TAG");
/// <summary>
/// Constant LF_TAG_POLICY for DataLakeResourceType
/// </summary>
public static readonly DataLakeResourceType LF_TAG_POLICY = new DataLakeResourceType("LF_TAG_POLICY");
/// <summary>
/// Constant LF_TAG_POLICY_DATABASE for DataLakeResourceType
/// </summary>
public static readonly DataLakeResourceType LF_TAG_POLICY_DATABASE = new DataLakeResourceType("LF_TAG_POLICY_DATABASE");
/// <summary>
/// Constant LF_TAG_POLICY_TABLE for DataLakeResourceType
/// </summary>
public static readonly DataLakeResourceType LF_TAG_POLICY_TABLE = new DataLakeResourceType("LF_TAG_POLICY_TABLE");
/// <summary>
/// Constant TABLE for DataLakeResourceType
/// </summary>
public static readonly DataLakeResourceType TABLE = new DataLakeResourceType("TABLE");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public DataLakeResourceType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static DataLakeResourceType FindValue(string value)
{
return FindValue<DataLakeResourceType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator DataLakeResourceType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type FieldNameString.
/// </summary>
public class FieldNameString : ConstantClass
{
/// <summary>
/// Constant LAST_MODIFIED for FieldNameString
/// </summary>
public static readonly FieldNameString LAST_MODIFIED = new FieldNameString("LAST_MODIFIED");
/// <summary>
/// Constant RESOURCE_ARN for FieldNameString
/// </summary>
public static readonly FieldNameString RESOURCE_ARN = new FieldNameString("RESOURCE_ARN");
/// <summary>
/// Constant ROLE_ARN for FieldNameString
/// </summary>
public static readonly FieldNameString ROLE_ARN = new FieldNameString("ROLE_ARN");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public FieldNameString(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static FieldNameString FindValue(string value)
{
return FindValue<FieldNameString>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator FieldNameString(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type OptimizerType.
/// </summary>
public class OptimizerType : ConstantClass
{
/// <summary>
/// Constant ALL for OptimizerType
/// </summary>
public static readonly OptimizerType ALL = new OptimizerType("ALL");
/// <summary>
/// Constant COMPACTION for OptimizerType
/// </summary>
public static readonly OptimizerType COMPACTION = new OptimizerType("COMPACTION");
/// <summary>
/// Constant GARBAGE_COLLECTION for OptimizerType
/// </summary>
public static readonly OptimizerType GARBAGE_COLLECTION = new OptimizerType("GARBAGE_COLLECTION");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public OptimizerType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static OptimizerType FindValue(string value)
{
return FindValue<OptimizerType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator OptimizerType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type Permission.
/// </summary>
public class Permission : ConstantClass
{
/// <summary>
/// Constant ALL for Permission
/// </summary>
public static readonly Permission ALL = new Permission("ALL");
/// <summary>
/// Constant ALTER for Permission
/// </summary>
public static readonly Permission ALTER = new Permission("ALTER");
/// <summary>
/// Constant ASSOCIATE for Permission
/// </summary>
public static readonly Permission ASSOCIATE = new Permission("ASSOCIATE");
/// <summary>
/// Constant CREATE_DATABASE for Permission
/// </summary>
public static readonly Permission CREATE_DATABASE = new Permission("CREATE_DATABASE");
/// <summary>
/// Constant CREATE_TABLE for Permission
/// </summary>
public static readonly Permission CREATE_TABLE = new Permission("CREATE_TABLE");
/// <summary>
/// Constant CREATE_TAG for Permission
/// </summary>
public static readonly Permission CREATE_TAG = new Permission("CREATE_TAG");
/// <summary>
/// Constant DATA_LOCATION_ACCESS for Permission
/// </summary>
public static readonly Permission DATA_LOCATION_ACCESS = new Permission("DATA_LOCATION_ACCESS");
/// <summary>
/// Constant DELETE for Permission
/// </summary>
public static readonly Permission DELETE = new Permission("DELETE");
/// <summary>
/// Constant DESCRIBE for Permission
/// </summary>
public static readonly Permission DESCRIBE = new Permission("DESCRIBE");
/// <summary>
/// Constant DROP for Permission
/// </summary>
public static readonly Permission DROP = new Permission("DROP");
/// <summary>
/// Constant INSERT for Permission
/// </summary>
public static readonly Permission INSERT = new Permission("INSERT");
/// <summary>
/// Constant SELECT for Permission
/// </summary>
public static readonly Permission SELECT = new Permission("SELECT");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public Permission(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static Permission FindValue(string value)
{
return FindValue<Permission>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator Permission(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type PermissionType.
/// </summary>
public class PermissionType : ConstantClass
{
/// <summary>
/// Constant CELL_FILTER_PERMISSION for PermissionType
/// </summary>
public static readonly PermissionType CELL_FILTER_PERMISSION = new PermissionType("CELL_FILTER_PERMISSION");
/// <summary>
/// Constant COLUMN_PERMISSION for PermissionType
/// </summary>
public static readonly PermissionType COLUMN_PERMISSION = new PermissionType("COLUMN_PERMISSION");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public PermissionType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static PermissionType FindValue(string value)
{
return FindValue<PermissionType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator PermissionType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type QueryStateString.
/// </summary>
public class QueryStateString : ConstantClass
{
/// <summary>
/// Constant ERROR for QueryStateString
/// </summary>
public static readonly QueryStateString ERROR = new QueryStateString("ERROR");
/// <summary>
/// Constant EXPIRED for QueryStateString
/// </summary>
public static readonly QueryStateString EXPIRED = new QueryStateString("EXPIRED");
/// <summary>
/// Constant FINISHED for QueryStateString
/// </summary>
public static readonly QueryStateString FINISHED = new QueryStateString("FINISHED");
/// <summary>
/// Constant PENDING for QueryStateString
/// </summary>
public static readonly QueryStateString PENDING = new QueryStateString("PENDING");
/// <summary>
/// Constant WORKUNITS_AVAILABLE for QueryStateString
/// </summary>
public static readonly QueryStateString WORKUNITS_AVAILABLE = new QueryStateString("WORKUNITS_AVAILABLE");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public QueryStateString(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static QueryStateString FindValue(string value)
{
return FindValue<QueryStateString>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator QueryStateString(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ResourceShareType.
/// </summary>
public class ResourceShareType : ConstantClass
{
/// <summary>
/// Constant ALL for ResourceShareType
/// </summary>
public static readonly ResourceShareType ALL = new ResourceShareType("ALL");
/// <summary>
/// Constant FOREIGN for ResourceShareType
/// </summary>
public static readonly ResourceShareType FOREIGN = new ResourceShareType("FOREIGN");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public ResourceShareType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ResourceShareType FindValue(string value)
{
return FindValue<ResourceShareType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ResourceShareType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ResourceType.
/// </summary>
public class ResourceType : ConstantClass
{
/// <summary>
/// Constant DATABASE for ResourceType
/// </summary>
public static readonly ResourceType DATABASE = new ResourceType("DATABASE");
/// <summary>
/// Constant TABLE for ResourceType
/// </summary>
public static readonly ResourceType TABLE = new ResourceType("TABLE");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public ResourceType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ResourceType FindValue(string value)
{
return FindValue<ResourceType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ResourceType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type TransactionStatus.
/// </summary>
public class TransactionStatus : ConstantClass
{
/// <summary>
/// Constant ABORTED for TransactionStatus
/// </summary>
public static readonly TransactionStatus ABORTED = new TransactionStatus("ABORTED");
/// <summary>
/// Constant ACTIVE for TransactionStatus
/// </summary>
public static readonly TransactionStatus ACTIVE = new TransactionStatus("ACTIVE");
/// <summary>
/// Constant COMMIT_IN_PROGRESS for TransactionStatus
/// </summary>
public static readonly TransactionStatus COMMIT_IN_PROGRESS = new TransactionStatus("COMMIT_IN_PROGRESS");
/// <summary>
/// Constant COMMITTED for TransactionStatus
/// </summary>
public static readonly TransactionStatus COMMITTED = new TransactionStatus("COMMITTED");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public TransactionStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static TransactionStatus FindValue(string value)
{
return FindValue<TransactionStatus>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator TransactionStatus(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type TransactionStatusFilter.
/// </summary>
public class TransactionStatusFilter : ConstantClass
{
/// <summary>
/// Constant ABORTED for TransactionStatusFilter
/// </summary>
public static readonly TransactionStatusFilter ABORTED = new TransactionStatusFilter("ABORTED");
/// <summary>
/// Constant ACTIVE for TransactionStatusFilter
/// </summary>
public static readonly TransactionStatusFilter ACTIVE = new TransactionStatusFilter("ACTIVE");
/// <summary>
/// Constant ALL for TransactionStatusFilter
/// </summary>
public static readonly TransactionStatusFilter ALL = new TransactionStatusFilter("ALL");
/// <summary>
/// Constant COMMITTED for TransactionStatusFilter
/// </summary>
public static readonly TransactionStatusFilter COMMITTED = new TransactionStatusFilter("COMMITTED");
/// <summary>
/// Constant COMPLETED for TransactionStatusFilter
/// </summary>
public static readonly TransactionStatusFilter COMPLETED = new TransactionStatusFilter("COMPLETED");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public TransactionStatusFilter(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static TransactionStatusFilter FindValue(string value)
{
return FindValue<TransactionStatusFilter>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator TransactionStatusFilter(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type TransactionType.
/// </summary>
public class TransactionType : ConstantClass
{
/// <summary>
/// Constant READ_AND_WRITE for TransactionType
/// </summary>
public static readonly TransactionType READ_AND_WRITE = new TransactionType("READ_AND_WRITE");
/// <summary>
/// Constant READ_ONLY for TransactionType
/// </summary>
public static readonly TransactionType READ_ONLY = new TransactionType("READ_ONLY");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public TransactionType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static TransactionType FindValue(string value)
{
return FindValue<TransactionType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator TransactionType(string value)
{
return FindValue(value);
}
}
} | 38.463446 | 128 | 0.613346 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/LakeFormation/Generated/ServiceEnumerations.cs | 29,463 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.Debugger.Interop;
using NetWebScript.Debug.Engine.Script;
namespace NetWebScript.Debug.Engine.Events
{
class ProgramDestroyEvent : SynchronousEvent, IDebugProgramDestroyEvent2
{
public static readonly Guid IID = new Guid("{E147E9E3-6440-4073-A7B7-A65592C714B5}");
private readonly uint m_exitCode;
private readonly ScriptProgram program;
public ProgramDestroyEvent(ScriptProgram program, uint exitCode)
{
this.program = program;
m_exitCode = exitCode;
}
internal ScriptProgram Program
{
get { return program; }
}
#region IDebugProgramDestroyEvent2 Members
int IDebugProgramDestroyEvent2.GetExitCode(out uint exitCode)
{
exitCode = m_exitCode;
return Constants.S_OK;
}
#endregion
}
}
| 26.358974 | 94 | 0.638132 | [
"MIT"
] | jetelain/NetWebScript | NetWebScript/NetWebScript.Debug.Engine/Events/ProgramDestroyEvent.cs | 1,030 | C# |
//------------------------------------------------------------------------------
// <auto-generated />
//
// This file was automatically generated by SWIG (http://www.swig.org).
// Version 3.0.12
//
// Do not make changes to this file unless you know what you are doing--modify
// the SWIG interface file instead.
//------------------------------------------------------------------------------
namespace pxr {
public class SWIGTYPE_p_TfDeclarePtrsT_SdfLayerStateDelegateBase_t__RefPtr {
private global::System.Runtime.InteropServices.HandleRef swigCPtr;
internal SWIGTYPE_p_TfDeclarePtrsT_SdfLayerStateDelegateBase_t__RefPtr(global::System.IntPtr cPtr, bool futureUse) {
swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr);
}
protected SWIGTYPE_p_TfDeclarePtrsT_SdfLayerStateDelegateBase_t__RefPtr() {
swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero);
}
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(SWIGTYPE_p_TfDeclarePtrsT_SdfLayerStateDelegateBase_t__RefPtr obj) {
return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
}
}
}
| 41.133333 | 143 | 0.685575 | [
"Apache-2.0"
] | MrDice/usd-unity-sdk | src/USD.NET/generated/SWIG/SWIGTYPE_p_TfDeclarePtrsT_SdfLayerStateDelegateBase_t__RefPtr.cs | 1,234 | C# |
using MyCMS.Data.Intefaces;
namespace MyCMS.Data.DataProviders
{
public class DataProviderManager : IDataProviderManager
{
public IDataProvider GetDataProvider(DataProviderType dataProviderType)
{
var dataProvider = dataProviderType switch
{
DataProviderType.SQLite => new SQLiteDataProvider(),
_ => throw new Exception(string.Format("Provider {0} not supported yet!", dataProviderType))
};
return dataProvider;
}
}
}
| 28.263158 | 108 | 0.629423 | [
"MIT"
] | manuelebagnolini/MyCMS | MyCMS.Data/DataProviderManager.cs | 539 | C# |
using UnityEngine;
using System;
namespace MoreMountains.Tools
{
/// <summary>
/// Int property setter
/// </summary>
public class MMPropertyLinkInt : MMPropertyLink
{
public Func<int> GetIntDelegate;
public Action<int> SetIntDelegate;
protected int _initialValue;
protected int _newValue;
/// <summary>
/// On init we grab our initial value
/// </summary>
/// <param name="property"></param>
public override void Initialization(MMProperty property)
{
base.Initialization(property);
_initialValue = (int)GetPropertyValue(property);
}
/// <summary>
/// Creates cached getter and setters for properties
/// </summary>
/// <param name="property"></param>
public override void CreateGettersAndSetters(MMProperty property)
{
base.CreateGettersAndSetters(property);
if (property.MemberType == MMProperty.MemberTypes.Property)
{
object firstArgument = (property.TargetScriptableObject == null) ? (object)property.TargetComponent : (object)property.TargetScriptableObject;
if (property.MemberPropertyInfo.GetGetMethod() != null)
{
GetIntDelegate = (Func<int>)Delegate.CreateDelegate(typeof(Func<int>),
firstArgument,
property.MemberPropertyInfo.GetGetMethod());
}
if (property.MemberPropertyInfo.GetSetMethod() != null)
{
SetIntDelegate = (Action<int>)Delegate.CreateDelegate(typeof(Action<int>),
firstArgument,
property.MemberPropertyInfo.GetSetMethod());
}
_getterSetterInitialized = true;
}
}
/// <summary>
/// Gets the raw value of the property, a normalized float value, caching the operation if possible
/// </summary>
/// <param name="emitter"></param>
/// <param name="property"></param>
/// <returns></returns>
public override object GetValue(MMPropertyEmitter emitter, MMProperty property)
{
return GetValueOptimized(property);
}
/// <summary>
/// Sets the raw property value, float normalized, caching the operation if possible
/// </summary>
/// <param name="receiver"></param>
/// <param name="property"></param>
/// <param name="level"></param>
public override void SetValue(MMPropertyReceiver receiver, MMProperty property, object newValue)
{
SetValueOptimized(property, (int)newValue);
}
/// <summary>
/// Returns this property link's level between 0 and 1
/// </summary>
/// <param name="receiver"></param>
/// <param name="property"></param>
/// <param name="level"></param>
/// <returns></returns>
public override float GetLevel(MMPropertyEmitter emitter, MMProperty property)
{
float returnValue = GetValueOptimized(property);
returnValue = MMMaths.Clamp(returnValue, emitter.IntRemapMinToZero, emitter.IntRemapMaxToOne, emitter.ClampMin, emitter.ClampMax);
returnValue = MMMaths.Remap(returnValue, emitter.IntRemapMinToZero, emitter.IntRemapMaxToOne, 0f, 1f);
emitter.Level = returnValue;
return returnValue;
}
/// <summary>
/// Sets the specified level
/// </summary>
/// <param name="receiver"></param>
/// <param name="property"></param>
/// <param name="level"></param>
public override void SetLevel(MMPropertyReceiver receiver, MMProperty property, float level)
{
base.SetLevel(receiver, property, level);
_newValue = (int)MMMaths.Remap(level, 0f, 1f, receiver.IntRemapZero, receiver.IntRemapOne);
if (receiver.RelativeValue)
{
_newValue = _initialValue + _newValue;
}
SetValueOptimized(property, _newValue);
}
/// <summary>
/// Gets either the cached value or the raw value
/// </summary>
/// <param name="property"></param>
/// <returns></returns>
protected virtual int GetValueOptimized(MMProperty property)
{
return _getterSetterInitialized ? GetIntDelegate() : (int)GetPropertyValue(property);
}
/// <summary>
/// Sets either the cached value or the raw value
/// </summary>
/// <param name="property"></param>
/// <param name="newValue"></param>
protected virtual void SetValueOptimized(MMProperty property, int newValue)
{
if (_getterSetterInitialized)
{
SetIntDelegate(_newValue);
}
else
{
SetPropertyValue(property, _newValue);
}
}
}
}
| 37.146853 | 158 | 0.546498 | [
"MIT"
] | random-agile/slowmo_mobile | Assets/Amazing Assets/Feel/MMTools/Tools/MMRadio/MMProperty/MMPropertyLink/MMPropertyLinkInt.cs | 5,312 | C# |
/*
* freee API
*
* <h1 id=\"freee_api\">freee API</h1> <hr /> <h2 id=\"\">スタートガイド</h2> <p>1. セットアップ</p> <ol> <ul><li><a href=\"https://support.freee.co.jp/hc/ja/articles/202847230\" class=\"external-link\" rel=\"nofollow\">freeeアカウント(無料)</a>を<a href=\"https://secure.freee.co.jp/users/sign_up\" class=\"external-link\" rel=\"nofollow\">作成</a>します(すでにお持ちの場合は次へ)</li><li><a href=\"https://app.secure.freee.co.jp/developers/demo_companies/description\" class=\"external-link\" rel=\"nofollow\">開発者向け事業所・環境を作成</a>します</li><li><span><a href=\"https://app.secure.freee.co.jp/developers/applications\" class=\"external-link\" rel=\"nofollow\">前のステップで作成した事業所を選択してfreeeアプリを追加</a>します</span></li><li>Client IDをCopyしておきます</li> </ul> </ol> <p>2. 実際にAPIを叩いてみる(ブラウザからAPIのレスポンスを確認する)</p> <ol> <ul><li><span><span>以下のURLの●をclient_idに入れ替えて<a href=\"https://app.secure.freee.co.jp/developers/tutorials/3-%E3%82%A2%E3%82%AF%E3%82%BB%E3%82%B9%E3%83%88%E3%83%BC%E3%82%AF%E3%83%B3%E3%82%92%E5%8F%96%E5%BE%97%E3%81%99%E3%82%8B#%E8%AA%8D%E5%8F%AF%E3%82%B3%E3%83%BC%E3%83%89%E3%82%92%E5%8F%96%E5%BE%97%E3%81%99%E3%82%8B\" class=\"external-link\" rel=\"nofollow\">アクセストークンを取得</a>します</span></span><ul><li><span><span><pre><code>https://accounts.secure.freee.co.jp/public_api/authorize?client_id=●&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&response_type=token</a></code></pre></span></span></li></ul></li><li><span><a href=\"https://developer.freee.co.jp/docs/accounting/reference#/%E9%80%A3%E7%B5%A1%E5%85%88\" class=\"external-link\" rel=\"nofollow\">APIリファレンス</a>で<code>Authorize</code>を押下します</span></li><li><span>アクセストークン<span><span>を入力して</span></span> もう一度<span><code>Authorize</code>を押下して<code>Close</code>を押下します</span></span></li><li>リファレンス内のCompanies(事業所)に移動し、<code>Try it out</code>を押下し、<code>Execute</code>を押下します</li><li>Response bodyを参照し、事業所ID(id属性)を活用して、Companies以外のエンドポイントでどのようなデータのやりとりできるのか確認します</li></ul> </ol> <p>3. 連携を実装する</p> <ol> <ul><li><a href=\"https://developer.freee.co.jp/tips\" class=\"external-link\" rel=\"nofollow\">API TIPS</a>を参考に、ユースケースごとの連携の概要を学びます。<span>例えば</span><span> </span><a href=\"https://developer.freee.co.jp/tips/how-to-cooperate-salesmanegement-system\" class=\"external-link\" rel=\"nofollow\">SFA、CRM、販売管理システムから会計freeeへの連携</a>や<a href=\"https://developer.freee.co.jp/tips/how-to-cooperate-excel-and-spreadsheet\" class=\"external-link\" rel=\"nofollow\">エクセルやgoogle spreadsheetからの連携</a>です</li><li>実利用向け事業所がすでにある場合は利用、ない場合は作成します(セットアップで作成したのは開発者向け環境のため活用不可)</li><li><a href=\"https://developer.freee.co.jp/docs/accounting/reference\" class=\"external-link\" rel=\"nofollow\">API documentation</a><span> を参照し、躓いた場合は</span><span> </span><a href=\"https://developer.freee.co.jp/community/forum/community\" class=\"external-link\" rel=\"nofollow\">Community</a><span> で質問してみましょう</span></li></ul> </ol> <p>アプリケーションの登録方法や認証方法、またはAPIの活用方法でご不明な点がある場合は<a href=\"https://support.freee.co.jp/hc/ja/sections/115000030743\">ヘルプセンター</a>もご確認ください</p> <hr /> <h2 id=\"_2\">仕様</h2> <h3 id=\"api\">APIエンドポイント</h3> <p>https://api.freee.co.jp/ (httpsのみ)</p> <h3 id=\"_3\">認証方式</h3> <p><a href=\"http://tools.ietf.org/html/rfc6749\">OAuth2</a>に対応</p> <ul> <li>Authorization Code Flow (Webアプリ向け)</li> <li>Implicit Flow (Mobileアプリ向け)</li> </ul> <h3 id=\"_4\">認証エンドポイント</h3> <p>https://accounts.secure.freee.co.jp/</p> <ul> <li>authorize : https://accounts.secure.freee.co.jp/public_api/authorize</li> <li>token : https://accounts.secure.freee.co.jp/public_api/token</li> </ul> <h3 id=\"_5\">アクセストークンのリフレッシュ</h3> <p>認証時に得たrefresh_token を使ってtoken の期限をリフレッシュして新規に発行することが出来ます。</p> <p>grant_type=refresh_token で https://accounts.secure.freee.co.jp/public_api/token にアクセスすればリフレッシュされます。</p> <p>e.g.)</p> <p>POST: https://accounts.secure.freee.co.jp/public_api/token</p> <p>params: grant_type=refresh_token&client_id=UID&client_secret=SECRET&refresh_token=REFRESH_TOKEN</p> <p>詳細は<a href=\"https://github.com/applicake/doorkeeper/wiki/Enable-Refresh-Token-Credentials#flow\">refresh_token</a>を参照下さい。</p> <h3 id=\"_6\">アクセストークンの破棄</h3> <p>認証時に得たaccess_tokenまたはrefresh_tokenを使って、tokenを破棄することができます。 token=access_tokenまたはtoken=refresh_tokenでhttps://accounts.secure.freee.co.jp/public_api/revokeにアクセスすると破棄されます。token_type_hintでaccess_tokenまたはrefresh_tokenを陽に指定できます。</p> <p>e.g.)</p> <p>POST: https://accounts.secure.freee.co.jp/public_api/revoke</p> <p>params: token=ACCESS_TOKEN</p> <p>または</p> <p>params: token=REFRESH_TOKEN</p> <p>または</p> <p>params: token=ACCESS_TOKEN&token_type_hint=access_token</p> <p>または</p> <p>params: token=REFRESH_TOKEN&token_type_hint=refresh_token</p> <p>詳細は <a href=\"https://tools.ietf.org/html/rfc7009\">OAuth 2.0 Token revocation</a> をご参照ください。</p> <h3 id=\"_7\">データフォーマット</h3> <p>リクエスト、レスポンスともにJSON形式をサポート</p> <h3 id=\"_8\">共通レスポンスヘッダー</h3> <p>すべてのAPIのレスポンスには以下のHTTPヘッダーが含まれます。</p> <ul> <li> <p>X-Freee-Request-ID</p> <ul> <li>各リクエスト毎に発行されるID</li> </ul> </li> </ul> <h3 id=\"_9\">共通エラーレスポンス</h3> <ul> <li> <p>ステータスコードはレスポンス内のJSONに含まれる他、HTTPヘッダにも含まれる</p> </li> <li> <p>type</p> <ul> <li>status : HTTPステータスコードの説明</li> <li>validation : エラーの詳細の説明(開発者向け)</li> </ul> </li> </ul> <p>レスポンスの例</p> <pre><code> { "status_code" : 400, "errors" : [ { "type" : "status", "messages" : ["不正なリクエストです。"] }, { "type" : "validation", "messages" : ["Date は不正な日付フォーマットです。入力例:2013-01-01"] } ] }</code></pre> <hr /> <h2 id=\"_10\">連絡先</h2> <p>ご不明点、ご要望等は <a href=\"https://support.freee.co.jp/hc/ja/requests/new\">freee サポートデスクへのお問い合わせフォーム</a> からご連絡ください。</p> <hr />© Since 2013 freee K.K.
*
* The version of the OpenAPI document: v1.0
*
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Net.Mime;
using Freee.Accounting.Client;
using Freee.Accounting.Models;
namespace Freee.Accounting.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IExpenseApplicationsApiSync : IApiAccessor
{
#region Synchronous Operations
/// <summary>
/// 経費申請の作成
/// </summary>
/// <remarks>
/// <h2 id=\"_1\">概要</h2> <p>指定した事業所の経費申請を作成する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを作成することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="parameters">経費申請の作成 (optional)</param>
/// <returns>ExpenseApplicationsResponse</returns>
ExpenseApplicationsResponse CreateExpenseApplication (CreateExpenseApplicationParams parameters = default(CreateExpenseApplicationParams));
/// <summary>
/// 経費申請の作成
/// </summary>
/// <remarks>
/// <h2 id=\"_1\">概要</h2> <p>指定した事業所の経費申請を作成する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを作成することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="parameters">経費申請の作成 (optional)</param>
/// <returns>ApiResponse of ExpenseApplicationsResponse</returns>
ApiResponse<ExpenseApplicationsResponse> CreateExpenseApplicationWithHttpInfo (CreateExpenseApplicationParams parameters = default(CreateExpenseApplicationParams));
/// <summary>
/// 経費申請の削除
/// </summary>
/// <remarks>
/// <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を削除する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="companyId">事業所ID</param>
/// <returns></returns>
void DestroyExpenseApplication (int id, int companyId);
/// <summary>
/// 経費申請の削除
/// </summary>
/// <remarks>
/// <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を削除する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="companyId">事業所ID</param>
/// <returns>ApiResponse of Object(void)</returns>
ApiResponse<Object> DestroyExpenseApplicationWithHttpInfo (int id, int companyId);
/// <summary>
/// 経費申請詳細の取得
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">経費申請ID</param>
/// <param name="companyId">事業所ID</param>
/// <returns>ExpenseApplicationsResponse</returns>
ExpenseApplicationsResponse GetExpenseApplication (int id, int companyId);
/// <summary>
/// 経費申請詳細の取得
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">経費申請ID</param>
/// <param name="companyId">事業所ID</param>
/// <returns>ApiResponse of ExpenseApplicationsResponse</returns>
ApiResponse<ExpenseApplicationsResponse> GetExpenseApplicationWithHttpInfo (int id, int companyId);
/// <summary>
/// 経費申請一覧の取得
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="companyId">事業所ID</param>
/// <param name="offset">取得レコードのオフセット (デフォルト: 0) (optional)</param>
/// <param name="limit">取得レコードの件数 (デフォルト: 50, 最大: 500) (optional)</param>
/// <returns>ExpenseApplicationsIndexResponse</returns>
ExpenseApplicationsIndexResponse GetExpenseApplications (int companyId, int? offset = default(int?), int? limit = default(int?));
/// <summary>
/// 経費申請一覧の取得
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="companyId">事業所ID</param>
/// <param name="offset">取得レコードのオフセット (デフォルト: 0) (optional)</param>
/// <param name="limit">取得レコードの件数 (デフォルト: 50, 最大: 500) (optional)</param>
/// <returns>ApiResponse of ExpenseApplicationsIndexResponse</returns>
ApiResponse<ExpenseApplicationsIndexResponse> GetExpenseApplicationsWithHttpInfo (int companyId, int? offset = default(int?), int? limit = default(int?));
/// <summary>
/// 経費申請の更新
/// </summary>
/// <remarks>
/// <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を更新する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを更新することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="parameters">経費申請の更新 (optional)</param>
/// <returns>ExpenseApplicationsResponse</returns>
ExpenseApplicationsResponse UpdateExpenseApplication (int id, UpdateExpenseApplicationParams parameters = default(UpdateExpenseApplicationParams));
/// <summary>
/// 経費申請の更新
/// </summary>
/// <remarks>
/// <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を更新する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを更新することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="parameters">経費申請の更新 (optional)</param>
/// <returns>ApiResponse of ExpenseApplicationsResponse</returns>
ApiResponse<ExpenseApplicationsResponse> UpdateExpenseApplicationWithHttpInfo (int id, UpdateExpenseApplicationParams parameters = default(UpdateExpenseApplicationParams));
#endregion Synchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IExpenseApplicationsApiAsync : IApiAccessor
{
#region Asynchronous Operations
/// <summary>
/// 経費申請の作成
/// </summary>
/// <remarks>
/// <h2 id=\"_1\">概要</h2> <p>指定した事業所の経費申請を作成する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを作成することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="parameters">経費申請の作成 (optional)</param>
/// <returns>Task of ExpenseApplicationsResponse</returns>
System.Threading.Tasks.Task<ExpenseApplicationsResponse> CreateExpenseApplicationAsync (CreateExpenseApplicationParams parameters = default(CreateExpenseApplicationParams));
/// <summary>
/// 経費申請の作成
/// </summary>
/// <remarks>
/// <h2 id=\"_1\">概要</h2> <p>指定した事業所の経費申請を作成する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを作成することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="parameters">経費申請の作成 (optional)</param>
/// <returns>Task of ApiResponse (ExpenseApplicationsResponse)</returns>
System.Threading.Tasks.Task<ApiResponse<ExpenseApplicationsResponse>> CreateExpenseApplicationAsyncWithHttpInfo (CreateExpenseApplicationParams parameters = default(CreateExpenseApplicationParams));
/// <summary>
/// 経費申請の削除
/// </summary>
/// <remarks>
/// <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を削除する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="companyId">事業所ID</param>
/// <returns>Task of void</returns>
System.Threading.Tasks.Task DestroyExpenseApplicationAsync (int id, int companyId);
/// <summary>
/// 経費申請の削除
/// </summary>
/// <remarks>
/// <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を削除する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="companyId">事業所ID</param>
/// <returns>Task of ApiResponse</returns>
System.Threading.Tasks.Task<ApiResponse<Object>> DestroyExpenseApplicationAsyncWithHttpInfo (int id, int companyId);
/// <summary>
/// 経費申請詳細の取得
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">経費申請ID</param>
/// <param name="companyId">事業所ID</param>
/// <returns>Task of ExpenseApplicationsResponse</returns>
System.Threading.Tasks.Task<ExpenseApplicationsResponse> GetExpenseApplicationAsync (int id, int companyId);
/// <summary>
/// 経費申請詳細の取得
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">経費申請ID</param>
/// <param name="companyId">事業所ID</param>
/// <returns>Task of ApiResponse (ExpenseApplicationsResponse)</returns>
System.Threading.Tasks.Task<ApiResponse<ExpenseApplicationsResponse>> GetExpenseApplicationAsyncWithHttpInfo (int id, int companyId);
/// <summary>
/// 経費申請一覧の取得
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="companyId">事業所ID</param>
/// <param name="offset">取得レコードのオフセット (デフォルト: 0) (optional)</param>
/// <param name="limit">取得レコードの件数 (デフォルト: 50, 最大: 500) (optional)</param>
/// <returns>Task of ExpenseApplicationsIndexResponse</returns>
System.Threading.Tasks.Task<ExpenseApplicationsIndexResponse> GetExpenseApplicationsAsync (int companyId, int? offset = default(int?), int? limit = default(int?));
/// <summary>
/// 経費申請一覧の取得
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="companyId">事業所ID</param>
/// <param name="offset">取得レコードのオフセット (デフォルト: 0) (optional)</param>
/// <param name="limit">取得レコードの件数 (デフォルト: 50, 最大: 500) (optional)</param>
/// <returns>Task of ApiResponse (ExpenseApplicationsIndexResponse)</returns>
System.Threading.Tasks.Task<ApiResponse<ExpenseApplicationsIndexResponse>> GetExpenseApplicationsAsyncWithHttpInfo (int companyId, int? offset = default(int?), int? limit = default(int?));
/// <summary>
/// 経費申請の更新
/// </summary>
/// <remarks>
/// <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を更新する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを更新することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="parameters">経費申請の更新 (optional)</param>
/// <returns>Task of ExpenseApplicationsResponse</returns>
System.Threading.Tasks.Task<ExpenseApplicationsResponse> UpdateExpenseApplicationAsync (int id, UpdateExpenseApplicationParams parameters = default(UpdateExpenseApplicationParams));
/// <summary>
/// 経費申請の更新
/// </summary>
/// <remarks>
/// <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を更新する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを更新することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="parameters">経費申請の更新 (optional)</param>
/// <returns>Task of ApiResponse (ExpenseApplicationsResponse)</returns>
System.Threading.Tasks.Task<ApiResponse<ExpenseApplicationsResponse>> UpdateExpenseApplicationAsyncWithHttpInfo (int id, UpdateExpenseApplicationParams parameters = default(UpdateExpenseApplicationParams));
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IExpenseApplicationsApi : IExpenseApplicationsApiSync, IExpenseApplicationsApiAsync
{
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public partial class ExpenseApplicationsApi : IExpenseApplicationsApi
{
private Freee.Accounting.Client.ExceptionFactory _exceptionFactory = (name, response) => null;
/// <summary>
/// Initializes a new instance of the <see cref="ExpenseApplicationsApi"/> class.
/// </summary>
/// <returns></returns>
public ExpenseApplicationsApi() : this((string) null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ExpenseApplicationsApi"/> class.
/// </summary>
/// <returns></returns>
public ExpenseApplicationsApi(String basePath)
{
this.Configuration = Freee.Accounting.Client.Configuration.MergeConfigurations(
Freee.Accounting.Client.GlobalConfiguration.Instance,
new Freee.Accounting.Client.Configuration { BasePath = basePath }
);
this.Client = new Freee.Accounting.Client.ApiClient(this.Configuration.BasePath);
this.AsynchronousClient = new Freee.Accounting.Client.ApiClient(this.Configuration.BasePath);
this.ExceptionFactory = Freee.Accounting.Client.Configuration.DefaultExceptionFactory;
}
/// <summary>
/// Initializes a new instance of the <see cref="ExpenseApplicationsApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public ExpenseApplicationsApi(Freee.Accounting.Client.Configuration configuration)
{
if (configuration == null) throw new ArgumentNullException("configuration");
this.Configuration = Freee.Accounting.Client.Configuration.MergeConfigurations(
Freee.Accounting.Client.GlobalConfiguration.Instance,
configuration
);
this.Client = new Freee.Accounting.Client.ApiClient(this.Configuration.BasePath);
this.AsynchronousClient = new Freee.Accounting.Client.ApiClient(this.Configuration.BasePath);
ExceptionFactory = Freee.Accounting.Client.Configuration.DefaultExceptionFactory;
}
/// <summary>
/// Initializes a new instance of the <see cref="ExpenseApplicationsApi"/> class
/// using a Configuration object and client instance.
/// </summary>
/// <param name="client">The client interface for synchronous API access.</param>
/// <param name="asyncClient">The client interface for asynchronous API access.</param>
/// <param name="configuration">The configuration object.</param>
public ExpenseApplicationsApi(Freee.Accounting.Client.ISynchronousClient client,Freee.Accounting.Client.IAsynchronousClient asyncClient, Freee.Accounting.Client.IReadableConfiguration configuration)
{
if(client == null) throw new ArgumentNullException("client");
if(asyncClient == null) throw new ArgumentNullException("asyncClient");
if(configuration == null) throw new ArgumentNullException("configuration");
this.Client = client;
this.AsynchronousClient = asyncClient;
this.Configuration = configuration;
this.ExceptionFactory = Freee.Accounting.Client.Configuration.DefaultExceptionFactory;
}
/// <summary>
/// The client for accessing this underlying API asynchronously.
/// </summary>
public Freee.Accounting.Client.IAsynchronousClient AsynchronousClient { get; set; }
/// <summary>
/// The client for accessing this underlying API synchronously.
/// </summary>
public Freee.Accounting.Client.ISynchronousClient Client { get; set; }
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.Configuration.BasePath;
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public Freee.Accounting.Client.IReadableConfiguration Configuration {get; set;}
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
public Freee.Accounting.Client.ExceptionFactory ExceptionFactory
{
get
{
if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1)
{
throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported.");
}
return _exceptionFactory;
}
set { _exceptionFactory = value; }
}
/// <summary>
/// 経費申請の作成 <h2 id=\"_1\">概要</h2> <p>指定した事業所の経費申請を作成する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを作成することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="parameters">経費申請の作成 (optional)</param>
/// <returns>ExpenseApplicationsResponse</returns>
public ExpenseApplicationsResponse CreateExpenseApplication (CreateExpenseApplicationParams parameters = default(CreateExpenseApplicationParams))
{
Freee.Accounting.Client.ApiResponse<ExpenseApplicationsResponse> localVarResponse = CreateExpenseApplicationWithHttpInfo(parameters);
return localVarResponse.Data;
}
/// <summary>
/// 経費申請の作成 <h2 id=\"_1\">概要</h2> <p>指定した事業所の経費申請を作成する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを作成することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="parameters">経費申請の作成 (optional)</param>
/// <returns>ApiResponse of ExpenseApplicationsResponse</returns>
public Freee.Accounting.Client.ApiResponse< ExpenseApplicationsResponse > CreateExpenseApplicationWithHttpInfo (CreateExpenseApplicationParams parameters = default(CreateExpenseApplicationParams))
{
Freee.Accounting.Client.RequestOptions localVarRequestOptions = new Freee.Accounting.Client.RequestOptions();
String[] _contentTypes = new String[] {
"application/json"
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = Freee.Accounting.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Freee.Accounting.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
localVarRequestOptions.Data = parameters;
// authentication (oauth2) required
// oauth required
if (!String.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
// make the HTTP request
var localVarResponse = this.Client.Post< ExpenseApplicationsResponse >("/api/1/expense_applications", localVarRequestOptions, this.Configuration);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("CreateExpenseApplication", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// 経費申請の作成 <h2 id=\"_1\">概要</h2> <p>指定した事業所の経費申請を作成する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを作成することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="parameters">経費申請の作成 (optional)</param>
/// <returns>Task of ExpenseApplicationsResponse</returns>
public async System.Threading.Tasks.Task<ExpenseApplicationsResponse> CreateExpenseApplicationAsync (CreateExpenseApplicationParams parameters = default(CreateExpenseApplicationParams))
{
Freee.Accounting.Client.ApiResponse<ExpenseApplicationsResponse> localVarResponse = await CreateExpenseApplicationAsyncWithHttpInfo(parameters);
return localVarResponse.Data;
}
/// <summary>
/// 経費申請の作成 <h2 id=\"_1\">概要</h2> <p>指定した事業所の経費申請を作成する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを作成することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="parameters">経費申請の作成 (optional)</param>
/// <returns>Task of ApiResponse (ExpenseApplicationsResponse)</returns>
public async System.Threading.Tasks.Task<Freee.Accounting.Client.ApiResponse<ExpenseApplicationsResponse>> CreateExpenseApplicationAsyncWithHttpInfo (CreateExpenseApplicationParams parameters = default(CreateExpenseApplicationParams))
{
Freee.Accounting.Client.RequestOptions localVarRequestOptions = new Freee.Accounting.Client.RequestOptions();
String[] _contentTypes = new String[] {
"application/json"
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
foreach (var _contentType in _contentTypes)
localVarRequestOptions.HeaderParameters.Add("Content-Type", _contentType);
foreach (var _accept in _accepts)
localVarRequestOptions.HeaderParameters.Add("Accept", _accept);
localVarRequestOptions.Data = parameters;
// authentication (oauth2) required
// oauth required
if (!String.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PostAsync<ExpenseApplicationsResponse>("/api/1/expense_applications", localVarRequestOptions, this.Configuration);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("CreateExpenseApplication", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// 経費申請の削除 <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を削除する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="companyId">事業所ID</param>
/// <returns></returns>
public void DestroyExpenseApplication (int id, int companyId)
{
DestroyExpenseApplicationWithHttpInfo(id, companyId);
}
/// <summary>
/// 経費申請の削除 <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を削除する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="companyId">事業所ID</param>
/// <returns>ApiResponse of Object(void)</returns>
public Freee.Accounting.Client.ApiResponse<Object> DestroyExpenseApplicationWithHttpInfo (int id, int companyId)
{
Freee.Accounting.Client.RequestOptions localVarRequestOptions = new Freee.Accounting.Client.RequestOptions();
String[] _contentTypes = new String[] {
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = Freee.Accounting.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Freee.Accounting.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
localVarRequestOptions.PathParameters.Add("id", Freee.Accounting.Client.ClientUtils.ParameterToString(id)); // path parameter
localVarRequestOptions.QueryParameters.Add(Freee.Accounting.Client.ClientUtils.ParameterToMultiMap("", "company_id", companyId));
// authentication (oauth2) required
// oauth required
if (!String.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
// make the HTTP request
var localVarResponse = this.Client.Delete<Object>("/api/1/expense_applications/{id}", localVarRequestOptions, this.Configuration);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("DestroyExpenseApplication", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// 経費申請の削除 <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を削除する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="companyId">事業所ID</param>
/// <returns>Task of void</returns>
public async System.Threading.Tasks.Task DestroyExpenseApplicationAsync (int id, int companyId)
{
await DestroyExpenseApplicationAsyncWithHttpInfo(id, companyId);
}
/// <summary>
/// 経費申請の削除 <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を削除する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="companyId">事業所ID</param>
/// <returns>Task of ApiResponse</returns>
public async System.Threading.Tasks.Task<Freee.Accounting.Client.ApiResponse<Object>> DestroyExpenseApplicationAsyncWithHttpInfo (int id, int companyId)
{
Freee.Accounting.Client.RequestOptions localVarRequestOptions = new Freee.Accounting.Client.RequestOptions();
String[] _contentTypes = new String[] {
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
foreach (var _contentType in _contentTypes)
localVarRequestOptions.HeaderParameters.Add("Content-Type", _contentType);
foreach (var _accept in _accepts)
localVarRequestOptions.HeaderParameters.Add("Accept", _accept);
localVarRequestOptions.PathParameters.Add("id", Freee.Accounting.Client.ClientUtils.ParameterToString(id)); // path parameter
localVarRequestOptions.QueryParameters.Add(Freee.Accounting.Client.ClientUtils.ParameterToMultiMap("", "company_id", companyId));
// authentication (oauth2) required
// oauth required
if (!String.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.DeleteAsync<Object>("/api/1/expense_applications/{id}", localVarRequestOptions, this.Configuration);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("DestroyExpenseApplication", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// 経費申請詳細の取得
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">経費申請ID</param>
/// <param name="companyId">事業所ID</param>
/// <returns>ExpenseApplicationsResponse</returns>
public ExpenseApplicationsResponse GetExpenseApplication (int id, int companyId)
{
Freee.Accounting.Client.ApiResponse<ExpenseApplicationsResponse> localVarResponse = GetExpenseApplicationWithHttpInfo(id, companyId);
return localVarResponse.Data;
}
/// <summary>
/// 経費申請詳細の取得
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">経費申請ID</param>
/// <param name="companyId">事業所ID</param>
/// <returns>ApiResponse of ExpenseApplicationsResponse</returns>
public Freee.Accounting.Client.ApiResponse< ExpenseApplicationsResponse > GetExpenseApplicationWithHttpInfo (int id, int companyId)
{
Freee.Accounting.Client.RequestOptions localVarRequestOptions = new Freee.Accounting.Client.RequestOptions();
String[] _contentTypes = new String[] {
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = Freee.Accounting.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Freee.Accounting.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
localVarRequestOptions.PathParameters.Add("id", Freee.Accounting.Client.ClientUtils.ParameterToString(id)); // path parameter
localVarRequestOptions.QueryParameters.Add(Freee.Accounting.Client.ClientUtils.ParameterToMultiMap("", "company_id", companyId));
// authentication (oauth2) required
// oauth required
if (!String.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
// make the HTTP request
var localVarResponse = this.Client.Get< ExpenseApplicationsResponse >("/api/1/expense_applications/{id}", localVarRequestOptions, this.Configuration);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("GetExpenseApplication", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// 経費申請詳細の取得
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">経費申請ID</param>
/// <param name="companyId">事業所ID</param>
/// <returns>Task of ExpenseApplicationsResponse</returns>
public async System.Threading.Tasks.Task<ExpenseApplicationsResponse> GetExpenseApplicationAsync (int id, int companyId)
{
Freee.Accounting.Client.ApiResponse<ExpenseApplicationsResponse> localVarResponse = await GetExpenseApplicationAsyncWithHttpInfo(id, companyId);
return localVarResponse.Data;
}
/// <summary>
/// 経費申請詳細の取得
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">経費申請ID</param>
/// <param name="companyId">事業所ID</param>
/// <returns>Task of ApiResponse (ExpenseApplicationsResponse)</returns>
public async System.Threading.Tasks.Task<Freee.Accounting.Client.ApiResponse<ExpenseApplicationsResponse>> GetExpenseApplicationAsyncWithHttpInfo (int id, int companyId)
{
Freee.Accounting.Client.RequestOptions localVarRequestOptions = new Freee.Accounting.Client.RequestOptions();
String[] _contentTypes = new String[] {
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
foreach (var _contentType in _contentTypes)
localVarRequestOptions.HeaderParameters.Add("Content-Type", _contentType);
foreach (var _accept in _accepts)
localVarRequestOptions.HeaderParameters.Add("Accept", _accept);
localVarRequestOptions.PathParameters.Add("id", Freee.Accounting.Client.ClientUtils.ParameterToString(id)); // path parameter
localVarRequestOptions.QueryParameters.Add(Freee.Accounting.Client.ClientUtils.ParameterToMultiMap("", "company_id", companyId));
// authentication (oauth2) required
// oauth required
if (!String.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.GetAsync<ExpenseApplicationsResponse>("/api/1/expense_applications/{id}", localVarRequestOptions, this.Configuration);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("GetExpenseApplication", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// 経費申請一覧の取得
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="companyId">事業所ID</param>
/// <param name="offset">取得レコードのオフセット (デフォルト: 0) (optional)</param>
/// <param name="limit">取得レコードの件数 (デフォルト: 50, 最大: 500) (optional)</param>
/// <returns>ExpenseApplicationsIndexResponse</returns>
public ExpenseApplicationsIndexResponse GetExpenseApplications (int companyId, int? offset = default(int?), int? limit = default(int?))
{
Freee.Accounting.Client.ApiResponse<ExpenseApplicationsIndexResponse> localVarResponse = GetExpenseApplicationsWithHttpInfo(companyId, offset, limit);
return localVarResponse.Data;
}
/// <summary>
/// 経費申請一覧の取得
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="companyId">事業所ID</param>
/// <param name="offset">取得レコードのオフセット (デフォルト: 0) (optional)</param>
/// <param name="limit">取得レコードの件数 (デフォルト: 50, 最大: 500) (optional)</param>
/// <returns>ApiResponse of ExpenseApplicationsIndexResponse</returns>
public Freee.Accounting.Client.ApiResponse< ExpenseApplicationsIndexResponse > GetExpenseApplicationsWithHttpInfo (int companyId, int? offset = default(int?), int? limit = default(int?))
{
Freee.Accounting.Client.RequestOptions localVarRequestOptions = new Freee.Accounting.Client.RequestOptions();
String[] _contentTypes = new String[] {
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = Freee.Accounting.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Freee.Accounting.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
localVarRequestOptions.QueryParameters.Add(Freee.Accounting.Client.ClientUtils.ParameterToMultiMap("", "company_id", companyId));
if (offset != null)
{
localVarRequestOptions.QueryParameters.Add(Freee.Accounting.Client.ClientUtils.ParameterToMultiMap("", "offset", offset));
}
if (limit != null)
{
localVarRequestOptions.QueryParameters.Add(Freee.Accounting.Client.ClientUtils.ParameterToMultiMap("", "limit", limit));
}
// authentication (oauth2) required
// oauth required
if (!String.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
// make the HTTP request
var localVarResponse = this.Client.Get< ExpenseApplicationsIndexResponse >("/api/1/expense_applications", localVarRequestOptions, this.Configuration);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("GetExpenseApplications", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// 経費申請一覧の取得
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="companyId">事業所ID</param>
/// <param name="offset">取得レコードのオフセット (デフォルト: 0) (optional)</param>
/// <param name="limit">取得レコードの件数 (デフォルト: 50, 最大: 500) (optional)</param>
/// <returns>Task of ExpenseApplicationsIndexResponse</returns>
public async System.Threading.Tasks.Task<ExpenseApplicationsIndexResponse> GetExpenseApplicationsAsync (int companyId, int? offset = default(int?), int? limit = default(int?))
{
Freee.Accounting.Client.ApiResponse<ExpenseApplicationsIndexResponse> localVarResponse = await GetExpenseApplicationsAsyncWithHttpInfo(companyId, offset, limit);
return localVarResponse.Data;
}
/// <summary>
/// 経費申請一覧の取得
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="companyId">事業所ID</param>
/// <param name="offset">取得レコードのオフセット (デフォルト: 0) (optional)</param>
/// <param name="limit">取得レコードの件数 (デフォルト: 50, 最大: 500) (optional)</param>
/// <returns>Task of ApiResponse (ExpenseApplicationsIndexResponse)</returns>
public async System.Threading.Tasks.Task<Freee.Accounting.Client.ApiResponse<ExpenseApplicationsIndexResponse>> GetExpenseApplicationsAsyncWithHttpInfo (int companyId, int? offset = default(int?), int? limit = default(int?))
{
Freee.Accounting.Client.RequestOptions localVarRequestOptions = new Freee.Accounting.Client.RequestOptions();
String[] _contentTypes = new String[] {
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
foreach (var _contentType in _contentTypes)
localVarRequestOptions.HeaderParameters.Add("Content-Type", _contentType);
foreach (var _accept in _accepts)
localVarRequestOptions.HeaderParameters.Add("Accept", _accept);
localVarRequestOptions.QueryParameters.Add(Freee.Accounting.Client.ClientUtils.ParameterToMultiMap("", "company_id", companyId));
if (offset != null)
{
localVarRequestOptions.QueryParameters.Add(Freee.Accounting.Client.ClientUtils.ParameterToMultiMap("", "offset", offset));
}
if (limit != null)
{
localVarRequestOptions.QueryParameters.Add(Freee.Accounting.Client.ClientUtils.ParameterToMultiMap("", "limit", limit));
}
// authentication (oauth2) required
// oauth required
if (!String.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.GetAsync<ExpenseApplicationsIndexResponse>("/api/1/expense_applications", localVarRequestOptions, this.Configuration);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("GetExpenseApplications", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// 経費申請の更新 <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を更新する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを更新することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="parameters">経費申請の更新 (optional)</param>
/// <returns>ExpenseApplicationsResponse</returns>
public ExpenseApplicationsResponse UpdateExpenseApplication (int id, UpdateExpenseApplicationParams parameters = default(UpdateExpenseApplicationParams))
{
Freee.Accounting.Client.ApiResponse<ExpenseApplicationsResponse> localVarResponse = UpdateExpenseApplicationWithHttpInfo(id, parameters);
return localVarResponse.Data;
}
/// <summary>
/// 経費申請の更新 <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を更新する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを更新することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="parameters">経費申請の更新 (optional)</param>
/// <returns>ApiResponse of ExpenseApplicationsResponse</returns>
public Freee.Accounting.Client.ApiResponse< ExpenseApplicationsResponse > UpdateExpenseApplicationWithHttpInfo (int id, UpdateExpenseApplicationParams parameters = default(UpdateExpenseApplicationParams))
{
Freee.Accounting.Client.RequestOptions localVarRequestOptions = new Freee.Accounting.Client.RequestOptions();
String[] _contentTypes = new String[] {
"application/json"
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = Freee.Accounting.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Freee.Accounting.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
localVarRequestOptions.PathParameters.Add("id", Freee.Accounting.Client.ClientUtils.ParameterToString(id)); // path parameter
localVarRequestOptions.Data = parameters;
// authentication (oauth2) required
// oauth required
if (!String.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
// make the HTTP request
var localVarResponse = this.Client.Put< ExpenseApplicationsResponse >("/api/1/expense_applications/{id}", localVarRequestOptions, this.Configuration);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("UpdateExpenseApplication", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// 経費申請の更新 <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を更新する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを更新することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="parameters">経費申請の更新 (optional)</param>
/// <returns>Task of ExpenseApplicationsResponse</returns>
public async System.Threading.Tasks.Task<ExpenseApplicationsResponse> UpdateExpenseApplicationAsync (int id, UpdateExpenseApplicationParams parameters = default(UpdateExpenseApplicationParams))
{
Freee.Accounting.Client.ApiResponse<ExpenseApplicationsResponse> localVarResponse = await UpdateExpenseApplicationAsyncWithHttpInfo(id, parameters);
return localVarResponse.Data;
}
/// <summary>
/// 経費申請の更新 <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を更新する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを更新することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="parameters">経費申請の更新 (optional)</param>
/// <returns>Task of ApiResponse (ExpenseApplicationsResponse)</returns>
public async System.Threading.Tasks.Task<Freee.Accounting.Client.ApiResponse<ExpenseApplicationsResponse>> UpdateExpenseApplicationAsyncWithHttpInfo (int id, UpdateExpenseApplicationParams parameters = default(UpdateExpenseApplicationParams))
{
Freee.Accounting.Client.RequestOptions localVarRequestOptions = new Freee.Accounting.Client.RequestOptions();
String[] _contentTypes = new String[] {
"application/json"
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
foreach (var _contentType in _contentTypes)
localVarRequestOptions.HeaderParameters.Add("Content-Type", _contentType);
foreach (var _accept in _accepts)
localVarRequestOptions.HeaderParameters.Add("Accept", _accept);
localVarRequestOptions.PathParameters.Add("id", Freee.Accounting.Client.ClientUtils.ParameterToString(id)); // path parameter
localVarRequestOptions.Data = parameters;
// authentication (oauth2) required
// oauth required
if (!String.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PutAsync<ExpenseApplicationsResponse>("/api/1/expense_applications/{id}", localVarRequestOptions, this.Configuration);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("UpdateExpenseApplication", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
}
}
| 64.115686 | 5,736 | 0.659776 | [
"MIT"
] | s-taira/freee-accounting-sdk-csharp | src/Freee.Accounting/Api/ExpenseApplicationsApi.cs | 78,510 | 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.SpecialNumbers")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("01.SpecialNumbers")]
[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("04ab05a3-aada-4ea1-8219-e305ac674f04")]
// 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.027027 | 84 | 0.745558 | [
"MIT"
] | stoyanov7/SoftwareUniversity | TechnologiesFundamentals/ProgrammingFundamentals-Extended/DataTypesAndVariables-Exercises/01.SpecialNumbers/01.SpecialNumbers/Properties/AssemblyInfo.cs | 1,410 | C# |
using SharpVectors.Dom.Events;
namespace SharpVectors.Dom.Svg
{
/// <summary>
/// The SvgRectElement interface corresponds to the 'rect' element.
/// </summary>
/// <developer>niklas@protocol7.com</developer>
/// <completed>100</completed>
public interface ISvgRectElement :
ISvgElement,
ISvgTests,
ISvgLangSpace,
ISvgExternalResourcesRequired,
ISvgStylable,
ISvgTransformable,
IEventTarget
{
/// <summary>
/// Corresponds to attribute x on the given 'rect' element.
/// </summary>
ISvgAnimatedLength X{get;}
/// <summary>
/// Corresponds to attribute y on the given 'rect' element.
/// </summary>
ISvgAnimatedLength Y{get;}
/// <summary>
/// Corresponds to attribute rx on the given 'rect' element.
/// </summary>
ISvgAnimatedLength Rx{get;}
/// <summary>
/// Corresponds to attribute ry on the given 'rect' element.
/// </summary>
ISvgAnimatedLength Ry{get;}
/// <summary>
/// Corresponds to attribute width on the given 'rect' element.
/// </summary>
ISvgAnimatedLength Width{get;}
/// <summary>
/// Corresponds to attribute height on the given 'rect' element.
/// </summary>
ISvgAnimatedLength Height{get;}
}
}
| 24.568627 | 70 | 0.648045 | [
"BSD-3-Clause"
] | GuillaumeSmartLiberty/SharpVectors | Main/Source/SharpVectorCore/Svg/Shapes/ISvgRectElement.cs | 1,253 | C# |
using System;
using SXL=System.Xml.Linq;
namespace VisioAutomation.VDX.Internal
{
public static class XMLUtil
{
public static SXL.XElement CreateVisioSchema2003Element(string name)
{
string fullname = String.Format("{0}{1}",Constants.VisioXmlNamespace2003,name);
var el = new SXL.XElement(fullname);
return el;
}
public static SXL.XElement CreateVisioSchema2006Element(string name)
{
string fullname = String.Format("{0}{1}", Constants.VisioXmlNamespace2006, name);
var el = new SXL.XElement(fullname);
return el;
}
}
} | 27.333333 | 93 | 0.620427 | [
"MIT"
] | saveenr/VisioAutomation.VDX | VisioAutomation.VDX/Internal/XMLUtil.cs | 658 | C# |
using EShop.Common.Constants;
using Microsoft.AspNetCore.Authentication;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace EShop.ViewModels.Account
{
public class LoginViewModel// : GoogleReCaptchaModelBase
{
[Display(Name = "نام کاربری")]
[Required(ErrorMessage = AttributesErrorMessages.RequiredMessage)]
[MinLength(3, ErrorMessage = AttributesErrorMessages.MinLengthMessage)]
[MaxLength(30, ErrorMessage = AttributesErrorMessages.MaxLengthMessage)]
public string UserName { get; set; }
[Display(Name = "رمز عبور")]
[Required(ErrorMessage = AttributesErrorMessages.RequiredMessage)]
//[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = "به خاطر سپاری رمز عبور ؟")]
public bool RememberMe { get; set; }
public List<AuthenticationScheme> ExternalLogins { get; set; }
}
} | 36.692308 | 80 | 0.702306 | [
"MIT"
] | sradd3/EShop | src/EShop.ViewModels/Account/LoginViewModel.cs | 991 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Text;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB
{
public class PortablePdbTests : CSharpPDBTestBase
{
[Fact]
public void SequencePointBlob()
{
string source = @"
class C
{
public static void Main()
{
if (F())
{
System.Console.WriteLine(1);
}
}
public static bool F() => false;
}
";
var c = CreateStandardCompilation(source, options: TestOptions.DebugDll);
var pdbStream = new MemoryStream();
var peBlob = c.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), pdbStream: pdbStream);
using (var peReader = new PEReader(peBlob))
using (var pdbMetadata = new PinnedMetadata(pdbStream.ToImmutable()))
{
var mdReader = peReader.GetMetadataReader();
var pdbReader = pdbMetadata.Reader;
foreach (var methodHandle in mdReader.MethodDefinitions)
{
var method = mdReader.GetMethodDefinition(methodHandle);
var methodDebugInfo = pdbReader.GetMethodDebugInformation(methodHandle);
var name = mdReader.GetString(method.Name);
TextWriter writer = new StringWriter();
foreach (var sp in methodDebugInfo.GetSequencePoints())
{
if (sp.IsHidden)
{
writer.WriteLine($"{sp.Offset}: <hidden>");
}
else
{
writer.WriteLine($"{sp.Offset}: ({sp.StartLine},{sp.StartColumn})-({sp.EndLine},{sp.EndColumn})");
}
}
var spString = writer.ToString();
var spBlob = pdbReader.GetBlobBytes(methodDebugInfo.SequencePointsBlob);
switch (name)
{
case "Main":
AssertEx.AssertEqualToleratingWhitespaceDifferences(@"
0: (5,5)-(5,6)
1: (6,9)-(6,17)
7: <hidden>
10: (7,9)-(7,10)
11: (8,13)-(8,41)
18: (9,9)-(9,10)
19: (10,5)-(10,6)
", spString);
AssertEx.Equal(new byte[]
{
0x01, // local signature
0x00, // IL offset
0x00, // Delta Lines
0x01, // Delta Columns
0x05, // Start Line
0x05, // Start Column
0x01, // delta IL offset
0x00, // Delta Lines
0x08, // Delta Columns
0x02, // delta Start Line (signed compressed)
0x08, // delta Start Column (signed compressed)
0x06, // delta IL offset
0x00, // hidden
0x00, // hidden
0x03, // delta IL offset
0x00, // Delta Lines
0x01, // Delta Columns
0x02, // delta Start Line (signed compressed)
0x00, // delta Start Column (signed compressed)
0x01, // delta IL offset
0x00, // Delta Lines
0x1C, // Delta Columns
0x02, // delta Start Line (signed compressed)
0x08, // delta Start Column (signed compressed)
0x07, // delta IL offset
0x00, // Delta Lines
0x01, // Delta Columns
0x02, // delta Start Line (signed compressed)
0x79, // delta Start Column (signed compressed)
0x01, // delta IL offset
0x00, // Delta Lines
0x01, // Delta Columns
0x02, // delta Start Line (signed compressed)
0x79, // delta Start Column (signed compressed)
}, spBlob);
break;
case "F":
AssertEx.AssertEqualToleratingWhitespaceDifferences("0: (12,31)-(12,36)", spString);
AssertEx.Equal(new byte[]
{
0x00, // local signature
0x00, // delta IL offset
0x00, // Delta Lines
0x05, // Delta Columns
0x0C, // Start Line
0x1F // Start Column
}, spBlob);
break;
}
}
}
}
[Fact]
public void EmbeddedPortablePdb()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
";
var c = CreateStandardCompilation(Parse(source, "goo.cs"), options: TestOptions.DebugDll);
var peBlob = c.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.Embedded).WithPdbFilePath(@"a/b/c/d.pdb"));
using (var peReader = new PEReader(peBlob))
{
var entries = peReader.ReadDebugDirectory();
AssertEx.Equal(new[] { DebugDirectoryEntryType.CodeView, DebugDirectoryEntryType.EmbeddedPortablePdb }, entries.Select(e => e.Type));
var codeView = entries[0];
var embedded = entries[1];
// EmbeddedPortablePdb entry:
Assert.Equal(0x0100, embedded.MajorVersion);
Assert.Equal(0x0100, embedded.MinorVersion);
Assert.Equal(0u, embedded.Stamp);
BlobContentId pdbId;
using (var embeddedMetadataProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embedded))
{
var mdReader = embeddedMetadataProvider.GetMetadataReader();
AssertEx.Equal(new[] { "goo.cs" }, mdReader.Documents.Select(doc => mdReader.GetString(mdReader.GetDocument(doc).Name)));
pdbId = new BlobContentId(mdReader.DebugMetadataHeader.Id);
}
// CodeView entry:
var codeViewData = peReader.ReadCodeViewDebugDirectoryData(codeView);
Assert.Equal(0x0100, codeView.MajorVersion);
Assert.Equal(0x504D, codeView.MinorVersion);
Assert.Equal(pdbId.Stamp, codeView.Stamp);
Assert.Equal(pdbId.Guid, codeViewData.Guid);
Assert.Equal("d.pdb", codeViewData.Path);
}
}
[Fact]
public void EmbeddedPortablePdb_Deterministic()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
";
var c = CreateStandardCompilation(Parse(source, "goo.cs"), options: TestOptions.DebugDll.WithDeterministic(true));
var peBlob = c.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.Embedded).WithPdbFilePath(@"a/b/c/d.pdb"));
using (var peReader = new PEReader(peBlob))
{
var entries = peReader.ReadDebugDirectory();
AssertEx.Equal(new[] { DebugDirectoryEntryType.CodeView, DebugDirectoryEntryType.Reproducible, DebugDirectoryEntryType.EmbeddedPortablePdb }, entries.Select(e => e.Type));
var codeView = entries[0];
var reproducible = entries[1];
var embedded = entries[2];
// EmbeddedPortablePdb entry:
Assert.Equal(0x0100, embedded.MajorVersion);
Assert.Equal(0x0100, embedded.MinorVersion);
Assert.Equal(0u, embedded.Stamp);
BlobContentId pdbId;
using (var embeddedMetadataProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embedded))
{
var mdReader = embeddedMetadataProvider.GetMetadataReader();
AssertEx.Equal(new[] { "goo.cs" }, mdReader.Documents.Select(doc => mdReader.GetString(mdReader.GetDocument(doc).Name)));
pdbId = new BlobContentId(mdReader.DebugMetadataHeader.Id);
}
// CodeView entry:
var codeViewData = peReader.ReadCodeViewDebugDirectoryData(codeView);
Assert.Equal(0x0100, codeView.MajorVersion);
Assert.Equal(0x504D, codeView.MinorVersion);
Assert.Equal(pdbId.Stamp, codeView.Stamp);
Assert.Equal(pdbId.Guid, codeViewData.Guid);
Assert.Equal("d.pdb", codeViewData.Path);
// Reproducible entry:
Assert.Equal(0, reproducible.MajorVersion);
Assert.Equal(0, reproducible.MinorVersion);
Assert.Equal(0U, reproducible.Stamp);
Assert.Equal(0, reproducible.DataSize);
}
}
[Fact]
public void SourceLink()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
";
var sourceLinkBlob = Encoding.UTF8.GetBytes(@"
{
""documents"": {
""f:/build/*"" : ""https://raw.githubusercontent.com/my-org/my-project/1111111111111111111111111111111111111111/*""
}
}
");
var c = CreateStandardCompilation(Parse(source, "f:/build/goo.cs"), options: TestOptions.DebugDll);
var pdbStream = new MemoryStream();
c.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), pdbStream: pdbStream, sourceLinkStream: new MemoryStream(sourceLinkBlob));
pdbStream.Position = 0;
using (var provider = MetadataReaderProvider.FromPortablePdbStream(pdbStream))
{
var pdbReader = provider.GetMetadataReader();
var actualBlob =
(from cdiHandle in pdbReader.GetCustomDebugInformation(EntityHandle.ModuleDefinition)
let cdi = pdbReader.GetCustomDebugInformation(cdiHandle)
where pdbReader.GetGuid(cdi.Kind) == PortableCustomDebugInfoKinds.SourceLink
select pdbReader.GetBlobBytes(cdi.Value)).Single();
AssertEx.Equal(sourceLinkBlob, actualBlob);
}
}
[Fact]
public void SourceLink_Embedded()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
";
var sourceLinkBlob = Encoding.UTF8.GetBytes(@"
{
""documents"": {
""f:/build/*"" : ""https://raw.githubusercontent.com/my-org/my-project/1111111111111111111111111111111111111111/*""
}
}
");
var c = CreateStandardCompilation(Parse(source, "f:/build/goo.cs"), options: TestOptions.DebugDll);
var peBlob = c.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.Embedded), sourceLinkStream: new MemoryStream(sourceLinkBlob));
using (var peReader = new PEReader(peBlob))
{
var embeddedEntry = peReader.ReadDebugDirectory().Single(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb);
using (var embeddedMetadataProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embeddedEntry))
{
var pdbReader = embeddedMetadataProvider.GetMetadataReader();
var actualBlob =
(from cdiHandle in pdbReader.GetCustomDebugInformation(EntityHandle.ModuleDefinition)
let cdi = pdbReader.GetCustomDebugInformation(cdiHandle)
where pdbReader.GetGuid(cdi.Kind) == PortableCustomDebugInfoKinds.SourceLink
select pdbReader.GetBlobBytes(cdi.Value)).Single();
AssertEx.Equal(sourceLinkBlob, actualBlob);
}
}
}
[Fact]
public void SourceLink_Errors()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
";
var sourceLinkStream = new TestStream(canRead: true, readFunc: (_, __, ___) => { throw new Exception("Error!"); });
var c = CreateStandardCompilation(Parse(source, "f:/build/goo.cs"), options: TestOptions.DebugDll);
var result = c.Emit(new MemoryStream(), new MemoryStream(), options: EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), sourceLinkStream: sourceLinkStream);
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'Error!'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("Error!").WithLocation(1, 1));
}
}
}
| 38.405995 | 201 | 0.538773 | [
"Apache-2.0"
] | ElanHasson/roslyn | src/Compilers/CSharp/Test/Emit/PDB/PortablePdbTests.cs | 14,097 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// 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("MarsRoverTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MarsRoverTests")]
[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("1d028dba-a4a1-4cae-8d53-058f76f3d228")]
// 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")]
[assembly: NeutralResourcesLanguageAttribute("en")]
| 37.871795 | 84 | 0.750169 | [
"MIT"
] | IAmAnubhavSaini/blog-posts | design/c_sharp/refactoring/MarsRoverSolution/MarsRoverAppTests/Properties/AssemblyInfo.cs | 1,480 | C# |
using System;
namespace Reddit.Inputs.Modmail
{
[Serializable]
public class ModmailNewConversationInput : ModmailMessageBodyInput
{
/// <summary>
/// subreddit name
/// </summary>
public string srName { get; set; }
/// <summary>
/// a string no longer than 100 characters
/// </summary>
public string subject { get; set; }
/// <summary>
/// Modmail conversation recipient username
/// </summary>
public string to { get; set; }
/// <summary>
/// Creates a new conversation for a particular SR.
/// </summary>
/// <param name="body">raw markdown text</param>
/// <param name="isAuthorHidden">boolean value</param>
/// <param name="srName">subreddit name</param>
/// <param name="subject">a string no longer than 100 characters</param>
/// <param name="to">Modmail conversation recipient username</param>
public ModmailNewConversationInput(string body = "", bool isAuthorHidden = false, string srName = "", string subject = "", string to = "")
: base(body, isAuthorHidden)
{
this.srName = srName;
this.subject = subject;
this.to = to;
}
}
}
| 32.275 | 146 | 0.566228 | [
"MIT"
] | DanClowry/Reddit.NET | src/Reddit.NET/Inputs/Modmail/ModmailNewConversationInput.cs | 1,293 | C# |
using System;
using BTDB.Buffer;
using BTDB.IL;
using BTDB.StreamLayer;
namespace BTDB.FieldHandler
{
public class ByteArrayFieldHandler : IFieldHandler
{
public virtual string Name => "Byte[]";
public byte[]? Configuration => null;
public virtual bool IsCompatibleWith(Type type, FieldHandlerOptions options)
{
return typeof(byte[]) == type || typeof(ByteBuffer) == type;
}
public Type HandledType()
{
return typeof(byte[]);
}
public bool NeedsCtx()
{
return false;
}
public virtual void Load(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen>? pushCtx)
{
pushReader(ilGenerator);
ilGenerator.Call(typeof(SpanReader).GetMethod(nameof(SpanReader.ReadByteArray))!);
}
public virtual void Skip(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen>? pushCtx)
{
pushReader(ilGenerator);
ilGenerator.Call(typeof(SpanReader).GetMethod(nameof(SpanReader.SkipByteArray))!);
}
public virtual void Save(IILGen ilGenerator, Action<IILGen> pushWriter, Action<IILGen>? pushCtx,
Action<IILGen> pushValue)
{
pushWriter(ilGenerator);
pushValue(ilGenerator);
ilGenerator.Call(typeof(SpanWriter).GetMethod(nameof(SpanWriter.WriteByteArray), new[] { typeof(byte[]) })!);
}
protected virtual void SaveByteBuffer(IILGen ilGenerator, Action<IILGen> pushWriter, Action<IILGen> pushValue)
{
pushWriter(ilGenerator);
pushValue(ilGenerator);
ilGenerator.Call(
typeof(SpanWriter).GetMethod(nameof(SpanWriter.WriteByteArray), new[] { typeof(ByteBuffer) })!);
}
public IFieldHandler SpecializeLoadForType(Type type, IFieldHandler? typeHandler)
{
if (typeof(ByteBuffer) == type)
{
return new ByteBufferHandler(this);
}
return this;
}
public NeedsFreeContent FreeContent(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen>? pushCtx)
{
Skip(ilGenerator, pushReader, pushCtx);
return NeedsFreeContent.No;
}
class ByteBufferHandler : IFieldHandler
{
readonly ByteArrayFieldHandler _fieldHandler;
public ByteBufferHandler(ByteArrayFieldHandler fieldHandler)
{
_fieldHandler = fieldHandler;
}
public string Name => _fieldHandler.Name;
public byte[]? Configuration => _fieldHandler.Configuration;
public bool IsCompatibleWith(Type type, FieldHandlerOptions options)
{
return typeof(ByteBuffer) == type;
}
public Type HandledType()
{
return typeof(ByteBuffer);
}
public bool NeedsCtx()
{
return false;
}
public void Load(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen>? pushCtx)
{
_fieldHandler.Load(ilGenerator, pushReader, pushCtx);
ilGenerator.Call(() => ByteBuffer.NewAsync(null));
}
public void Skip(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen>? pushCtx)
{
_fieldHandler.Skip(ilGenerator, pushReader, pushCtx);
}
public void Save(IILGen ilGenerator, Action<IILGen> pushWriter, Action<IILGen>? pushCtx,
Action<IILGen> pushValue)
{
_fieldHandler.SaveByteBuffer(ilGenerator, pushWriter, pushValue);
}
public IFieldHandler SpecializeLoadForType(Type type, IFieldHandler? typeHandler)
{
throw new InvalidOperationException();
}
public IFieldHandler SpecializeSaveForType(Type type)
{
throw new InvalidOperationException();
}
public NeedsFreeContent FreeContent(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen>? pushCtx)
{
_fieldHandler.Skip(ilGenerator, pushReader, pushCtx);
return NeedsFreeContent.No;
}
}
public IFieldHandler SpecializeSaveForType(Type type)
{
if (typeof(ByteBuffer) == type)
{
return new ByteBufferHandler(this);
}
return this;
}
}
}
| 32.055172 | 121 | 0.580034 | [
"MIT"
] | karimtafsi/BTDB | BTDB/FieldHandler/ByteArrayFieldHandler.cs | 4,648 | C# |
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System.Threading;
using System.Threading.Tasks;
namespace Ixy.Infrastructure.Interface
{
public interface IDbContext
{
DbSet<TEntity> Set<TEntity>()
where TEntity : class;
EntityEntry<TEntity> Entry<TEntity>(TEntity entity)
where TEntity : class;
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken));
int SaveChanges();
}
}
| 25.333333 | 101 | 0.712406 | [
"MIT"
] | sgwzxg/Ixy | src/Ixy.Infrastructure.Interface/IDbContext.cs | 534 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using NBitcoin;
using Newtonsoft.Json;
using Stratis.Bitcoin.Utilities;
using Stratis.Bitcoin.Utilities.JsonConverters;
namespace Stratis.Bitcoin.Features.Wallet
{
/// <summary>
/// A wallet.
/// </summary>
public class Wallet
{
/// <summary>
/// Initializes a new instance of the wallet.
/// </summary>
public Wallet()
{
this.AccountsRoot = new List<AccountRoot>();
}
/// <summary>
/// The name of this wallet.
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
/// <summary>
/// Flag indicating if it is a watch only wallet.
/// </summary>
[JsonProperty(PropertyName = "isExtPubKeyWallet")]
public bool IsExtPubKeyWallet { get; set; }
/// <summary>
/// The seed for this wallet, password encrypted.
/// </summary>
[JsonProperty(PropertyName = "encryptedSeed", NullValueHandling = NullValueHandling.Ignore)]
public string EncryptedSeed { get; set; }
/// <summary>
/// The chain code.
/// </summary>
[JsonProperty(PropertyName = "chainCode", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(ByteArrayConverter))]
public byte[] ChainCode { get; set; }
/// <summary>
/// Gets or sets the merkle path.
/// </summary>
[JsonProperty(PropertyName = "blockLocator", ItemConverterType = typeof(UInt256JsonConverter))]
public ICollection<uint256> BlockLocator { get; set; }
/// <summary>
/// The network this wallet is for.
/// </summary>
[JsonProperty(PropertyName = "network")]
[JsonConverter(typeof(NetworkConverter))]
public Network Network { get; set; }
/// <summary>
/// The time this wallet was created.
/// </summary>
[JsonProperty(PropertyName = "creationTime")]
[JsonConverter(typeof(DateTimeOffsetConverter))]
public DateTimeOffset CreationTime { get; set; }
/// <summary>
/// The root of the accounts tree.
/// </summary>
[JsonProperty(PropertyName = "accountsRoot")]
public ICollection<AccountRoot> AccountsRoot { get; set; }
/// <summary>
/// Gets the accounts the wallet has for this type of coin.
/// </summary>
/// <param name="coinType">Type of the coin.</param>
/// <returns>The accounts in the wallet corresponding to this type of coin.</returns>
public IEnumerable<HdAccount> GetAccountsByCoinType(CoinType coinType)
{
return this.AccountsRoot.Where(a => a.CoinType == coinType).SelectMany(a => a.Accounts);
}
/// <summary>
/// Gets an account from the wallet's accounts.
/// </summary>
/// <param name="accountName">The name of the account to retrieve.</param>
/// <param name="coinType">The type of the coin this account is for.</param>
/// <returns>The requested account.</returns>
public HdAccount GetAccountByCoinType(string accountName, CoinType coinType)
{
AccountRoot accountRoot = this.AccountsRoot.SingleOrDefault(a => a.CoinType == coinType);
return accountRoot?.GetAccountByName(accountName);
}
/// <summary>
/// Update the last block synced height and hash in the wallet.
/// </summary>
/// <param name="coinType">The type of the coin this account is for.</param>
/// <param name="block">The block whose details are used to update the wallet.</param>
public void SetLastBlockDetailsByCoinType(CoinType coinType, ChainedHeader block)
{
AccountRoot accountRoot = this.AccountsRoot.SingleOrDefault(a => a.CoinType == coinType);
if (accountRoot == null) return;
accountRoot.LastBlockSyncedHeight = block.Height;
accountRoot.LastBlockSyncedHash = block.HashBlock;
}
/// <summary>
/// Gets all the transactions by coin type.
/// </summary>
/// <param name="coinType">Type of the coin.</param>
/// <returns></returns>
public IEnumerable<TransactionData> GetAllTransactionsByCoinType(CoinType coinType)
{
List<HdAccount> accounts = this.GetAccountsByCoinType(coinType).ToList();
foreach (TransactionData txData in accounts.SelectMany(x => x.ExternalAddresses).SelectMany(x => x.Transactions))
{
yield return txData;
}
foreach (TransactionData txData in accounts.SelectMany(x => x.InternalAddresses).SelectMany(x => x.Transactions))
{
yield return txData;
}
}
/// <summary>
/// Gets all the pub keys contained in this wallet.
/// </summary>
/// <param name="coinType">Type of the coin.</param>
/// <returns></returns>
public IEnumerable<Script> GetAllPubKeysByCoinType(CoinType coinType)
{
List<HdAccount> accounts = this.GetAccountsByCoinType(coinType).ToList();
foreach (Script script in accounts.SelectMany(x => x.ExternalAddresses).Select(x => x.ScriptPubKey))
{
yield return script;
}
foreach (Script script in accounts.SelectMany(x => x.InternalAddresses).Select(x => x.ScriptPubKey))
{
yield return script;
}
}
/// <summary>
/// Gets all the addresses contained in this wallet.
/// </summary>
/// <param name="coinType">Type of the coin.</param>
/// <returns>A list of all the addresses contained in this wallet.</returns>
public IEnumerable<HdAddress> GetAllAddressesByCoinType(CoinType coinType)
{
List<HdAccount> accounts = this.GetAccountsByCoinType(coinType).ToList();
var allAddresses = new List<HdAddress>();
foreach (HdAccount account in accounts)
{
allAddresses.AddRange(account.GetCombinedAddresses());
}
return allAddresses;
}
/// <summary>
/// Adds an account to the current wallet.
/// </summary>
/// <remarks>
/// The name given to the account is of the form "account (i)" by default, where (i) is an incremental index starting at 0.
/// According to BIP44, an account at index (i) can only be created when the account at index (i - 1) contains at least one transaction.
/// </remarks>
/// <seealso cref="https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki"/>
/// <param name="password">The password used to decrypt the wallet's <see cref="EncryptedSeed"/>.</param>
/// <param name="coinType">The type of coin this account is for.</param>
/// <param name="accountCreationTime">Creation time of the account to be created.</param>
/// <returns>A new HD account.</returns>
public HdAccount AddNewAccount(string password, CoinType coinType, DateTimeOffset accountCreationTime)
{
Guard.NotEmpty(password, nameof(password));
AccountRoot accountRoot = this.AccountsRoot.Single(a => a.CoinType == coinType);
return accountRoot.AddNewAccount(password, this.EncryptedSeed, this.ChainCode, this.Network, accountCreationTime);
}
/// <summary>
/// Adds an account to the current wallet.
/// </summary>
/// <remarks>
/// The name given to the account is of the form "account (i)" by default, where (i) is an incremental index starting at 0.
/// According to BIP44, an account at index (i) can only be created when the account at index (i - 1) contains at least one transaction.
/// </remarks>
/// <seealso cref="https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki"/>
/// <param name="extPubKey">The extended public key for the wallet<see cref="EncryptedSeed"/>.</param>
/// <param name="coinType">The type of coin this account is for.</param>
/// <param name="accountIndex">Zero-based index of the account to add.</param>
/// <param name="accountCreationTime">Creation time of the account to be created.</param>
/// <returns>A new HD account.</returns>
public HdAccount AddNewAccount(CoinType coinType, ExtPubKey extPubKey, int accountIndex, DateTimeOffset accountCreationTime)
{
AccountRoot accountRoot = this.AccountsRoot.Single(a => a.CoinType == coinType);
return accountRoot.AddNewAccount(extPubKey, accountIndex, this.Network, accountCreationTime);
}
/// <summary>
/// Gets the first account that contains no transaction.
/// </summary>
/// <returns>An unused account.</returns>
public HdAccount GetFirstUnusedAccount(CoinType coinType)
{
// Get the accounts root for this type of coin.
AccountRoot accountsRoot = this.AccountsRoot.Single(a => a.CoinType == coinType);
if (accountsRoot.Accounts.Any())
{
// Get an unused account.
HdAccount firstUnusedAccount = accountsRoot.GetFirstUnusedAccount();
if (firstUnusedAccount != null)
{
return firstUnusedAccount;
}
}
return null;
}
/// <summary>
/// Determines whether the wallet contains the specified address.
/// </summary>
/// <param name="address">The address to check.</param>
/// <returns>A value indicating whether the wallet contains the specified address.</returns>
public bool ContainsAddress(HdAddress address)
{
if (!this.AccountsRoot.Any(r => r.Accounts.Any(
a => a.ExternalAddresses.Any(i => i.Address == address.Address) ||
a.InternalAddresses.Any(i => i.Address == address.Address))))
{
return false;
}
return true;
}
/// <summary>
/// Gets the extended private key for the given address.
/// </summary>
/// <param name="password">The password used to encrypt/decrypt sensitive info.</param>
/// <param name="address">The address to get the private key for.</param>
/// <returns>The extended private key.</returns>
public ISecret GetExtendedPrivateKeyForAddress(string password, HdAddress address)
{
Guard.NotEmpty(password, nameof(password));
Guard.NotNull(address, nameof(address));
// Check if the wallet contains the address.
if (!this.ContainsAddress(address))
{
throw new WalletException("Address not found on wallet.");
}
// get extended private key
Key privateKey = HdOperations.DecryptSeed(this.EncryptedSeed, password, this.Network);
return HdOperations.GetExtendedPrivateKey(privateKey, this.ChainCode, address.HdPath, this.Network);
}
/// <summary>
/// Lists all spendable transactions from all accounts in the wallet.
/// </summary>
/// <param name="coinType">Type of the coin to get transactions from.</param>
/// <param name="currentChainHeight">Height of the current chain, used in calculating the number of confirmations.</param>
/// <param name="confirmations">The number of confirmations required to consider a transaction spendable.</param>
/// <returns>A collection of spendable outputs.</returns>
public IEnumerable<UnspentOutputReference> GetAllSpendableTransactions(CoinType coinType, int currentChainHeight, int confirmations = 0)
{
IEnumerable<HdAccount> accounts = this.GetAccountsByCoinType(coinType);
return accounts
.SelectMany(x => x.GetSpendableTransactions(currentChainHeight, confirmations));
}
}
/// <summary>
/// The root for the accounts for any type of coins.
/// </summary>
public class AccountRoot
{
/// <summary>
/// Initializes a new instance of the object.
/// </summary>
public AccountRoot()
{
this.Accounts = new List<HdAccount>();
}
/// <summary>
/// The type of coin, Bitcoin or Stratis.
/// </summary>
[JsonProperty(PropertyName = "coinType")]
public CoinType CoinType { get; set; }
/// <summary>
/// The height of the last block that was synced.
/// </summary>
[JsonProperty(PropertyName = "lastBlockSyncedHeight", NullValueHandling = NullValueHandling.Ignore)]
public int? LastBlockSyncedHeight { get; set; }
/// <summary>
/// The hash of the last block that was synced.
/// </summary>
[JsonProperty(PropertyName = "lastBlockSyncedHash", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(UInt256JsonConverter))]
public uint256 LastBlockSyncedHash { get; set; }
/// <summary>
/// The accounts used in the wallet.
/// </summary>
[JsonProperty(PropertyName = "accounts")]
public ICollection<HdAccount> Accounts { get; set; }
/// <summary>
/// Gets the first account that contains no transaction.
/// </summary>
/// <returns>An unused account</returns>
public HdAccount GetFirstUnusedAccount()
{
if (this.Accounts == null)
return null;
List<HdAccount> unusedAccounts = this.Accounts.Where(acc => !acc.ExternalAddresses.Any() && !acc.InternalAddresses.Any()).ToList();
if (!unusedAccounts.Any())
return null;
// gets the unused account with the lowest index
int index = unusedAccounts.Min(a => a.Index);
return unusedAccounts.Single(a => a.Index == index);
}
/// <summary>
/// Gets the account matching the name passed as a parameter.
/// </summary>
/// <param name="accountName">The name of the account to get.</param>
/// <returns></returns>
/// <exception cref="System.Exception"></exception>
public HdAccount GetAccountByName(string accountName)
{
if (this.Accounts == null)
throw new WalletException($"No account with the name {accountName} could be found.");
// get the account
HdAccount account = this.Accounts.SingleOrDefault(a => a.Name == accountName);
if (account == null)
throw new WalletException($"No account with the name {accountName} could be found.");
return account;
}
/// <summary>
/// Adds an account to the current account root using encrypted seed and password.
/// </summary>
/// <remarks>The name given to the account is of the form "account (i)" by default, where (i) is an incremental index starting at 0.
/// According to BIP44, an account at index (i) can only be created when the account at index (i - 1) contains transactions.
/// <seealso cref="https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki"/></remarks>
/// <param name="password">The password used to decrypt the wallet's encrypted seed.</param>
/// <param name="encryptedSeed">The encrypted private key for this wallet.</param>
/// <param name="chainCode">The chain code for this wallet.</param>
/// <param name="network">The network for which this account will be created.</param>
/// <param name="accountCreationTime">Creation time of the account to be created.</param>
/// <returns>A new HD account.</returns>
public HdAccount AddNewAccount(string password, string encryptedSeed, byte[] chainCode, Network network, DateTimeOffset accountCreationTime)
{
Guard.NotEmpty(password, nameof(password));
Guard.NotEmpty(encryptedSeed, nameof(encryptedSeed));
Guard.NotNull(chainCode, nameof(chainCode));
int newAccountIndex = 0;
ICollection<HdAccount> hdAccounts = this.Accounts.ToList();
if (hdAccounts.Any())
{
newAccountIndex = hdAccounts.Max(a => a.Index) + 1;
}
// Get the extended pub key used to generate addresses for this account.
string accountHdPath = HdOperations.GetAccountHdPath((int) this.CoinType, newAccountIndex);
Key privateKey = HdOperations.DecryptSeed(encryptedSeed, password, network);
ExtPubKey accountExtPubKey = HdOperations.GetExtendedPublicKey(privateKey, chainCode, accountHdPath);
var newAccount = new HdAccount
{
Index = newAccountIndex,
ExtendedPubKey = accountExtPubKey.ToString(network),
ExternalAddresses = new List<HdAddress>(),
InternalAddresses = new List<HdAddress>(),
Name = $"account {newAccountIndex}",
HdPath = accountHdPath,
CreationTime = accountCreationTime
};
hdAccounts.Add(newAccount);
this.Accounts = hdAccounts;
return newAccount;
}
/// <inheritdoc cref="AddNewAccount(string, string, byte[], Network, DateTimeOffset)"/>
/// <summary>
/// Adds an account to the current account root using extended public key and account index.
/// </summary>
/// <param name="accountExtPubKey">The extended public key for the account.</param>
/// <param name="accountIndex">The zero-based account index.</param>
public HdAccount AddNewAccount(ExtPubKey accountExtPubKey, int accountIndex, Network network, DateTimeOffset accountCreationTime)
{
ICollection<HdAccount> hdAccounts = this.Accounts.ToList();
if (hdAccounts.Any(a => a.Index == accountIndex))
{
throw new WalletException("There is already an account in this wallet with index: " + accountIndex);
}
if (hdAccounts.Any(x => x.ExtendedPubKey == accountExtPubKey.ToString(network)))
{
throw new WalletException("There is already an account in this wallet with this xpubkey: " +
accountExtPubKey.ToString(network));
}
string accountHdPath = HdOperations.GetAccountHdPath((int) this.CoinType, accountIndex);
var newAccount = new HdAccount
{
Index = accountIndex,
ExtendedPubKey = accountExtPubKey.ToString(network),
ExternalAddresses = new List<HdAddress>(),
InternalAddresses = new List<HdAddress>(),
Name = $"account {accountIndex}",
HdPath = accountHdPath,
CreationTime = accountCreationTime
};
hdAccounts.Add(newAccount);
this.Accounts = hdAccounts;
return newAccount;
}
}
/// <summary>
/// An HD account's details.
/// </summary>
public class HdAccount
{
public HdAccount()
{
this.ExternalAddresses = new List<HdAddress>();
this.InternalAddresses = new List<HdAddress>();
}
/// <summary>
/// The index of the account.
/// </summary>
/// <remarks>
/// According to BIP44, an account at index (i) can only be created when the account
/// at index (i - 1) contains transactions.
/// </remarks>
[JsonProperty(PropertyName = "index")]
public int Index { get; set; }
/// <summary>
/// The name of this account.
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
/// <summary>
/// A path to the account as defined in BIP44.
/// </summary>
[JsonProperty(PropertyName = "hdPath")]
public string HdPath { get; set; }
/// <summary>
/// An extended pub key used to generate addresses.
/// </summary>
[JsonProperty(PropertyName = "extPubKey")]
public string ExtendedPubKey { get; set; }
/// <summary>
/// Gets or sets the creation time.
/// </summary>
[JsonProperty(PropertyName = "creationTime")]
[JsonConverter(typeof(DateTimeOffsetConverter))]
public DateTimeOffset CreationTime { get; set; }
/// <summary>
/// The list of external addresses, typically used for receiving money.
/// </summary>
[JsonProperty(PropertyName = "externalAddresses")]
public ICollection<HdAddress> ExternalAddresses { get; set; }
/// <summary>
/// The list of internal addresses, typically used to receive change.
/// </summary>
[JsonProperty(PropertyName = "internalAddresses")]
public ICollection<HdAddress> InternalAddresses { get; set; }
/// <summary>
/// Gets the type of coin this account is for.
/// </summary>
/// <returns>A <see cref="CoinType"/>.</returns>
public CoinType GetCoinType()
{
return (CoinType)HdOperations.GetCoinType(this.HdPath);
}
/// <summary>
/// Gets the first receiving address that contains no transaction.
/// </summary>
/// <returns>An unused address</returns>
public HdAddress GetFirstUnusedReceivingAddress()
{
return this.GetFirstUnusedAddress(false);
}
/// <summary>
/// Gets the first change address that contains no transaction.
/// </summary>
/// <returns>An unused address</returns>
public HdAddress GetFirstUnusedChangeAddress()
{
return this.GetFirstUnusedAddress(true);
}
/// <summary>
/// Gets the first receiving address that contains no transaction.
/// </summary>
/// <returns>An unused address</returns>
private HdAddress GetFirstUnusedAddress(bool isChange)
{
IEnumerable<HdAddress> addresses = isChange ? this.InternalAddresses : this.ExternalAddresses;
if (addresses == null)
return null;
List<HdAddress> unusedAddresses = addresses.Where(acc => !acc.Transactions.Any()).ToList();
if (!unusedAddresses.Any())
{
return null;
}
// gets the unused address with the lowest index
int index = unusedAddresses.Min(a => a.Index);
return unusedAddresses.Single(a => a.Index == index);
}
/// <summary>
/// Gets the last address that contains transactions.
/// </summary>
/// <param name="isChange">Whether the address is a change (internal) address or receiving (external) address.</param>
/// <returns></returns>
public HdAddress GetLastUsedAddress(bool isChange)
{
IEnumerable<HdAddress> addresses = isChange ? this.InternalAddresses : this.ExternalAddresses;
if (addresses == null)
return null;
List<HdAddress> usedAddresses = addresses.Where(acc => acc.Transactions.Any()).ToList();
if (!usedAddresses.Any())
{
return null;
}
// gets the used address with the highest index
int index = usedAddresses.Max(a => a.Index);
return usedAddresses.Single(a => a.Index == index);
}
/// <summary>
/// Gets a collection of transactions by id.
/// </summary>
/// <param name="id">The identifier.</param>
/// <returns></returns>
public IEnumerable<TransactionData> GetTransactionsById(uint256 id)
{
Guard.NotNull(id, nameof(id));
IEnumerable<HdAddress> addresses = this.GetCombinedAddresses();
return addresses.Where(r => r.Transactions != null).SelectMany(a => a.Transactions.Where(t => t.Id == id));
}
/// <summary>
/// Gets a collection of transactions with spendable outputs.
/// </summary>
/// <returns></returns>
public IEnumerable<TransactionData> GetSpendableTransactions()
{
IEnumerable<HdAddress> addresses = this.GetCombinedAddresses();
return addresses.Where(r => r.Transactions != null).SelectMany(a => a.Transactions.Where(t => t.IsSpendable()));
}
/// <summary>
/// Get the accounts total spendable value for both confirmed and unconfirmed UTXO.
/// </summary>
public (Money ConfirmedAmount, Money UnConfirmedAmount) GetSpendableAmount()
{
List<TransactionData> allTransactions = this.ExternalAddresses.SelectMany(a => a.Transactions)
.Concat(this.InternalAddresses.SelectMany(i => i.Transactions)).ToList();
long confirmed = allTransactions.Sum(t => t.SpendableAmount(true));
long total = allTransactions.Sum(t => t.SpendableAmount(false));
return (confirmed, total - confirmed);
}
/// <summary>
/// Finds the addresses in which a transaction is contained.
/// </summary>
/// <remarks>
/// Returns a collection because a transaction can be contained in a change address as well as in a receive address (as a spend).
/// </remarks>
/// <param name="predicate">A predicate by which to filter the transactions.</param>
/// <returns></returns>
public IEnumerable<HdAddress> FindAddressesForTransaction(Func<TransactionData, bool> predicate)
{
Guard.NotNull(predicate, nameof(predicate));
IEnumerable<HdAddress> addresses = this.GetCombinedAddresses();
return addresses.Where(t => t.Transactions != null).Where(a => a.Transactions.Any(predicate));
}
/// <summary>
/// Return both the external and internal (change) address from an account.
/// </summary>
/// <returns>All addresses that belong to this account.</returns>
public IEnumerable<HdAddress> GetCombinedAddresses()
{
IEnumerable<HdAddress> addresses = new List<HdAddress>();
if (this.ExternalAddresses != null)
{
addresses = this.ExternalAddresses;
}
if (this.InternalAddresses != null)
{
addresses = addresses.Concat(this.InternalAddresses);
}
return addresses;
}
/// <summary>
/// Creates a number of additional addresses in the current account.
/// </summary>
/// <remarks>
/// The name given to the account is of the form "account (i)" by default, where (i) is an incremental index starting at 0.
/// According to BIP44, an account at index (i) can only be created when the account at index (i - 1) contains at least one transaction.
/// </remarks>
/// <param name="network">The network these addresses will be for.</param>
/// <param name="addressesQuantity">The number of addresses to create.</param>
/// <param name="isChange">Whether the addresses added are change (internal) addresses or receiving (external) addresses.</param>
/// <returns>The created addresses.</returns>
public IEnumerable<HdAddress> CreateAddresses(Network network, int addressesQuantity, bool isChange = false)
{
ICollection<HdAddress> addresses = isChange ? this.InternalAddresses : this.ExternalAddresses;
// Get the index of the last address.
int firstNewAddressIndex = 0;
if (addresses.Any())
{
firstNewAddressIndex = addresses.Max(add => add.Index) + 1;
}
var addressesCreated = new List<HdAddress>();
for (int i = firstNewAddressIndex; i < firstNewAddressIndex + addressesQuantity; i++)
{
// Generate a new address.
PubKey pubkey = HdOperations.GeneratePublicKey(this.ExtendedPubKey, i, isChange);
BitcoinPubKeyAddress address = pubkey.GetAddress(network);
// Add the new address details to the list of addresses.
var newAddress = new HdAddress
{
Index = i,
HdPath = HdOperations.CreateHdPath((int) this.GetCoinType(), this.Index, isChange, i),
ScriptPubKey = address.ScriptPubKey,
Pubkey = pubkey.ScriptPubKey,
Address = address.ToString(),
Transactions = new List<TransactionData>()
};
addresses.Add(newAddress);
addressesCreated.Add(newAddress);
}
if (isChange)
{
this.InternalAddresses = addresses;
}
else
{
this.ExternalAddresses = addresses;
}
return addressesCreated;
}
/// <summary>
/// Lists all spendable transactions in the current account.
/// </summary>
/// <param name="currentChainHeight">The current height of the chain. Used for calculating the number of confirmations a transaction has.</param>
/// <param name="confirmations">The minimum number of confirmations required for transactions to be considered.</param>
/// <returns>A collection of spendable outputs that belong to the given account.</returns>
public IEnumerable<UnspentOutputReference> GetSpendableTransactions(int currentChainHeight, int confirmations = 0)
{
// This will take all the spendable coins that belong to the account and keep the reference to the HDAddress and HDAccount.
// This is useful so later the private key can be calculated just from a given UTXO.
foreach (HdAddress address in this.GetCombinedAddresses())
{
// A block that is at the tip has 1 confirmation.
// When calculating the confirmations the tip must be advanced by one.
int countFrom = currentChainHeight + 1;
foreach (TransactionData transactionData in address.UnspentTransactions())
{
int? confirmationCount = 0;
if (transactionData.BlockHeight != null)
confirmationCount = countFrom >= transactionData.BlockHeight ? countFrom - transactionData.BlockHeight : 0;
if (confirmationCount >= confirmations)
{
yield return new UnspentOutputReference
{
Account = this,
Address = address,
Transaction = transactionData
};
}
}
}
}
}
/// <summary>
/// An HD address.
/// </summary>
public class HdAddress
{
public HdAddress()
{
this.Transactions = new List<TransactionData>();
}
/// <summary>
/// The index of the address.
/// </summary>
[JsonProperty(PropertyName = "index")]
public int Index { get; set; }
/// <summary>
/// The script pub key for this address.
/// </summary>
[JsonProperty(PropertyName = "scriptPubKey")]
[JsonConverter(typeof(ScriptJsonConverter))]
public Script ScriptPubKey { get; set; }
/// <summary>
/// The script pub key for this address.
/// </summary>
[JsonProperty(PropertyName = "pubkey")]
[JsonConverter(typeof(ScriptJsonConverter))]
public Script Pubkey { get; set; }
/// <summary>
/// The Base58 representation of this address.
/// </summary>
[JsonProperty(PropertyName = "address")]
public string Address { get; set; }
/// <summary>
/// A path to the address as defined in BIP44.
/// </summary>
[JsonProperty(PropertyName = "hdPath")]
public string HdPath { get; set; }
/// <summary>
/// A list of transactions involving this address.
/// </summary>
[JsonProperty(PropertyName = "transactions")]
public ICollection<TransactionData> Transactions { get; set; }
/// <summary>
/// Determines whether this is a change address or a receive address.
/// </summary>
/// <returns>
/// <c>true</c> if it is a change address; otherwise, <c>false</c>.
/// </returns>
public bool IsChangeAddress()
{
return HdOperations.IsChangeAddress(this.HdPath);
}
/// <summary>
/// List all spendable transactions in an address.
/// </summary>
/// <returns></returns>
public IEnumerable<TransactionData> UnspentTransactions()
{
if (this.Transactions == null)
{
return new List<TransactionData>();
}
return this.Transactions.Where(t => t.IsSpendable());
}
/// <summary>
/// Get the address total spendable value for both confirmed and unconfirmed UTXO.
/// </summary>
public (Money confirmedAmount, Money unConfirmedAmount) GetSpendableAmount()
{
List<TransactionData> allTransactions = this.Transactions.ToList();
long confirmed = allTransactions.Sum(t => t.SpendableAmount(true));
long total = allTransactions.Sum(t => t.SpendableAmount(false));
return (confirmed, total - confirmed);
}
}
/// <summary>
/// An object containing transaction data.
/// </summary>
public class TransactionData
{
/// <summary>
/// Transaction id.
/// </summary>
[JsonProperty(PropertyName = "id")]
[JsonConverter(typeof(UInt256JsonConverter))]
public uint256 Id { get; set; }
/// <summary>
/// The transaction amount.
/// </summary>
[JsonProperty(PropertyName = "amount")]
[JsonConverter(typeof(MoneyJsonConverter))]
public Money Amount { get; set; }
/// <summary>
/// A value indicating whether this is a coin stake transaction or not.
/// </summary>
[JsonProperty(PropertyName = "isCoinStake", NullValueHandling = NullValueHandling.Ignore)]
public bool? IsCoinStake { get; set; }
/// <summary>
/// The index of this scriptPubKey in the transaction it is contained.
/// </summary>
/// <remarks>
/// This is effectively the index of the output, the position of the output in the parent transaction.
/// </remarks>
[JsonProperty(PropertyName = "index", NullValueHandling = NullValueHandling.Ignore)]
public int Index { get; set; }
/// <summary>
/// The height of the block including this transaction.
/// </summary>
[JsonProperty(PropertyName = "blockHeight", NullValueHandling = NullValueHandling.Ignore)]
public int? BlockHeight { get; set; }
/// <summary>
/// The hash of the block including this transaction.
/// </summary>
[JsonProperty(PropertyName = "blockHash", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(UInt256JsonConverter))]
public uint256 BlockHash { get; set; }
/// <summary>
/// Gets or sets the creation time.
/// </summary>
[JsonProperty(PropertyName = "creationTime")]
[JsonConverter(typeof(DateTimeOffsetConverter))]
public DateTimeOffset CreationTime { get; set; }
/// <summary>
/// Gets or sets the Merkle proof for this transaction.
/// </summary>
[JsonProperty(PropertyName = "merkleProof", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(BitcoinSerializableJsonConverter))]
public PartialMerkleTree MerkleProof { get; set; }
/// <summary>
/// The script pub key for this address.
/// </summary>
[JsonProperty(PropertyName = "scriptPubKey")]
[JsonConverter(typeof(ScriptJsonConverter))]
public Script ScriptPubKey { get; set; }
/// <summary>
/// Hexadecimal representation of this transaction.
/// </summary>
[JsonProperty(PropertyName = "hex", NullValueHandling = NullValueHandling.Ignore)]
public string Hex { get; set; }
/// <summary>
/// Propagation state of this transaction.
/// </summary>
/// <remarks>Assume it's <c>true</c> if the field is <c>null</c>.</remarks>
[JsonProperty(PropertyName = "isPropagated", NullValueHandling = NullValueHandling.Ignore)]
public bool? IsPropagated { get; set; }
/// <summary>
/// The details of the transaction in which the output referenced in this transaction is spent.
/// </summary>
[JsonProperty(PropertyName = "spendingDetails", NullValueHandling = NullValueHandling.Ignore)]
public SpendingDetails SpendingDetails { get; set; }
/// <summary>
/// Determines whether this transaction is confirmed.
/// </summary>
public bool IsConfirmed()
{
return this.BlockHeight != null;
}
/// <summary>
/// Indicates an output is spendable.
/// </summary>
public bool IsSpendable()
{
return this.SpendingDetails == null;
}
public Money SpendableAmount(bool confirmedOnly)
{
// This method only returns a UTXO that has no spending output.
// If a spending output exists (even if its not confirmed) this will return as zero balance.
if (this.IsSpendable())
{
// If the 'confirmedOnly' flag is set check that the UTXO is confirmed.
if (confirmedOnly && !this.IsConfirmed())
{
return Money.Zero;
}
return this.Amount;
}
return Money.Zero;
}
}
/// <summary>
/// An object representing a payment.
/// </summary>
public class PaymentDetails
{
/// <summary>
/// The script pub key of the destination address.
/// </summary>
[JsonProperty(PropertyName = "destinationScriptPubKey")]
[JsonConverter(typeof(ScriptJsonConverter))]
public Script DestinationScriptPubKey { get; set; }
/// <summary>
/// The Base58 representation of the destination address.
/// </summary>
[JsonProperty(PropertyName = "destinationAddress")]
public string DestinationAddress { get; set; }
/// <summary>
/// The transaction amount.
/// </summary>
[JsonProperty(PropertyName = "amount")]
[JsonConverter(typeof(MoneyJsonConverter))]
public Money Amount { get; set; }
}
public class SpendingDetails
{
public SpendingDetails()
{
this.Payments = new List<PaymentDetails>();
}
/// <summary>
/// The id of the transaction in which the output referenced in this transaction is spent.
/// </summary>
[JsonProperty(PropertyName = "transactionId", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(UInt256JsonConverter))]
public uint256 TransactionId { get; set; }
/// <summary>
/// A list of payments made out in this transaction.
/// </summary>
[JsonProperty(PropertyName = "payments", NullValueHandling = NullValueHandling.Ignore)]
public ICollection<PaymentDetails> Payments { get; set; }
/// <summary>
/// The height of the block including this transaction.
/// </summary>
[JsonProperty(PropertyName = "blockHeight", NullValueHandling = NullValueHandling.Ignore)]
public int? BlockHeight { get; set; }
/// <summary>
/// A value indicating whether this is a coin stake transaction or not.
/// </summary>
[JsonProperty(PropertyName = "isCoinStake", NullValueHandling = NullValueHandling.Ignore)]
public bool? IsCoinStake { get; set; }
/// <summary>
/// Gets or sets the creation time.
/// </summary>
[JsonProperty(PropertyName = "creationTime")]
[JsonConverter(typeof(DateTimeOffsetConverter))]
public DateTimeOffset CreationTime { get; set; }
/// <summary>
/// Hexadecimal representation of this spending transaction.
/// </summary>
[JsonProperty(PropertyName = "hex", NullValueHandling = NullValueHandling.Ignore)]
public string Hex { get; set; }
/// <summary>
/// Determines whether this transaction being spent is confirmed.
/// </summary>
public bool IsSpentConfirmed()
{
return this.BlockHeight != null;
}
}
/// <summary>
/// Represents an UTXO that keeps a reference to <see cref="HdAddress"/> and <see cref="HdAccount"/>.
/// </summary>
/// <remarks>
/// This is useful when an UTXO needs access to its HD properties like the HD path when reconstructing a private key.
/// </remarks>
public class UnspentOutputReference
{
/// <summary>
/// The account associated with this UTXO
/// </summary>
public HdAccount Account { get; set; }
/// <summary>
/// The address associated with this UTXO
/// </summary>
public HdAddress Address { get; set; }
/// <summary>
/// The transaction representing the UTXO.
/// </summary>
public TransactionData Transaction { get; set; }
/// <summary>
/// Convert the <see cref="TransactionData"/> to an <see cref="OutPoint"/>
/// </summary>
/// <returns>The corresponding <see cref="OutPoint"/>.</returns>
public OutPoint ToOutPoint()
{
return new OutPoint(this.Transaction.Id, (uint)this.Transaction.Index);
}
}
}
| 40.267606 | 153 | 0.589204 | [
"MIT"
] | ArcSin2000X/StratisBitcoinFullNode | src/Stratis.Bitcoin.Features.Wallet/Wallet.cs | 42,887 | C# |
using System.Collections.Generic;
/*
* Copyright (C) 2016 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
namespace com.opengamma.strata.pricer.option
{
//JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#:
// import static com.opengamma.strata.collect.TestHelper.assertSerialization;
//JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#:
// import static com.opengamma.strata.collect.TestHelper.coverBeanEquals;
//JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#:
// import static com.opengamma.strata.collect.TestHelper.coverImmutableBean;
//JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#:
// import static org.testng.Assert.assertEquals;
//JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#:
// import static org.testng.Assert.assertFalse;
using Test = org.testng.annotations.Test;
using DoubleArray = com.opengamma.strata.collect.array.DoubleArray;
using DoubleMatrix = com.opengamma.strata.collect.array.DoubleMatrix;
using Pair = com.opengamma.strata.collect.tuple.Pair;
using ValueType = com.opengamma.strata.market.ValueType;
/// <summary>
/// Tests <seealso cref="RawOptionData"/>.
/// </summary>
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public class RawOptionDataTest
public class RawOptionDataTest
{
private static readonly DoubleArray MONEYNESS = DoubleArray.of(-0.010, 0.00, 0.0100, 0.0200);
private static readonly DoubleArray STRIKES = DoubleArray.of(-0.0050, 0.0050, 0.0150, 0.0250);
private static readonly IList<Period> EXPIRIES = new List<Period>();
static RawOptionDataTest()
{
EXPIRIES.Add(Period.ofMonths(1));
EXPIRIES.Add(Period.ofMonths(3));
EXPIRIES.Add(Period.ofYears(1));
}
private static readonly DoubleMatrix DATA_FULL = DoubleMatrix.ofUnsafe(new double[][]
{
new double[] {0.08, 0.09, 0.10, 0.11},
new double[] {0.09, 0.10, 0.11, 0.12},
new double[] {0.10, 0.11, 0.12, 0.13}
});
private static readonly DoubleMatrix DATA_SPARSE = DoubleMatrix.ofUnsafe(new double[][]
{
new double[] {Double.NaN, Double.NaN, Double.NaN, Double.NaN},
new double[] {Double.NaN, 0.10, 0.11, 0.12},
new double[] {0.10, 0.11, 0.12, 0.13}
});
private static readonly DoubleMatrix ERROR = DoubleMatrix.ofUnsafe(new double[][]
{
new double[] {1.0e-4, 1.0e-4, 1.0e-4, 1.0e-4},
new double[] {1.0e-4, 1.0e-4, 1.0e-4, 1.0e-4},
new double[] {1.0e-3, 1.0e-3, 1.0e-3, 1.0e-3}
});
//-------------------------------------------------------------------------
public virtual void of()
{
RawOptionData test = sut();
assertEquals(test.Strikes, MONEYNESS);
assertEquals(test.StrikeType, ValueType.SIMPLE_MONEYNESS);
assertEquals(test.Data, DATA_FULL);
assertEquals(test.DataType, ValueType.NORMAL_VOLATILITY);
}
public virtual void ofBlackVolatility()
{
double shift = 0.0075;
RawOptionData test = RawOptionData.ofBlackVolatility(EXPIRIES, STRIKES, ValueType.STRIKE, DATA_SPARSE, shift);
assertEquals(test.Strikes, STRIKES);
assertEquals(test.StrikeType, ValueType.STRIKE);
assertEquals(test.Data, DATA_SPARSE);
assertEquals(test.DataType, ValueType.BLACK_VOLATILITY);
assertEquals(test.Shift, double?.of(shift));
assertFalse(test.Error.Present);
}
public virtual void available_smile_at_expiry()
{
double shift = 0.0075;
RawOptionData test = RawOptionData.ofBlackVolatility(EXPIRIES, STRIKES, ValueType.STRIKE, DATA_SPARSE, shift);
DoubleArray[] strikesAvailable = new DoubleArray[3];
strikesAvailable[0] = DoubleArray.EMPTY;
strikesAvailable[1] = DoubleArray.of(0.0050, 0.0150, 0.0250);
strikesAvailable[2] = DoubleArray.of(-0.0050, 0.0050, 0.0150, 0.0250);
DoubleArray[] volAvailable = new DoubleArray[3];
volAvailable[0] = DoubleArray.EMPTY;
volAvailable[1] = DoubleArray.of(0.10, 0.11, 0.12);
volAvailable[2] = DoubleArray.of(0.10, 0.11, 0.12, 0.13);
for (int i = 0; i < DATA_SPARSE.rowCount(); i++)
{
Pair<DoubleArray, DoubleArray> smile = test.availableSmileAtExpiry(EXPIRIES[i]);
assertEquals(smile.First, strikesAvailable[i]);
}
}
public virtual void of_error()
{
RawOptionData test = sut3();
assertEquals(test.Strikes, MONEYNESS);
assertEquals(test.StrikeType, ValueType.SIMPLE_MONEYNESS);
assertEquals(test.Data, DATA_FULL);
assertEquals(test.DataType, ValueType.NORMAL_VOLATILITY);
assertEquals(test.Error.get(), ERROR);
}
public virtual void ofBlackVolatility_error()
{
double shift = 0.0075;
RawOptionData test = RawOptionData.ofBlackVolatility(EXPIRIES, STRIKES, ValueType.STRIKE, DATA_SPARSE, ERROR, shift);
assertEquals(test.Strikes, STRIKES);
assertEquals(test.StrikeType, ValueType.STRIKE);
assertEquals(test.Data, DATA_SPARSE);
assertEquals(test.DataType, ValueType.BLACK_VOLATILITY);
assertEquals(test.Shift, double?.of(shift));
assertEquals(test.Error.get(), ERROR);
}
//-------------------------------------------------------------------------
public virtual void coverage()
{
RawOptionData test = sut();
coverImmutableBean(test);
RawOptionData test2 = sut2();
coverBeanEquals(test, test2);
}
public virtual void test_serialization()
{
RawOptionData test = RawOptionData.of(EXPIRIES, MONEYNESS, ValueType.SIMPLE_MONEYNESS, DATA_FULL, ValueType.BLACK_VOLATILITY);
assertSerialization(test);
}
//-------------------------------------------------------------------------
internal static RawOptionData sut()
{
return RawOptionData.of(EXPIRIES, MONEYNESS, ValueType.SIMPLE_MONEYNESS, DATA_FULL, ValueType.NORMAL_VOLATILITY);
}
internal static RawOptionData sut2()
{
IList<Period> expiries2 = new List<Period>();
expiries2.Add(Period.ofMonths(3));
expiries2.Add(Period.ofYears(1));
expiries2.Add(Period.ofYears(5));
RawOptionData test2 = RawOptionData.of(expiries2, STRIKES, ValueType.STRIKE, DATA_SPARSE, ERROR, ValueType.BLACK_VOLATILITY);
return test2;
}
internal static RawOptionData sut3()
{
return RawOptionData.of(EXPIRIES, MONEYNESS, ValueType.SIMPLE_MONEYNESS, DATA_FULL, ERROR, ValueType.NORMAL_VOLATILITY);
}
}
} | 38.538922 | 128 | 0.704009 | [
"Apache-2.0"
] | ckarcz/Strata.ConvertedToCSharp | modules/pricer/src/test/java/com/opengamma/strata/pricer/option/RawOptionDataTest.cs | 6,438 | C# |
/**
* Copyright 2013 Canada Health Infoway, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: $LastChangedBy: gng $
* Last modified: $LastChangedDate: 2015-11-19 18:20:12 -0500 (Fri, 30 Jan 2015) $
* Revision: $LastChangedRevision: 9755 $
*/
namespace Ca.Infoway.Messagebuilder.Transport.Rest
{
/// <summary>sharpen.ignore - transport - TBD!</summary>
public interface Client
{
/*HttpState GetState();
HttpClientParams GetParams();*/
int ExecuteMethod(PostMethod method);
}
}
| 28.916667 | 82 | 0.710855 | [
"ECL-2.0",
"Apache-2.0"
] | CanadaHealthInfoway/message-builder-dotnet | message-builder-core/Main/Ca/Infoway/Messagebuilder/Transport/Rest/Client.cs | 1,041 | C# |
using Microsoft.AspNetCore.Identity;
namespace Trov.IdentityServer4.Admin.Helpers.Identity
{
/// <inheritdoc />
/// <summary>
/// If you want to create localization for Asp.Net Identity - it is one way how do that - override methods here
/// And register this class into DI system - services.AddTransient - IdentityErrorDescriber, IdentityErrorMessages
/// Or install package with specific language - https://www.nuget.org/packages?q=Microsoft.AspNet.Identity.Core
/// </summary>
public class IdentityErrorMessages : IdentityErrorDescriber
{
}
}
| 37.0625 | 118 | 0.716695 | [
"MIT"
] | ATronMorebis/IdentityServer4.Admin.MySql | src/Trov.IdentityServer4.Admin/Helpers/Identity/IdentityErrorMessages.cs | 595 | C# |
using Microsoft.Extensions.Logging;
using PS.Shared.HttpClients;
using System.Threading;
using System.Threading.Tasks;
namespace PS.Web.Scraper.Interfaces
{
public interface IWebScraper
{
public Task Scrape(ScraperTextClient client, ILogger logger, CancellationToken token);
}
public interface ITestWebScraper : IWebScraper { }
public interface I5SecondWebScraper : IWebScraper { }
public interface I30SecondWebScraper : IWebScraper { }
public interface I1MinuteWebScraper : IWebScraper { }
} | 26.7 | 94 | 0.758427 | [
"Apache-2.0"
] | Unskilledcrab/Polysense | PS.Web.Scraper/Interfaces/IWebScraper.cs | 536 | C# |
#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Pchp.Core;
using Pchp.Core.Utilities;
using Pchp.Library.Streams;
namespace Peachpie.Library.Network
{
[PhpExtension(CURLConstants.ExtensionName)]
public static class CURLFunctions
{
/// <summary>
/// Create a CURLFile object.
/// </summary>
public static CURLFile/*!*/curl_file_create(string filename, string? mimetype = null, string? postname = null) => new CURLFile(filename, mimetype, postname);
public static CURLResource/*!*/curl_init(string? url = null) => new CURLResource() { Url = url };
/// <summary>
/// Close a cURL session.
/// </summary>
public static void curl_close(Context ctx, CURLResource ch)
{
if (ch != null)
{
if (ch.TryGetOption<CurlOption_CookieJar>(out var jar))
{
jar.PrintCookies(ctx, ch);
}
//
ch.Dispose();
}
else
{
PhpException.ArgumentNull(nameof(ch));
}
}
/// <summary>
/// Reset all options set on the given cURL handle to the default values.
/// </summary>
public static void curl_reset(CURLResource ch)
{
if (ch == null)
{
PhpException.ArgumentNull(nameof(ch));
return;
}
ch.ResetOptions();
}
/// <summary>
/// Sets an option on the given cURL session handle.
/// </summary>
public static bool curl_setopt(
[ImportValue(ImportValueAttribute.ValueSpec.CallerClass)] RuntimeTypeHandle callerCtx,
CURLResource ch, int option, PhpValue value)
{
return ch.TrySetOption(option, value, callerCtx);
}
/// <summary>
/// URL encodes the given string.
/// </summary>
public static string curl_escape(CURLResource ch, string str) => WebUtility.UrlEncode(str);
/// <summary>
/// Decodes the given URL encoded string.
/// </summary>
public static string curl_unescape(CURLResource ch, string str) => WebUtility.UrlDecode(str);
/// <summary>
/// Gets cURL version information.
/// </summary>
/// <param name="version">Ignored.
/// Should be set to the version of this functionality by the time you write your program.
/// This way, libcurl will always return a proper struct that your program understands, while programs
/// in the future might get a different struct.
/// <c>CURLVERSION_NOW</c> will be the most recent one for the library you have installed.</param>
/// <returns>Array with version information.</returns>
public static PhpArray curl_version(int version = CURLConstants.CURLVERSION_NOW)
{
// version_number cURL 24 bit version number
// version cURL version number, as a string
// ssl_version_number OpenSSL 24 bit version number
// ssl_version OpenSSL version number, as a string
// libz_version zlib version number, as a string
// host Information about the host where cURL was built
// age
// features A bitmask of the CURL_VERSION_XXX constants
// protocols An array of protocols names supported by cURL
var fakever = CURLConstants.FakeCurlVersion;
return new PhpArray(9)
{
{"version_number", (fakever.Major << 16) | (fakever.Minor << 8) | (fakever.Build) },
{"age", CURLConstants.CURLVERSION_NOW},
{"features", CURLConstants.CURL_VERSION_HTTP2|CURLConstants.CURL_VERSION_IPV6|CURLConstants.CURL_VERSION_KERBEROS4|CURLConstants.CURL_VERSION_LIBZ|CURLConstants.CURL_VERSION_SSL},
{"ssl_version_number", 0}, // always 0
{"version", fakever.ToString()},
{"host", "dotnet"},
{"ssl_version", ""},
{"libz_version", "1"},
{"protocols", new PhpArray(){ "http", "https", "ftp" } },
};
}
/// <summary>
/// Set multiple options for a cURL transfer.
/// </summary>
public static bool curl_setopt_array(
[ImportValue(ImportValueAttribute.ValueSpec.CallerClass)] RuntimeTypeHandle callerCtx,
CURLResource ch, PhpArray options)
{
if (ch == null || !ch.IsValid)
{
PhpException.ArgumentNull(nameof(ch));
return false;
}
if (options != null)
{
var enumerator = options.GetFastEnumerator();
while (enumerator.MoveNext())
{
var key = enumerator.CurrentKey;
if (key.IsInteger && ch.TrySetOption(key.Integer, enumerator.CurrentValue, callerCtx))
{
// ok
continue;
}
else
{
// stop on first fail and return FALSE
return false;
}
}
}
return true;
}
/// <summary>
/// Return the last error number.
/// </summary>
public static int curl_errno(CURLResource ch)
=> (int)(ch?.Result != null ? ch.Result.ErrorCode : CurlErrors.CURLE_OK);
/// <summary>
/// Return a string containing the last error for the current session.
/// </summary>
public static string curl_error(CURLResource ch)
{
if (ch != null && ch.Result != null)
{
var err = ch.Result.ErrorCode;
if (err != CurlErrors.CURLE_OK)
{
return ch.Result.ErrorMessage ?? err.ToString(); // TODO: default error messages in resources
}
}
return string.Empty;
}
/// <summary>
/// Get information regarding a specific transfer.
/// </summary>
public static PhpValue curl_getinfo(CURLResource ch, int option = 0)
{
if (ch == null)
{
PhpException.ArgumentNull(nameof(ch));
return PhpValue.Null;
}
var r = ch.Result ?? CURLResponse.Empty;
switch (option)
{
case 0:
// array of all information
var arr = new PhpArray(38)
{
{ "url", ch.Url ?? string.Empty },
{ "content_type", r.ContentType },
{ "http_code", (long)r.StatusCode },
{ "header_size", r.HeaderSize },
{ "filetime", r.LastModifiedTimeStamp },
{ "total_time", r.TotalTime.TotalSeconds },
{ "download_content_length", r.ContentLength },
{ "redirect_url", ch.FollowLocation && r.ResponseUri != null ? r.ResponseUri.AbsoluteUri : string.Empty },
//{ "http_version", CURL_HTTP_VERSION_*** }
//{ "protocol", CURLPROTO_*** },
//{ "scheme", STRING },
};
if (ch.RequestHeaders != null)
{
arr["request_header"] = ch.RequestHeaders;
}
return arr;
case CURLConstants.CURLINFO_EFFECTIVE_URL:
return ch.Url ?? string.Empty;
case CURLConstants.CURLINFO_REDIRECT_URL:
return (ch.FollowLocation && r.ResponseUri != null ? r.ResponseUri.AbsoluteUri : string.Empty);
case CURLConstants.CURLINFO_HTTP_CODE:
return (int)r.StatusCode;
case CURLConstants.CURLINFO_FILETIME:
return r.LastModifiedTimeStamp;
case CURLConstants.CURLINFO_CONTENT_TYPE:
return r.ContentType;
case CURLConstants.CURLINFO_CONTENT_LENGTH_DOWNLOAD:
return r.ContentLength;
case CURLConstants.CURLINFO_TOTAL_TIME:
return r.TotalTime.TotalSeconds;
case CURLConstants.CURLINFO_PRIVATE:
return Operators.IsSet(r.Private) ? r.Private.DeepCopy() : PhpValue.False;
case CURLConstants.CURLINFO_COOKIELIST:
return ((ch.CookieContainer != null && ch.Result != null) ? CreateCookiePhpArray(ch.Result.Cookies) : PhpArray.Empty);
case CURLConstants.CURLINFO_HEADER_SIZE:
return r.HeaderSize;
case CURLConstants.CURLINFO_HEADER_OUT:
return r.RequestHeaders ?? PhpValue.False;
default:
PhpException.ArgumentValueNotSupported(nameof(option), option);
return PhpValue.False;
}
}
internal static IEnumerable<string> CookiesToNetscapeStyle(CookieCollection cookies)
{
if (cookies == null || cookies.Count == 0)
{
yield break;
}
foreach (Cookie c in cookies)
{
string prefix = c.HttpOnly ? "#HttpOnly_" : "";
string subdomainAccess = "TRUE"; // Simplified
string secure = c.Secure.ToString().ToUpperInvariant();
long expires = (c.Expires.Ticks == 0) ? 0 : DateTimeUtils.UtcToUnixTimeStamp(c.Expires);
yield return $"{prefix}{c.Domain}\t{subdomainAccess}\t{c.Path}\t{secure}\t{expires}\t{c.Name}\t{c.Value}";
}
}
static PhpArray CreateCookiePhpArray(CookieCollection cookies)
{
return new PhpArray(CookiesToNetscapeStyle(cookies));
}
static void AddCookies(CookieCollection from, CookieContainer container)
{
if (from != null)
{
container?.Add(from);
}
}
static Uri? TryCreateUri(CURLResource ch)
{
var url = ch.Url;
if (string.IsNullOrEmpty(url))
{
return null;
}
//
if (url.IndexOf("://", StringComparison.Ordinal) == -1)
{
url = string.Concat(ch.DefaultSheme, "://", url);
}
// TODO: implicit port
//
Uri.TryCreate(url, UriKind.Absolute, out Uri result);
return result;
}
static async Task<CURLResponse> ProcessHttpResponseTask(Context ctx, CURLResource ch, Task<WebResponse> responseTask)
{
try
{
using (var response = (HttpWebResponse)responseTask.Result)
{
return new CURLResponse(await ProcessResponse(ctx, ch, response), response, ch);
}
}
catch (AggregateException agEx)
{
var ex = agEx.InnerException;
ch.VerboseOutput(ex.ToString());
if (ex is WebException webEx)
{
// TODO: ch.FailOnError ?
var exception = webEx.InnerException ?? webEx;
switch (webEx.Status)
{
case WebExceptionStatus.ProtocolError:
// actually ok, 301, 500, etc .. process the response:
return new CURLResponse(await ProcessResponse(ctx, ch, (HttpWebResponse)webEx.Response), (HttpWebResponse)webEx.Response, ch);
case WebExceptionStatus.Timeout:
return CURLResponse.CreateError(CurlErrors.CURLE_OPERATION_TIMEDOUT, exception);
case WebExceptionStatus.TrustFailure:
return CURLResponse.CreateError(CurlErrors.CURLE_SSL_CACERT, exception);
default:
return CURLResponse.CreateError(CurlErrors.CURLE_COULDNT_CONNECT, exception);
}
}
else if (ex is ProtocolViolationException)
{
return CURLResponse.CreateError(CurlErrors.CURLE_FAILED_INIT, ex);
}
else if (ex is CryptographicException)
{
return CURLResponse.CreateError(CurlErrors.CURLE_SSL_CERTPROBLEM, ex);
}
else
{
throw ex;
}
}
}
static readonly IWebProxy s_DefaultProxy = new WebProxy();
static Task<WebResponse> ExecHttpRequestInternalAsync(Context ctx, CURLResource ch, Uri uri)
{
var req = WebRequest.CreateHttp(uri);
// setup request:
Debug.Assert(ch.Method != null, "Method == null");
req.Method = ch.Method;
req.AllowAutoRedirect = ch.FollowLocation && ch.MaxRedirects != 0;
req.Timeout = ch.Timeout <= 0 ? System.Threading.Timeout.Infinite : ch.Timeout;
req.ContinueTimeout = ch.ContinueTimeout;
req.Accept = "*/*"; // default value
if (req.AllowAutoRedirect)
{
// equal or less than 0 will cause exception
req.MaximumAutomaticRedirections = ch.MaxRedirects < 0 ? int.MaxValue : ch.MaxRedirects;
}
if (ch.CookieContainer != null)
{
if (ch.Result != null)
{
// pass cookies from previous response to the request
AddCookies(ch.Result.Cookies, ch.CookieContainer);
}
req.CookieContainer = ch.CookieContainer;
}
//req.AutomaticDecompression = (DecompressionMethods)~0; // NOTICE: this nullify response Content-Length and Content-Encoding
if (ch.CookieHeader != null) TryAddCookieHeader(req, ch.CookieHeader);
if (ch.Username != null) req.Credentials = new NetworkCredential(ch.Username, ch.Password ?? string.Empty);
// TODO: certificate
if (!string.IsNullOrEmpty(ch.ProxyType) && !string.IsNullOrEmpty(ch.ProxyHost))
{
req.Proxy = new WebProxy($"{ch.ProxyType}://{ch.ProxyHost}:{ch.ProxyPort}")
{
Credentials = string.IsNullOrEmpty(ch.ProxyUsername)
? null
: new NetworkCredential(ch.ProxyUsername, ch.ProxyPassword ?? string.Empty)
};
}
else
{
// by default, curl does not go through system proxy
req.Proxy = s_DefaultProxy;
}
//
ch.ApplyOptions(ctx, req);
// make request:
// GET, HEAD
if (string.Equals(ch.Method, WebRequestMethods.Http.Get, StringComparison.OrdinalIgnoreCase))
{
WriteRequestStream(ctx, req, ch, ch.ProcessingRequest.Stream);
}
else if (string.Equals(ch.Method, WebRequestMethods.Http.Head, StringComparison.OrdinalIgnoreCase))
{
//
}
// POST
else if (string.Equals(ch.Method, WebRequestMethods.Http.Post, StringComparison.OrdinalIgnoreCase))
{
ProcessPost(ctx, req, ch);
}
// PUT
else if (string.Equals(ch.Method, WebRequestMethods.Http.Put, StringComparison.OrdinalIgnoreCase))
{
ProcessPut(ctx, req, ch);
}
// DELETE, or custom method
else
{
// custom method, nothing to do
}
//
if (ch.StoreRequestHeaders)
{
ch.RequestHeaders = HttpHeaders.HeaderString(req); // and restore it when constructing CURLResponse
}
//
return req.GetResponseAsync();
}
static void ProcessPut(Context ctx, HttpWebRequest req, CURLResource ch)
{
WriteRequestStream(ctx, req, ch, ch.ProcessingRequest.Stream);
}
static void ProcessPost(Context ctx, HttpWebRequest req, CURLResource ch)
{
byte[] bytes;
if (ch.PostFields.IsPhpArray(out var arr) && arr != null)
{
string boundary = "----------" + DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture);
string contentType = "multipart/form-data; boundary=" + boundary;
bytes = GetMultipartFormData(ctx, arr, boundary);
req.ContentType = contentType;
}
else
{
bytes = ch.PostFields.ToBytes(ctx);
if (string.IsNullOrEmpty(req.ContentType))
{
req.ContentType = "application/x-www-form-urlencoded";
}
}
req.ContentLength = bytes.Length;
using (var stream = req.GetRequestStream())
{
stream.Write(bytes);
}
}
static bool WriteRequestStream(Context ctx, HttpWebRequest req, CURLResource ch, PhpStream infile)
{
if (infile != null)
{
using (var stream = req.GetRequestStream())
{
if (ch.ReadFunction == null)
{
// req.ContentLength = bytes.Length;
infile.RawStream.CopyTo(stream);
return true;
}
else
{
for (; ; )
{
var result = ch.ReadFunction.Invoke(ctx, ch, infile, ch.BufferSize);
if (result.IsString() || !result.IsEmpty)
{
var bytes = result.ToBytes(ctx);
if (bytes.Length != 0)
{
stream.Write(bytes);
continue;
}
}
break;
}
return true;
}
}
}
return false;
}
static byte[] GetMultipartFormData(Context ctx, PhpArray postParameters, string boundary)
{
var encoding = Encoding.ASCII;
var formDataStream = new MemoryStream();
bool needsCLRF = false;
var param = postParameters.GetFastEnumerator();
while (param.MoveNext())
{
// Skip it on the first parameter, add it to subsequent parameters.
if (needsCLRF)
{
formDataStream.Write(encoding.GetBytes("\r\n"));
}
needsCLRF = true;
if (param.CurrentValue.AsObject() is CURLFile fileToUpload)
{
// Add just the first part of this param, since we will write the file data directly to the Stream
string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n",
boundary,
param.CurrentKey.ToString(),
string.IsNullOrEmpty(fileToUpload.postname) ? fileToUpload.name : fileToUpload.postname,
string.IsNullOrEmpty(fileToUpload.mime) ? "application/octet-stream" : fileToUpload.mime);
formDataStream.Write(encoding.GetBytes(header));
// Write the file data directly to the Stream, rather than serializing it to a string.
formDataStream.Write(File.ReadAllBytes(fileToUpload.name));
}
else
{
string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n",
boundary,
param.CurrentKey.ToString());
formDataStream.Write(encoding.GetBytes(postData));
formDataStream.Write(param.CurrentValue.ToBytes(ctx));
}
}
// Add the end of the request. Start with a newline
string footer = "\r\n--" + boundary + "--\r\n";
formDataStream.Write(encoding.GetBytes(footer));
// Dump the Stream into a byte[]
return formDataStream.ToArray();
}
/// <summary>
/// Add the Cookie header if not present.
/// </summary>
static void TryAddCookieHeader(WebRequest req, string value)
{
if (req.Headers.Get(HttpRequestHeader.Cookie.ToString()) == null)
{
req.Headers.Add(HttpRequestHeader.Cookie, value);
}
}
static async Task<PhpValue> ProcessResponse(Context ctx, CURLResource ch, HttpWebResponse response)
{
// in case we are returning the response value
var returnstream = ch.ProcessingResponse.Method == ProcessMethodEnum.RETURN
? new MemoryStream()
: null;
// handle headers
if (!ch.ProcessingHeaders.IsEmpty)
{
var statusHeaders = HttpHeaders.StatusHeader(response) + HttpHeaders.HeaderSeparator; // HTTP/1.1 xxx xxx\r\n
Stream? outputHeadersStream = null;
switch (ch.ProcessingHeaders.Method)
{
case ProcessMethodEnum.RETURN:
case ProcessMethodEnum.STDOUT:
outputHeadersStream = (returnstream ?? ctx.OutputStream);
goto default;
case ProcessMethodEnum.FILE:
outputHeadersStream = ch.ProcessingHeaders.Stream.RawStream;
goto default;
case ProcessMethodEnum.USER:
// pass headers one by one,
// in original implementation we should pass them as they are read from socket:
ch.ProcessingHeaders.User.Invoke(ctx, new[] {
PhpValue.FromClass(ch),
PhpValue.Create(statusHeaders)
});
for (int i = 0; i < response.Headers.Count; i++)
{
var key = response.Headers.GetKey(i);
var value = response.Headers.Get(i);
if (key == null || key.Length != 0)
{
// header
ch.ProcessingHeaders.User.Invoke(ctx, new[] {
PhpValue.FromClr(ch),
PhpValue.Create(key + ": " + value + HttpHeaders.HeaderSeparator),
});
}
}
// \r\n
ch.ProcessingHeaders.User.Invoke(ctx, new[] {
PhpValue.FromClr(ch),
PhpValue.Create(HttpHeaders.HeaderSeparator)
});
break;
default:
if (outputHeadersStream != null)
{
await outputHeadersStream.WriteAsync(Encoding.ASCII.GetBytes(statusHeaders));
await outputHeadersStream.WriteAsync(response.Headers.ToByteArray());
}
else
{
Debug.Fail("Unexpected ProcessingHeaders " + ch.ProcessingHeaders.Method);
}
break;
}
}
var stream = response.GetResponseStream();
// gzip decode if necessary
if (response.ContentEncoding == "gzip") // TODO: // && ch.AcceptEncoding.Contains("gzip") ??
{
ch.VerboseOutput("Decompressing the output stream using GZipStream.");
stream = new GZipStream(stream, CompressionMode.Decompress, leaveOpen: false);
}
// read into output stream:
switch (ch.ProcessingResponse.Method)
{
case ProcessMethodEnum.STDOUT: await stream.CopyToAsync(ctx.OutputStream); break;
case ProcessMethodEnum.RETURN: stream.CopyTo(returnstream); break;
case ProcessMethodEnum.FILE: await stream.CopyToAsync(ch.ProcessingResponse.Stream.RawStream); break;
case ProcessMethodEnum.USER:
if (response.ContentLength != 0)
{
// preallocate a buffer to read to,
// this should be according to PHP's behavior and slightly more effective than memory stream
byte[] buffer = new byte[ch.BufferSize > 0 ? ch.BufferSize : 2048];
int bufferread;
while ((bufferread = stream.Read(buffer, 0, buffer.Length)) > 0)
{
ch.ProcessingResponse.User.Invoke(ctx, new[]
{
PhpValue.FromClr(ch),
PhpValue.Create(new PhpString(buffer.AsSpan(0, bufferread).ToArray())), // clone the array and pass to function
});
}
}
break;
case ProcessMethodEnum.IGNORE: break;
}
//
stream.Dispose();
//
if (response.ResponseUri != null)
{
ch.Url = response.ResponseUri.AbsoluteUri;
}
return (returnstream != null)
? PhpValue.Create(new PhpString(returnstream.ToArray()))
: PhpValue.True;
}
static bool IsProtocol(CURLResource ch, Uri uri, string scheme, int proto)
{
return
string.Equals(uri.Scheme, scheme, StringComparison.OrdinalIgnoreCase) &&
(ch.Protocols & proto) != 0;
}
static void StartRequestExecution(Context ctx, CURLResource ch)
{
ch.StartTime = DateTime.UtcNow;
var uri = TryCreateUri(ch);
if (uri == null)
{
ch.VerboseOutput("Cannot create URI for '" + ch.Url + "'.");
ch.Result = CURLResponse.CreateError(CurlErrors.CURLE_URL_MALFORMAT);
}
else if (
IsProtocol(ch, uri, "http", CURLConstants.CURLPROTO_HTTP) ||
IsProtocol(ch, uri, "https", CURLConstants.CURLPROTO_HTTPS))
{
ch.VerboseOutput("Initiating HTTP(S) request.");
ch.ResponseTask = ExecHttpRequestInternalAsync(ctx, ch, uri);
ch.Result = null;
}
else
{
ch.VerboseOutput("The protocol '" + uri.Scheme + "' is not supported.");
ch.Result = CURLResponse.CreateError(CurlErrors.CURLE_UNSUPPORTED_PROTOCOL);
}
}
static void EndRequestExecution(Context ctx, CURLResource ch)
{
if (ch.ResponseTask != null)
{
ch.Result = ProcessHttpResponseTask(ctx, ch, ch.ResponseTask).GetAwaiter().GetResult();
ch.ResponseTask = null;
}
ch.Result.TotalTime = (DateTime.UtcNow - ch.StartTime);
if (ch.TryGetOption<CurlOption_Private>(out var opt_private))
{
ch.Result.Private = opt_private.OptionValue;
}
}
/// <summary>
/// Perform a cURL session.
/// </summary>
public static PhpValue curl_exec(Context ctx, CURLResource ch)
{
StartRequestExecution(ctx, ch);
EndRequestExecution(ctx, ch);
return ch.Result.ExecValue;
}
/// <summary>
/// Return the content of a cURL handle if <see cref="CURLConstants.CURLOPT_RETURNTRANSFER"/> is set.
/// </summary>
public static PhpValue curl_multi_getcontent(CURLResource ch)
{
if (ch.ProcessingResponse.Method == ProcessMethodEnum.RETURN && ch.Result != null && Operators.IsSet(ch.Result.ExecValue))
{
return ch.Result.ExecValue;
}
else
{
return PhpValue.Null;
}
}
/// <summary>
/// Return a new cURL multi handle.
/// </summary>
public static CURLMultiResource/*!*/curl_multi_init() => new CURLMultiResource();
/// <summary>
/// Close a set of cURL handles.
/// </summary>
public static void curl_multi_close(CURLMultiResource mh) => mh?.Dispose();
/// <summary>
/// Add a normal cURL handle to a cURL multi handle.
/// </summary>
public static int curl_multi_add_handle(CURLMultiResource mh, CURLResource ch) => (int)mh.TryAddHandle(ch);
/// <summary>
/// Remove a multi handle from a set of cURL handles
/// </summary>
/// <remarks>
/// Removes a given <paramref name="ch"/> handle from the given <paramref name="mh"/> handle.
/// When the <paramref name="ch"/> handle has been removed, it is again perfectly legal to run
/// <see cref="curl_exec(Context, CURLResource)"/> on this handle. Removing the <paramref name="ch"/>
/// handle while being used, will effectively halt the transfer in progress involving that handle.
/// </remarks>
public static int curl_multi_remove_handle(CURLMultiResource mh, CURLResource ch)
{
if (mh.Handles.Remove(ch) && ch.ResponseTask != null)
{
// We will simply remove the only reference to the ongoing request and let the framework either
// finish it or cancel it
ch.ResponseTask = null;
}
return CURLConstants.CURLM_OK;
}
/// <summary>
/// Run the sub-connections of the current cURL handle.
/// </summary>
public static int curl_multi_exec(Context ctx, CURLMultiResource mh, out int still_running)
{
int runningCount = 0;
foreach (var handle in mh.Handles)
{
if (handle.ResponseTask != null)
{
if (handle.ResponseTask.IsCompleted)
{
EndRequestExecution(ctx, handle);
mh.AddResultMessage(handle);
}
else
{
runningCount++;
}
}
else if (handle.Result == null)
{
StartRequestExecution(ctx, handle);
runningCount++;
}
}
still_running = runningCount;
return CURLConstants.CURLM_OK;
}
/// <summary>
/// Get information about the current transfers.
/// </summary>
[return: CastToFalse]
public static PhpArray? curl_multi_info_read(CURLMultiResource mh) => curl_multi_info_read(mh, out _);
/// <summary>
/// Get information about the current transfers.
/// </summary>
[return: CastToFalse]
public static PhpArray? curl_multi_info_read(CURLMultiResource mh, out int msgs_in_queue)
{
if (mh.MessageQueue.Count == 0)
{
msgs_in_queue = 0;
return null;
}
else
{
var msg = mh.MessageQueue.Dequeue();
msgs_in_queue = mh.MessageQueue.Count;
return msg;
}
}
/// <summary>
/// Wait for activity on any curl_multi connection.
/// </summary>
public static int curl_multi_select(CURLMultiResource mh, float timeout = 1.0f)
{
var tasks = mh.Handles
.Select(h => h.ResponseTask)
.Where(t => t != null)
.ToArray();
if (tasks.Length == 0)
{
return 0;
}
// Already completed and not yet processed by curl_multi_exec -> no waiting
int finished = tasks.Count(t => t.IsCompleted);
if (finished > 0 || timeout == 0.0f)
{
return finished;
}
Task.WaitAny(tasks, TimeSpan.FromSeconds(timeout));
return tasks.Count(t => t.IsCompleted);
}
/// <summary>
/// Return the last multi curl error number.
/// </summary>
public static int curl_multi_errno(CURLMultiResource mh) => (int)mh.LastError;
/// <summary>
/// Return string describing error code.
/// </summary>
public static string curl_multi_strerror(CurlMultiErrors errornum) => CURLConstants.GetErrorString(errornum);
/// <summary>
/// Set an option for the cURL multi handle.
/// </summary>
public static bool curl_multi_setopt(CURLMultiResource sh, int option, PhpValue value)
{
// We keep the responsibility of multiple request handling completely on .NET framework
PhpException.FunctionNotSupported(nameof(curl_multi_setopt));
return false;
}
}
}
| 38.488398 | 195 | 0.505397 | [
"Apache-2.0"
] | G7h7/peachpie | src/Peachpie.Library.Network/CURLFunctions.cs | 34,834 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Buffers;
using System.ComponentModel;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Blobs.Specialized;
using Azure.Storage.Cryptography;
using Metadata = System.Collections.Generic.IDictionary<string, string>;
using Tags = System.Collections.Generic.IDictionary<string, string>;
#pragma warning disable SA1402 // File may only contain a single type
namespace Azure.Storage.Blobs
{
/// <summary>
/// The <see cref="BlobClient"/> allows you to manipulate Azure Storage
/// blobs.
/// </summary>
public class BlobClient : BlobBaseClient
{
#region ctors
/// <summary>
/// Initializes a new instance of the <see cref="BlobClient"/>
/// class for mocking.
/// </summary>
protected BlobClient()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BlobClient"/>
/// class.
/// </summary>
/// <param name="connectionString">
/// A connection string includes the authentication information
/// required for your application to access data in an Azure Storage
/// account at runtime.
///
/// For more information,
/// <see href="https://docs.microsoft.com/azure/storage/common/storage-configure-connection-string">
/// Configure Azure Storage connection strings</see>.
/// </param>
/// <param name="blobContainerName">
/// The name of the container containing this blob.
/// </param>
/// <param name="blobName">
/// The name of this blob.
/// </param>
public BlobClient(string connectionString, string blobContainerName, string blobName)
: base(connectionString, blobContainerName, blobName)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BlobClient"/>
/// class.
/// </summary>
/// <param name="connectionString">
/// A connection string includes the authentication information
/// required for your application to access data in an Azure Storage
/// account at runtime.
///
/// For more information,
/// <see href="https://docs.microsoft.com/azure/storage/common/storage-configure-connection-string">
/// Configure Azure Storage connection strings</see>.
/// </param>
/// <param name="blobContainerName">
/// The name of the container containing this blob.
/// </param>
/// <param name="blobName">
/// The name of this blob.
/// </param>
/// <param name="options">
/// Optional client options that define the transport pipeline
/// policies for authentication, retries, etc., that are applied to
/// every request.
/// </param>
public BlobClient(string connectionString, string blobContainerName, string blobName, BlobClientOptions options)
: base(connectionString, blobContainerName, blobName, options)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BlobClient"/>
/// class.
/// </summary>
/// <param name="blobUri">
/// A <see cref="Uri"/> referencing the blob that includes the
/// name of the account, the name of the container, and the name of
/// the blob.
/// This is likely to be similar to "https://{account_name}.blob.core.windows.net/{container_name}/{blob_name}".
/// </param>
/// <param name="options">
/// Optional client options that define the transport pipeline
/// policies for authentication, retries, etc., that are applied to
/// every request.
/// </param>
public BlobClient(Uri blobUri, BlobClientOptions options = default)
: base(blobUri, options)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BlobClient"/>
/// class.
/// </summary>
/// <param name="blobUri">
/// A <see cref="Uri"/> referencing the blob that includes the
/// name of the account, the name of the container, and the name of
/// the blob.
/// This is likely to be similar to "https://{account_name}.blob.core.windows.net/{container_name}/{blob_name}".
/// </param>
/// <param name="credential">
/// The shared key credential used to sign requests.
/// </param>
/// <param name="options">
/// Optional client options that define the transport pipeline
/// policies for authentication, retries, etc., that are applied to
/// every request.
/// </param>
public BlobClient(Uri blobUri, StorageSharedKeyCredential credential, BlobClientOptions options = default)
: base(blobUri, credential, options)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BlobClient"/>
/// class.
/// </summary>
/// <param name="blobUri">
/// A <see cref="Uri"/> referencing the blob that includes the
/// name of the account, the name of the container, and the name of
/// the blob.
/// This is likely to be similar to "https://{account_name}.blob.core.windows.net/{container_name}/{blob_name}".
/// Must not contain shared access signature, which should be passed in the second parameter.
/// </param>
/// <param name="credential">
/// The shared access signature credential used to sign requests.
/// </param>
/// <param name="options">
/// Optional client options that define the transport pipeline
/// policies for authentication, retries, etc., that are applied to
/// every request.
/// </param>
/// <remarks>
/// This constructor should only be used when shared access signature needs to be updated during lifespan of this client.
/// </remarks>
public BlobClient(Uri blobUri, AzureSasCredential credential, BlobClientOptions options = default)
: base(blobUri, credential, options)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BlobClient"/>
/// class.
/// </summary>
/// <param name="blobUri">
/// A <see cref="Uri"/> referencing the blob that includes the
/// name of the account, the name of the container, and the name of
/// the blob.
/// This is likely to be similar to "https://{account_name}.blob.core.windows.net/{container_name}/{blob_name}".
/// </param>
/// <param name="credential">
/// The token credential used to sign requests.
/// </param>
/// <param name="options">
/// Optional client options that define the transport pipeline
/// policies for authentication, retries, etc., that are applied to
/// every request.
/// </param>
public BlobClient(Uri blobUri, TokenCredential credential, BlobClientOptions options = default)
: base(blobUri, credential, options)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BlobClient"/>
/// class.
/// </summary>
/// <param name="blobUri">
/// A <see cref="Uri"/> referencing the blob that includes the
/// name of the account, the name of the container, and the name of
/// the blob.
/// This is likely to be similar to "https://{account_name}.blob.core.windows.net/{container_name}/{blob_name}".
/// </param>
/// <param name="pipeline">
/// The transport pipeline used to send every request.
/// </param>
/// <param name="storageSharedKeyCredential">
/// The shared key credential used to sign requests.
/// </param>
/// <param name="version">
/// The version of the service to use when sending requests.
/// </param>
/// <param name="clientDiagnostics">Client diagnostics.</param>
/// <param name="customerProvidedKey">Customer provided key.</param>
/// <param name="clientSideEncryption">Client-side encryption options.</param>
/// <param name="encryptionScope">Encryption scope.</param>
internal BlobClient(
Uri blobUri,
HttpPipeline pipeline,
StorageSharedKeyCredential storageSharedKeyCredential,
BlobClientOptions.ServiceVersion version,
ClientDiagnostics clientDiagnostics,
CustomerProvidedKey? customerProvidedKey,
ClientSideEncryptionOptions clientSideEncryption,
string encryptionScope)
: base(blobUri, pipeline, storageSharedKeyCredential, version, clientDiagnostics, customerProvidedKey, clientSideEncryption, encryptionScope)
{
}
#endregion ctors
/// <summary>
/// Initializes a new instance of the <see cref="BlobClient"/>
/// class with an identical <see cref="Uri"/> source but the specified
/// <paramref name="snapshot"/> timestamp.
///
/// For more information, see <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/creating-a-snapshot-of-a-blob">
/// Create a snapshot of a blob</see>.
/// </summary>
/// <param name="snapshot">The snapshot identifier.</param>
/// <returns>A new <see cref="BlobClient"/> instance.</returns>
/// <remarks>
/// Pass null or empty string to remove the snapshot returning a URL
/// to the base blob.
/// </remarks>
public new BlobClient WithSnapshot(string snapshot)
{
BlobUriBuilder blobUriBuilder = new BlobUriBuilder(Uri)
{
Snapshot = snapshot
};
return new BlobClient(
blobUriBuilder.ToUri(),
Pipeline,
SharedKeyCredential,
Version,
ClientDiagnostics,
CustomerProvidedKey,
ClientSideEncryption,
EncryptionScope);
}
/// <summary>
/// Initializes a new instance of the <see cref="BlobClient"/>
/// class with an identical <see cref="Uri"/> source but the specified
/// <paramref name="versionId"/> timestamp.
///
/// </summary>
/// <param name="versionId">The version identifier.</param>
/// <returns>A new <see cref="BlobClient"/> instance.</returns>
/// <remarks>
/// Pass null or empty string to remove the version returning a URL
/// to the base blob.
/// </remarks>
public new BlobClient WithVersion(string versionId)
{
BlobUriBuilder blobUriBuilder = new BlobUriBuilder(Uri)
{
VersionId = versionId
};
return new BlobClient(
blobUriBuilder.ToUri(),
Pipeline,
SharedKeyCredential,
Version,
ClientDiagnostics,
CustomerProvidedKey,
ClientSideEncryption,
EncryptionScope);
}
/// <summary>
/// Creates a new instance of the <see cref="BlobClient"/> class, maintaining all the same
/// internals but specifying new <see cref="ClientSideEncryptionOptions"/>.
/// </summary>
/// <param name="clientSideEncryptionOptions">New encryption options. Setting this to <code>default</code> will clear client-side encryption.</param>
/// <returns>New instance with provided options and same internals otherwise.</returns>
protected internal virtual BlobClient WithClientSideEncryptionOptionsCore(ClientSideEncryptionOptions clientSideEncryptionOptions)
{
return new BlobClient(
Uri,
Pipeline,
SharedKeyCredential,
Version,
ClientDiagnostics,
CustomerProvidedKey,
clientSideEncryptionOptions,
EncryptionScope);
}
#region Upload
/// <summary>
/// The <see cref="Upload(Stream)"/> operation creates a new block blob
/// or updates the content of an existing block blob. Updating an
/// existing block blob overwrites any existing metadata on the blob.
///
/// For partial block blob updates and other advanced features, please
/// see <see cref="BlockBlobClient"/>. To create or modify page or
/// append blobs, please see <see cref="PageBlobClient"/> or
/// <see cref="AppendBlobClient"/>.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/put-blob">
/// Put Blob</see>.
/// </summary>
/// <param name="content">
/// A <see cref="Stream"/> containing the content to upload.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual Response<BlobContentInfo> Upload(Stream content) =>
Upload(content, CancellationToken.None);
/// <summary>
/// The <see cref="Upload(string)"/> operation creates a new block blob
/// or updates the content of an existing block blob. Updating an
/// existing block blob overwrites any existing metadata on the blob.
///
/// For partial block blob updates and other advanced features, please
/// see <see cref="BlockBlobClient"/>. To create or modify page or
/// append blobs, please see <see cref="PageBlobClient"/> or
/// <see cref="AppendBlobClient"/>.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/put-blob">
/// Put Blob</see>.
/// </summary>
/// <param name="path">
/// A file path containing the content to upload.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual Response<BlobContentInfo> Upload(string path) =>
Upload(path, CancellationToken.None);
/// <summary>
/// The <see cref="UploadAsync(Stream)"/> operation creates a new block blob
/// or updates the content of an existing block blob. Updating an
/// existing block blob overwrites any existing metadata on the blob.
///
/// For partial block blob updates and other advanced features, please
/// see <see cref="BlockBlobClient"/>. To create or modify page or
/// append blobs, please see <see cref="PageBlobClient"/> or
/// <see cref="AppendBlobClient"/>.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/put-blob">
/// Put Blob</see>.
/// </summary>
/// <param name="content">
/// A <see cref="Stream"/> containing the content to upload.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual async Task<Response<BlobContentInfo>> UploadAsync(Stream content) =>
await UploadAsync(content, CancellationToken.None).ConfigureAwait(false);
/// <summary>
/// The <see cref="UploadAsync(string)"/> operation creates a new block blob
/// or updates the content of an existing block blob. Updating an
/// existing block blob overwrites any existing metadata on the blob.
///
/// For partial block blob updates and other advanced features, please
/// see <see cref="BlockBlobClient"/>. To create or modify page or
/// append blobs, please see <see cref="PageBlobClient"/> or
/// <see cref="AppendBlobClient"/>.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/put-blob">
/// Put Blob</see>.
/// </summary>
/// <param name="path">
/// A file path containing the content to upload.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual async Task<Response<BlobContentInfo>> UploadAsync(string path) =>
await UploadAsync(path, CancellationToken.None).ConfigureAwait(false);
/// <summary>
/// The <see cref="Upload(Stream, CancellationToken)"/> operation
/// creates a new block blob or updates the content of an existing
/// block blob. Updating an existing block blob overwrites any
/// existing metadata on the blob.
///
/// For partial block blob updates and other advanced features, please
/// see <see cref="BlockBlobClient"/>. To create or modify page or
/// append blobs, please see <see cref="PageBlobClient"/> or
/// <see cref="AppendBlobClient"/>.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/put-blob">
/// Put Blob</see>.
/// </summary>
/// <param name="content">
/// A <see cref="Stream"/> containing the content to upload.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual Response<BlobContentInfo> Upload(
Stream content,
CancellationToken cancellationToken) =>
Upload(
content,
overwrite: false,
cancellationToken: cancellationToken);
/// <summary>
/// The <see cref="Upload(string, CancellationToken)"/> operation
/// creates a new block blob or updates the content of an existing
/// block blob. Updating an existing block blob overwrites any
/// existing metadata on the blob.
///
/// For partial block blob updates and other advanced features, please
/// see <see cref="BlockBlobClient"/>. To create or modify page or
/// append blobs, please see <see cref="PageBlobClient"/> or
/// <see cref="AppendBlobClient"/>.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/put-blob">
/// Put Blob</see>.
/// </summary>
/// <param name="path">
/// A file path containing the content to upload.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual Response<BlobContentInfo> Upload(
string path,
CancellationToken cancellationToken) =>
Upload(
path,
overwrite: false,
cancellationToken: cancellationToken);
/// <summary>
/// The <see cref="UploadAsync(Stream, CancellationToken)"/> operation
/// creates a new block blob or updates the content of an existing
/// block blob. Updating an existing block blob overwrites any
/// existing metadata on the blob.
///
/// For partial block blob updates and other advanced features, please
/// see <see cref="BlockBlobClient"/>. To create or modify page or
/// append blobs, please see <see cref="PageBlobClient"/> or
/// <see cref="AppendBlobClient"/>.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/put-blob">
/// Put Blob</see>.
/// </summary>
/// <param name="content">
/// A <see cref="Stream"/> containing the content to upload.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual Task<Response<BlobContentInfo>> UploadAsync(
Stream content,
CancellationToken cancellationToken) =>
UploadAsync(
content,
overwrite: false,
cancellationToken: cancellationToken);
/// <summary>
/// The <see cref="UploadAsync(string, CancellationToken)"/> operation
/// creates a new block blob or updates the content of an existing
/// block blob. Updating an existing block blob overwrites any
/// existing metadata on the blob.
///
/// For partial block blob updates and other advanced features, please
/// see <see cref="BlockBlobClient"/>. To create or modify page or
/// append blobs, please see <see cref="PageBlobClient"/> or
/// <see cref="AppendBlobClient"/>.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/put-blob">
/// Put Blob</see>.
/// </summary>
/// <param name="path">
/// A file path containing the content to upload.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual async Task<Response<BlobContentInfo>> UploadAsync(
string path,
CancellationToken cancellationToken) =>
await UploadAsync(
path,
overwrite: false,
cancellationToken: cancellationToken)
.ConfigureAwait(false);
/// <summary>
/// The <see cref="Upload(Stream, CancellationToken)"/> operation
/// creates a new block blob or updates the content of an existing
/// block blob. Updating an existing block blob overwrites any
/// existing metadata on the blob.
///
/// For partial block blob updates and other advanced features, please
/// see <see cref="BlockBlobClient"/>. To create or modify page or
/// append blobs, please see <see cref="PageBlobClient"/> or
/// <see cref="AppendBlobClient"/>.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/put-blob">
/// Put Blob</see>.
/// </summary>
/// <param name="content">
/// A <see cref="Stream"/> containing the content to upload.
/// </param>
/// <param name="overwrite">
/// Whether the upload should overwrite any existing blobs. The
/// default value is false.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual Response<BlobContentInfo> Upload(
Stream content,
bool overwrite = false,
CancellationToken cancellationToken = default) =>
Upload(
content,
conditions: overwrite ? null : new BlobRequestConditions { IfNoneMatch = new ETag(Constants.Wildcard) },
cancellationToken: cancellationToken);
/// <summary>
/// The <see cref="Upload(string, CancellationToken)"/> operation
/// creates a new block blob or updates the content of an existing
/// block blob. Updating an existing block blob overwrites any
/// existing metadata on the blob.
///
/// For partial block blob updates and other advanced features, please
/// see <see cref="BlockBlobClient"/>. To create or modify page or
/// append blobs, please see <see cref="PageBlobClient"/> or
/// <see cref="AppendBlobClient"/>.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/put-blob">
/// Put Blob</see>.
/// </summary>
/// <param name="path">
/// A file path containing the content to upload.
/// </param>
/// <param name="overwrite">
/// Whether the upload should overwrite any existing blobs. The
/// default value is false.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual Response<BlobContentInfo> Upload(
string path,
bool overwrite = false,
CancellationToken cancellationToken = default) =>
Upload(
path,
conditions: overwrite ? null : new BlobRequestConditions { IfNoneMatch = new ETag(Constants.Wildcard) },
cancellationToken: cancellationToken);
/// <summary>
/// The <see cref="UploadAsync(Stream, CancellationToken)"/> operation
/// creates a new block blob or updates the content of an existing
/// block blob. Updating an existing block blob overwrites any
/// existing metadata on the blob.
///
/// For partial block blob updates and other advanced features, please
/// see <see cref="BlockBlobClient"/>. To create or modify page or
/// append blobs, please see <see cref="PageBlobClient"/> or
/// <see cref="AppendBlobClient"/>.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/put-blob">
/// Put Blob</see>.
/// </summary>
/// <param name="content">
/// A <see cref="Stream"/> containing the content to upload.
/// </param>
/// <param name="overwrite">
/// Whether the upload should overwrite any existing blobs. The
/// default value is false.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual Task<Response<BlobContentInfo>> UploadAsync(
Stream content,
bool overwrite = false,
CancellationToken cancellationToken = default) =>
UploadAsync(
content,
conditions: overwrite ? null : new BlobRequestConditions { IfNoneMatch = new ETag(Constants.Wildcard) },
cancellationToken: cancellationToken);
/// <summary>
/// The <see cref="UploadAsync(string, CancellationToken)"/> operation
/// creates a new block blob or updates the content of an existing
/// block blob. Updating an existing block blob overwrites any
/// existing metadata on the blob.
///
/// For partial block blob updates and other advanced features, please
/// see <see cref="BlockBlobClient"/>. To create or modify page or
/// append blobs, please see <see cref="PageBlobClient"/> or
/// <see cref="AppendBlobClient"/>.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/put-blob">
/// Put Blob</see>.
/// </summary>
/// <param name="path">
/// A file path containing the content to upload.
/// </param>
/// <param name="overwrite">
/// Whether the upload should overwrite any existing blobs. The
/// default value is false.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual async Task<Response<BlobContentInfo>> UploadAsync(
string path,
bool overwrite = false,
CancellationToken cancellationToken = default) =>
await UploadAsync(
path,
conditions: overwrite ? null : new BlobRequestConditions { IfNoneMatch = new ETag(Constants.Wildcard) },
cancellationToken: cancellationToken)
.ConfigureAwait(false);
/// <summary>
/// The <see cref="Upload(Stream, BlobUploadOptions, CancellationToken)"/>
/// operation creates a new block blob or updates the content of an
/// existing block blob. Updating an existing block blob overwrites
/// any existing metadata on the blob.
///
/// For partial block blob updates and other advanced features, please
/// see <see cref="BlockBlobClient"/>. To create or modify page or
/// append blobs, please see <see cref="PageBlobClient"/> or
/// <see cref="AppendBlobClient"/>.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/put-blob">
/// Put Blob</see>.
/// </summary>
/// <param name="content">
/// A <see cref="Stream"/> containing the content to upload.
/// </param>
/// <param name="options">
/// Optional parameters.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual Response<BlobContentInfo> Upload(
Stream content,
BlobUploadOptions options,
CancellationToken cancellationToken = default) =>
StagedUploadInternal(
content,
options,
async: false,
cancellationToken: cancellationToken)
.EnsureCompleted();
/// <summary>
/// The <see cref="Upload(Stream, BlobHttpHeaders, Metadata, BlobRequestConditions, IProgress{long}, AccessTier?, StorageTransferOptions, CancellationToken)"/>
/// operation creates a new block blob or updates the content of an
/// existing block blob. Updating an existing block blob overwrites
/// any existing metadata on the blob.
///
/// For partial block blob updates and other advanced features, please
/// see <see cref="BlockBlobClient"/>. To create or modify page or
/// append blobs, please see <see cref="PageBlobClient"/> or
/// <see cref="AppendBlobClient"/>.
///
/// For more information,
/// <see href="https://docs.microsoft.com/rest/api/storageservices/put-blob">
/// Put Blob</see>.
/// </summary>
/// <param name="content">
/// A <see cref="Stream"/> containing the content to upload.
/// </param>
/// <param name="httpHeaders">
/// Optional standard HTTP header properties that can be set for the
/// block blob.
/// </param>
/// <param name="metadata">
/// Optional custom metadata to set for this block blob.
/// </param>
/// <param name="conditions">
/// Optional <see cref="BlobRequestConditions"/> to add conditions on
/// the creation of this new block blob.
/// </param>
/// <param name="progressHandler">
/// Optional <see cref="IProgress{Long}"/> to provide
/// progress updates about data transfers.
/// </param>
/// <param name="accessTier">
/// Optional <see cref="AccessTier"/>
/// Indicates the tier to be set on the blob.
/// </param>
/// <param name="transferOptions">
/// Optional <see cref="StorageTransferOptions"/> to configure
/// parallel transfer behavior.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual Response<BlobContentInfo> Upload(
Stream content,
BlobHttpHeaders httpHeaders = default,
Metadata metadata = default,
BlobRequestConditions conditions = default,
IProgress<long> progressHandler = default,
AccessTier? accessTier = default,
StorageTransferOptions transferOptions = default,
CancellationToken cancellationToken = default) =>
StagedUploadInternal(
content,
new BlobUploadOptions
{
HttpHeaders = httpHeaders,
Metadata = metadata,
Conditions = conditions,
ProgressHandler = progressHandler,
AccessTier = accessTier,
TransferOptions = transferOptions
},
async: false,
cancellationToken: cancellationToken)
.EnsureCompleted();
/// <summary>
/// The <see cref="Upload(string, BlobUploadOptions, CancellationToken)"/>
/// operation creates a new block blob or updates the content of an
/// existing block blob. Updating an existing block blob overwrites
/// any existing metadata on the blob.
///
/// For partial block blob updates and other advanced features, please
/// see <see cref="BlockBlobClient"/>. To create or modify page or
/// append blobs, please see <see cref="PageBlobClient"/> or
/// <see cref="AppendBlobClient"/>.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/put-blob">
/// Put Blob</see>.
/// </summary>
/// <param name="path">
/// A file path containing the content to upload.
/// </param>
/// <param name="options">
/// Optional parameters.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual Response<BlobContentInfo> Upload(
string path,
BlobUploadOptions options,
CancellationToken cancellationToken = default)
{
using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
return StagedUploadInternal(
stream,
options,
async: false,
cancellationToken: cancellationToken)
.EnsureCompleted();
}
}
/// <summary>
/// The <see cref="Upload(string, BlobHttpHeaders, Metadata, BlobRequestConditions, IProgress{long}, AccessTier?, StorageTransferOptions, CancellationToken)"/>
/// operation creates a new block blob or updates the content of an
/// existing block blob. Updating an existing block blob overwrites
/// any existing metadata on the blob.
///
/// For partial block blob updates and other advanced features, please
/// see <see cref="BlockBlobClient"/>. To create or modify page or
/// append blobs, please see <see cref="PageBlobClient"/> or
/// <see cref="AppendBlobClient"/>.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/put-blob">
/// Put Blob</see>.
/// </summary>
/// <param name="path">
/// A file path containing the content to upload.
/// </param>
/// <param name="httpHeaders">
/// Optional standard HTTP header properties that can be set for the
/// block blob.
/// </param>
/// <param name="metadata">
/// Optional custom metadata to set for this block blob.
/// </param>
/// <param name="conditions">
/// Optional <see cref="BlobRequestConditions"/> to add conditions on
/// the creation of this new block blob.
/// </param>
/// <param name="progressHandler">
/// Optional <see cref="IProgress{Long}"/> to provide
/// progress updates about data transfers.
/// </param>
/// <param name="accessTier">
/// Optional <see cref="AccessTier"/>
/// Indicates the tier to be set on the blob.
/// </param>
/// <param name="transferOptions">
/// Optional <see cref="StorageTransferOptions"/> to configure
/// parallel transfer behavior.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual Response<BlobContentInfo> Upload(
string path,
BlobHttpHeaders httpHeaders = default,
Metadata metadata = default,
BlobRequestConditions conditions = default,
IProgress<long> progressHandler = default,
AccessTier? accessTier = default,
StorageTransferOptions transferOptions = default,
CancellationToken cancellationToken = default)
{
using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
return StagedUploadInternal(
stream,
new BlobUploadOptions
{
HttpHeaders = httpHeaders,
Metadata = metadata,
Conditions = conditions,
ProgressHandler = progressHandler,
AccessTier = accessTier,
TransferOptions = transferOptions
},
async: false,
cancellationToken: cancellationToken)
.EnsureCompleted();
}
}
/// <summary>
/// The <see cref="UploadAsync(Stream, BlobHttpHeaders, Metadata, BlobRequestConditions, IProgress{long}, AccessTier?, StorageTransferOptions, CancellationToken)"/>
/// operation creates a new block blob or updates the content of an
/// existing block blob. Updating an existing block blob overwrites
/// any existing metadata on the blob.
///
/// For partial block blob updates and other advanced features, please
/// see <see cref="BlockBlobClient"/>. To create or modify page or
/// append blobs, please see <see cref="PageBlobClient"/> or
/// <see cref="AppendBlobClient"/>.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/put-blob">
/// Put Blob</see>.
/// </summary>
/// <param name="content">
/// A <see cref="Stream"/> containing the content to upload.
/// </param>
/// <param name="options">
/// Optional parameters.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual async Task<Response<BlobContentInfo>> UploadAsync(
Stream content,
BlobUploadOptions options,
CancellationToken cancellationToken = default) =>
await StagedUploadInternal(
content,
options,
async: true,
cancellationToken: cancellationToken)
.ConfigureAwait(false);
/// <summary>
/// The <see cref="UploadAsync(Stream, BlobHttpHeaders, Metadata, BlobRequestConditions, IProgress{long}, AccessTier?, StorageTransferOptions, CancellationToken)"/>
/// operation creates a new block blob or updates the content of an
/// existing block blob. Updating an existing block blob overwrites
/// any existing metadata on the blob.
///
/// For partial block blob updates and other advanced features, please
/// see <see cref="BlockBlobClient"/>. To create or modify page or
/// append blobs, please see <see cref="PageBlobClient"/> or
/// <see cref="AppendBlobClient"/>.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/put-blob">
/// Put Blob</see>.
/// </summary>
/// <param name="content">
/// A <see cref="Stream"/> containing the content to upload.
/// </param>
/// <param name="httpHeaders">
/// Optional standard HTTP header properties that can be set for the
/// block blob.
/// </param>
/// <param name="metadata">
/// Optional custom metadata to set for this block blob.
/// </param>
/// <param name="conditions">
/// Optional <see cref="BlobRequestConditions"/> to add conditions on
/// the creation of this new block blob.
/// </param>
/// <param name="transferOptions">
/// Optional <see cref="StorageTransferOptions"/> to configure
/// parallel transfer behavior.
/// </param>
/// <param name="progressHandler">
/// Optional <see cref="IProgress{Long}"/> to provide
/// progress updates about data transfers.
/// </param>
/// <param name="accessTier">
/// Optional <see cref="AccessTier"/>
/// Indicates the tier to be set on the blob.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
[ForwardsClientCalls]
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual Task<Response<BlobContentInfo>> UploadAsync(
Stream content,
BlobHttpHeaders httpHeaders = default,
Metadata metadata = default,
BlobRequestConditions conditions = default,
IProgress<long> progressHandler = default,
AccessTier? accessTier = default,
StorageTransferOptions transferOptions = default,
CancellationToken cancellationToken = default) =>
StagedUploadInternal(
content,
new BlobUploadOptions
{
HttpHeaders = httpHeaders,
Metadata = metadata,
Conditions = conditions,
ProgressHandler = progressHandler,
AccessTier = accessTier,
TransferOptions = transferOptions
},
async: true,
cancellationToken: cancellationToken);
/// <summary>
/// The <see cref="UploadAsync(Stream, BlobUploadOptions, CancellationToken)"/>
/// operation creates a new block blob or updates the content of an
/// existing block blob. Updating an existing block blob overwrites
/// any existing metadata on the blob.
///
/// For partial block blob updates and other advanced features, please
/// see <see cref="BlockBlobClient"/>. To create or modify page or
/// append blobs, please see <see cref="PageBlobClient"/> or
/// <see cref="AppendBlobClient"/>.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/put-blob">
/// Put Blob</see>..
/// </summary>
/// <param name="path">
/// A file path containing the content to upload.
/// </param>
/// <param name="options">
/// Optional parameters.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual async Task<Response<BlobContentInfo>> UploadAsync(
string path,
BlobUploadOptions options,
CancellationToken cancellationToken = default)
{
using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
return await StagedUploadInternal(
stream,
options,
async: true,
cancellationToken: cancellationToken)
.ConfigureAwait(false);
}
}
/// <summary>
/// The <see cref="UploadAsync(string, BlobHttpHeaders, Metadata, BlobRequestConditions, IProgress{long}, AccessTier?, StorageTransferOptions, CancellationToken)"/>
/// operation creates a new block blob or updates the content of an
/// existing block blob. Updating an existing block blob overwrites
/// any existing metadata on the blob.
///
/// For partial block blob updates and other advanced features, please
/// see <see cref="BlockBlobClient"/>. To create or modify page or
/// append blobs, please see <see cref="PageBlobClient"/> or
/// <see cref="AppendBlobClient"/>.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/put-blob">
/// Put Blob</see>.
/// </summary>
/// <param name="path">
/// A file path containing the content to upload.
/// </param>
/// <param name="httpHeaders">
/// Optional standard HTTP header properties that can be set for the
/// block blob.
/// </param>
/// <param name="metadata">
/// Optional custom metadata to set for this block blob.
/// </param>
/// <param name="conditions">
/// Optional <see cref="BlobRequestConditions"/> to add conditions on
/// the creation of this new block blob.
/// </param>
/// <param name="progressHandler">
/// Optional <see cref="IProgress{Long}"/> to provide
/// progress updates about data transfers.
/// </param>
/// <param name="accessTier">
/// Optional <see cref="AccessTier"/>
/// Indicates the tier to be set on the blob.
/// </param>
/// <param name="transferOptions">
/// Optional <see cref="StorageTransferOptions"/> to configure
/// parallel transfer behavior.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
[ForwardsClientCalls]
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual async Task<Response<BlobContentInfo>> UploadAsync(
string path,
BlobHttpHeaders httpHeaders = default,
Metadata metadata = default,
BlobRequestConditions conditions = default,
IProgress<long> progressHandler = default,
AccessTier? accessTier = default,
StorageTransferOptions transferOptions = default,
CancellationToken cancellationToken = default)
{
using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
return await StagedUploadInternal(
stream,
new BlobUploadOptions
{
HttpHeaders = httpHeaders,
Metadata = metadata,
Conditions = conditions,
ProgressHandler = progressHandler,
AccessTier = accessTier,
TransferOptions = transferOptions
},
async: true,
cancellationToken).ConfigureAwait(false);
}
}
/// <summary>
/// This operation will create a new
/// block blob of arbitrary size by uploading it as indiviually staged
/// blocks if it's larger than the
/// <paramref name="options"/> MaximumTransferLength.
/// </summary>
/// <param name="content">
/// A <see cref="Stream"/> containing the content to upload.
/// </param>
/// <param name="options">
/// Options for this upload.
/// </param>
/// <param name="async">
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
internal async Task<Response<BlobContentInfo>> StagedUploadInternal(
Stream content,
BlobUploadOptions options,
bool async = true,
CancellationToken cancellationToken = default)
{
if (UsingClientSideEncryption)
{
// content is now unseekable, so PartitionedUploader will be forced to do a buffered multipart upload
(content, options.Metadata) = await new BlobClientSideEncryptor(new ClientSideEncryptor(ClientSideEncryption))
.ClientSideEncryptInternal(content, options.Metadata, async, cancellationToken).ConfigureAwait(false);
}
var client = new BlockBlobClient(Uri, Pipeline, SharedKeyCredential, Version, ClientDiagnostics, CustomerProvidedKey, EncryptionScope);
var uploader = GetPartitionedUploader(
transferOptions: options?.TransferOptions ?? default,
operationName: $"{nameof(BlobClient)}.{nameof(Upload)}");
return await uploader.UploadInternal(
content,
options,
options.ProgressHandler,
async,
cancellationToken)
.ConfigureAwait(false);
}
/// <summary>
/// This operation will create a new
/// block blob of arbitrary size by uploading it as indiviually staged
/// blocks if it's larger than the
/// <paramref name="options"/>. MaximumTransferLength.
/// </summary>
/// <param name="path">
/// A file path of the file to upload.
/// </param>
/// <param name="options">
/// Options for this upload.
/// </param>
/// <param name="async">
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
internal async Task<Response<BlobContentInfo>> StagedUploadInternal(
string path,
BlobUploadOptions options,
bool async = true,
CancellationToken cancellationToken = default)
{
// TODO Upload from file will get it's own implementation in the future that opens more
// than one stream at once. This is incompatible with .NET's CryptoStream. We will
// need to uncomment the below code and revert to upload from stream if client-side
// encryption is enabled.
//if (ClientSideEncryption != default)
//{
// using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
// {
// return await StagedUploadAsync(
// stream,
// blobHttpHeaders,
// metadata,
// conditions,
// progressHandler,
// accessTier,
// transferOptions: transferOptions,
// async: async,
// cancellationToken: cancellationToken)
// .ConfigureAwait(false);
// }
//}
using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
return await StagedUploadInternal(
stream,
options,
async: async,
cancellationToken: cancellationToken)
.ConfigureAwait(false);
}
}
#endregion Upload
internal PartitionedUploader<BlobUploadOptions, BlobContentInfo> GetPartitionedUploader(
StorageTransferOptions transferOptions,
ArrayPool<byte> arrayPool = null,
string operationName = null)
=> new BlockBlobClient(Uri, Pipeline, SharedKeyCredential, Version, ClientDiagnostics, CustomerProvidedKey, EncryptionScope)
.GetPartitionedUploader(transferOptions, arrayPool, operationName);
}
}
| 43.72093 | 172 | 0.570462 | [
"MIT"
] | Youssef1313/azure-sdk-for-net | sdk/storage/Azure.Storage.Blobs/src/BlobClient.cs | 60,162 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.SymbolDisplay;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class SymbolDisplayVisitor
{
private void VisitTypeSymbolWithAnnotations(TypeSymbolWithAnnotations type, AbstractSymbolDisplayVisitor visitorOpt = null)
{
var visitor = (SymbolDisplayVisitor)(visitorOpt ?? this.NotFirstVisitor);
var typeSymbol = type.TypeSymbol;
if (typeSymbol.TypeKind == TypeKind.Array)
{
visitor.VisitArrayType((IArrayTypeSymbol)typeSymbol, typeOpt: type);
}
else
{
typeSymbol.Accept(visitor);
AddNullableAnnotations(type);
}
}
public override void VisitArrayType(IArrayTypeSymbol symbol)
{
VisitArrayType(symbol, typeOpt: default);
}
private void VisitArrayType(IArrayTypeSymbol symbol, TypeSymbolWithAnnotations typeOpt)
{
if (TryAddAlias(symbol, builder))
{
return;
}
//See spec section 12.1 for the order of rank specifiers
//e.g. int[][,][,,] is stored as
// ArrayType
// Rank = 1
// ElementType = ArrayType
// Rank = 2
// ElementType = ArrayType
// Rank = 3
// ElementType = int
if (format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.ReverseArrayRankSpecifiers))
{
// Ironically, reverse order is simpler - we just have to recurse on the element type and then add a rank specifier.
symbol.ElementType.Accept(this);
AddArrayRank(symbol);
return;
}
TypeSymbolWithAnnotations underlyingNonArrayTypeWithAnnotations = (symbol as ArrayTypeSymbol)?.ElementType ?? default;
var underlyingNonArrayType = symbol.ElementType;
while (underlyingNonArrayType.Kind == SymbolKind.ArrayType)
{
underlyingNonArrayTypeWithAnnotations = (underlyingNonArrayType as ArrayTypeSymbol)?.ElementType ?? default;
underlyingNonArrayType = ((IArrayTypeSymbol)underlyingNonArrayType).ElementType;
}
if (!underlyingNonArrayTypeWithAnnotations.IsNull)
{
VisitTypeSymbolWithAnnotations(underlyingNonArrayTypeWithAnnotations);
}
else
{
underlyingNonArrayType.Accept(this.NotFirstVisitor);
}
var arrayType = symbol;
while (arrayType != null)
{
if (!this.isFirstSymbolVisited)
{
AddCustomModifiersIfRequired(arrayType.CustomModifiers, leadingSpace: true);
}
AddArrayRank(arrayType);
AddNullableAnnotations(typeOpt);
typeOpt = (arrayType as ArrayTypeSymbol)?.ElementType ?? default;
arrayType = arrayType.ElementType as IArrayTypeSymbol;
}
}
private void AddNullableAnnotations(TypeSymbolWithAnnotations typeOpt)
{
if (typeOpt.IsNull)
{
return;
}
if (format.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier) &&
!typeOpt.IsNullableType() && !typeOpt.IsValueType &&
(typeOpt.NullableAnnotation == NullableAnnotation.Annotated ||
(typeOpt.NullableAnnotation == NullableAnnotation.Nullable && !typeOpt.TypeSymbol.IsTypeParameterDisallowingAnnotation())))
{
AddPunctuation(SyntaxKind.QuestionToken);
}
else if (format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.IncludeNonNullableTypeModifier) &&
!typeOpt.IsValueType &&
typeOpt.NullableAnnotation.IsAnyNotNullable() && !typeOpt.TypeSymbol.IsTypeParameterDisallowingAnnotation())
{
AddPunctuation(SyntaxKind.ExclamationToken);
}
}
private void AddArrayRank(IArrayTypeSymbol symbol)
{
bool insertStars = format.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.UseAsterisksInMultiDimensionalArrays);
AddPunctuation(SyntaxKind.OpenBracketToken);
if (symbol.Rank > 1)
{
if (insertStars)
{
AddPunctuation(SyntaxKind.AsteriskToken);
}
}
else
{
var array = symbol as ArrayTypeSymbol;
if ((object)array != null && !array.IsSZArray)
{
// Always add an asterisk in this case in order to distinguish between SZArray and MDArray.
AddPunctuation(SyntaxKind.AsteriskToken);
}
}
for (int i = 0; i < symbol.Rank - 1; i++)
{
AddPunctuation(SyntaxKind.CommaToken);
if (insertStars)
{
AddPunctuation(SyntaxKind.AsteriskToken);
}
}
AddPunctuation(SyntaxKind.CloseBracketToken);
}
public override void VisitPointerType(IPointerTypeSymbol symbol)
{
var pointer = symbol as PointerTypeSymbol;
if ((object)pointer == null)
{
symbol.PointedAtType.Accept(this.NotFirstVisitor);
}
else
{
VisitTypeSymbolWithAnnotations(pointer.PointedAtType);
}
if (!this.isFirstSymbolVisited)
{
AddCustomModifiersIfRequired(symbol.CustomModifiers, leadingSpace: true);
}
AddPunctuation(SyntaxKind.AsteriskToken);
}
public override void VisitTypeParameter(ITypeParameterSymbol symbol)
{
if (this.isFirstSymbolVisited)
{
AddTypeParameterVarianceIfRequired(symbol);
}
//variance and constraints are handled by methods and named types
builder.Add(CreatePart(SymbolDisplayPartKind.TypeParameterName, symbol, symbol.Name));
}
public override void VisitDynamicType(IDynamicTypeSymbol symbol)
{
builder.Add(CreatePart(SymbolDisplayPartKind.Keyword, symbol, symbol.Name));
}
public override void VisitNamedType(INamedTypeSymbol symbol)
{
if (this.IsMinimizing && TryAddAlias(symbol, builder))
{
return;
}
if (format.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.UseSpecialTypes))
{
if (AddSpecialTypeKeyword(symbol))
{
//if we're using special type keywords and this is a special type, then no other work is required
return;
}
}
if (!format.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.ExpandNullable))
{
//if we're expanding nullable, we just visit nullable types normally
if (ITypeSymbolHelpers.IsNullableType(symbol) && !symbol.IsDefinition)
{
// Can't have a type called "int*?".
var typeArg = symbol.TypeArguments[0];
if (typeArg.TypeKind != TypeKind.Pointer)
{
typeArg.Accept(this.NotFirstVisitor);
AddCustomModifiersIfRequired(symbol.GetTypeArgumentCustomModifiers(0), leadingSpace: true, trailingSpace: false);
AddPunctuation(SyntaxKind.QuestionToken);
//visiting the underlying type did all of the work for us
return;
}
}
}
if (this.IsMinimizing || symbol.IsTupleType)
{
MinimallyQualify(symbol);
return;
}
AddTypeKind(symbol);
if (CanShowDelegateSignature(symbol))
{
if (format.DelegateStyle == SymbolDisplayDelegateStyle.NameAndSignature)
{
var invokeMethod = symbol.DelegateInvokeMethod;
if (invokeMethod.ReturnsByRef)
{
AddRefIfRequired();
}
else if (invokeMethod.ReturnsByRefReadonly)
{
AddRefReadonlyIfRequired();
}
if (invokeMethod.ReturnsVoid)
{
AddKeyword(SyntaxKind.VoidKeyword);
}
else
{
AddReturnType(symbol.DelegateInvokeMethod);
}
AddSpace();
}
}
//only visit the namespace if the style requires it and there isn't an enclosing type
var containingSymbol = symbol.ContainingSymbol;
if (ShouldVisitNamespace(containingSymbol))
{
var namespaceSymbol = (INamespaceSymbol)containingSymbol;
var shouldSkip = namespaceSymbol.IsGlobalNamespace && symbol.TypeKind == TypeKind.Error;
if (!shouldSkip)
{
namespaceSymbol.Accept(this.NotFirstVisitor);
AddPunctuation(namespaceSymbol.IsGlobalNamespace ? SyntaxKind.ColonColonToken : SyntaxKind.DotToken);
}
}
//visit the enclosing type if the style requires it
if (format.TypeQualificationStyle == SymbolDisplayTypeQualificationStyle.NameAndContainingTypes ||
format.TypeQualificationStyle == SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces)
{
if (IncludeNamedType(symbol.ContainingType))
{
symbol.ContainingType.Accept(this.NotFirstVisitor);
AddPunctuation(SyntaxKind.DotToken);
}
}
AddNameAndTypeArgumentsOrParameters(symbol);
}
private void AddNameAndTypeArgumentsOrParameters(INamedTypeSymbol symbol)
{
if (symbol.IsAnonymousType)
{
AddAnonymousTypeName(symbol);
return;
}
else if (symbol.IsTupleType)
{
// If top level tuple uses non-default names, there is no way to preserve them
// unless we use tuple syntax for the type. So, we give them priority.
if (!format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseValueTuple))
{
if (HasNonDefaultTupleElements(symbol) || CanUseTupleTypeName(symbol))
{
AddTupleTypeName(symbol);
return;
}
}
// Fall back to displaying the underlying type.
symbol = symbol.TupleUnderlyingType;
}
string symbolName = null;
// It would be nice to handle VB NoPia symbols too, but it's not worth the effort.
var illegalGenericInstantiationSymbol = symbol as NoPiaIllegalGenericInstantiationSymbol;
if ((object)illegalGenericInstantiationSymbol != null)
{
symbol = illegalGenericInstantiationSymbol.UnderlyingSymbol;
}
else
{
var ambiguousCanonicalTypeSymbol = symbol as NoPiaAmbiguousCanonicalTypeSymbol;
if ((object)ambiguousCanonicalTypeSymbol != null)
{
symbol = ambiguousCanonicalTypeSymbol.FirstCandidate;
}
else
{
var missingCanonicalTypeSymbol = symbol as NoPiaMissingCanonicalTypeSymbol;
if ((object)missingCanonicalTypeSymbol != null)
{
symbolName = missingCanonicalTypeSymbol.FullTypeName;
}
}
}
var partKind = GetPartKind(symbol);
if (symbolName == null)
{
symbolName = symbol.Name;
}
if (format.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName) &&
partKind == SymbolDisplayPartKind.ErrorTypeName &&
string.IsNullOrEmpty(symbolName))
{
builder.Add(CreatePart(partKind, symbol, "?"));
}
else
{
symbolName = RemoveAttributeSufficeIfNecessary(symbol, symbolName);
builder.Add(CreatePart(partKind, symbol, symbolName));
}
if (format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseArityForGenericTypes))
{
// Only the compiler can set the internal option and the compiler doesn't use other implementations of INamedTypeSymbol.
if (((NamedTypeSymbol)symbol).MangleName)
{
Debug.Assert(symbol.Arity > 0);
builder.Add(CreatePart(InternalSymbolDisplayPartKind.Arity, null,
MetadataHelpers.GetAritySuffix(symbol.Arity)));
}
}
else if (symbol.Arity > 0 && format.GenericsOptions.IncludesOption(SymbolDisplayGenericsOptions.IncludeTypeParameters))
{
// It would be nice to handle VB symbols too, but it's not worth the effort.
if (symbol is UnsupportedMetadataTypeSymbol || symbol is MissingMetadataTypeSymbol || symbol.IsUnboundGenericType)
{
AddPunctuation(SyntaxKind.LessThanToken);
for (int i = 0; i < symbol.Arity - 1; i++)
{
AddPunctuation(SyntaxKind.CommaToken);
}
AddPunctuation(SyntaxKind.GreaterThanToken);
}
else
{
var modifiers = default(ImmutableArray<ImmutableArray<CustomModifier>>);
if (this.format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.IncludeCustomModifiers))
{
var namedType = symbol as NamedTypeSymbol;
if ((object)namedType != null)
{
modifiers = namedType.TypeArgumentsNoUseSiteDiagnostics.SelectAsArray(a => a.CustomModifiers);
}
}
AddTypeArguments(symbol, modifiers);
AddDelegateParameters(symbol);
// TODO: do we want to skip these if we're being visited as a containing type?
AddTypeParameterConstraints(symbol.TypeArguments);
}
}
else
{
AddDelegateParameters(symbol);
}
// Only the compiler can set the internal option and the compiler doesn't use other implementations of INamedTypeSymbol.
if (symbol.OriginalDefinition is MissingMetadataTypeSymbol &&
format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.FlagMissingMetadataTypes))
{
//add it as punctuation - it's just for testing
AddPunctuation(SyntaxKind.OpenBracketToken);
builder.Add(CreatePart(InternalSymbolDisplayPartKind.Other, symbol, "missing"));
AddPunctuation(SyntaxKind.CloseBracketToken);
}
}
private void AddDelegateParameters(INamedTypeSymbol symbol)
{
if (CanShowDelegateSignature(symbol))
{
if (format.DelegateStyle == SymbolDisplayDelegateStyle.NameAndParameters ||
format.DelegateStyle == SymbolDisplayDelegateStyle.NameAndSignature)
{
var method = symbol.DelegateInvokeMethod;
AddPunctuation(SyntaxKind.OpenParenToken);
AddParametersIfRequired(hasThisParameter: false, isVarargs: method.IsVararg, parameters: method.Parameters);
AddPunctuation(SyntaxKind.CloseParenToken);
}
}
}
private void AddAnonymousTypeName(INamedTypeSymbol symbol)
{
// TODO: revise to generate user-friendly name
var members = string.Join(", ", symbol.GetMembers().OfType<IPropertySymbol>().Select(CreateAnonymousTypeMember));
if (members.Length == 0)
{
builder.Add(new SymbolDisplayPart(SymbolDisplayPartKind.ClassName, symbol, "<empty anonymous type>"));
}
else
{
var name = $"<anonymous type: {members}>";
builder.Add(new SymbolDisplayPart(SymbolDisplayPartKind.ClassName, symbol, name));
}
}
/// <summary>
/// Returns true if tuple type syntax can be used to refer to the tuple type without loss of information.
/// For example, it cannot be used when extension tuple is using non-default friendly names.
/// </summary>
/// <param name="tupleSymbol"></param>
/// <returns></returns>
private bool CanUseTupleTypeName(INamedTypeSymbol tupleSymbol)
{
INamedTypeSymbol currentUnderlying = tupleSymbol.TupleUnderlyingType;
if (currentUnderlying.Arity == 1)
{
return false;
}
while (currentUnderlying.Arity == TupleTypeSymbol.RestPosition)
{
tupleSymbol = (INamedTypeSymbol)currentUnderlying.TypeArguments[TupleTypeSymbol.RestPosition - 1];
Debug.Assert(tupleSymbol.IsTupleType);
if (HasNonDefaultTupleElements(tupleSymbol))
{
return false;
}
currentUnderlying = tupleSymbol.TupleUnderlyingType;
}
return true;
}
private static bool HasNonDefaultTupleElements(INamedTypeSymbol tupleSymbol)
{
return tupleSymbol.TupleElements.Any(e => !e.IsDefaultTupleElement());
}
private void AddTupleTypeName(INamedTypeSymbol symbol)
{
Debug.Assert(symbol.IsTupleType);
ImmutableArray<IFieldSymbol> elements = symbol.TupleElements;
AddPunctuation(SyntaxKind.OpenParenToken);
for (int i = 0; i < elements.Length; i++)
{
var element = elements[i];
if (i != 0)
{
AddPunctuation(SyntaxKind.CommaToken);
AddSpace();
}
VisitFieldType(element);
if (!element.IsImplicitlyDeclared)
{
AddSpace();
builder.Add(CreatePart(SymbolDisplayPartKind.FieldName, symbol, element.Name));
}
}
AddPunctuation(SyntaxKind.CloseParenToken);
}
private string CreateAnonymousTypeMember(IPropertySymbol property)
{
return property.Type.ToDisplayString(format) + " " + property.Name;
}
private bool CanShowDelegateSignature(INamedTypeSymbol symbol)
{
return
isFirstSymbolVisited &&
symbol.TypeKind == TypeKind.Delegate &&
format.DelegateStyle != SymbolDisplayDelegateStyle.NameOnly &&
symbol.DelegateInvokeMethod != null;
}
private static SymbolDisplayPartKind GetPartKind(INamedTypeSymbol symbol)
{
switch (symbol.TypeKind)
{
case TypeKind.Submission:
case TypeKind.Module:
case TypeKind.Class:
return SymbolDisplayPartKind.ClassName;
case TypeKind.Delegate:
return SymbolDisplayPartKind.DelegateName;
case TypeKind.Enum:
return SymbolDisplayPartKind.EnumName;
case TypeKind.Error:
return SymbolDisplayPartKind.ErrorTypeName;
case TypeKind.Interface:
return SymbolDisplayPartKind.InterfaceName;
case TypeKind.Struct:
return SymbolDisplayPartKind.StructName;
default:
throw ExceptionUtilities.UnexpectedValue(symbol.TypeKind);
}
}
private bool AddSpecialTypeKeyword(INamedTypeSymbol symbol)
{
var specialTypeName = GetSpecialTypeName(symbol.SpecialType);
if (specialTypeName == null)
{
return false;
}
// cheat - skip escapeKeywordIdentifiers. not calling AddKeyword because someone
// else is working out the text for us
builder.Add(CreatePart(SymbolDisplayPartKind.Keyword, symbol, specialTypeName));
return true;
}
private static string GetSpecialTypeName(SpecialType specialType)
{
switch (specialType)
{
case SpecialType.System_Void:
return "void";
case SpecialType.System_SByte:
return "sbyte";
case SpecialType.System_Int16:
return "short";
case SpecialType.System_Int32:
return "int";
case SpecialType.System_Int64:
return "long";
case SpecialType.System_Byte:
return "byte";
case SpecialType.System_UInt16:
return "ushort";
case SpecialType.System_UInt32:
return "uint";
case SpecialType.System_UInt64:
return "ulong";
case SpecialType.System_Single:
return "float";
case SpecialType.System_Double:
return "double";
case SpecialType.System_Decimal:
return "decimal";
case SpecialType.System_Char:
return "char";
case SpecialType.System_Boolean:
return "bool";
case SpecialType.System_String:
return "string";
case SpecialType.System_Object:
return "object";
default:
return null;
}
}
private void AddTypeKind(INamedTypeSymbol symbol)
{
if (isFirstSymbolVisited && format.KindOptions.IncludesOption(SymbolDisplayKindOptions.IncludeTypeKeyword))
{
if (symbol.IsAnonymousType)
{
builder.Add(new SymbolDisplayPart(SymbolDisplayPartKind.AnonymousTypeIndicator, null, "AnonymousType"));
AddSpace();
}
else if (symbol.IsTupleType)
{
builder.Add(new SymbolDisplayPart(SymbolDisplayPartKind.AnonymousTypeIndicator, null, "Tuple"));
AddSpace();
}
else
{
switch (symbol.TypeKind)
{
case TypeKind.Module:
case TypeKind.Class:
AddKeyword(SyntaxKind.ClassKeyword);
AddSpace();
break;
case TypeKind.Enum:
AddKeyword(SyntaxKind.EnumKeyword);
AddSpace();
break;
case TypeKind.Delegate:
AddKeyword(SyntaxKind.DelegateKeyword);
AddSpace();
break;
case TypeKind.Interface:
AddKeyword(SyntaxKind.InterfaceKeyword);
AddSpace();
break;
case TypeKind.Struct:
if (symbol is NamedTypeSymbol csharpType)
{
if (csharpType.IsReadOnly)
{
AddKeyword(SyntaxKind.ReadOnlyKeyword);
AddSpace();
}
if (csharpType.IsRefLikeType)
{
AddKeyword(SyntaxKind.RefKeyword);
AddSpace();
}
}
AddKeyword(SyntaxKind.StructKeyword);
AddSpace();
break;
}
}
}
}
private void AddTypeParameterVarianceIfRequired(ITypeParameterSymbol symbol)
{
if (format.GenericsOptions.IncludesOption(SymbolDisplayGenericsOptions.IncludeVariance))
{
switch (symbol.Variance)
{
case VarianceKind.In:
AddKeyword(SyntaxKind.InKeyword);
AddSpace();
break;
case VarianceKind.Out:
AddKeyword(SyntaxKind.OutKeyword);
AddSpace();
break;
}
}
}
//returns true if there are constraints
private void AddTypeArguments(ISymbol owner, ImmutableArray<ImmutableArray<CustomModifier>> modifiers)
{
ImmutableArray<ITypeSymbol> typeArguments;
ImmutableArray<TypeSymbolWithAnnotations>? typeArgumentsWithAnnotations;
if (owner.Kind == SymbolKind.Method)
{
typeArguments = ((IMethodSymbol)owner).TypeArguments;
typeArgumentsWithAnnotations = (owner as MethodSymbol)?.TypeArguments;
}
else
{
typeArguments = ((INamedTypeSymbol)owner).TypeArguments;
typeArgumentsWithAnnotations = (owner as NamedTypeSymbol)?.TypeArgumentsNoUseSiteDiagnostics;
}
if (typeArguments.Length > 0 && format.GenericsOptions.IncludesOption(SymbolDisplayGenericsOptions.IncludeTypeParameters))
{
AddPunctuation(SyntaxKind.LessThanToken);
var first = true;
for (int i = 0; i < typeArguments.Length; i++)
{
var typeArg = typeArguments[i];
if (!first)
{
AddPunctuation(SyntaxKind.CommaToken);
AddSpace();
}
first = false;
AbstractSymbolDisplayVisitor visitor;
if (typeArg.Kind == SymbolKind.TypeParameter)
{
var typeParam = (ITypeParameterSymbol)typeArg;
AddTypeParameterVarianceIfRequired(typeParam);
visitor = this.NotFirstVisitor;
}
else
{
visitor = this.NotFirstVisitorNamespaceOrType;
}
if (typeArgumentsWithAnnotations == null)
{
typeArg.Accept(visitor);
}
else
{
VisitTypeSymbolWithAnnotations(typeArgumentsWithAnnotations.GetValueOrDefault()[i], visitor);
}
if (!modifiers.IsDefault)
{
AddCustomModifiersIfRequired(modifiers[i], leadingSpace: true, trailingSpace: false);
}
}
AddPunctuation(SyntaxKind.GreaterThanToken);
}
}
private static bool TypeParameterHasConstraints(ITypeParameterSymbol typeParam)
{
return !typeParam.ConstraintTypes.IsEmpty || typeParam.HasConstructorConstraint ||
typeParam.HasReferenceTypeConstraint || typeParam.HasValueTypeConstraint;
}
private void AddTypeParameterConstraints(ImmutableArray<ITypeSymbol> typeArguments)
{
if (this.isFirstSymbolVisited && format.GenericsOptions.IncludesOption(SymbolDisplayGenericsOptions.IncludeTypeConstraints))
{
foreach (var typeArg in typeArguments)
{
if (typeArg.Kind == SymbolKind.TypeParameter)
{
var typeParam = (ITypeParameterSymbol)typeArg;
if (TypeParameterHasConstraints(typeParam))
{
AddSpace();
AddKeyword(SyntaxKind.WhereKeyword);
AddSpace();
typeParam.Accept(this.NotFirstVisitor);
AddSpace();
AddPunctuation(SyntaxKind.ColonToken);
AddSpace();
bool needComma = false;
var typeParameterSymbol = typeParam as TypeParameterSymbol;
//class/struct constraint must be first
if (typeParam.HasReferenceTypeConstraint)
{
AddKeyword(SyntaxKind.ClassKeyword);
switch (typeParameterSymbol?.ReferenceTypeConstraintIsNullable) // https://github.com/dotnet/roslyn/issues/26198 Switch to public API when we will have one.
{
case true:
if (format.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier))
{
AddPunctuation(SyntaxKind.QuestionToken);
}
break;
case false:
if (format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.IncludeNonNullableTypeModifier))
{
AddPunctuation(SyntaxKind.ExclamationToken);
}
break;
}
needComma = true;
}
else if (typeParam.HasUnmanagedTypeConstraint)
{
builder.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Keyword, null, "unmanaged"));
needComma = true;
}
else if (typeParam.HasValueTypeConstraint)
{
AddKeyword(SyntaxKind.StructKeyword);
needComma = true;
}
ImmutableArray<TypeSymbolWithAnnotations>? annotatedConstraints = typeParameterSymbol?.ConstraintTypesNoUseSiteDiagnostics; // https://github.com/dotnet/roslyn/issues/26198 Switch to public API when we will have one.
for (int i = 0; i < typeParam.ConstraintTypes.Length; i++)
{
ITypeSymbol baseType = typeParam.ConstraintTypes[i];
if (needComma)
{
AddPunctuation(SyntaxKind.CommaToken);
AddSpace();
}
if (annotatedConstraints.HasValue)
{
VisitTypeSymbolWithAnnotations(annotatedConstraints.GetValueOrDefault()[i], this.NotFirstVisitor);
}
else
{
baseType.Accept(this.NotFirstVisitor);
}
needComma = true;
}
//ctor constraint must be last
if (typeParam.HasConstructorConstraint)
{
if (needComma)
{
AddPunctuation(SyntaxKind.CommaToken);
AddSpace();
}
AddKeyword(SyntaxKind.NewKeyword);
AddPunctuation(SyntaxKind.OpenParenToken);
AddPunctuation(SyntaxKind.CloseParenToken);
}
}
}
}
}
}
}
}
| 40.151796 | 244 | 0.513347 | [
"Apache-2.0"
] | DustinCampbell/roslyn | src/Compilers/CSharp/Portable/SymbolDisplay/SymbolDisplayVisitor.Types.cs | 34,653 | C# |
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AmazingShop.Product.Application.Repository.Abstraction;
using AmazingShop.Product.Application.Resource.Dto;
using AmazingShop.Shared.Core.Model;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace AmazingShop.Product.Application.Resource.Command.Handler
{
public class GetAllResourcesHandler : IRequestHandler<GetAllResources, PagedList<GetAllResourceDto>>
{
private readonly IResourceRepository _resourceRepository;
public GetAllResourcesHandler(IResourceRepository resourceRepository)
{
_resourceRepository = resourceRepository;
}
public async Task<PagedList<GetAllResourceDto>> Handle(GetAllResources request, CancellationToken cancellationToken)
{
var resources = await _resourceRepository.Resources.AsNoTracking().ToListAsync(cancellationToken);
var result = resources.Select(GetAllResourceDto.Create);
return PagedList<GetAllResourceDto>.Create(result);
}
}
} | 41.192308 | 124 | 0.764706 | [
"Apache-2.0"
] | hoangthanh28/amazing-shop | src/api/product-service/src/AmazingShop.Product.Application/Resources/Commands/Handlers/GetAllResourcesHandler.cs | 1,071 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Assent;
using FluentAssertions;
using Newtonsoft.Json;
using NSubstitute;
using NUnit.Framework;
using Octopus.Cli.Commands.Releases;
using Octopus.Cli.Tests.Helpers;
using Octopus.Client.Model;
using Octopus.Client.Model.VersionControl;
namespace Octo.Tests.Commands
{
[TestFixture]
public class ListReleasesCommandFixture : ApiCommandFixtureBase
{
ListReleasesCommand listReleasesCommand;
const string VersionControlledProjectId = "Projects-3";
[SetUp]
public void SetUp()
{
listReleasesCommand = new ListReleasesCommand(RepositoryFactory, FileSystem, ClientFactory, CommandOutputProvider);
}
[Test]
public async Task ShouldGetListOfReleases()
{
Repository.Projects.FindByNames(Arg.Any<IEnumerable<string>>()).Returns(new List<ProjectResource>
{
new ProjectResource {Name = "ProjectA", Id = "projectaid"},
new ProjectResource {Name = "ProjectB", Id = "projectbid"},
new ProjectResource {Name = "Version controlled project", Id = VersionControlledProjectId}
});
Repository.Releases.FindMany(Arg.Any<Func<ReleaseResource, bool>>()).Returns(new List<ReleaseResource>
{
new ReleaseResource
{
ProjectId = "projectaid",
Version = "1.0",
Assembled = DateTimeOffset.MinValue,
SelectedPackages = new List<SelectedPackage>
{
new SelectedPackage("Deploy a package", "1.0")
},
ReleaseNotes = "Release Notes 1"
},
new ReleaseResource
{
ProjectId = "projectaid",
Version = "2.0",
Assembled = DateTimeOffset.MaxValue,
ReleaseNotes = "Release Notes 2"
},
new ReleaseResource
{
ProjectId = VersionControlledProjectId,
Version = "1.2.3",
Assembled = DateTimeOffset.MaxValue,
ReleaseNotes = "Version controlled release notes",
VersionControlReference = new VersionControlReferenceResource
{
GitCommit = "87a072ad2b4a2e9bf2d7ff84d8636a032786394d",
GitRef = "main"
}
}
});
CommandLineArgs.Add("--project=ProjectA");
await listReleasesCommand.Execute(CommandLineArgs.ToArray()).ConfigureAwait(false);
this.Assent(LogOutput.ToString().ScrubApprovalString());
}
[Test]
public async Task JsonFormat_ShouldBeWellFormed()
{
Repository.Projects.FindByNames(Arg.Any<IEnumerable<string>>()).Returns(new List<ProjectResource>
{
new ProjectResource {Name = "ProjectA", Id = "projectaid"},
new ProjectResource {Name = "ProjectB", Id = "projectbid"},
new ProjectResource {Name = "Version controlled project", Id = VersionControlledProjectId}
});
Repository.Releases.FindMany(Arg.Any<Func<ReleaseResource, bool>>()).Returns(new List<ReleaseResource>
{
new ReleaseResource
{
ProjectId = "projectaid",
Version = "1.0",
Assembled = DateTimeOffset.MinValue,
ReleaseNotes = "Release Notes 1"
},
new ReleaseResource
{
ProjectId = "projectaid",
Version = "2.0",
Assembled = DateTimeOffset.MaxValue,
ReleaseNotes = "Release Notes 2"
},
new ReleaseResource
{
ProjectId = VersionControlledProjectId,
Version = "1.2.3",
Assembled = DateTimeOffset.MaxValue,
ReleaseNotes = "Version controlled release notes",
VersionControlReference = new VersionControlReferenceResource
{
GitCommit = "87a072ad2b4a2e9bf2d7ff84d8636a032786394d",
GitRef = "main"
}
}
});
CommandLineArgs.Add("--project=ProjectA");
CommandLineArgs.Add("--outputFormat=json");
await listReleasesCommand.Execute(CommandLineArgs.ToArray()).ConfigureAwait(false);
this.Assent(LogOutput.ToString().ScrubApprovalString());
}
}
}
| 38.054688 | 127 | 0.538698 | [
"Apache-2.0"
] | eberzosa/OctopusCLI | source/Octo.Tests/Commands/ListReleasesCommandFixture.cs | 4,873 | C# |
using System;
using Microsoft.AspNetCore.SignalR;
namespace OptimaJet.DWKit.StarterApplication.Utility
{
public class ScriptoriaIdProvider : IUserIdProvider
{
public virtual string GetUserId(HubConnectionContext connection)
{
var auth0Id = connection.GetHttpContext()?.GetAuth0Id();
return auth0Id;
}
}
}
| 24.466667 | 72 | 0.683924 | [
"MIT"
] | garrett-hopper/appbuilder-portal | source/OptimaJet.DWKit.StarterApplication/Utility/ScriptoriaIdProvider.cs | 369 | 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 sagemaker-2017-07-24.normal.json service model.
*/
using Amazon.Runtime;
namespace Amazon.SageMaker.Model
{
/// <summary>
/// Paginator for the ListDataQualityJobDefinitions operation
///</summary>
public interface IListDataQualityJobDefinitionsPaginator
{
/// <summary>
/// Enumerable containing all full responses for the operation
/// </summary>
IPaginatedEnumerable<ListDataQualityJobDefinitionsResponse> Responses { get; }
/// <summary>
/// Enumerable containing all of the JobDefinitionSummaries
/// </summary>
IPaginatedEnumerable<MonitoringJobDefinitionSummary> JobDefinitionSummaries { get; }
}
}
#endif | 34.1 | 107 | 0.708211 | [
"Apache-2.0"
] | PureKrome/aws-sdk-net | sdk/src/Services/SageMaker/Generated/Model/_bcl45+netstandard/IListDataQualityJobDefinitionsPaginator.cs | 1,364 | C# |
#region Apache License Version 2.0
/*----------------------------------------------------------------
Copyright 2021 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd.
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.
Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md
----------------------------------------------------------------*/
#endregion Apache License Version 2.0
using Senparc.Weixin.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Senparc.Weixin.MP.AdvancedAPIs.UserTag
{
public class TagJson : WxJsonResult
{
public List<TagJson_Tag> tags { get; set; }
}
public class TagJson_Tag
{
public int id { get; set; }
public string name { get; set; }
public int count { get; set; }
}
}
| 32.634146 | 90 | 0.670404 | [
"Apache-2.0"
] | 554393109/WeiXinMPSDK | src/Senparc.Weixin.MP/Senparc.Weixin.MP/AdvancedAPIs/UserTag/UserTagJson/TagJson.cs | 1,340 | 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 CloudAwesome.Xrm.Customisation
{
[System.Runtime.Serialization.DataContractAttribute()]
public enum AppModuleState
{
[System.Runtime.Serialization.EnumMemberAttribute()]
Active = 0,
[System.Runtime.Serialization.EnumMemberAttribute()]
Inactive = 1,
}
/// <summary>
/// A role-based, modular business app that provides task-based functionality for a particular area of work.
/// </summary>
[System.Runtime.Serialization.DataContractAttribute()]
[Microsoft.Xrm.Sdk.Client.EntityLogicalNameAttribute("appmodule")]
public partial class AppModule : Microsoft.Xrm.Sdk.Entity, System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged
{
public static class Fields
{
public const string AppModuleId = "appmoduleid";
public const string Id = "appmoduleid";
public const string AppModuleIdUnique = "appmoduleidunique";
public const string AppModuleVersion = "appmoduleversion";
public const string AppModuleXmlManaged = "appmodulexmlmanaged";
public const string ClientType = "clienttype";
public const string ComponentState = "componentstate";
public const string ConfigXML = "configxml";
public const string CreatedBy = "createdby";
public const string CreatedOn = "createdon";
public const string CreatedOnBehalfBy = "createdonbehalfby";
public const string Description = "description";
public const string Descriptor = "descriptor";
public const string EventHandlers = "eventhandlers";
public const string FormFactor = "formfactor";
public const string ImportSequenceNumber = "importsequencenumber";
public const string IntroducedVersion = "introducedversion";
public const string IsDefault = "isdefault";
public const string IsFeatured = "isfeatured";
public const string IsManaged = "ismanaged";
public const string ModifiedBy = "modifiedby";
public const string ModifiedOn = "modifiedon";
public const string ModifiedOnBehalfBy = "modifiedonbehalfby";
public const string Name = "name";
public const string NavigationType = "navigationtype";
public const string OptimizedFor = "optimizedfor";
public const string OrganizationId = "organizationid";
public const string OverriddenCreatedOn = "overriddencreatedon";
public const string OverwriteTime = "overwritetime";
public const string PublishedOn = "publishedon";
public const string PublisherId = "publisherid";
public const string SolutionId = "solutionid";
public const string StateCode = "statecode";
public const string StatusCode = "statuscode";
public const string UniqueName = "uniquename";
public const string URL = "url";
public const string VersionNumber = "versionnumber";
public const string WebResourceId = "webresourceid";
public const string WelcomePageId = "welcomepageid";
public const string publisher_appmodule = "publisher_appmodule";
}
/// <summary>
/// Default Constructor.
/// </summary>
[System.Diagnostics.DebuggerNonUserCode()]
public AppModule() :
base(EntityLogicalName)
{
}
public const string AlternateKeys = "componentstate,overwritetime,uniquename";
public const string EntityLogicalName = "appmodule";
public const string EntitySchemaName = "AppModule";
public const string PrimaryIdAttribute = "appmoduleid";
public const string PrimaryNameAttribute = "name";
public const string EntityLogicalCollectionName = "appmodules";
public const string EntitySetName = "appmodules";
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;
[System.Diagnostics.DebuggerNonUserCode()]
private void OnPropertyChanged(string propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
[System.Diagnostics.DebuggerNonUserCode()]
private void OnPropertyChanging(string propertyName)
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, new System.ComponentModel.PropertyChangingEventArgs(propertyName));
}
}
/// <summary>
/// Unique identifier for entity instances
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("appmoduleid")]
public System.Nullable<System.Guid> AppModuleId
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<System.Guid>>("appmoduleid");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("AppModuleId");
this.SetAttributeValue("appmoduleid", value);
if (value.HasValue)
{
base.Id = value.Value;
}
else
{
base.Id = System.Guid.Empty;
}
this.OnPropertyChanged("AppModuleId");
}
}
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("appmoduleid")]
public override System.Guid Id
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return base.Id;
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.AppModuleId = value;
}
}
/// <summary>
/// Unique identifier of the App Module used when synchronizing customizations for the Microsoft Dynamics 365 client for Outlook
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("appmoduleidunique")]
public System.Nullable<System.Guid> AppModuleIdUnique
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<System.Guid>>("appmoduleidunique");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("AppModuleIdUnique");
this.SetAttributeValue("appmoduleidunique", value);
this.OnPropertyChanged("AppModuleIdUnique");
}
}
/// <summary>
/// App Module Version
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("appmoduleversion")]
public string AppModuleVersion
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<string>("appmoduleversion");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("AppModuleVersion");
this.SetAttributeValue("appmoduleversion", value);
this.OnPropertyChanged("AppModuleVersion");
}
}
/// <summary>
/// App Module Xml Managed
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("appmodulexmlmanaged")]
public string AppModuleXmlManaged
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<string>("appmodulexmlmanaged");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("AppModuleXmlManaged");
this.SetAttributeValue("appmodulexmlmanaged", value);
this.OnPropertyChanged("AppModuleXmlManaged");
}
}
/// <summary>
/// Client Type such as Web or UCI
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("clienttype")]
public System.Nullable<int> ClientType
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<int>>("clienttype");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("ClientType");
this.SetAttributeValue("clienttype", value);
this.OnPropertyChanged("ClientType");
}
}
/// <summary>
/// For internal use only
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("componentstate")]
public virtual ComponentState? ComponentState
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return ((ComponentState?)(EntityOptionSetEnum.GetEnum(this, "componentstate")));
}
}
/// <summary>
/// Contains configuration XML
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("configxml")]
public string ConfigXML
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<string>("configxml");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("ConfigXML");
this.SetAttributeValue("configxml", value);
this.OnPropertyChanged("ConfigXML");
}
}
/// <summary>
/// Unique identifier of the user who created the record.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdby")]
public Microsoft.Xrm.Sdk.EntityReference CreatedBy
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("createdby");
}
}
/// <summary>
/// Date and time when the record was created.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdon")]
public System.Nullable<System.DateTime> CreatedOn
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<System.DateTime>>("createdon");
}
}
/// <summary>
/// Unique identifier of the delegate user who created the record.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdonbehalfby")]
public Microsoft.Xrm.Sdk.EntityReference CreatedOnBehalfBy
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("createdonbehalfby");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("CreatedOnBehalfBy");
this.SetAttributeValue("createdonbehalfby", value);
this.OnPropertyChanged("CreatedOnBehalfBy");
}
}
/// <summary>
/// Description for entity
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("description")]
public string Description
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<string>("description");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("Description");
this.SetAttributeValue("description", value);
this.OnPropertyChanged("Description");
}
}
/// <summary>
/// App Module Descriptor
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("descriptor")]
public string Descriptor
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<string>("descriptor");
}
}
/// <summary>
/// App Module Event Handlers
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("eventhandlers")]
public string EventHandlers
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<string>("eventhandlers");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("EventHandlers");
this.SetAttributeValue("eventhandlers", value);
this.OnPropertyChanged("EventHandlers");
}
}
/// <summary>
/// Form Factor
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("formfactor")]
public System.Nullable<int> FormFactor
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<int>>("formfactor");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("FormFactor");
this.SetAttributeValue("formfactor", value);
this.OnPropertyChanged("FormFactor");
}
}
/// <summary>
/// Unique identifier of the data import or data migration that created this record.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("importsequencenumber")]
public System.Nullable<int> ImportSequenceNumber
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<int>>("importsequencenumber");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("ImportSequenceNumber");
this.SetAttributeValue("importsequencenumber", value);
this.OnPropertyChanged("ImportSequenceNumber");
}
}
/// <summary>
/// Version in which the similarity rule is introduced.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("introducedversion")]
public string IntroducedVersion
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<string>("introducedversion");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("IntroducedVersion");
this.SetAttributeValue("introducedversion", value);
this.OnPropertyChanged("IntroducedVersion");
}
}
/// <summary>
/// Is Default
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("isdefault")]
public System.Nullable<bool> IsDefault
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<bool>>("isdefault");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("IsDefault");
this.SetAttributeValue("isdefault", value);
this.OnPropertyChanged("IsDefault");
}
}
/// <summary>
/// Is Featured
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("isfeatured")]
public System.Nullable<bool> IsFeatured
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<bool>>("isfeatured");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("IsFeatured");
this.SetAttributeValue("isfeatured", value);
this.OnPropertyChanged("IsFeatured");
}
}
/// <summary>
/// Is Managed
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("ismanaged")]
public System.Nullable<bool> IsManaged
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<bool>>("ismanaged");
}
}
/// <summary>
/// Unique identifier of the user who modified the record.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedby")]
public Microsoft.Xrm.Sdk.EntityReference ModifiedBy
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("modifiedby");
}
}
/// <summary>
/// Date and time when the record was modified.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedon")]
public System.Nullable<System.DateTime> ModifiedOn
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<System.DateTime>>("modifiedon");
}
}
/// <summary>
/// Unique identifier of the delegate user who modified the record.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedonbehalfby")]
public Microsoft.Xrm.Sdk.EntityReference ModifiedOnBehalfBy
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("modifiedonbehalfby");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("ModifiedOnBehalfBy");
this.SetAttributeValue("modifiedonbehalfby", value);
this.OnPropertyChanged("ModifiedOnBehalfBy");
}
}
/// <summary>
/// Name of App Module
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("name")]
public string Name
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<string>("name");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("Name");
this.SetAttributeValue("name", value);
this.OnPropertyChanged("Name");
}
}
/// <summary>
/// App navigation type
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("navigationtype")]
public virtual AppModule_NavigationType? NavigationType
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return ((AppModule_NavigationType?)(EntityOptionSetEnum.GetEnum(this, "navigationtype")));
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("NavigationType");
this.SetAttributeValue("navigationtype", value.HasValue ? new Microsoft.Xrm.Sdk.OptionSetValue((int)value) : null);
this.OnPropertyChanged("NavigationType");
}
}
/// <summary>
/// The client that this app is optimized for
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("optimizedfor")]
public string OptimizedFor
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<string>("optimizedfor");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("OptimizedFor");
this.SetAttributeValue("optimizedfor", value);
this.OnPropertyChanged("OptimizedFor");
}
}
/// <summary>
/// Unique identifier of the organization associated with the app.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("organizationid")]
public Microsoft.Xrm.Sdk.EntityReference OrganizationId
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("organizationid");
}
}
/// <summary>
/// Date and time that the record was migrated.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("overriddencreatedon")]
public System.Nullable<System.DateTime> OverriddenCreatedOn
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<System.DateTime>>("overriddencreatedon");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("OverriddenCreatedOn");
this.SetAttributeValue("overriddencreatedon", value);
this.OnPropertyChanged("OverriddenCreatedOn");
}
}
/// <summary>
/// Internal use only
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("overwritetime")]
public System.Nullable<System.DateTime> OverwriteTime
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<System.DateTime>>("overwritetime");
}
}
/// <summary>
/// Date and time when the record was published.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("publishedon")]
public System.Nullable<System.DateTime> PublishedOn
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<System.DateTime>>("publishedon");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("PublishedOn");
this.SetAttributeValue("publishedon", value);
this.OnPropertyChanged("PublishedOn");
}
}
/// <summary>
/// Unique identifier of the publisher.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("publisherid")]
public Microsoft.Xrm.Sdk.EntityReference PublisherId
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("publisherid");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("PublisherId");
this.SetAttributeValue("publisherid", value);
this.OnPropertyChanged("PublisherId");
}
}
/// <summary>
/// Unique identifier of the associated solution.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("solutionid")]
public System.Nullable<System.Guid> SolutionId
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<System.Guid>>("solutionid");
}
}
/// <summary>
/// Status of the Model-driven App
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("statecode")]
public System.Nullable<CloudAwesome.Xrm.Customisation.AppModuleState> StateCode
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
Microsoft.Xrm.Sdk.OptionSetValue optionSet = this.GetAttributeValue<Microsoft.Xrm.Sdk.OptionSetValue>("statecode");
if ((optionSet != null))
{
return ((CloudAwesome.Xrm.Customisation.AppModuleState)(System.Enum.ToObject(typeof(CloudAwesome.Xrm.Customisation.AppModuleState), optionSet.Value)));
}
else
{
return null;
}
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("StateCode");
if ((value == null))
{
this.SetAttributeValue("statecode", null);
}
else
{
this.SetAttributeValue("statecode", new Microsoft.Xrm.Sdk.OptionSetValue(((int)(value))));
}
this.OnPropertyChanged("StateCode");
}
}
/// <summary>
/// Reason for the status of the Model-driven App
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("statuscode")]
public virtual AppModule_StatusCode? StatusCode
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return ((AppModule_StatusCode?)(EntityOptionSetEnum.GetEnum(this, "statuscode")));
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("StatusCode");
this.SetAttributeValue("statuscode", value.HasValue ? new Microsoft.Xrm.Sdk.OptionSetValue((int)value) : null);
this.OnPropertyChanged("StatusCode");
}
}
/// <summary>
/// Unique Name of App Module
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("uniquename")]
public string UniqueName
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<string>("uniquename");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("UniqueName");
this.SetAttributeValue("uniquename", value);
this.OnPropertyChanged("UniqueName");
}
}
/// <summary>
/// Contains URL
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("url")]
public string URL
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<string>("url");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("URL");
this.SetAttributeValue("url", value);
this.OnPropertyChanged("URL");
}
}
/// <summary>
///
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("versionnumber")]
public System.Nullable<long> VersionNumber
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<long>>("versionnumber");
}
}
/// <summary>
/// Unique identifier of the Web Resource
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("webresourceid")]
public System.Nullable<System.Guid> WebResourceId
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<System.Guid>>("webresourceid");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("WebResourceId");
this.SetAttributeValue("webresourceid", value);
this.OnPropertyChanged("WebResourceId");
}
}
/// <summary>
/// Unique identifier of the Web Resource as Welcome Page Id
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("welcomepageid")]
public System.Nullable<System.Guid> WelcomePageId
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<System.Guid>>("welcomepageid");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("WelcomePageId");
this.SetAttributeValue("welcomepageid", value);
this.OnPropertyChanged("WelcomePageId");
}
}
/// <summary>
/// 1:N appmodule_appelement_parentappmoduleid
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("appmodule_appelement_parentappmoduleid")]
public System.Collections.Generic.IEnumerable<CloudAwesome.Xrm.Customisation.AppElement> appmodule_appelement_parentappmoduleid
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<CloudAwesome.Xrm.Customisation.AppElement>("appmodule_appelement_parentappmoduleid", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("appmodule_appelement_parentappmoduleid");
this.SetRelatedEntities<CloudAwesome.Xrm.Customisation.AppElement>("appmodule_appelement_parentappmoduleid", null, value);
this.OnPropertyChanged("appmodule_appelement_parentappmoduleid");
}
}
/// <summary>
/// 1:N appmodule_appmodulecomponent
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("appmodule_appmodulecomponent")]
public System.Collections.Generic.IEnumerable<CloudAwesome.Xrm.Customisation.AppModuleComponent> appmodule_appmodulecomponent
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<CloudAwesome.Xrm.Customisation.AppModuleComponent>("appmodule_appmodulecomponent", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("appmodule_appmodulecomponent");
this.SetRelatedEntities<CloudAwesome.Xrm.Customisation.AppModuleComponent>("appmodule_appmodulecomponent", null, value);
this.OnPropertyChanged("appmodule_appmodulecomponent");
}
}
/// <summary>
/// 1:N appmodule_appsetting_parentappmoduleid
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("appmodule_appsetting_parentappmoduleid")]
public System.Collections.Generic.IEnumerable<CloudAwesome.Xrm.Customisation.AppSetting> appmodule_appsetting_parentappmoduleid
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<CloudAwesome.Xrm.Customisation.AppSetting>("appmodule_appsetting_parentappmoduleid", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("appmodule_appsetting_parentappmoduleid");
this.SetRelatedEntities<CloudAwesome.Xrm.Customisation.AppSetting>("appmodule_appsetting_parentappmoduleid", null, value);
this.OnPropertyChanged("appmodule_appsetting_parentappmoduleid");
}
}
/// <summary>
/// N:N appmoduleroles_association
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("appmoduleroles_association")]
public System.Collections.Generic.IEnumerable<CloudAwesome.Xrm.Customisation.Role> appmoduleroles_association
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<CloudAwesome.Xrm.Customisation.Role>("appmoduleroles_association", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("appmoduleroles_association");
this.SetRelatedEntities<CloudAwesome.Xrm.Customisation.Role>("appmoduleroles_association", null, value);
this.OnPropertyChanged("appmoduleroles_association");
}
}
/// <summary>
/// N:1 publisher_appmodule
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("publisherid")]
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("publisher_appmodule")]
public CloudAwesome.Xrm.Customisation.Publisher publisher_appmodule
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntity<CloudAwesome.Xrm.Customisation.Publisher>("publisher_appmodule", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("publisher_appmodule");
this.SetRelatedEntity<CloudAwesome.Xrm.Customisation.Publisher>("publisher_appmodule", null, value);
this.OnPropertyChanged("publisher_appmodule");
}
}
/// <summary>
/// Constructor for populating via LINQ queries given a LINQ anonymous type
/// <param name="anonymousType">LINQ anonymous type.</param>
/// </summary>
[System.Diagnostics.DebuggerNonUserCode()]
public AppModule(object anonymousType) :
this()
{
foreach (var p in anonymousType.GetType().GetProperties())
{
var value = p.GetValue(anonymousType, null);
var name = p.Name.ToLower();
if (name.EndsWith("enum") && value.GetType().BaseType == typeof(System.Enum))
{
value = new Microsoft.Xrm.Sdk.OptionSetValue((int) value);
name = name.Remove(name.Length - "enum".Length);
}
switch (name)
{
case "id":
base.Id = (System.Guid)value;
Attributes["appmoduleid"] = base.Id;
break;
case "appmoduleid":
var id = (System.Nullable<System.Guid>) value;
if(id == null){ continue; }
base.Id = id.Value;
Attributes[name] = base.Id;
break;
case "formattedvalues":
// Add Support for FormattedValues
FormattedValues.AddRange((Microsoft.Xrm.Sdk.FormattedValueCollection)value);
break;
default:
Attributes[name] = value;
break;
}
}
}
}
} | 29.959432 | 156 | 0.699255 | [
"MIT"
] | Cloud-Awesome/cds-customisation | src/CloudAwesome.Xrm.Customisation/CloudAwesome.Xrm.Customisation/EarlyBoundModels/AppModule.cs | 29,540 | C# |
using System.Text.Json.Serialization;
using Newtonsoft.Json;
using ProtoBuf;
namespace BO4E.COM
{
/// <summary>Diese Komponente liefert die Geokoordinaten für einen Ort.</summary>
[ProtoContract]
public class Geokoordinaten : COM
{
/// <summary>Gibt den Breitengrad eines entsprechenden Ortes an.</summary>
[JsonProperty(PropertyName = "breitengrad", Required = Required.Always)]
[JsonPropertyName("breitengrad")]
[ProtoMember(3)]
public decimal Breitengrad { get; set; }
/// <summary>Gibt den Längengrad eines entsprechenden Ortes an.</summary>
[JsonProperty(PropertyName = "laengengrad", Required = Required.Always)]
[JsonPropertyName("laengengrad")]
[ProtoMember(4)]
public decimal Laengengrad { get; set; }
}
} | 36.434783 | 86 | 0.658711 | [
"MIT"
] | HFInnovation/BO4E-dotnet | BO4E/COM/Geokoordinaten.cs | 818 | C# |
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
namespace k8s
{
/// <summary>
/// <para>
/// The <see cref="StreamDemuxer"/> allows you to interact with processes running in a container in a Kubernetes pod. You can start an exec or attach command
/// by calling <see cref="Kubernetes.WebSocketNamespacedPodExecAsync(string, string, IEnumerable{string}, string, bool, bool, bool, bool, Dictionary{string, List{string}}, CancellationToken)"/>
/// or <see cref="Kubernetes.WebSocketNamespacedPodAttachAsync(string, string, string, bool, bool, bool, bool, Dictionary{string, List{string}}, CancellationToken)"/>. These methods
/// will return you a <see cref="WebSocket"/> connection.
/// </para>
/// <para>
/// Kubernetes 'multiplexes' multiple channels over this <see cref="WebSocket"/> connection, such as standard input, standard output and standard error. The <see cref="StreamDemuxer"/>
/// allows you to extract individual <see cref="Stream"/>s from this <see cref="WebSocket"/> class. You can then use these streams to send/receive data from that process.
/// </para>
/// </summary>
public class StreamDemuxer : IStreamDemuxer
{
private readonly WebSocket webSocket;
private readonly Dictionary<byte, ByteBuffer> buffers = new Dictionary<byte, ByteBuffer>();
private readonly CancellationTokenSource cts = new CancellationTokenSource();
private readonly StreamType streamType;
private readonly bool ownsSocket;
private Task runLoop;
/// <summary>
/// Initializes a new instance of the <see cref="StreamDemuxer"/> class.
/// </summary>
/// <param name="webSocket">
/// A <see cref="WebSocket"/> which contains a multiplexed stream, such as the <see cref="WebSocket"/> returned by the exec or attach commands.
/// </param>
/// <param name="streamType">
/// A <see cref="StreamType"/> specifies the type of the stream.
/// </param>
/// <param name="ownsSocket">
/// A value indicating whether this instance of the <see cref="StreamDemuxer"/> owns the underlying <see cref="WebSocket"/>,
/// and should dispose of it when this instance is disposed of.
/// </param>
public StreamDemuxer(WebSocket webSocket, StreamType streamType = StreamType.RemoteCommand, bool ownsSocket = false)
{
this.streamType = streamType;
this.webSocket = webSocket ?? throw new ArgumentNullException(nameof(webSocket));
this.ownsSocket = ownsSocket;
}
public event EventHandler ConnectionClosed;
/// <summary>
/// Starts reading the data sent by the server.
/// </summary>
public void Start()
{
this.runLoop = this.RunLoop(this.cts.Token);
}
/// <inheritdoc/>
public void Dispose()
{
try
{
if (this.runLoop != null)
{
this.cts.Cancel();
this.runLoop.Wait();
}
}
catch (Exception ex)
{
// Dispose methods can never throw.
Debug.Write(ex);
}
if (this.ownsSocket)
{
this.webSocket.Dispose();
}
}
/// <summary>
/// Gets a <see cref="Stream"/> which allows you to read to and/or write from a remote channel.
/// </summary>
/// <param name="inputIndex">
/// The index of the channel from which to read.
/// </param>
/// <param name="outputIndex">
/// The index of the channel to which to write.
/// </param>
/// <returns>
/// A <see cref="Stream"/> which allows you to read/write to the requested channels.
/// </returns>
public Stream GetStream(ChannelIndex? inputIndex, ChannelIndex? outputIndex)
{
return GetStream((byte?)inputIndex, (byte?)outputIndex);
}
/// <summary>
/// Gets a <see cref="Stream"/> which allows you to read to and/or write from a remote channel.
/// </summary>
/// <param name="inputIndex">
/// The index of the channel from which to read.
/// </param>
/// <param name="outputIndex">
/// The index of the channel to which to write.
/// </param>
/// <returns>
/// A <see cref="Stream"/> which allows you to read/write to the requested channels.
/// </returns>
public Stream GetStream(byte? inputIndex, byte? outputIndex)
{
lock (this.buffers)
{
if (inputIndex != null && !this.buffers.ContainsKey(inputIndex.Value))
{
var buffer = new ByteBuffer();
this.buffers.Add(inputIndex.Value, buffer);
}
}
var inputBuffer = inputIndex == null ? null : this.buffers[inputIndex.Value];
return new MuxedStream(this, inputBuffer, outputIndex);
}
/// <summary>
/// Directly writes data to a channel.
/// </summary>
/// <param name="index">
/// The index of the channel to which to write.
/// </param>
/// <param name="buffer">
/// The buffer from which to read data.
/// </param>
/// <param name="offset">
/// The offset at which to start reading.
/// </param>
/// <param name="count">
/// The number of bytes to read.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> which can be used to cancel the asynchronous operation.
/// </param>
/// <returns>
/// A <see cref="Task"/> which represents the asynchronous operation.
/// </returns>
public Task Write(ChannelIndex index, byte[] buffer, int offset, int count, CancellationToken cancellationToken = default(CancellationToken))
{
return Write((byte)index, buffer, offset, count, cancellationToken);
}
/// <summary>
/// Directly writes data to a channel.
/// </summary>
/// <param name="index">
/// The index of the channel to which to write.
/// </param>
/// <param name="buffer">
/// The buffer from which to read data.
/// </param>
/// <param name="offset">
/// The offset at which to start reading.
/// </param>
/// <param name="count">
/// The number of bytes to read.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> which can be used to cancel the asynchronous operation.
/// </param>
/// <returns>
/// A <see cref="Task"/> which represents the asynchronous operation.
/// </returns>
public async Task Write(byte index, byte[] buffer, int offset, int count, CancellationToken cancellationToken = default(CancellationToken))
{
byte[] writeBuffer = ArrayPool<byte>.Shared.Rent(count + 1);
try
{
writeBuffer[0] = (byte)index;
Array.Copy(buffer, offset, writeBuffer, 1, count);
ArraySegment<byte> segment = new ArraySegment<byte>(writeBuffer, 0, count + 1);
await this.webSocket.SendAsync(segment, WebSocketMessageType.Binary, false, cancellationToken).ConfigureAwait(false);
}
finally
{
ArrayPool<byte>.Shared.Return(writeBuffer);
}
}
protected async Task RunLoop(CancellationToken cancellationToken)
{
// This is a background task. Immediately yield to the caller.
await Task.Yield();
// Get a 1KB buffer
byte[] buffer = ArrayPool<byte>.Shared.Rent(1024 * 1024);
// This maps remembers bytes skipped for each stream.
Dictionary<byte, int> streamBytesToSkipMap = new Dictionary<byte, int>();
try
{
var segment = new ArraySegment<byte>(buffer);
while (!cancellationToken.IsCancellationRequested && this.webSocket.CloseStatus == null)
{
// We always get data in this format:
// [stream index] (1 for stdout, 2 for stderr)
// [payload]
var result = await this.webSocket.ReceiveAsync(segment, cancellationToken).ConfigureAwait(false);
// Ignore empty messages
if (result.Count < 2)
{
continue;
}
var streamIndex = buffer[0];
var extraByteCount = 1;
while (true)
{
int bytesToSkip = 0;
if (!streamBytesToSkipMap.TryGetValue(streamIndex, out bytesToSkip))
{
// When used in port-forwarding, the first 2 bytes from the web socket is port bytes, skip.
// https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/server/portforward/websocket.go
bytesToSkip = this.streamType == StreamType.PortForward ? 2 : 0;
}
int bytesCount = result.Count - extraByteCount;
if (bytesToSkip > 0 && bytesToSkip >= bytesCount)
{
// skip the entire data.
bytesToSkip -= bytesCount;
extraByteCount += bytesCount;
bytesCount = 0;
}
else
{
bytesCount -= bytesToSkip;
extraByteCount += bytesToSkip;
bytesToSkip = 0;
if (this.buffers.ContainsKey(streamIndex))
{
this.buffers[streamIndex].Write(buffer, extraByteCount, bytesCount);
}
}
streamBytesToSkipMap[streamIndex] = bytesToSkip;
if (result.EndOfMessage == true)
{
break;
}
extraByteCount = 0;
result = await this.webSocket.ReceiveAsync(segment, cancellationToken).ConfigureAwait(false);
}
}
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
this.runLoop = null;
foreach (var b in this.buffers.Values)
{
b.WriteEnd();
}
this.ConnectionClosed?.Invoke(this, EventArgs.Empty);
}
}
}
}
| 40.571429 | 201 | 0.527993 | [
"Apache-2.0"
] | Gearset/kubernetes-client | src/KubernetesClient/StreamDemuxer.cs | 11,360 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Harmony;
using System.Reflection;
using Verse;
using RimWorld;
using UnityEngine;
namespace RD_WildAnimalAlert
{
[StaticConstructorOnStartup]
class Main
{
static Main()
{
Log.Message("[RD_WildAnimalAlert] Initialising...");
var harmony = HarmonyInstance.Create("org.rd.wildanimalalert");
harmony.PatchAll(Assembly.GetExecutingAssembly());
Log.Message("[RD_WildAnimalAlert] Success! Probably.");
}
}
[HarmonyPatch(typeof(WildSpawner))]
[HarmonyPatch("SpawnRandomWildAnimalAt")]
[HarmonyPatch(new Type[] { typeof(IntVec3)})]
class Patch
{
static float CurrentTotalAnimalNumber(WildSpawner __instance)
{
// map is a private field so we access it with Traverse
var trv = Traverse.Create(__instance);
Map map = trv.Field("map").GetValue<Map>();
// count all animals on the map
float num = 0f;
List<Pawn> allPawnsSpawned = map.mapPawns.AllPawnsSpawned;
for (int i = 0; i < allPawnsSpawned.Count; i++)
{
if (allPawnsSpawned[i].kindDef.wildSpawn_spawnWild && allPawnsSpawned[i].Faction == null)
{
num ++;
}
}
// return the amount of animals on the map
return num;
}
static bool Prefix(WildSpawner __instance, IntVec3 loc)
{
// map is private so we access it with Traverse
var trv = Traverse.Create(__instance);
Map map = trv.Field("map").GetValue<Map>();
Pawn newThing = null;
if (map == null)
{
Log.Message("[RD_WildAnimalAlert] Map is null, something is wrong here");
return false;
}
// select a valid pawnkind to spawn
PawnKindDef pawnKindDef = (from a in map.Biome.AllWildAnimals
where map.mapTemperature.SeasonAcceptableFor(a.race)
select a).RandomElementByWeight((PawnKindDef def) => map.Biome.CommonalityOfAnimal(def) / def.wildSpawn_GroupSizeRange.Average);
if (pawnKindDef == null)
{
Log.Error("No spawnable animals right now.");
return false;
}
// choose an amount of pawns to spawn
int randomInRange = pawnKindDef.wildSpawn_GroupSizeRange.RandomInRange;
// and a radius within which to spawn them
int radius = Mathf.CeilToInt(Mathf.Sqrt((float)pawnKindDef.wildSpawn_GroupSizeRange.max));
string text = "DEBUG STRING: something went wrong, contact lost_RD with details";
// check the amount of animals on the map
float animals_before_current_spawns = CurrentTotalAnimalNumber(__instance);
if (randomInRange > 1)
{
// text to use when spawning more than one animal
text = String.Concat(new string[] { "A group of ", randomInRange.ToString(), " wild ", pawnKindDef.label, " appeared!" });
}
for (int i = 0; i < randomInRange; i++)
{
// find a valid place to spawn the pawns
IntVec3 loc2 = CellFinder.RandomClosewalkCellNear(loc, map, radius);
newThing = PawnGenerator.GeneratePawn(pawnKindDef, null);
GenSpawn.Spawn(newThing, loc2, map);
if (randomInRange == 1)
{
// text to use when spawning only one animal
text = String.Concat(new string[] { "A wild ", newThing.Label, " appeared! ",
newThing.gender.ToString(), " ", newThing.Label, ", ",
newThing.ageTracker.AgeBiologicalYears.ToString(), " years old. ",
});
}
}
// check whether the alert should be played
//ternary operators are a thing of beauty.
if ((animals_before_current_spawns < Settings.AnimalCount) && (Settings.EnableMod) && ((Settings.PredatorOnly) ? newThing.RaceProps.predator : true))
{
Messages.Message(text, new TargetInfo(loc, map, false), MessageTypeDefOf.NeutralEvent);
}
// return false to prevent the vanilla code from running (which would spawn another animal/group of animals)
return false;
}
}
}
| 35.082569 | 152 | 0.6875 | [
"MIT"
] | Mehni/WildAnimalAlert | Source/WildAnimalAlert/Main.cs | 3,826 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Linq;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.Integration;
using Microsoft.Bot.Builder.Integration.AspNet.Core;
using Microsoft.Bot.Configuration;
using Microsoft.Bot.Connector.Authentication;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Microsoft.BotBuilderSamples
{
/// <summary>
/// The Startup class configures services and the app's request pipeline.
/// </summary>
public class Startup
{
private ILoggerFactory _loggerFactory;
private bool _isProduction = false;
public Startup(IHostingEnvironment env)
{
_isProduction = env.IsProduction();
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddEnvironmentVariables();
this.Configuration = builder.Build();
}
/// <summary>
/// Gets the configuration that represents a set of key/value application configuration properties.
/// </summary>
/// <value>
/// The <see cref="IConfiguration"/> that represents a set of key/value application configuration properties.
/// </value>
public IConfiguration Configuration { get; }
/// <summary>
/// This method gets called by the runtime. Use this method to add services to the container.
/// </summary>
/// <param name="services">Specifies the contract for a <see cref="IServiceCollection"/> of service descriptors.</param>
/// <seealso cref="IStatePropertyAccessor{T}"/>
/// <seealso cref="https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/dependency-injection"/>
/// <seealso cref="https://docs.microsoft.com/en-us/azure/bot-service/bot-service-manage-channels?view=azure-bot-service-4.0"/>
public void ConfigureServices(IServiceCollection services)
{
services.AddBot<CardsBot>(options =>
{
var secretKey = Configuration.GetSection("botFileSecret")?.Value;
var botFilePath = Configuration.GetSection("botFilePath")?.Value;
// Loads .bot configuration file and adds a singleton that your Bot can access through dependency injection.
var botConfig = BotConfiguration.Load(botFilePath ?? @".\BotConfiguration.bot", secretKey);
services.AddSingleton(sp => botConfig ?? throw new InvalidOperationException($"The .bot configuration file could not be loaded. botFilePath: {botFilePath}"));
// Retrieve current endpoint.
var environment = _isProduction ? "production" : "development";
var service = botConfig.Services.FirstOrDefault(s => s.Type == "endpoint" && s.Name == environment);
if (!(service is EndpointService endpointService))
{
throw new InvalidOperationException($"The .bot file does not contain an endpoint with name '{environment}'.");
}
options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword);
// Creates a logger for the application to use.
ILogger logger = _loggerFactory.CreateLogger<CardsBot>();
// Catches any errors that occur during a conversation turn and logs them.
options.OnTurnError = async (context, exception) =>
{
logger.LogError($"Exception caught : {exception}");
await context.SendActivityAsync("Sorry, it looks like something went wrong.");
};
// The Memory Storage used here is for local bot debugging only. When the bot
// is restarted, everything stored in memory will be gone.
IStorage dataStore = new MemoryStorage();
// For production bots use the Azure Blob or
// Azure CosmosDB storage providers. For the Azure
// based storage providers, add the Microsoft.Bot.Builder.Azure
// Nuget package to your solution. That package is found at:
// https://www.nuget.org/packages/Microsoft.Bot.Builder.Azure/
// Uncomment the following lines to use Azure Blob Storage
// //Storage configuration name or ID from the .bot file.
// const string StorageConfigurationId = "<STORAGE-NAME-OR-ID-FROM-BOT-FILE>";
// var blobConfig = botConfig.FindServiceByNameOrId(StorageConfigurationId);
// if (!(blobConfig is BlobStorageService blobStorageConfig))
// {
// throw new InvalidOperationException($"The .bot file does not contain an blob storage with name '{StorageConfigurationId}'.");
// }
// // Default container name.
// const string DefaultBotContainer = "<DEFAULT-CONTAINER>";
// var storageContainer = string.IsNullOrWhiteSpace(blobStorageConfig.Container) ? DefaultBotContainer : blobStorageConfig.Container;
// IStorage dataStore = new Microsoft.Bot.Builder.Azure.AzureBlobStorage(blobStorageConfig.ConnectionString, storageContainer);
// Create Conversation State object.
// The Conversation State object is where we persist anything at the conversation-scope.
var conversationState = new ConversationState(dataStore);
options.State.Add(conversationState);
});
// Create and register state accessors.
// Accessors created here are passed into the IBot-derived class on every turn.
services.AddSingleton<CardsBotAccessors>(sp =>
{
var options = sp.GetRequiredService<IOptions<BotFrameworkOptions>>().Value;
if (options == null)
{
throw new InvalidOperationException(
"BotFrameworkOptions must be configured prior to setting up the State Accessors");
}
var conversationState = options.State.OfType<ConversationState>().FirstOrDefault();
if (conversationState == null)
{
throw new InvalidOperationException(
"ConversationState must be defined and added before adding conversation-scoped state accessors.");
}
// Create custom state property accessors.
// State property accessors enable components to read and write individual properties,
// without having to pass the entire state object.
var accessors = new CardsBotAccessors(conversationState)
{
ConversationDialogState = conversationState.CreateProperty<DialogState>(CardsBotAccessors.DialogStateName),
};
return accessors;
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
_loggerFactory = loggerFactory;
app.UseDefaultFiles()
.UseStaticFiles()
.UseBotFramework();
}
}
}
| 49.193548 | 174 | 0.628066 | [
"MIT"
] | amr-elsehemy/BotBuilder-Samples | samples/csharp_dotnetcore/06.using-cards/Startup.cs | 7,627 | C# |
using System;
using Fonet.Layout;
using Fonet.Pdf;
using Fonet.Pdf.Gdi;
namespace Fonet.Render.Pdf.Fonts
{
/// <summary>
/// A proxy object that delegates all operations to a concrete
/// subclass of the Font class.
/// </summary>
internal class ProxyFont : Font, IFontDescriptor
{
/// <summary>
/// Flag that indicates whether the underlying font has been loaded.
/// </summary>
private bool _fontLoaded;
/// <summary>
/// Determines what type of "real" font to instantiate.
/// </summary>
private readonly FontType _fontType;
/// <summary>
/// Font details such as face name, bold and italic flags
/// </summary>
private readonly FontProperties _properties;
/// <summary>
/// The font that does all the work.
/// </summary>
private Font _realFont;
/// <summary>
/// Class constructor.
/// </summary>
/// <param name="properties"></param>
/// <param name="fontType"></param>
public ProxyFont( FontProperties properties, FontType fontType )
{
this._properties = properties;
this._fontType = fontType;
}
/// <summary>
/// Gets the underlying font.
/// </summary>
public Font RealFont
{
get
{
LoadIfNecessary();
return _realFont;
}
}
/// <summary>
/// Loads the underlying font.
/// </summary>
private void LoadIfNecessary()
{
if ( !_fontLoaded )
{
switch ( _fontType )
{
case FontType.Link:
_realFont = new TrueTypeFont( _properties );
break;
case FontType.Embed:
case FontType.Subset:
_realFont = LoadCidFont();
break;
default:
throw new Exception( "Unknown font type: " + _fontType );
}
_fontLoaded = true;
}
}
private Font LoadCidFont()
{
switch ( _fontType )
{
case FontType.Embed:
_realFont = new Type2CidFont( _properties );
break;
case FontType.Subset:
_realFont = new Type2CidSubsetFont( _properties );
break;
}
// Flag that indicates whether the CID font should be replaced by a
// base 14 font due to a license violation
var replaceFont = false;
IFontDescriptor descriptor = _realFont.Descriptor;
if ( !descriptor.IsEmbeddable )
{
FonetDriver.ActiveDriver.FireFonetWarning(
string.Format(
"Unable to embed font '{0}' because the license states embedding is not allowed. Will default to Helvetica.",
_realFont.FontName ) );
replaceFont = true;
}
// TODO: Do not permit subsetting if license does not allow it
if ( _realFont is Type2CidSubsetFont && !descriptor.IsSubsettable )
{
FonetDriver.ActiveDriver.FireFonetWarning(
string.Format(
"Unable to subset font '{0}' because the license states subsetting is not allowed.. Will default to Helvetica.",
_realFont.FontName ) );
replaceFont = true;
}
if ( replaceFont )
{
if ( _properties.IsBoldItalic )
_realFont = Base14Font.HelveticaBoldItalic;
else if ( _properties.IsBold )
_realFont = Base14Font.HelveticaBold;
else if ( _properties.IsItalic )
_realFont = Base14Font.HelveticaItalic;
else
_realFont = Base14Font.Helvetica;
}
return _realFont;
}
#region Implementation of Font members
public override PdfFontSubTypeEnum SubType
{
get
{
LoadIfNecessary();
return _realFont.SubType;
}
}
public override string FontName
{
get
{
LoadIfNecessary();
return _realFont.FontName;
}
}
public override PdfFontTypeEnum Type
{
get
{
LoadIfNecessary();
return _realFont.Type;
}
}
public override string Encoding
{
get
{
LoadIfNecessary();
return _realFont.Encoding;
}
}
public override IFontDescriptor Descriptor
{
get
{
LoadIfNecessary();
return _realFont.Descriptor;
}
}
public override bool MultiByteFont
{
get
{
LoadIfNecessary();
return _realFont.MultiByteFont;
}
}
public override ushort MapCharacter( char c )
{
LoadIfNecessary();
return _realFont.MapCharacter( c );
}
public override int Ascender
{
get
{
LoadIfNecessary();
return _realFont.Ascender;
}
}
public override int Descender
{
get
{
LoadIfNecessary();
return _realFont.Descender;
}
}
public override int CapHeight
{
get
{
LoadIfNecessary();
return _realFont.CapHeight;
}
}
public override int FirstChar
{
get
{
LoadIfNecessary();
return _realFont.FirstChar;
}
}
public override int LastChar
{
get
{
LoadIfNecessary();
return _realFont.LastChar;
}
}
public override int GetWidth( ushort charIndex )
{
LoadIfNecessary();
return _realFont.GetWidth( charIndex );
}
public override int[] Widths
{
get
{
LoadIfNecessary();
return _realFont.Widths;
}
}
#endregion
#region Implementation of IFontDescriptior interface
public int Flags
{
get
{
LoadIfNecessary();
return _realFont.Descriptor.Flags;
}
}
public int[] FontBBox
{
get
{
LoadIfNecessary();
return _realFont.Descriptor.FontBBox;
}
}
public int ItalicAngle
{
get
{
LoadIfNecessary();
return _realFont.Descriptor.ItalicAngle;
}
}
public int StemV
{
get
{
LoadIfNecessary();
return _realFont.Descriptor.StemV;
}
}
public bool HasKerningInfo
{
get
{
LoadIfNecessary();
return _realFont.Descriptor.HasKerningInfo;
}
}
public bool IsEmbeddable
{
get
{
LoadIfNecessary();
return _realFont.Descriptor.IsEmbeddable;
}
}
public bool IsSubsettable
{
get
{
LoadIfNecessary();
return _realFont.Descriptor.IsSubsettable;
}
}
public byte[] FontData
{
get
{
LoadIfNecessary();
return _realFont.Descriptor.FontData;
}
}
public GdiKerningPairs KerningInfo
{
get
{
LoadIfNecessary();
return _realFont.Descriptor.KerningInfo;
}
}
#endregion
}
} | 25.064327 | 137 | 0.448787 | [
"Apache-2.0"
] | modiCAS/fo.net | Render/Pdf/Fonts/ProxyFont.cs | 8,572 | C# |
using System.ComponentModel.DataAnnotations;
using commercetools.Sdk.Domain.Types;
namespace commercetools.Sdk.Domain.ProductTypes.UpdateActions
{
public class ChangeAttributeDefinitionInputHintUpdateAction : UpdateAction<ProductType>
{
public string Action => "changeInputHint";
[Required]
public string AttributeName { get; set; }
[Required]
public TextInputHint NewValue { get; set; }
}
} | 31.785714 | 91 | 0.721348 | [
"Apache-2.0"
] | commercetools/commercetools-dotnet-core-sdk | commercetools.Sdk/commercetools.Sdk.Domain/ProductTypes/UpdateActions/ChangeAttributeDefinitionInputHintUpdateAction.cs | 447 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace mdryden.cflapi.v1.Models.Games
{
public enum Quarters
{
First = 1,
Second = 2,
Third = 3,
Fourth = 4,
OT = 5,
}
}
| 14.166667 | 40 | 0.694118 | [
"MIT"
] | pudds/cfl-api.net | src/v1/Core/Models/Games/Quarters.cs | 257 | C# |
namespace Membership
{
public interface IMembershipService
{
void CreateService(string name, string servicName);
}
} | 19.571429 | 59 | 0.693431 | [
"MIT"
] | Amphibian007/DotNetSelfPractise_Home | source/Classes/EFCorePractise/Contracts/IMembershipService.cs | 139 | C# |
using System;
using System.Threading.Tasks;
namespace Seedwork.CQRS.Bus.Core.Tests.UnitTests.Configurations.Stubs
{
internal class BusSerializerStub : IBusSerializer
{
public T Deserialize<T>(byte[] data)
{
throw new InvalidOperationException();
}
public byte[] Serialize<T>(T obj)
{
throw new InvalidOperationException();
}
}
} | 23 | 69 | 0.623188 | [
"MIT"
] | tiagor87/Seedwork.CQRS.Bus | tests/Core/UnitTests/Configurations/Stubs/BusSerializerStub.cs | 414 | C# |
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace Rosie
{
public class WebRequestHandler : IDeviceService
{
public WebRequestHandler ()
{
}
public static string Identifier = "Web";
public string ServiceIdentifier => Identifier;
HttpClient client = new HttpClient ();
public event EventHandler<DeviceState> CurrentStateUpdated;
public event EventHandler<Device> DeviceAdded;
public async Task<bool> HandleRequest (Device device, DeviceUpdate request)
{
try {
if (request.DataType != DataTypes.Bool)
return false;
//TODO: Fixme
//var url = device.ad
//var resp = await client.GetAsync (request.BoolValue.Value ? device.OnUrl : device.OffUrl);
//resp.EnsureSuccessStatusCode ();
} catch (Exception ex) {
Console.WriteLine (ex);
}
return false;
}
}
}
| 21.74359 | 96 | 0.704009 | [
"Apache-2.0"
] | Clancey/Rosie | src/Core/Rosie/Devices/Handlers/WebRequestHandler.cs | 850 | 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("FluentInterfaceExample.Types")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FluentInterfaceExample.Types")]
[assembly: AssemblyCopyright("Copyright © 2011")]
[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("8f94eba8-56e3-49a9-b836-98f196e63fc6")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 39.567568 | 85 | 0.731557 | [
"Unlicense"
] | primaryobjects/Fluent-Simple-RPG-Game | FluentInterfaceExample.Types/Properties/AssemblyInfo.cs | 1,467 | C# |
using System.Collections.Generic;
using Unity.UIWidgets.foundation;
using Unity.UIWidgets.ui;
namespace Unity.UIWidgets.widgets {
public class Form : StatefulWidget {
public Form(
Key key = null,
Widget child = null,
bool autovalidate = false,
WillPopCallback onWillPop = null,
VoidCallback onChanged = null
) : base(key: key) {
D.assert(child != null);
this.child = child;
this.autovalidate = autovalidate;
this.onWillPop = onWillPop;
this.onChanged = onChanged;
}
public static FormState of(BuildContext context) {
_FormScope scope = (_FormScope) context.inheritFromWidgetOfExactType(typeof(_FormScope));
return scope?._formState;
}
public readonly Widget child;
public readonly bool autovalidate;
public readonly WillPopCallback onWillPop;
public readonly VoidCallback onChanged;
public override State createState() {
return new FormState();
}
}
public class FormState : State<Form> {
int _generation = 0;
readonly HashSet<FormFieldState> _fields = new HashSet<FormFieldState>();
public FormState() {
}
public void _fieldDidChange() {
if (this.widget.onChanged != null) {
this.widget.onChanged();
}
this._forceRebuild();
}
void _forceRebuild() {
this.setState(() => { ++this._generation; });
}
public void _register(FormFieldState field) {
this._fields.Add(field);
}
public void _unregister(FormFieldState field) {
this._fields.Remove(field);
}
public override Widget build(BuildContext context) {
if (this.widget.autovalidate) {
this._validate();
}
return new WillPopScope(
onWillPop: this.widget.onWillPop,
child: new _FormScope(
formState: this,
generation: this._generation,
child: this.widget.child
)
);
}
public void save() {
foreach (FormFieldState field in this._fields) {
field.save();
}
}
public void reset() {
foreach (FormFieldState field in this._fields) {
field.reset();
}
this._fieldDidChange();
}
public bool validate() {
this._forceRebuild();
return this._validate();
}
bool _validate() {
bool hasError = false;
foreach (FormFieldState field in this._fields) {
hasError = !field.validate() || hasError;
}
return !hasError;
}
}
class _FormScope : InheritedWidget {
public _FormScope(
Key key = null,
Widget child = null,
FormState formState = null,
int? generation = null
) :
base(key: key, child: child) {
this._formState = formState;
this._generation = generation;
}
public readonly FormState _formState;
public readonly int? _generation;
public Form form {
get { return this._formState.widget; }
}
public override bool updateShouldNotify(InheritedWidget _old) {
_FormScope old = _old as _FormScope;
return this._generation != old._generation;
}
}
public delegate string FormFieldValidator<T>(T value);
public delegate void FormFieldSetter<T>(T newValue);
public delegate Widget FormFieldBuilder<T>(FormFieldState<T> field) where T : class;
public class FormField<T> : StatefulWidget where T : class {
public FormField(
Key key = null,
FormFieldBuilder<T> builder = null,
FormFieldSetter<T> onSaved = null,
FormFieldValidator<T> validator = null,
T initialValue = null,
bool autovalidate = false,
bool enabled = true
) : base(key: key) {
D.assert(builder != null);
this.onSaved = onSaved;
this.validator = validator;
this.builder = builder;
this.initialValue = initialValue;
this.autovalidate = autovalidate;
this.enabled = enabled;
}
public readonly FormFieldSetter<T> onSaved;
public readonly FormFieldValidator<T> validator;
public readonly FormFieldBuilder<T> builder;
public readonly T initialValue;
public readonly bool autovalidate;
public readonly bool enabled;
public override State createState() {
return new FormFieldState<T>();
}
}
public interface FormFieldState {
void save();
bool validate();
void reset();
}
public class FormFieldState<T> : State<FormField<T>>, FormFieldState where T : class {
T _value;
string _errorText;
public T value {
get { return this._value; }
}
public string errorText {
get { return this._errorText; }
}
public bool hasError {
get { return this._errorText != null; }
}
public void save() {
if (this.widget.onSaved != null) {
this.widget.onSaved(this.value);
}
}
public virtual void reset() {
this.setState(() => {
this._value = this.widget.initialValue;
this._errorText = null;
});
}
public bool validate() {
this.setState(() => { this._validate(); });
return !this.hasError;
}
void _validate() {
if (this.widget.validator != null) {
this._errorText = this.widget.validator(this._value);
}
}
public virtual void didChange(T value) {
this.setState(() => { this._value = value; });
Form.of(this.context)?._fieldDidChange();
}
protected void setValue(T value) {
this._value = value;
}
public override void initState() {
base.initState();
this._value = this.widget.initialValue;
}
public override void deactivate() {
Form.of(this.context)?._unregister(this);
base.deactivate();
}
public override Widget build(BuildContext context) {
if (this.widget.autovalidate && this.widget.enabled) {
this._validate();
}
Form.of(context)?._register(this);
return this.widget.builder(this);
}
}
} | 28.370079 | 102 | 0.517069 | [
"Apache-2.0"
] | Luciano-0/2048-Demo | Library/PackageCache/com.unity.uiwidgets@1.5.4-preview.12/Runtime/widgets/form.cs | 7,206 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using Amazon.MachineLearning.Model;
using Amazon.MachineLearning.Util;
using Amazon.MachineLearning.Model.Internal.MarshallTransformations;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.MachineLearning
{
/// <summary>
/// Implementation for accessing MachineLearning
///
/// Definition of the public APIs exposed by Amazon Machine Learning
/// </summary>
public partial class AmazonMachineLearningClient
{
/// <summary>
/// Creates a simple client that just does realtime predictions.
/// </summary>
/// <remarks>
/// Fetches the realtime prediction endpoint for the specified model using the GetMLModel call.
/// </remarks>
/// <param name="modelId">The model to create the realtime predictor for.</param>
/// <returns>A realtime prediction client.</returns>
/// <exception cref="Amazon.MachineLearning.Model.InternalServerException">
/// An error on the server occurred when trying to process a request.
/// </exception>
/// <exception cref="Amazon.MachineLearning.Model.InvalidInputException">
/// An error on the client occurred. Typically, the cause is an invalid input value.
/// </exception>
/// <exception cref="Amazon.MachineLearning.Model.LimitExceededException">
/// The subscriber exceeded the maximum number of operations. This exception can occur
/// when listing objects such as <code>DataSource</code>.
/// </exception>
/// <exception cref="Amazon.MachineLearning.Model.PredictorNotMountedException">
/// The exception is thrown when a predict request is made to an unmounted <code>MLModel</code>.
/// </exception>
/// <exception cref="Amazon.MachineLearning.Model.ResourceNotFoundException">
/// A specified resource cannot be located.
/// </exception>
public RealtimePredictor CreateRealtimePredictor(string modelId)
{
return new RealtimePredictor(this, modelId);
}
}
} | 42.876923 | 104 | 0.693219 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/MachineLearning/Custom/AmazonMachineLearningClient.Extensions.cs | 2,787 | C# |
/* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. 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.Runtime.Serialization;
namespace OpenSearch.Client
{
public class ShrinkIndexResponse : AcknowledgedResponseBase
{
[DataMember(Name ="shards_acknowledged")]
public bool ShardsAcknowledged { get; internal set; }
}
}
| 34.447368 | 64 | 0.76929 | [
"Apache-2.0"
] | opensearch-project/opensearch-net | src/OpenSearch.Client/Indices/IndexManagement/ShrinkIndex/ShrinkIndexResponse.cs | 1,309 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Solid.IdentityModel.Tokens.Crypto
{
public struct SignatureAlgorithmName
{
public SignatureAlgorithmName(string algorithm)
{
Algorithm = algorithm;
}
public string Algorithm { get; }
}
}
| 19 | 55 | 0.659443 | [
"MIT"
] | SOLIDSoftworks/Solid.IdentityModel | src/Solid.IdentityModel.Tokens/Crypto/SignatureAlgorithmName.cs | 325 | C# |
using System.Collections.Generic;
namespace onlysats.domain.Services.Request.ContentManagement
{
public class GetAssetsRequest : RequestBase
{
public int CreatorId { get; set; }
public List<int> AssetIds { get; set; } = new List<int>(); // Empty means all
public int? VaultId { get; set; }
public int Top { get; set; } = 10;
public int Skip { get; set; } = 0;
public override bool IsValid()
{
return CreatorId > 0;
}
}
} | 28.333333 | 85 | 0.586275 | [
"MIT"
] | conradcreel/onlysats | src/onlysatsdomain/Services/Request/ContentManagement/GetAssetsRequest.cs | 510 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace PhonebookAPI.Migrations
{
public partial class TestNumber : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "PhoneNumber",
table: "Numbers",
type: "varchar(9)",
maxLength: 9,
nullable: false,
oldClrType: typeof(string),
oldType: "varchar(10)",
oldMaxLength: 10);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "PhoneNumber",
table: "Numbers",
type: "varchar(10)",
maxLength: 10,
nullable: false,
oldClrType: typeof(string),
oldType: "varchar(9)",
oldMaxLength: 9);
}
}
}
| 29.676471 | 71 | 0.512389 | [
"MIT"
] | Barnacle/PhonebookApp | PhonebookAPI/Migrations/20200713110408_TestNumber.cs | 1,011 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
namespace Microsoft.CodeAnalysis
{
public class DocumentEventArgs : EventArgs
{
public Document Document { get; private set; }
public DocumentEventArgs(Document document)
{
this.Document = document;
}
}
}
| 25.882353 | 161 | 0.672727 | [
"Apache-2.0"
] | DavidKarlas/roslyn | src/Workspaces/Core/Portable/Workspace/DocumentEventArgs.cs | 442 | 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("WebResources")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WebResources")]
[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("f73abef7-0f6a-4f6e-b82d-9c07ee4515e1")]
// 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("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.694444 | 84 | 0.74871 | [
"MIT"
] | chrisjsherm/FinanceWeb | WebResources/Properties/AssemblyInfo.cs | 1,360 | C# |
using System.Collections.Generic;
using System.Linq;
namespace Qualm.Supervised.Classification
{
public class DecisionTrees : IClassifier
{
/// <summary>
/// Builds a tree using the Iterative Dichotimiser 3 (ID3) algorithm
/// <see href="http://en.wikipedia.org/wiki/ID3_algorithm" />
/// </summary>
/// <returns></returns>
public static ITreeNode ID3(Matrix dataSet, IList<string> labels, DisorderType disorderType)
{
return CreateTree(dataSet, labels, disorderType);
}
public static ITreeNode ID3(Matrix dataSet, IList<string> labels)
{
return CreateTree(dataSet, labels, DisorderType.ShannonEntropy);
}
private static ITreeNode CreateTree(Matrix dataSet, IList<string> labels, DisorderType disorderType)
{
var outcomes = dataSet.GetOutcomes();
if(outcomes.Distinct().Count().Equals(1))
{
return new DecisionTreeLeafNode(outcomes[0]);
}
var outcome = dataSet.GetMajorityOutcome();
if(dataSet.Columns == 1)
{
return new DecisionTreeLeafNode(outcome);
}
ITreeNode node = new DecisionTreeNode(dataSet, outcome);
var casted = (DecisionTreeNode) node;
var best = casted.GetInformationGain(disorderType).First();
var label = labels[best.Key];
casted.Label = label;
labels = labels.Where(l => !l.Equals(label)).ToList();
var subset = dataSet.Select(row => row[best.Key]).ToList();
var values = subset.Distinct().ToList();
foreach(var value in values)
{
var copy = new List<string>(labels);
var split = casted.Split(best.Key, value);
var child = CreateTree(split, copy, disorderType);
casted.AddChild(child);
}
ReverseNodeOrder(casted);
return node;
}
private static void ReverseNodeOrder(DecisionTreeNode casted)
{
var reversed = casted.Children.Reverse().ToList();
casted.Children.Clear();
foreach(var item in reversed)
{
casted.Children.Add(item);
}
}
}
}
| 30.139241 | 108 | 0.559429 | [
"Apache-2.0"
] | danielcrenna/graveyard | qualm/src/Qualm/Supervised/Classification/DecisionTrees.cs | 2,383 | C# |
using System.CodeDom.Compiler;
using System.Runtime.Serialization;
using System.Collections.Generic;
namespace SolidRpc.Test.Vitec.Types.Image.Models {
/// <summary>
///
/// </summary>
[GeneratedCode("OpenApiCodeGeneratorV2","1.0.0.0")]
public class ImageCategories {
/// <summary>
/// Kundid
/// </summary>
[DataMember(Name="customerId",EmitDefaultValue=false)]
public string CustomerId { get; set; }
/// <summary>
/// Lista av bildkategorier
/// </summary>
[DataMember(Name="categories",EmitDefaultValue=false)]
public IEnumerable<string> Categories { get; set; }
}
} | 29.73913 | 62 | 0.612573 | [
"MIT"
] | aarrgard/solidrpc | SolidRpc.Test.Vitec/Types/Image/Models/ImageCategories.cs | 684 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
/// <summary> Helper for invoke coroutines from is not MonoBehaviour </summary>
public class CoroutineHelper : MonoBehaviour {
static CoroutineHelper instance;
static CoroutineHelper Instance {
get {
if (instance == null) {
var go = Instantiate<GameObject>(new GameObject());
DontDestroyOnLoad(go);
instance = go.AddComponent<CoroutineHelper>();
}
return instance;
}
}
/// <summary> LaunchCoroutine method </summary>
/// <param name="iEnumerator"> Coroutine </param>
/// <param name="onCompleteAction"> Action invoked on end coroutine </param>
/// <returns> Link on coroutine </returns>
public static Coroutine LaunchCoroutineWithEndAction (IEnumerator iEnumerator, Action onCompleteAction = null) {
return Instance.StartCoroutine(Instance.LaunchCoroutine(iEnumerator, onCompleteAction));
}
/// <summary> Stop coroutine </summary>
public static void BreakCoroutine (Coroutine coroutine) {
Instance.StopCoroutine(coroutine);
}
/// <summary> LaunchCoroutine logic </summary>
private IEnumerator LaunchCoroutine (IEnumerator iEnumerator, Action onCompleteAction) {
while (true) {
object current = null;
try {
if (!iEnumerator.MoveNext()) {
break;
}
current = iEnumerator.Current;
}
catch (Exception ex) {
Debug.LogException(ex);
}
yield return current;
}
onCompleteAction.Invoke();
}
}
| 27.924528 | 113 | 0.718243 | [
"MIT"
] | santoyox714/space-time-pilgrim | space-time-pilgrim/Assets/2DPlatformer/Scripts/Game/CoroutineHelper.cs | 1,482 | C# |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagve = Google.Ads.GoogleAds.V6.Enums;
using gagvr = Google.Ads.GoogleAds.V6.Resources;
using gaxgrpc = Google.Api.Gax.Grpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V6.Services;
namespace Google.Ads.GoogleAds.Tests.V6.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedAccountBudgetProposalServiceClientTest
{
[Category("Smoke")][Test]
public void GetAccountBudgetProposalRequestObject()
{
moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient>(moq::MockBehavior.Strict);
GetAccountBudgetProposalRequest request = new GetAccountBudgetProposalRequest
{
ResourceNameAsAccountBudgetProposalName = gagvr::AccountBudgetProposalName.FromCustomerAccountBudgetProposal("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_PROPOSAL_ID]"),
};
gagvr::AccountBudgetProposal expectedResponse = new gagvr::AccountBudgetProposal
{
ResourceNameAsAccountBudgetProposalName = gagvr::AccountBudgetProposalName.FromCustomerAccountBudgetProposal("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_PROPOSAL_ID]"),
ProposalType = gagve::AccountBudgetProposalTypeEnum.Types.AccountBudgetProposalType.Remove,
ProposedStartTimeType = gagve::TimeTypeEnum.Types.TimeType.Unspecified,
ProposedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown,
ProposedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown,
Status = gagve::AccountBudgetProposalStatusEnum.Types.AccountBudgetProposalStatus.ApprovedHeld,
ApprovedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Forever,
ApprovedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown,
Id = -6774108720365892680L,
BillingSetupAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"),
AccountBudgetAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"),
ProposedName = "proposed_name7d4b2591",
ProposedStartDateTime = "proposed_start_date_time4e2f84a3",
ApprovedStartDateTime = "approved_start_date_time20090a2c",
ProposedEndDateTime = "proposed_end_date_time39aa28a5",
ApprovedEndDateTime = "approved_end_date_time99d3ab5d",
ProposedSpendingLimitMicros = 6806956772888455592L,
ApprovedSpendingLimitMicros = 1674109600829643495L,
ProposedPurchaseOrderNumber = "proposed_purchase_order_numbere58f9418",
ProposedNotes = "proposed_notes1d6c3942",
CreationDateTime = "creation_date_time2f8c0159",
ApprovalDateTime = "approval_date_timecefef4db",
};
mockGrpcClient.Setup(x => x.GetAccountBudgetProposal(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AccountBudgetProposalServiceClient client = new AccountBudgetProposalServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AccountBudgetProposal response = client.GetAccountBudgetProposal(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Smoke")][Test]
public async stt::Task GetAccountBudgetProposalRequestObjectAsync()
{
moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient>(moq::MockBehavior.Strict);
GetAccountBudgetProposalRequest request = new GetAccountBudgetProposalRequest
{
ResourceNameAsAccountBudgetProposalName = gagvr::AccountBudgetProposalName.FromCustomerAccountBudgetProposal("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_PROPOSAL_ID]"),
};
gagvr::AccountBudgetProposal expectedResponse = new gagvr::AccountBudgetProposal
{
ResourceNameAsAccountBudgetProposalName = gagvr::AccountBudgetProposalName.FromCustomerAccountBudgetProposal("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_PROPOSAL_ID]"),
ProposalType = gagve::AccountBudgetProposalTypeEnum.Types.AccountBudgetProposalType.Remove,
ProposedStartTimeType = gagve::TimeTypeEnum.Types.TimeType.Unspecified,
ProposedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown,
ProposedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown,
Status = gagve::AccountBudgetProposalStatusEnum.Types.AccountBudgetProposalStatus.ApprovedHeld,
ApprovedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Forever,
ApprovedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown,
Id = -6774108720365892680L,
BillingSetupAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"),
AccountBudgetAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"),
ProposedName = "proposed_name7d4b2591",
ProposedStartDateTime = "proposed_start_date_time4e2f84a3",
ApprovedStartDateTime = "approved_start_date_time20090a2c",
ProposedEndDateTime = "proposed_end_date_time39aa28a5",
ApprovedEndDateTime = "approved_end_date_time99d3ab5d",
ProposedSpendingLimitMicros = 6806956772888455592L,
ApprovedSpendingLimitMicros = 1674109600829643495L,
ProposedPurchaseOrderNumber = "proposed_purchase_order_numbere58f9418",
ProposedNotes = "proposed_notes1d6c3942",
CreationDateTime = "creation_date_time2f8c0159",
ApprovalDateTime = "approval_date_timecefef4db",
};
mockGrpcClient.Setup(x => x.GetAccountBudgetProposalAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AccountBudgetProposal>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AccountBudgetProposalServiceClient client = new AccountBudgetProposalServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AccountBudgetProposal responseCallSettings = await client.GetAccountBudgetProposalAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::AccountBudgetProposal responseCancellationToken = await client.GetAccountBudgetProposalAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Smoke")][Test]
public void GetAccountBudgetProposal()
{
moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient>(moq::MockBehavior.Strict);
GetAccountBudgetProposalRequest request = new GetAccountBudgetProposalRequest
{
ResourceNameAsAccountBudgetProposalName = gagvr::AccountBudgetProposalName.FromCustomerAccountBudgetProposal("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_PROPOSAL_ID]"),
};
gagvr::AccountBudgetProposal expectedResponse = new gagvr::AccountBudgetProposal
{
ResourceNameAsAccountBudgetProposalName = gagvr::AccountBudgetProposalName.FromCustomerAccountBudgetProposal("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_PROPOSAL_ID]"),
ProposalType = gagve::AccountBudgetProposalTypeEnum.Types.AccountBudgetProposalType.Remove,
ProposedStartTimeType = gagve::TimeTypeEnum.Types.TimeType.Unspecified,
ProposedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown,
ProposedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown,
Status = gagve::AccountBudgetProposalStatusEnum.Types.AccountBudgetProposalStatus.ApprovedHeld,
ApprovedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Forever,
ApprovedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown,
Id = -6774108720365892680L,
BillingSetupAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"),
AccountBudgetAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"),
ProposedName = "proposed_name7d4b2591",
ProposedStartDateTime = "proposed_start_date_time4e2f84a3",
ApprovedStartDateTime = "approved_start_date_time20090a2c",
ProposedEndDateTime = "proposed_end_date_time39aa28a5",
ApprovedEndDateTime = "approved_end_date_time99d3ab5d",
ProposedSpendingLimitMicros = 6806956772888455592L,
ApprovedSpendingLimitMicros = 1674109600829643495L,
ProposedPurchaseOrderNumber = "proposed_purchase_order_numbere58f9418",
ProposedNotes = "proposed_notes1d6c3942",
CreationDateTime = "creation_date_time2f8c0159",
ApprovalDateTime = "approval_date_timecefef4db",
};
mockGrpcClient.Setup(x => x.GetAccountBudgetProposal(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AccountBudgetProposalServiceClient client = new AccountBudgetProposalServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AccountBudgetProposal response = client.GetAccountBudgetProposal(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Smoke")][Test]
public async stt::Task GetAccountBudgetProposalAsync()
{
moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient>(moq::MockBehavior.Strict);
GetAccountBudgetProposalRequest request = new GetAccountBudgetProposalRequest
{
ResourceNameAsAccountBudgetProposalName = gagvr::AccountBudgetProposalName.FromCustomerAccountBudgetProposal("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_PROPOSAL_ID]"),
};
gagvr::AccountBudgetProposal expectedResponse = new gagvr::AccountBudgetProposal
{
ResourceNameAsAccountBudgetProposalName = gagvr::AccountBudgetProposalName.FromCustomerAccountBudgetProposal("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_PROPOSAL_ID]"),
ProposalType = gagve::AccountBudgetProposalTypeEnum.Types.AccountBudgetProposalType.Remove,
ProposedStartTimeType = gagve::TimeTypeEnum.Types.TimeType.Unspecified,
ProposedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown,
ProposedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown,
Status = gagve::AccountBudgetProposalStatusEnum.Types.AccountBudgetProposalStatus.ApprovedHeld,
ApprovedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Forever,
ApprovedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown,
Id = -6774108720365892680L,
BillingSetupAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"),
AccountBudgetAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"),
ProposedName = "proposed_name7d4b2591",
ProposedStartDateTime = "proposed_start_date_time4e2f84a3",
ApprovedStartDateTime = "approved_start_date_time20090a2c",
ProposedEndDateTime = "proposed_end_date_time39aa28a5",
ApprovedEndDateTime = "approved_end_date_time99d3ab5d",
ProposedSpendingLimitMicros = 6806956772888455592L,
ApprovedSpendingLimitMicros = 1674109600829643495L,
ProposedPurchaseOrderNumber = "proposed_purchase_order_numbere58f9418",
ProposedNotes = "proposed_notes1d6c3942",
CreationDateTime = "creation_date_time2f8c0159",
ApprovalDateTime = "approval_date_timecefef4db",
};
mockGrpcClient.Setup(x => x.GetAccountBudgetProposalAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AccountBudgetProposal>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AccountBudgetProposalServiceClient client = new AccountBudgetProposalServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AccountBudgetProposal responseCallSettings = await client.GetAccountBudgetProposalAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::AccountBudgetProposal responseCancellationToken = await client.GetAccountBudgetProposalAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Smoke")][Test]
public void GetAccountBudgetProposalResourceNames()
{
moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient>(moq::MockBehavior.Strict);
GetAccountBudgetProposalRequest request = new GetAccountBudgetProposalRequest
{
ResourceNameAsAccountBudgetProposalName = gagvr::AccountBudgetProposalName.FromCustomerAccountBudgetProposal("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_PROPOSAL_ID]"),
};
gagvr::AccountBudgetProposal expectedResponse = new gagvr::AccountBudgetProposal
{
ResourceNameAsAccountBudgetProposalName = gagvr::AccountBudgetProposalName.FromCustomerAccountBudgetProposal("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_PROPOSAL_ID]"),
ProposalType = gagve::AccountBudgetProposalTypeEnum.Types.AccountBudgetProposalType.Remove,
ProposedStartTimeType = gagve::TimeTypeEnum.Types.TimeType.Unspecified,
ProposedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown,
ProposedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown,
Status = gagve::AccountBudgetProposalStatusEnum.Types.AccountBudgetProposalStatus.ApprovedHeld,
ApprovedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Forever,
ApprovedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown,
Id = -6774108720365892680L,
BillingSetupAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"),
AccountBudgetAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"),
ProposedName = "proposed_name7d4b2591",
ProposedStartDateTime = "proposed_start_date_time4e2f84a3",
ApprovedStartDateTime = "approved_start_date_time20090a2c",
ProposedEndDateTime = "proposed_end_date_time39aa28a5",
ApprovedEndDateTime = "approved_end_date_time99d3ab5d",
ProposedSpendingLimitMicros = 6806956772888455592L,
ApprovedSpendingLimitMicros = 1674109600829643495L,
ProposedPurchaseOrderNumber = "proposed_purchase_order_numbere58f9418",
ProposedNotes = "proposed_notes1d6c3942",
CreationDateTime = "creation_date_time2f8c0159",
ApprovalDateTime = "approval_date_timecefef4db",
};
mockGrpcClient.Setup(x => x.GetAccountBudgetProposal(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AccountBudgetProposalServiceClient client = new AccountBudgetProposalServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AccountBudgetProposal response = client.GetAccountBudgetProposal(request.ResourceNameAsAccountBudgetProposalName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Smoke")][Test]
public async stt::Task GetAccountBudgetProposalResourceNamesAsync()
{
moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient>(moq::MockBehavior.Strict);
GetAccountBudgetProposalRequest request = new GetAccountBudgetProposalRequest
{
ResourceNameAsAccountBudgetProposalName = gagvr::AccountBudgetProposalName.FromCustomerAccountBudgetProposal("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_PROPOSAL_ID]"),
};
gagvr::AccountBudgetProposal expectedResponse = new gagvr::AccountBudgetProposal
{
ResourceNameAsAccountBudgetProposalName = gagvr::AccountBudgetProposalName.FromCustomerAccountBudgetProposal("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_PROPOSAL_ID]"),
ProposalType = gagve::AccountBudgetProposalTypeEnum.Types.AccountBudgetProposalType.Remove,
ProposedStartTimeType = gagve::TimeTypeEnum.Types.TimeType.Unspecified,
ProposedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown,
ProposedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown,
Status = gagve::AccountBudgetProposalStatusEnum.Types.AccountBudgetProposalStatus.ApprovedHeld,
ApprovedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Forever,
ApprovedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown,
Id = -6774108720365892680L,
BillingSetupAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"),
AccountBudgetAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"),
ProposedName = "proposed_name7d4b2591",
ProposedStartDateTime = "proposed_start_date_time4e2f84a3",
ApprovedStartDateTime = "approved_start_date_time20090a2c",
ProposedEndDateTime = "proposed_end_date_time39aa28a5",
ApprovedEndDateTime = "approved_end_date_time99d3ab5d",
ProposedSpendingLimitMicros = 6806956772888455592L,
ApprovedSpendingLimitMicros = 1674109600829643495L,
ProposedPurchaseOrderNumber = "proposed_purchase_order_numbere58f9418",
ProposedNotes = "proposed_notes1d6c3942",
CreationDateTime = "creation_date_time2f8c0159",
ApprovalDateTime = "approval_date_timecefef4db",
};
mockGrpcClient.Setup(x => x.GetAccountBudgetProposalAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AccountBudgetProposal>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AccountBudgetProposalServiceClient client = new AccountBudgetProposalServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AccountBudgetProposal responseCallSettings = await client.GetAccountBudgetProposalAsync(request.ResourceNameAsAccountBudgetProposalName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::AccountBudgetProposal responseCancellationToken = await client.GetAccountBudgetProposalAsync(request.ResourceNameAsAccountBudgetProposalName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Smoke")][Test]
public void MutateAccountBudgetProposalRequestObject()
{
moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient>(moq::MockBehavior.Strict);
MutateAccountBudgetProposalRequest request = new MutateAccountBudgetProposalRequest
{
CustomerId = "customer_id3b3724cb",
Operation = new AccountBudgetProposalOperation(),
ValidateOnly = true,
};
MutateAccountBudgetProposalResponse expectedResponse = new MutateAccountBudgetProposalResponse
{
Result = new MutateAccountBudgetProposalResult(),
};
mockGrpcClient.Setup(x => x.MutateAccountBudgetProposal(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AccountBudgetProposalServiceClient client = new AccountBudgetProposalServiceClientImpl(mockGrpcClient.Object, null);
MutateAccountBudgetProposalResponse response = client.MutateAccountBudgetProposal(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Smoke")][Test]
public async stt::Task MutateAccountBudgetProposalRequestObjectAsync()
{
moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient>(moq::MockBehavior.Strict);
MutateAccountBudgetProposalRequest request = new MutateAccountBudgetProposalRequest
{
CustomerId = "customer_id3b3724cb",
Operation = new AccountBudgetProposalOperation(),
ValidateOnly = true,
};
MutateAccountBudgetProposalResponse expectedResponse = new MutateAccountBudgetProposalResponse
{
Result = new MutateAccountBudgetProposalResult(),
};
mockGrpcClient.Setup(x => x.MutateAccountBudgetProposalAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAccountBudgetProposalResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AccountBudgetProposalServiceClient client = new AccountBudgetProposalServiceClientImpl(mockGrpcClient.Object, null);
MutateAccountBudgetProposalResponse responseCallSettings = await client.MutateAccountBudgetProposalAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateAccountBudgetProposalResponse responseCancellationToken = await client.MutateAccountBudgetProposalAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Smoke")][Test]
public void MutateAccountBudgetProposal()
{
moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient>(moq::MockBehavior.Strict);
MutateAccountBudgetProposalRequest request = new MutateAccountBudgetProposalRequest
{
CustomerId = "customer_id3b3724cb",
Operation = new AccountBudgetProposalOperation(),
};
MutateAccountBudgetProposalResponse expectedResponse = new MutateAccountBudgetProposalResponse
{
Result = new MutateAccountBudgetProposalResult(),
};
mockGrpcClient.Setup(x => x.MutateAccountBudgetProposal(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AccountBudgetProposalServiceClient client = new AccountBudgetProposalServiceClientImpl(mockGrpcClient.Object, null);
MutateAccountBudgetProposalResponse response = client.MutateAccountBudgetProposal(request.CustomerId, request.Operation);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Smoke")][Test]
public async stt::Task MutateAccountBudgetProposalAsync()
{
moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient>(moq::MockBehavior.Strict);
MutateAccountBudgetProposalRequest request = new MutateAccountBudgetProposalRequest
{
CustomerId = "customer_id3b3724cb",
Operation = new AccountBudgetProposalOperation(),
};
MutateAccountBudgetProposalResponse expectedResponse = new MutateAccountBudgetProposalResponse
{
Result = new MutateAccountBudgetProposalResult(),
};
mockGrpcClient.Setup(x => x.MutateAccountBudgetProposalAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAccountBudgetProposalResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AccountBudgetProposalServiceClient client = new AccountBudgetProposalServiceClientImpl(mockGrpcClient.Object, null);
MutateAccountBudgetProposalResponse responseCallSettings = await client.MutateAccountBudgetProposalAsync(request.CustomerId, request.Operation, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateAccountBudgetProposalResponse responseCancellationToken = await client.MutateAccountBudgetProposalAsync(request.CustomerId, request.Operation, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| 75.643836 | 262 | 0.723615 | [
"Apache-2.0"
] | GraphikaPS/google-ads-dotnet | tests/V6/Services/AccountBudgetProposalServiceClientTest.g.cs | 27,610 | C# |
namespace ILStripWPFTestLib.ViewModel
{
static class AnotherStaticClass
{
public static readonly string TestString = "Test String";
}
}
| 19.25 | 62 | 0.714286 | [
"MIT-0"
] | BrokenEvent/ILStrip | ILStripWPFTestLib/ViewModel/AnotherStaticClass.cs | 156 | C# |
using LexShop.Core.Models;
using System.Linq;
namespace LexShop.Core.Contracts
{
public interface IRepository<T> where T : BaseEntity
{
IQueryable<T> Collection();
void Commit();
void Delete(string Id);
T Find(string Id);
void Insert(T t);
void Update(T t);
}
} | 21.533333 | 56 | 0.603715 | [
"MIT"
] | Anette-K/Lexshop | LexShop/LexShop.Core/Contracts/IRepository.cs | 325 | C# |
namespace Library.Models
{
public class Rectangle : Figure
{
public double A { get; }
public double B { get; }
public Rectangle(double a, double b)
{
A = a;
B = b;
}
public override double CalculateArea()
{
return A * B;
}
public static bool IsRectangle(Figure figure)
{
return figure.Type == typeof(Rectangle).Name;
}
}
}
| 19 | 57 | 0.48 | [
"MIT"
] | LeadenYume/Example-Library | Library/Models/Rectangle.cs | 477 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Xml.Linq;
using Azure.Core;
namespace Azure.Storage.Files.DataLake.Models
{
internal partial class BlobPrefix
{
internal static BlobPrefix DeserializeBlobPrefix(XElement element)
{
string name = default;
if (element.Element("Name") is XElement nameElement)
{
name = (string)nameElement;
}
return new BlobPrefix(name);
}
}
}
| 22.615385 | 74 | 0.620748 | [
"MIT"
] | 93mishra/azure-sdk-for-net | sdk/storage/Azure.Storage.Files.DataLake/src/Generated/Models/BlobPrefix.Serialization.cs | 588 | C# |
using System;
using System.Collections.Generic;
using Entitas;
using Entitas.Generic;
public struct TestCompStruct_ToString_Implemented
: IComponent
, ICompData
, Scope<TestScope1>
{
public TestCompStruct_ToString_Implemented( String s = "test" )
{
Str = "test";
}
public String Str;
public override String ToString( )
{
return Str;
}
}
public struct TestCompStruct_ToString_NotImplemented
: IComponent
, ICompData
, Scope<TestScope1>
{
public TestCompStruct_ToString_NotImplemented( String s = "test" )
{
Str = "test";
}
public String Str;
}
public struct TestCompStruct_ToString_ToGenericTypeString
: IComponent
, ICompData
, Scope<TestScope1>
{
public TestCompStruct_ToString_ToGenericTypeString( String s = "test" )
{
Str = "test";
}
public String Str;
public override String ToString( )
{
return typeof(Dictionary<String,Dictionary<String,Int32>>).ToGenericTypeString( );
}
}
| 17.333333 | 85 | 0.738248 | [
"MIT"
] | c0ffeeartc/EntitasGenericAddon | Tests/Tests_Performance/Sources/Fixtures/TestCompStruct_ToString.cs | 936 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyController : MonoBehaviour
{
public float speed;
public float rangeY;
Vector3 initialPos;
int direction = 1;
// Start is called before the first frame update
void Start()
{
var rand = new System.Random((int)transform.position.x);
initialPos = transform.position;
transform.position += new Vector3(0, rand.Next(0, 50), 0);
}
// Update is called once per frame
void Update()
{
float movementY = speed * Time.deltaTime * direction;
float newY = transform.position.y + movementY;
if(Mathf.Abs(newY - initialPos.y) > rangeY)
{
direction *= -1;
}
else
{
if(direction == -1)
{
transform.position += new Vector3(0, (movementY * 1.2f), 0);
}
else
{
transform.position += new Vector3(0, movementY, 0);
}
}
}
}
| 21.893617 | 71 | 0.562682 | [
"MIT"
] | fatlewis/ludem-dare-47 | Assets/Scripts/EnemyController.cs | 1,031 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BlazorWasmApp.AuthServer.Dao;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace BlazorWasmApp.AuthServer.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
private readonly IUsersDao _usersDao;
public UsersController(IUsersDao usersDao)
{
_usersDao = usersDao;
}
[HttpGet]
public async Task<JsonResult> GetAll()
{
var result = await _usersDao.GetUsersAsync();
return new JsonResult(result);
}
}
} | 24.241379 | 57 | 0.664296 | [
"Apache-2.0"
] | mofajke/BlazorWasmApp | BlazorWasmApp.AuthServer/Controllers/UsersController.cs | 705 | C# |
using AutoFixture;
using AutoFixture.Xunit2;
using EntityFrameworkCore.AutoFixture.Tests.Common.Customizations;
namespace EntityFrameworkCore.AutoFixture.Tests.Common.Attributes
{
public class AutoDomainDataWithContextAttribute : AutoDataAttribute
{
public AutoDomainDataWithContextAttribute()
: base(() => new Fixture()
.Customize(new DomainDataWithContextCustomization()))
{
}
}
}
| 28.0625 | 71 | 0.712695 | [
"MIT"
] | ccpu/EntityFrameworkCore.AutoFixture | src/EntityFrameworkCore.AutoFixture.Tests/Common/Attributes/AutoDomainDataWithContextAttribute.cs | 451 | C# |
using AlephVault.Unity.Meetgard.Auth.Protocols.Simple;
using AlephVault.Unity.Meetgard.Types;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace AlephVault.Unity.Meetgard.Auth
{
namespace Samples
{
/// <summary>
/// This sample login protocol has only one mean
/// of login: "Login:Sample" (Username, Password).
/// </summary>
public class SampleSimpleAuthProtocolDefinition : SimpleAuthProtocolDefinition<Nothing, LoginFailed, Kicked>
{
protected override void DefineLoginMessages()
{
DefineLoginMessage<UserPass>("Sample");
}
}
}
}
| 29.041667 | 116 | 0.649928 | [
"MIT"
] | AlephVault/unity-meetgard-auth | Samples/Scripts/SampleSimpleAuthProtocolDefinition.cs | 697 | 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.
namespace System.Drawing
{
/// <summary>
/// This interface defines methods for obtaining a display/window device context handle (Win32 hdc).
/// Note: Display and window dc handles are obtained and released using BeginPaint/EndPaint and
/// GetDC/ReleaseDC; this interface is intended to be used with the last method only.
///
/// Warning to implementors: Creating and releasing non-display dc handles using this interface needs
/// special care, for instance using other Win32 functions like CreateDC or CreateCompatibleDC require
/// DeleteDC instead of ReleaseDC to properly free the dc handle.
///
/// See the DeviceContext class for an implementation of this interface, it uses the Dispose method
/// for freeing non-display dc handles.
///
/// This is a low-level API that is expected to be used with TextRenderer or PInvoke calls.
/// </summary>
public interface IDeviceContext : IDisposable
{
IntPtr GetHdc();
void ReleaseHdc();
}
}
| 43.964286 | 106 | 0.714054 | [
"MIT"
] | 06needhamt/runtime | src/libraries/System.Drawing.Common/src/System/Drawing/IDeviceContext.cs | 1,231 | C# |
namespace Cuku.Event
{
using UnityEngine;
using UnityEngine.EventSystems;
public class OnPointerClickEvent : PointerEvent, IPointerDownHandler, IPointerUpHandler
{
[SerializeField]
private double clickCount = 1;
[SerializeField]
private float clickTime = 0.2f;
[Sirenix.OdinInspector.PropertyOrder(3)]
public ByteSheep.Events.AdvancedEvent OnFail;
private float pointerDownTime;
private float lastClickTime;
private int clicksMade;
public void OnPointerDown(PointerEventData eventData)
{
pointerDownTime = Time.time;
}
public void OnPointerUp(PointerEventData eventData)
{
if (eventData.button != Button)
return;
// Valid click
if (clickTime > Time.time - pointerDownTime)
{
UpdateClicks();
}
else
{
Failed();
}
}
void UpdateClicks()
{
clicksMade++;
// Valid multiple click
if (clicksMade == 1 || clickTime > Time.time - lastClickTime)
{
if (clickCount == clicksMade)
{
CancelInvoke();
OnEvent.Invoke();
clicksMade = 0;
return;
}
}
else
{
Failed();
}
lastClickTime = Time.time;
Invoke("Failed", clickTime);
}
void Failed()
{
clicksMade = 0;
OnFail.Invoke();
}
}
}
| 16.810811 | 88 | 0.651125 | [
"MIT"
] | Besjan/Event-Inspector | Pointer/OnPointerClickEvent.cs | 1,246 | C# |
using System.Web.Security;
namespace Sporty.Controllers
{
public class FormsAuthenticationService : IFormsAuthentication
{
#region IFormsAuthentication Members
public void SignIn(string userName, bool createPersistentCookie)
{
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}
public void SignOut()
{
FormsAuthentication.SignOut();
}
#endregion
}
} | 22.52381 | 80 | 0.651163 | [
"MIT"
] | chstein/sportdiary | sources/Sporty/Controllers/FormsAuthenticationService.cs | 473 | C# |
using Informapp.InformSystem.WebApi.Models.ExampleValues;
using Informapp.InformSystem.WebApi.Models.Requests;
using Informapp.InformSystem.WebApi.Models.Version1.Constants;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
namespace Informapp.InformSystem.WebApi.Models.Version1.EndPoints.Countries.ListCountry
{
/// <summary>
/// List country response
/// </summary>
[DataContract(Namespace = Version1Constants.Namespace)]
public class ListCountryV1Response : BaseResponse
{
/// <summary>
/// List of countries
/// </summary>
[DataMember]
public IReadOnlyList<ListCountryV1ResponseCountry> Countries { get; set; }
= Array.Empty<ListCountryV1ResponseCountry>();
/// <summary>
/// Total number of records matching the request
/// </summary>
[DataMember]
[ExampleValue(CountryV1Constants.NumberOfCountries)]
[Range(Version1PageTotalConstants.Min, Version1PageTotalConstants.Max)]
[Required]
public int? Total { get; set; }
}
}
| 33.882353 | 87 | 0.698785 | [
"MIT"
] | InformappNL/informapp-api-dotnet-client | src/WebApi.Models/Version1/EndPoints/Countries/ListCountry/ListCountryV1Response.cs | 1,154 | C# |
// Generated class v2.50.0.0, don't modify
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
namespace NHtmlUnit.Svg
{
public partial class SvgEllipse : NHtmlUnit.Svg.SvgElement, NHtmlUnit.W3C.Dom.INode, NHtmlUnit.W3C.Dom.IElement
{
static SvgEllipse()
{
ObjectWrapper.RegisterWrapperCreator((com.gargoylesoftware.htmlunit.svg.SvgEllipse o) =>
new SvgEllipse(o));
}
public SvgEllipse(com.gargoylesoftware.htmlunit.svg.SvgEllipse wrappedObject) : base(wrappedObject) {}
public new com.gargoylesoftware.htmlunit.svg.SvgEllipse WObj
{
get { return (com.gargoylesoftware.htmlunit.svg.SvgEllipse)WrappedObject; }
}
}
}
| 26.833333 | 115 | 0.688199 | [
"Apache-2.0"
] | HtmlUnit/NHtmlUnit | app/NHtmlUnit/Generated/Svg/SvgEllipse.cs | 805 | 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.
#nullable disable
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
namespace System.Windows.Forms
{
internal class Formatter
{
private static readonly Type stringType = typeof(string);
private static readonly Type booleanType = typeof(bool);
private static readonly Type checkStateType = typeof(CheckState);
private static readonly object parseMethodNotFound = new object();
private static readonly object defaultDataSourceNullValue = System.DBNull.Value;
/// <summary>
/// Converts a binary value into a format suitable for display to the end user.
/// Used when pushing a value from a back-end data source into a data-bound property on a control.
///
/// The real conversion work happens inside FormatObjectInternal(). Before calling FormatObjectInternal(),
/// we check for any use of nullable types or values (eg. <see cref="Nullable{T}"/>) and 'unwrap'
/// them to get at the real types and values, which are then used in the actual conversion.
/// If the caller is expecting a nullable value back, we must also re-wrap the final result
/// inside a nullable value before returning.
/// </summary>
public static object FormatObject(object value,
Type targetType,
TypeConverter sourceConverter,
TypeConverter targetConverter,
string formatString,
IFormatProvider formatInfo,
object formattedNullValue,
object dataSourceNullValue)
{
//
// On the way in, see if value represents 'null' for this back-end field type, and substitute DBNull.
// For most types, 'null' is actually represented by DBNull. But for a nullable type, its represented
// by an instance of that type with no value. And for business objects it may be represented by a
// simple null reference.
//
if (Formatter.IsNullData(value, dataSourceNullValue))
{
value = System.DBNull.Value;
}
//
// Strip away any use of nullable types (eg. Nullable<int>), leaving just the 'real' types
//
Type oldTargetType = targetType;
targetType = NullableUnwrap(targetType);
sourceConverter = NullableUnwrap(sourceConverter);
targetConverter = NullableUnwrap(targetConverter);
bool isNullableTargetType = (targetType != oldTargetType);
//
// Call the 'real' method to perform the conversion
//
object result = FormatObjectInternal(value, targetType, sourceConverter, targetConverter, formatString, formatInfo, formattedNullValue);
if (oldTargetType.IsValueType && result is null && !isNullableTargetType)
{
throw new FormatException(GetCantConvertMessage(value, targetType));
}
return result;
}
/// <summary>
///
/// Converts a value into a format suitable for display to the end user.
///
/// - Converts DBNull or null into a suitable formatted representation of 'null'
/// - Performs some special-case conversions (eg. Boolean to CheckState)
/// - Uses TypeConverters or IConvertible where appropriate
/// - Throws a FormatException is no suitable conversion can be found
/// </summary>
private static object FormatObjectInternal(object value,
Type targetType,
TypeConverter sourceConverter,
TypeConverter targetConverter,
string formatString,
IFormatProvider formatInfo,
object formattedNullValue)
{
if (value == System.DBNull.Value || value is null)
{
//
// Convert DBNull to the formatted representation of 'null' (if possible)
//
if (formattedNullValue != null)
{
return formattedNullValue;
}
//
// Convert DBNull or null to a specific 'known' representation of null (otherwise fail)
//
if (targetType == stringType)
{
return string.Empty;
}
if (targetType == checkStateType)
{
return CheckState.Indeterminate;
}
// Just pass null through: if this is a value type, it's been unwrapped here, so we return null
// and the caller has to wrap if appropriate.
return null;
}
//
// Special case conversions
//
if (targetType == stringType)
{
if (value is IFormattable && !string.IsNullOrEmpty(formatString))
{
return (value as IFormattable).ToString(formatString, formatInfo);
}
}
//The converters for properties should take precedence. Unfortunately, we don't know whether we have one. Check vs. the
//type's TypeConverter. We're punting the case where the property-provided converter is the same as the type's converter.
Type sourceType = value.GetType();
TypeConverter sourceTypeTypeConverter = TypeDescriptor.GetConverter(sourceType);
if (sourceConverter != null && sourceConverter != sourceTypeTypeConverter && sourceConverter.CanConvertTo(targetType))
{
return sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, targetType);
}
TypeConverter targetTypeTypeConverter = TypeDescriptor.GetConverter(targetType);
if (targetConverter != null && targetConverter != targetTypeTypeConverter && targetConverter.CanConvertFrom(sourceType))
{
return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), value);
}
if (targetType == checkStateType)
{
if (sourceType == booleanType)
{
return ((bool)value) ? CheckState.Checked : CheckState.Unchecked;
}
else
{
if (sourceConverter is null)
{
sourceConverter = sourceTypeTypeConverter;
}
if (sourceConverter != null && sourceConverter.CanConvertTo(booleanType))
{
return (bool)sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, booleanType)
? CheckState.Checked : CheckState.Unchecked;
}
}
}
if (targetType.IsAssignableFrom(sourceType))
{
return value;
}
//
// If explicit type converters not provided, supply default ones instead
//
if (sourceConverter is null)
{
sourceConverter = sourceTypeTypeConverter;
}
if (targetConverter is null)
{
targetConverter = targetTypeTypeConverter;
}
//
// Standardized conversions
//
if (sourceConverter != null && sourceConverter.CanConvertTo(targetType))
{
return sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, targetType);
}
else if (targetConverter != null && targetConverter.CanConvertFrom(sourceType))
{
return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), value);
}
else if (value is IConvertible)
{
return ChangeType(value, targetType, formatInfo);
}
//
// Fail if no suitable conversion found
//
throw new FormatException(GetCantConvertMessage(value, targetType));
}
/// <summary>
/// Converts a value entered by the end user (through UI) into the corresponding binary value.
/// Used when pulling input from a data-bound property on a control to store in a back-end data source.
///
/// The real conversion work happens inside ParseObjectInternal(). Before calling ParseObjectInternal(),
/// we check for any use of nullable types or values (eg. <see cref="Nullable{T}"/>) and 'unwrap'
/// them to get at the real types and values, which are then used in the actual conversion.
/// If the caller is expecting a nullable value back, we must also re-wrap the final result
/// inside a nullable value before returning.
/// </summary>
public static object ParseObject(object value,
Type targetType,
Type sourceType,
TypeConverter targetConverter,
TypeConverter sourceConverter,
IFormatProvider formatInfo,
object formattedNullValue,
object dataSourceNullValue)
{
//
// Strip away any use of nullable types (eg. Nullable<int>), leaving just the 'real' types
//
Type oldTargetType = targetType;
sourceType = NullableUnwrap(sourceType);
targetType = NullableUnwrap(targetType);
sourceConverter = NullableUnwrap(sourceConverter);
targetConverter = NullableUnwrap(targetConverter);
bool isNullableTargetType = (targetType != oldTargetType);
//
// Call the 'real' method to perform the conversion
//
object result = ParseObjectInternal(value, targetType, sourceType, targetConverter, sourceConverter, formatInfo, formattedNullValue);
//
// On the way out, substitute DBNull with the appropriate representation of 'null' for the final target type.
// For most types, this is just DBNull. But for a nullable type, its an instance of that type with no value.
//
if (result == System.DBNull.Value)
{
return Formatter.NullData(oldTargetType, dataSourceNullValue);
}
return result;
}
/// <summary>
///
/// Converts a value entered by the end user (through UI) into the corresponding binary value.
///
/// - Converts formatted representations of 'null' into DBNull
/// - Performs some special-case conversions (eg. CheckState to Boolean)
/// - Uses TypeConverters or IConvertible where appropriate
/// - Throws a FormatException is no suitable conversion can be found
/// </summary>
private static object ParseObjectInternal(object value,
Type targetType,
Type sourceType,
TypeConverter targetConverter,
TypeConverter sourceConverter,
IFormatProvider formatInfo,
object formattedNullValue)
{
//
// Convert the formatted representation of 'null' to DBNull (if possible)
//
if (EqualsFormattedNullValue(value, formattedNullValue, formatInfo) || value == System.DBNull.Value)
{
return System.DBNull.Value;
}
//
// Special case conversions
//
TypeConverter targetTypeTypeConverter = TypeDescriptor.GetConverter(targetType);
if (targetConverter != null && targetTypeTypeConverter != targetConverter && targetConverter.CanConvertFrom(sourceType))
{
return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), value);
}
TypeConverter sourceTypeTypeConverter = TypeDescriptor.GetConverter(sourceType);
if (sourceConverter != null && sourceTypeTypeConverter != sourceConverter && sourceConverter.CanConvertTo(targetType))
{
return sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, targetType);
}
if (value is string)
{
// If target type has a suitable Parse method, use that to parse strings
object parseResult = InvokeStringParseMethod(value, targetType, formatInfo);
if (parseResult != parseMethodNotFound)
{
return parseResult;
}
}
else if (value is CheckState state)
{
if (state == CheckState.Indeterminate)
{
return DBNull.Value;
}
// Explicit conversion from CheckState to Boolean
if (targetType == booleanType)
{
return (state == CheckState.Checked);
}
if (targetConverter is null)
{
targetConverter = targetTypeTypeConverter;
}
if (targetConverter != null && targetConverter.CanConvertFrom(booleanType))
{
return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), state == CheckState.Checked);
}
}
else if (value != null && targetType.IsAssignableFrom(value.GetType()))
{
// If value is already of a compatible type, just go ahead and use it
return value;
}
//
// If explicit type converters not provided, supply default ones instead
//
if (targetConverter is null)
{
targetConverter = targetTypeTypeConverter;
}
if (sourceConverter is null)
{
sourceConverter = sourceTypeTypeConverter;
}
//
// Standardized conversions
//
if (targetConverter != null && targetConverter.CanConvertFrom(sourceType))
{
return targetConverter.ConvertFrom(null, GetFormatterCulture(formatInfo), value);
}
else if (sourceConverter != null && sourceConverter.CanConvertTo(targetType))
{
return sourceConverter.ConvertTo(null, GetFormatterCulture(formatInfo), value, targetType);
}
else if (value is IConvertible)
{
return ChangeType(value, targetType, formatInfo);
}
//
// Fail if no suitable conversion found
//
throw new FormatException(GetCantConvertMessage(value, targetType));
}
/// <summary>
/// Converts a value to the specified type using Convert.ChangeType()
/// </summary>
private static object ChangeType(object value, Type type, IFormatProvider formatInfo)
{
try
{
if (formatInfo is null)
{
formatInfo = CultureInfo.CurrentCulture;
}
return Convert.ChangeType(value, type, formatInfo);
}
catch (InvalidCastException ex)
{
throw new FormatException(ex.Message, ex);
}
}
/// <summary>
/// Indicates whether the specified value matches the display-formatted representation of 'null data' for a given binding.
/// </summary>
private static bool EqualsFormattedNullValue(object value, object formattedNullValue, IFormatProvider formatInfo)
{
if (formattedNullValue is string formattedNullValueStr && value is string valueStr)
{
// Use same optimization as in WindowsFormsUtils.SafeCompareStrings(...). This addresses
if (formattedNullValueStr.Length != valueStr.Length)
{
return false;
}
// Always do a case insensitive comparison for strings
return string.Compare(valueStr, formattedNullValueStr, true, GetFormatterCulture(formatInfo)) == 0;
}
else
{
// Otherwise perform default comparison based on object types
return Object.Equals(value, formattedNullValue);
}
}
/// <summary>
/// Returns the FormatException message used when formatting/parsing fails to find any suitable conversion
/// </summary>
private static string GetCantConvertMessage(object value, Type targetType)
{
string stringResId = (value is null) ? SR.Formatter_CantConvertNull : SR.Formatter_CantConvert;
return string.Format(CultureInfo.CurrentCulture, stringResId, value, targetType.Name);
}
/// <summary>
/// Determines the correct culture to use during formatting and parsing
/// </summary>
private static CultureInfo GetFormatterCulture(IFormatProvider formatInfo)
{
if (formatInfo is CultureInfo)
{
return formatInfo as CultureInfo;
}
else
{
return CultureInfo.CurrentCulture;
}
}
/// <summary>
/// Converts a value to the specified type using best Parse() method on that type
/// </summary>
public static object InvokeStringParseMethod(object value, Type targetType, IFormatProvider formatInfo)
{
try
{
MethodInfo mi;
mi = targetType.GetMethod("Parse",
BindingFlags.Public | BindingFlags.Static,
null,
new Type[] { stringType, typeof(NumberStyles), typeof(IFormatProvider) },
null);
if (mi != null)
{
return mi.Invoke(null, new object[] { (string)value, NumberStyles.Any, formatInfo });
}
mi = targetType.GetMethod("Parse",
BindingFlags.Public | BindingFlags.Static,
null,
new Type[] { stringType, typeof(IFormatProvider) },
null);
if (mi != null)
{
return mi.Invoke(null, new object[] { (string)value, formatInfo });
}
mi = targetType.GetMethod("Parse",
BindingFlags.Public | BindingFlags.Static,
null,
new Type[] { stringType },
null);
if (mi != null)
{
return mi.Invoke(null, new object[] { (string)value });
}
return parseMethodNotFound;
}
catch (TargetInvocationException ex)
{
throw new FormatException(ex.InnerException.Message, ex.InnerException);
}
}
/// <summary>
/// Indicates whether a given value represents 'null' for data source fields of the same type.
/// </summary>
public static bool IsNullData(object value, object dataSourceNullValue)
{
return value is null ||
value == System.DBNull.Value ||
Object.Equals(value, NullData(value.GetType(), dataSourceNullValue));
}
/// <summary>
/// Returns the default representation of 'null' for a given data source field type.
/// </summary>
public static object NullData(Type type, object dataSourceNullValue)
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
// For nullable types, null is represented by an instance of that type with no assigned value.
// The value could also be DBNull.Value (the default for dataSourceNullValue).
if (dataSourceNullValue is null || dataSourceNullValue == DBNull.Value)
{
// We don't have a special value that represents null on the data source:
// use the Nullable<T>'s representation
return null;
}
else
{
return dataSourceNullValue;
}
}
else
{
// For all other types, the default representation of null is defined by
// the caller (this will usually be System.DBNull.Value for ADO.NET data
// sources, or a null reference for 'business object' data sources).
return dataSourceNullValue;
}
}
/// <summary>
/// Extract the inner type from a nullable type
/// </summary>
private static Type NullableUnwrap(Type type)
{
if (type == stringType) // ...performance optimization for the most common case
{
return stringType;
}
Type underlyingType = Nullable.GetUnderlyingType(type);
return underlyingType ?? type;
}
/// <summary>
/// Extract the inner type converter from a nullable type converter
/// </summary>
private static TypeConverter NullableUnwrap(TypeConverter typeConverter)
{
return (typeConverter is NullableConverter nullableConverter) ? nullableConverter.UnderlyingTypeConverter : typeConverter;
}
public static object GetDefaultDataSourceNullValue(Type type)
{
return (type != null && !type.IsValueType) ? null : defaultDataSourceNullValue;
}
}
}
| 42.030466 | 148 | 0.534686 | [
"MIT"
] | Amy-Li03/winforms | src/System.Windows.Forms/src/System/Windows/Forms/Formatter.cs | 23,455 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AspStore.Models
{
public class Order
{
public long Id { get; set; }
[Required]
[StringLength(maximumLength: 50)]
public string Name { get; set; }
[Required]
[EmailAddress]
[StringLength(maximumLength: 150)]
public string Email { get; set; }
[Required]
[StringLength(maximumLength: 500)]
public string Address { get; set; }
[Required]
[Range(0, int.MaxValue)]
public double TotalAmount { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
[Required]
public string ApplicationUserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
public IEnumerable<OrderItem> OrderItems { get; set; }
}
}
| 23.15 | 62 | 0.603672 | [
"MIT"
] | mishelshaji/Asp-.Net-Core-Demo | AspStore.Models/Order.cs | 928 | C# |
using ExoMerge.Analysis;
namespace ExoMerge.Aspose
{
/// <summary>
/// Overrides the keyword token parser to cleanse token text, i.e. replacing "fancy" quotes
/// before passing on the token text to the underlying keyword token parser.
/// </summary>
public class DocumentKeywordTokenParser<TSourceType> : KeywordTokenParser<TSourceType>
{
public DocumentKeywordTokenParser()
: base(caseSensitive: true)
{
}
/// <summary>
/// Attempt to parse the given text.
/// </summary>
protected override bool TryParse(TSourceType sourceType, string text, out TokenType type, out string value)
{
// When authoring field expressions, Word may insert fancy "curly" quotes rather than standard quotes. Since the expression parser
// is unlikely to expect these characeters, this could result in a syntax error. So, replace the outer quotes with standard quotes.
var cleansedText = DocumentTokenCleanser.Cleanse(text);
return base.TryParse(sourceType, cleansedText, out type, out value);
}
}
}
| 35.241379 | 134 | 0.74364 | [
"MIT"
] | vc3/ExoMerge | ExoMerge.Aspose/DocumentKeywordTokenParser.cs | 1,024 | C# |
using System;
using System.Xml.Serialization;
namespace Aop.Api.Domain
{
/// <summary>
/// LoanRepayPlanTerm Data Structure.
/// </summary>
[Serializable]
public class LoanRepayPlanTerm : AopObject
{
/// <summary>
/// 是否当前期
/// </summary>
[XmlElement("current_term")]
public bool CurrentTerm { get; set; }
/// <summary>
/// 当期已还金额
/// </summary>
[XmlElement("paid_amt")]
public LoanMoneyTypeAmt PaidAmt { get; set; }
/// <summary>
/// 剩余应还金额
/// </summary>
[XmlElement("remain_amt")]
public LoanMoneyTypeAmt RemainAmt { get; set; }
/// <summary>
/// 分期状态,目前支持的分期状态有: NORMAL: 正常 OVD: 逾期 CLEAR: 结清
/// </summary>
[XmlElement("status")]
public string Status { get; set; }
/// <summary>
/// 本期到期日
/// </summary>
[XmlElement("term_end_date")]
public string TermEndDate { get; set; }
/// <summary>
/// 期次号
/// </summary>
[XmlElement("term_no")]
public long TermNo { get; set; }
/// <summary>
/// 本期开始日
/// </summary>
[XmlElement("term_start_date")]
public string TermStartDate { get; set; }
/// <summary>
/// 当期总金额
/// </summary>
[XmlElement("total_amt")]
public LoanMoneyTypeAmt TotalAmt { get; set; }
}
}
| 24.918033 | 61 | 0.482895 | [
"Apache-2.0"
] | 554393109/alipay-sdk-net-all | AlipaySDKNet.Standard/Domain/LoanRepayPlanTerm.cs | 1,634 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Security.Claims;
namespace RegionOrebroLan.Security.Claims
{
public class ClaimBuilder : IClaimBuilder
{
#region Fields
private string _issuer;
private string _originalIssuer;
private readonly IDictionary<string, string> _properties = new Dictionary<string, string>();
private string _type;
private string _value;
private string _valueType;
#endregion
#region Constructors
public ClaimBuilder() { }
public ClaimBuilder(Claim claim)
{
claim = claim?.Clone();
this._issuer = claim?.Issuer;
this._originalIssuer = claim?.OriginalIssuer;
this._type = claim?.Type;
this._value = claim?.Value;
this._valueType = claim?.ValueType;
if(claim?.Properties == null)
return;
foreach(var property in claim.Properties)
{
this._properties.Add(property.Key, property.Value);
}
}
#endregion
#region Properties
public virtual string Issuer
{
get => this._issuer;
set => this._issuer = value;
}
public virtual string OriginalIssuer
{
get => this._originalIssuer;
set => this._originalIssuer = value;
}
public virtual IDictionary<string, string> Properties => this._properties;
public virtual string Type
{
get => this._type;
set => this._type = value;
}
public virtual string Value
{
get => this._value;
set => this._value = value;
}
public virtual string ValueType
{
get => this._valueType;
set => this._valueType = value;
}
#endregion
#region Methods
[SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters")]
public virtual Claim Build()
{
try
{
var claim = new Claim(this.Type, this.Value, this.ValueType, this.Issuer, this.OriginalIssuer);
foreach(var property in this.Properties)
{
claim.Properties.Add(property.Key, property.Value);
}
return claim;
}
catch(Exception exception)
{
throw new InvalidOperationException("Could not build claim.", exception);
}
}
object ICloneable.Clone()
{
return this.Clone();
}
public virtual IClaimBuilder Clone()
{
var clone = new ClaimBuilder
{
Issuer = this.Issuer,
OriginalIssuer = this.OriginalIssuer,
Type = this.Type,
Value = this.Value,
ValueType = this.ValueType,
};
foreach(var property in this.Properties)
{
clone.Properties.Add(property.Key, property.Value);
}
return clone;
}
#endregion
}
} | 19.492308 | 99 | 0.68311 | [
"MIT"
] | RegionOrebroLan/.NET-Extensions | Source/Project/Security/Claims/ClaimBuilder.cs | 2,534 | C# |
using Mosaik.Core;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
//using MessagePack;
namespace Catalyst
{
public struct Span : ISpan
{
public Span(Document parent, int index)
{
Parent = parent;
Index = index;
_begin = Parent.SpanBounds[Index][0];
_end = Parent.SpanBounds[Index][1];
_value = "";
}
public IToken this[int key]
{
get
{
if (key >= 0 && key < TokensCount)
{
var td = Parent.TokensData[Index][key];
return new Token(Parent, key, Index, hasReplacement: td.Replacement is object, td.LowerBound, td.UpperBound);
}
else { throw new Exception("Invalid token index"); }
}
set { throw new InvalidOperationException(); }
}
public Language Language { get { return Parent.Language; } }
private int _begin;
private int _end;
private string _value;
private Document Parent;
private int Index;
public int Begin { get { if (_begin < 0) { _begin = Parent.SpanBounds[Index][0]; } return _begin; } set { Parent.SpanBounds[Index][0] = value; _begin = value; } }
public int End { get { if (_end < 0) { _end = Parent.SpanBounds[Index][1]; } return _end; } set { Parent.SpanBounds[Index][1] = value; _end = value; } }
public int Length { get { return End - Begin + 1; } }
public string Value { get { if (string.IsNullOrEmpty(_value)) { _value = Parent.GetSpanValue(Index); } return _value; } }
public ReadOnlySpan<char> ValueAsSpan { get { return Parent.GetSpanValue2(Index); } }
public int TokensCount { get { return Parent.TokensData[Index].Count; } }
public IEnumerable<IToken> Tokens
{
get
{
var sd = Parent.TokensData[Index];
int count = sd.Count;
for (int i = 0; i < count; i++)
{
var td = sd[i];
yield return new Token(Parent, i, Index, hasReplacement: td.Replacement is object, td.LowerBound, td.UpperBound);
}
}
}
public IToken AddToken(int begin, int end)
{
return Parent.AddToken(Index, begin, end);
}
//Used by the sentence detector
public IToken AddToken(IToken token)
{
var newtoken = Parent.AddToken(Index, token.Begin, token.End);
if (token.Replacement is object)
{
newtoken.Replacement = token.Replacement;
}
return token;
}
public void ReserveTokens(int expectedTokenCount)
{
Parent.ReserveTokens(Index, expectedTokenCount);
}
public IEnumerator<IToken> GetEnumerator()
{
return Tokens.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return Tokens.GetEnumerator();
}
public void SetTokenTag(int tokenIndex, PartOfSpeech tag)
{
Parent.SetTokenTag(tokenIndex, Index, tag);
}
[JsonIgnore]
public string TokenizedValue
{
get
{
var sb = new StringBuilder(Length + TokensCount + 100);
foreach (var token in this)
{
if (token.EntityTypes.Any(et => et.Tag == EntityTag.Begin || et.Tag == EntityTag.Inside))
{
bool isHyphen = token.ValueAsSpan.IsHyphen();
bool isNormalToken = !isHyphen && !token.ValueAsSpan.IsSentencePunctuation();
if (!isNormalToken)
{
if (sb[sb.Length - 1] == '_')
{
sb.Length--; //if we have a punctuation or hyphen, and the previous token added a '_', remove it here
}
}
if (!isHyphen)
{
sb.Append(token.Value);
}
else
{
sb.Append("_");
}
if (isNormalToken) { sb.Append("_"); } //don't add _ when the token is already a hyphen
}
else
{
sb.Append(token.Value).Append(" ");
}
}
return Regex.Replace(sb.ToString(), @"\s+", " ").TrimEnd(); //Remove the last space added during the loop
}
}
/// <summary>
/// Return the tokenized text. Entities will be returned as a single Tokens instance with the inner tokens as children. This method will always prefer to return the longest possible entity match.
/// </summary>
/// <returns></returns>
public IEnumerable<IToken> GetCapturedTokens(Func<IEnumerable<EntityType>, IEnumerable<EntityType>> entitySorter = null)
{
entitySorter ??= PreferLongerEntities;
var tokensCount = TokensCount; //Cache the property to avoid fetching the value on every iteration
for (int i = 0; i < tokensCount; i++)
{
var token = this[i];
var entityTypes = token.EntityTypes;
if (entityTypes.Any())
{
bool foundEntity = false;
foreach (var et in entitySorter(entityTypes.Where(et => et.Tag == EntityTag.Begin || et.Tag == EntityTag.Single)))
{
if (et.Tag == EntityTag.Single)
{
foundEntity = true;
yield return new Tokens(Parent, Index, new int[] { token.Index }, entityType: et) { Frequency = token.Frequency };
break;
}
else if (et.Tag == EntityTag.Begin)
{
var entityEnd = FindEntityEnd(tokensCount, token.Index, token.Frequency, entityTypes);
if(entityEnd.index > token.Index)
{
i = entityEnd.index;
foundEntity = true;
yield return new Tokens(Parent, Index, Enumerable.Range(token.Index, entityEnd.index - token.Index + 1).ToArray(), entityType: entityEnd.entityType) { Frequency = entityEnd.lowestTokenFrequency };
break;
}
}
}
if (!foundEntity)
{
yield return token;
}
}
else
{
yield return token;
}
}
}
/// <summary>
/// Return only tokens that have entities attached to them. This method will always prefer to return the longest possible entity match.
/// </summary>
/// <param name="filter">Optional function to decide which entities to return. Should return true if you want to return the entity, or false if you want to skip it.</param>
/// <returns></returns>
public IEnumerable<ITokens> GetEntities(Func<EntityType, bool> filter = null)
{
int tokensCount = TokensCount;
bool hasFilter = filter is object;
for (int i = 0; i < tokensCount; i++)
{
var token = this[i];
var entityTypes = token.EntityTypes;
if (entityTypes.Length > 0)
{
foreach (var et in PreferLongerEntities(entityTypes))
{
if (hasFilter && !filter(et))
{
continue; // Skip unwanted entities
}
if (et.Tag == EntityTag.Single)
{
yield return new Tokens(Parent, Index, new int[] { token.Index }, entityType: et) { Frequency = token.Frequency };
}
else if (et.Tag == EntityTag.Begin)
{
var entityEnd = FindEntityEnd(tokensCount, token.Index, token.Frequency, entityTypes);
if (entityEnd.index > token.Index)
{
i = entityEnd.index;
yield return new Tokens(Parent, Index, Enumerable.Range(token.Index, entityEnd.index - token.Index + 1).ToArray(), entityType: entityEnd.entityType) { Frequency = entityEnd.lowestTokenFrequency };
break;
}
}
}
}
}
}
/// <summary>
/// Attempts to find the end of an entity marked by an initial token with EntityType.Tag == EntityTag.Begin.
/// Will return the first longest possible match for a given [Begin] token.
/// </summary>
private (int index, EntityType entityType, float lowestTokenFrequency) FindEntityEnd(int tokenCount, int currentIndex, float tokenFrequency, EntityType[] entityTypes)
{
EntityType longestEntityType = default;
int finalIndex = -1;
float finalFrequency = tokenFrequency;
foreach (var beginEntityType in entityTypes.Where(et => et.Tag == EntityTag.Begin))
{
int possibleFinal = -1;
float possibleFrequency = tokenFrequency;
bool foundEnd = false;
for (int j = currentIndex + 1; j < tokenCount; j++)
{
var other = this[j];
var otherET = other.EntityTypes.Where(oet => (oet.Tag == EntityTag.Inside || oet.Tag == EntityTag.End) && oet.Type == beginEntityType.Type);
if (otherET.Any())
{
possibleFinal = j;
possibleFrequency = Math.Min(possibleFrequency, other.Frequency);
foundEnd |= otherET.Any(oet => oet.Tag == EntityTag.End);
}
else
{
break;
}
}
if (foundEnd)
{
if (possibleFinal > finalIndex)
{
finalIndex = possibleFinal;
finalFrequency = possibleFrequency;
longestEntityType = beginEntityType;
}
}
}
return (finalIndex, longestEntityType, finalFrequency);
}
public static IOrderedEnumerable<EntityType> PreferLongerEntities(IEnumerable<EntityType> entityTypes)
{
//This method ensures we first try to enumerate the longest entities (i.e. starting with Begin), followed by Single entities
return entityTypes.OrderBy(et => (char)et.Tag);
}
public Span<Token> ToTokenSpan()
{
var tkc = TokensCount;
var tokens = new Token[tkc];
var sd = Parent.TokensData[Index];
for (int i = 0; i < tkc; i++)
{
var td = sd[i];
tokens[i] = new Token(Parent, i, Index, td.Replacement is object, td.LowerBound, td.UpperBound);
}
return tokens;
}
}
} | 39.577049 | 228 | 0.482313 | [
"MIT"
] | andmattia/catalyst | Catalyst/src/Base/Span.cs | 12,073 | C# |
using System;
using System.ComponentModel;
using EfsTools.Attributes;
namespace EfsTools.Items.Efs
{
[Serializable]
[EfsFile("/nv/item_files/ims/qipcall_octet_aligned_mode_amr_nb", true, 0xE1FF)]
[Attributes(9)]
public class QipcallOctetAlignedModeAmrNb
{
[ElementsCount(1)]
[ElementType("uint8")]
[Description("")]
public byte Value { get; set; }
}
} | 24.941176 | 84 | 0.643868 | [
"MIT"
] | HomerSp/EfsTools | EfsTools/Items/Efs/QipcallOctetAlignedModeAmrNb.cs | 424 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace Microsoft.EntityFrameworkCore.TestUtilities
{
public abstract class QueryAsserterBase
{
public virtual Func<DbContext, ISetSource> SetSourceCreator { get; set; }
public virtual ISetSource ExpectedData { get; set; }
public abstract Task AssertSingleResultTyped<TResult>(
Func<ISetSource, TResult> actualSyncQuery,
Func<ISetSource, Task<TResult>> actualAsyncQuery,
Func<ISetSource, TResult> expectedQuery,
Action<TResult, TResult> asserter,
int entryCount,
bool isAsync,
string testMethodName);
public abstract Task AssertQuery<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Func<TResult, object> elementSorter,
Action<TResult, TResult> elementAsserter,
bool assertOrder,
int entryCount,
bool isAsync,
string testMethodName)
where TResult : class;
public abstract Task AssertQueryScalar<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
bool assertOrder,
bool isAsync,
string testMethodName)
where TResult : struct;
public abstract Task AssertQueryScalar<TResult>(
Func<ISetSource, IQueryable<TResult?>> actualQuery,
Func<ISetSource, IQueryable<TResult?>> expectedQuery,
bool assertOrder,
bool isAsync,
string testMethodName)
where TResult : struct;
public abstract Task<List<TResult>> AssertIncludeQuery<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
List<IExpectedInclude> expectedIncludes,
Func<TResult, object> elementSorter,
List<Func<TResult, object>> clientProjections,
bool assertOrder,
int entryCount,
bool isAsync,
string testMethodName);
#region Assert termination operation methods
public abstract Task AssertAny<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
bool isAsync = false);
public abstract Task AssertAny<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, bool>> actualPredicate,
Expression<Func<TResult, bool>> expectedPredicate,
bool isAsync = false);
public abstract Task AssertAll<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, bool>> actualPredicate,
Expression<Func<TResult, bool>> expectedPredicate,
bool isAsync = false);
public abstract Task AssertFirst<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Action<TResult, TResult> asserter = null,
int entryCount = 0,
bool isAsync = false);
public abstract Task AssertFirst<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, bool>> actualPredicate,
Expression<Func<TResult, bool>> expectedPredicate,
Action<TResult, TResult> asserter = null,
int entryCount = 0,
bool isAsync = false);
public abstract Task AssertFirstOrDefault<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Action<TResult, TResult> asserter = null,
int entryCount = 0,
bool isAsync = false);
public abstract Task AssertFirstOrDefault<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, bool>> actualPredicate,
Expression<Func<TResult, bool>> expectedPredicate,
Action<TResult, TResult> asserter = null,
int entryCount = 0,
bool isAsync = false);
public abstract Task AssertSingle<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Action<TResult, TResult> asserter = null,
int entryCount = 0,
bool isAsync = false);
public abstract Task AssertSingle<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, bool>> actualPredicate,
Expression<Func<TResult, bool>> expectedPredicate,
Action<TResult, TResult> asserter = null,
int entryCount = 0,
bool isAsync = false);
public abstract Task AssertSingleOrDefault<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Action<TResult, TResult> asserter = null,
int entryCount = 0,
bool isAsync = false);
public abstract Task AssertSingleOrDefault<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, bool>> actualPredicate,
Expression<Func<TResult, bool>> expectedPredicate,
Action<TResult, TResult> asserter = null,
int entryCount = 0,
bool isAsync = false);
public abstract Task AssertLast<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Action<TResult, TResult> asserter = null,
int entryCount = 0,
bool isAsync = false);
public abstract Task AssertLast<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, bool>> actualPredicate,
Expression<Func<TResult, bool>> expectedPredicate,
Action<TResult, TResult> asserter = null,
int entryCount = 0,
bool isAsync = false);
public abstract Task AssertLastOrDefault<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Action<TResult, TResult> asserter = null,
int entryCount = 0,
bool isAsync = false);
public abstract Task AssertLastOrDefault<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, bool>> actualPredicate,
Expression<Func<TResult, bool>> expectedPredicate,
Action<TResult, TResult> asserter = null,
int entryCount = 0,
bool isAsync = false);
public abstract Task AssertCount<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
bool isAsync = false);
public abstract Task AssertCount<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, bool>> actualPredicate,
Expression<Func<TResult, bool>> expectedPredicate,
bool isAsync = false);
public abstract Task AssertLongCount<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
bool isAsync = false);
public abstract Task AssertLongCount<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, bool>> actualPredicate,
Expression<Func<TResult, bool>> expectedPredicate,
bool isAsync = false);
public abstract Task AssertMin<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Action<TResult, TResult> asserter = null,
int entryCount = 0,
bool isAsync = false);
public abstract Task AssertMin<TResult, TSelector>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, TSelector>> actualSelector,
Expression<Func<TResult, TSelector>> expectedSelector,
Action<TSelector, TSelector> asserter = null,
int entryCount = 0,
bool isAsync = false);
public abstract Task AssertMax<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Action<TResult, TResult> asserter = null,
int entryCount = 0,
bool isAsync = false);
public abstract Task AssertMax<TResult, TSelector>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, TSelector>> actualSelector,
Expression<Func<TResult, TSelector>> expectedSelector,
Action<TSelector, TSelector> asserter = null,
int entryCount = 0,
bool isAsync = false);
public abstract Task AssertSum(
Func<ISetSource, IQueryable<int>> actualQuery,
Func<ISetSource, IQueryable<int>> expectedQuery,
Action<int, int> asserter = null,
bool isAsync = false);
public abstract Task AssertSum(
Func<ISetSource, IQueryable<int?>> actualQuery,
Func<ISetSource, IQueryable<int?>> expectedQuery,
Action<int?, int?> asserter = null,
bool isAsync = false);
public abstract Task AssertSum(
Func<ISetSource, IQueryable<long>> actualQuery,
Func<ISetSource, IQueryable<long>> expectedQuery,
Action<long, long> asserter = null,
bool isAsync = false);
public abstract Task AssertSum(
Func<ISetSource, IQueryable<long?>> actualQuery,
Func<ISetSource, IQueryable<long?>> expectedQuery,
Action<long?, long?> asserter = null,
bool isAsync = false);
public abstract Task AssertSum(
Func<ISetSource, IQueryable<decimal>> actualQuery,
Func<ISetSource, IQueryable<decimal>> expectedQuery,
Action<decimal, decimal> asserter = null,
bool isAsync = false);
public abstract Task AssertSum(
Func<ISetSource, IQueryable<decimal?>> actualQuery,
Func<ISetSource, IQueryable<decimal?>> expectedQuery,
Action<decimal?, decimal?> asserter = null,
bool isAsync = false);
public abstract Task AssertSum(
Func<ISetSource, IQueryable<float>> actualQuery,
Func<ISetSource, IQueryable<float>> expectedQuery,
Action<float, float> asserter = null,
bool isAsync = false);
public abstract Task AssertSum(
Func<ISetSource, IQueryable<float?>> actualQuery,
Func<ISetSource, IQueryable<float?>> expectedQuery,
Action<float?, float?> asserter = null,
bool isAsync = false);
public abstract Task AssertSum(
Func<ISetSource, IQueryable<double>> actualQuery,
Func<ISetSource, IQueryable<double>> expectedQuery,
Action<double, double> asserter = null,
bool isAsync = false);
public abstract Task AssertSum(
Func<ISetSource, IQueryable<double?>> actualQuery,
Func<ISetSource, IQueryable<double?>> expectedQuery,
Action<double?, double?> asserter = null,
bool isAsync = false);
public abstract Task AssertSum<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, int>> actualSelector,
Expression<Func<TResult, int>> expectedSelector,
Action<int, int> asserter = null,
bool isAsync = false);
public abstract Task AssertSum<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, int?>> actualSelector,
Expression<Func<TResult, int?>> expectedSelector,
Action<int?, int?> asserter = null,
bool isAsync = false);
public abstract Task AssertSum<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, long>> actualSelector,
Expression<Func<TResult, long>> expectedSelector,
Action<long, long> asserter = null,
bool isAsync = false);
public abstract Task AssertSum<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, long?>> actualSelector,
Expression<Func<TResult, long?>> expectedSelector,
Action<long?, long?> asserter = null,
bool isAsync = false);
public abstract Task AssertSum<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, decimal>> actualSelector,
Expression<Func<TResult, decimal>> expectedSelector,
Action<decimal, decimal> asserter = null,
bool isAsync = false);
public abstract Task AssertSum<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, decimal?>> actualSelector,
Expression<Func<TResult, decimal?>> expectedSelector,
Action<decimal?, decimal?> asserter = null,
bool isAsync = false);
public abstract Task AssertSum<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, float>> actualSelector,
Expression<Func<TResult, float>> expectedSelector,
Action<float, float> asserter = null,
bool isAsync = false);
public abstract Task AssertSum<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, float?>> actualSelector,
Expression<Func<TResult, float?>> expectedSelector,
Action<float?, float?> asserter = null,
bool isAsync = false);
public abstract Task AssertSum<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, double>> actualSelector,
Expression<Func<TResult, double>> expectedSelector,
Action<double, double> asserter = null,
bool isAsync = false);
public abstract Task AssertSum<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, double?>> actualSelector,
Expression<Func<TResult, double?>> expectedSelector,
Action<double?, double?> asserter = null,
bool isAsync = false);
public abstract Task AssertAverage(
Func<ISetSource, IQueryable<int>> actualQuery,
Func<ISetSource, IQueryable<int>> expectedQuery,
Action<double, double> asserter = null,
bool isAsync = false);
public abstract Task AssertAverage(
Func<ISetSource, IQueryable<int?>> actualQuery,
Func<ISetSource, IQueryable<int?>> expectedQuery,
Action<double?, double?> asserter = null,
bool isAsync = false);
public abstract Task AssertAverage(
Func<ISetSource, IQueryable<long>> actualQuery,
Func<ISetSource, IQueryable<long>> expectedQuery,
Action<double, double> asserter = null,
bool isAsync = false);
public abstract Task AssertAverage(
Func<ISetSource, IQueryable<long?>> actualQuery,
Func<ISetSource, IQueryable<long?>> expectedQuery,
Action<double?, double?> asserter = null,
bool isAsync = false);
public abstract Task AssertAverage(
Func<ISetSource, IQueryable<decimal>> actualQuery,
Func<ISetSource, IQueryable<decimal>> expectedQuery,
Action<decimal, decimal> asserter = null,
bool isAsync = false);
public abstract Task AssertAverage(
Func<ISetSource, IQueryable<decimal?>> actualQuery,
Func<ISetSource, IQueryable<decimal?>> expectedQuery,
Action<decimal?, decimal?> asserter = null,
bool isAsync = false);
public abstract Task AssertAverage(
Func<ISetSource, IQueryable<float>> actualQuery,
Func<ISetSource, IQueryable<float>> expectedQuery,
Action<float, float> asserter = null,
bool isAsync = false);
public abstract Task AssertAverage(
Func<ISetSource, IQueryable<float?>> actualQuery,
Func<ISetSource, IQueryable<float?>> expectedQuery,
Action<float?, float?> asserter = null,
bool isAsync = false);
public abstract Task AssertAverage(
Func<ISetSource, IQueryable<double>> actualQuery,
Func<ISetSource, IQueryable<double>> expectedQuery,
Action<double, double> asserter = null,
bool isAsync = false);
public abstract Task AssertAverage(
Func<ISetSource, IQueryable<double?>> actualQuery,
Func<ISetSource, IQueryable<double?>> expectedQuery,
Action<double?, double?> asserter = null,
bool isAsync = false);
public abstract Task AssertAverage<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, int>> actualSelector,
Expression<Func<TResult, int>> expectedSelector,
Action<double, double> asserter = null,
bool isAsync = false);
public abstract Task AssertAverage<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, int?>> actualSelector,
Expression<Func<TResult, int?>> expectedSelector,
Action<double?, double?> asserter = null,
bool isAsync = false);
public abstract Task AssertAverage<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, long>> actualSelector,
Expression<Func<TResult, long>> expectedSelector,
Action<double, double> asserter = null,
bool isAsync = false);
public abstract Task AssertAverage<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, long?>> actualSelector,
Expression<Func<TResult, long?>> expectedSelector,
Action<double?, double?> asserter = null,
bool isAsync = false);
public abstract Task AssertAverage<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, decimal>> actualSelector,
Expression<Func<TResult, decimal>> expectedSelector,
Action<decimal, decimal> asserter = null,
bool isAsync = false);
public abstract Task AssertAverage<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, decimal?>> actualSelector,
Expression<Func<TResult, decimal?>> expectedSelector,
Action<decimal?, decimal?> asserter = null,
bool isAsync = false);
public abstract Task AssertAverage<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, float>> actualSelector,
Expression<Func<TResult, float>> expectedSelector,
Action<float, float> asserter = null,
bool isAsync = false);
public abstract Task AssertAverage<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, float?>> actualSelector,
Expression<Func<TResult, float?>> expectedSelector,
Action<float?, float?> asserter = null,
bool isAsync = false);
public abstract Task AssertAverage<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, double>> actualSelector,
Expression<Func<TResult, double>> expectedSelector,
Action<double, double> asserter = null,
bool isAsync = false);
public abstract Task AssertAverage<TResult>(
Func<ISetSource, IQueryable<TResult>> actualQuery,
Func<ISetSource, IQueryable<TResult>> expectedQuery,
Expression<Func<TResult, double?>> actualSelector,
Expression<Func<TResult, double?>> expectedSelector,
Action<double?, double?> asserter = null,
bool isAsync = false);
#endregion
#region Helpers
public abstract void AssertEqual<T>(
T expected,
T actual,
Action<T, T> asserter = null);
public abstract void AssertEqual<T>(
T? expected,
T? actual,
Action<T?, T?> asserter = null)
where T : struct;
public abstract void AssertCollection<TElement>(
IEnumerable<TElement> expected,
IEnumerable<TElement> actual,
bool ordered = false,
Func<TElement, object> elementSorter = null,
Action<TElement, TElement> elementAsserter = null);
#endregion
}
}
| 44.270718 | 111 | 0.62748 | [
"Apache-2.0"
] | HeMinzhang/EntityFrameworkCore | test/EFCore.Specification.Tests/TestUtilities/QueryAsserterBase.cs | 24,039 | 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.
//
// This file was autogenerated by a tool.
// Do not modify it.
//
namespace Microsoft.Azure.Batch
{
using Models = Microsoft.Azure.Batch.Protocol.Models;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// A network security group rule to apply to an inbound endpoint.
/// </summary>
public partial class NetworkSecurityGroupRule : ITransportObjectProvider<Models.NetworkSecurityGroupRule>, IPropertyMetadata
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="NetworkSecurityGroupRule"/> class.
/// </summary>
/// <param name='priority'>The priority for this rule.</param>
/// <param name='access'>The action that should be taken for a specified IP address, subnet range or tag.</param>
/// <param name='sourceAddressPrefix'>The source address prefix or tag to match for the rule.</param>
/// <param name='sourcePortRanges'>The source port ranges to match for the rule.</param>
public NetworkSecurityGroupRule(
int priority,
Common.NetworkSecurityGroupRuleAccess access,
string sourceAddressPrefix,
IReadOnlyList<string> sourcePortRanges = default(IReadOnlyList<string>))
{
this.Priority = priority;
this.Access = access;
this.SourceAddressPrefix = sourceAddressPrefix;
this.SourcePortRanges = sourcePortRanges;
}
internal NetworkSecurityGroupRule(Models.NetworkSecurityGroupRule protocolObject)
{
this.Access = UtilitiesInternal.MapEnum<Models.NetworkSecurityGroupRuleAccess, Common.NetworkSecurityGroupRuleAccess>(protocolObject.Access);
this.Priority = protocolObject.Priority;
this.SourceAddressPrefix = protocolObject.SourceAddressPrefix;
this.SourcePortRanges = UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.SourcePortRanges, o => o.ToList().AsReadOnly());
}
#endregion Constructors
#region NetworkSecurityGroupRule
/// <summary>
/// Gets the action that should be taken for a specified IP address, subnet range or tag.
/// </summary>
public Common.NetworkSecurityGroupRuleAccess Access { get; }
/// <summary>
/// Gets the priority for this rule.
/// </summary>
/// <remarks>
/// Priorities within a pool must be unique and are evaluated in order of priority. The lower the number the higher
/// the priority. For example, rules could be specified with order numbers of 150, 250, and 350. The rule with the
/// order number of 150 takes precedence over the rule that has an order of 250. Allowed priorities are 150 to 3500.
/// </remarks>
public int Priority { get; }
/// <summary>
/// Gets the source address prefix or tag to match for the rule.
/// </summary>
/// <remarks>
/// Valid values are a single IP address (i.e. 10.10.10.10), IP subnet (i.e. 192.168.1.0/24), default tag, or * (for
/// all addresses).
/// </remarks>
public string SourceAddressPrefix { get; }
/// <summary>
/// Gets the source port ranges to match for the rule.
/// </summary>
/// <remarks>
/// Valid values are '*' (for all ports 0 - 65535), a specific port (i.e. 22), or a port range (i.e. 100-200). The
/// ports must be in the range of 0 to 65535. Each entry in this collection must not overlap any other entry (either
/// a range or an individual port). If any other values are provided the request fails with HTTP status code 400.
/// The default value is '*'
/// </remarks>
public IReadOnlyList<string> SourcePortRanges { get; }
#endregion // NetworkSecurityGroupRule
#region IPropertyMetadata
bool IModifiable.HasBeenModified
{
//This class is compile time readonly so it cannot have been modified
get { return false; }
}
bool IReadOnly.IsReadOnly
{
get { return true; }
set
{
// This class is compile time readonly already
}
}
#endregion // IPropertyMetadata
#region Internal/private methods
/// <summary>
/// Return a protocol object of the requested type.
/// </summary>
/// <returns>The protocol object of the requested type.</returns>
Models.NetworkSecurityGroupRule ITransportObjectProvider<Models.NetworkSecurityGroupRule>.GetTransportObject()
{
Models.NetworkSecurityGroupRule result = new Models.NetworkSecurityGroupRule()
{
Access = UtilitiesInternal.MapEnum<Common.NetworkSecurityGroupRuleAccess, Models.NetworkSecurityGroupRuleAccess>(this.Access),
Priority = this.Priority,
SourceAddressPrefix = this.SourceAddressPrefix,
SourcePortRanges = UtilitiesInternal.CreateObjectWithNullCheck(this.SourcePortRanges, o => o.ToList()),
};
return result;
}
/// <summary>
/// Converts a collection of protocol layer objects to object layer collection objects.
/// </summary>
internal static IList<NetworkSecurityGroupRule> ConvertFromProtocolCollection(IEnumerable<Models.NetworkSecurityGroupRule> protoCollection)
{
ConcurrentChangeTrackedModifiableList<NetworkSecurityGroupRule> converted = UtilitiesInternal.CollectionToThreadSafeCollectionIModifiable(
items: protoCollection,
objectCreationFunc: o => new NetworkSecurityGroupRule(o));
return converted;
}
/// <summary>
/// Converts a collection of protocol layer objects to object layer collection objects, in a frozen state.
/// </summary>
internal static IList<NetworkSecurityGroupRule> ConvertFromProtocolCollectionAndFreeze(IEnumerable<Models.NetworkSecurityGroupRule> protoCollection)
{
ConcurrentChangeTrackedModifiableList<NetworkSecurityGroupRule> converted = UtilitiesInternal.CollectionToThreadSafeCollectionIModifiable(
items: protoCollection,
objectCreationFunc: o => new NetworkSecurityGroupRule(o).Freeze());
converted = UtilitiesInternal.CreateObjectWithNullCheck(converted, o => o.Freeze());
return converted;
}
/// <summary>
/// Converts a collection of protocol layer objects to object layer collection objects, with each object marked readonly
/// and returned as a readonly collection.
/// </summary>
internal static IReadOnlyList<NetworkSecurityGroupRule> ConvertFromProtocolCollectionReadOnly(IEnumerable<Models.NetworkSecurityGroupRule> protoCollection)
{
IReadOnlyList<NetworkSecurityGroupRule> converted =
UtilitiesInternal.CreateObjectWithNullCheck(
UtilitiesInternal.CollectionToNonThreadSafeCollection(
items: protoCollection,
objectCreationFunc: o => new NetworkSecurityGroupRule(o).Freeze()), o => o.AsReadOnly());
return converted;
}
#endregion // Internal/private methods
}
} | 44.382857 | 163 | 0.653148 | [
"MIT"
] | Azkel/azure-sdk-for-net | sdk/batch/Microsoft.Azure.Batch/src/Generated/NetworkSecurityGroupRule.cs | 7,767 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
public class FullNameTests : CSharpResultProviderTestBase
{
[Fact]
public void RootComment()
{
var source = @"
class C
{
public int F;
}
";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(type.Instantiate());
var root = FormatResult("a // Comment", value);
Assert.Equal("a.F", GetChildren(root).Single().FullName);
root = FormatResult(" a // Comment", value);
Assert.Equal("a.F", GetChildren(root).Single().FullName);
root = FormatResult("a// Comment", value);
Assert.Equal("a.F", GetChildren(root).Single().FullName);
root = FormatResult("a /*b*/ +c /*d*/// Comment", value);
Assert.Equal("(a +c).F", GetChildren(root).Single().FullName);
root = FormatResult("a /*//*/+ c// Comment", value);
Assert.Equal("(a + c).F", GetChildren(root).Single().FullName);
root = FormatResult("a /*/**/+ c// Comment", value);
Assert.Equal("(a + c).F", GetChildren(root).Single().FullName);
root = FormatResult("/**/a// Comment", value);
Assert.Equal("a.F", GetChildren(root).Single().FullName);
}
[Fact]
public void RootFormatSpecifiers()
{
var source = @"
class C
{
public int F;
}
";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(type.Instantiate());
var root = FormatResult("a, raw", value); // simple
Assert.Equal("a, raw", root.FullName);
Assert.Equal("a.F", GetChildren(root).Single().FullName);
root = FormatResult("a, raw, ac, h", value); // multiple specifiers
Assert.Equal("a, raw, ac, h", root.FullName);
Assert.Equal("a.F", GetChildren(root).Single().FullName);
root = FormatResult("M(a, b), raw", value); // non-specifier comma
Assert.Equal("M(a, b), raw", root.FullName);
Assert.Equal("M(a, b).F", GetChildren(root).Single().FullName);
root = FormatResult("a, raw1", value); // alpha-numeric
Assert.Equal("a, raw1", root.FullName);
Assert.Equal("a.F", GetChildren(root).Single().FullName);
root = FormatResult("a, $raw", value); // other punctuation
Assert.Equal("a, $raw", root.FullName);
Assert.Equal("(a, $raw).F", GetChildren(root).Single().FullName); // not ideal
}
[Fact]
public void RootParentheses()
{
var source = @"
class C
{
public int F;
}
";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(type.Instantiate());
var root = FormatResult("a + b", value);
Assert.Equal("(a + b).F", GetChildren(root).Single().FullName); // required
root = FormatResult("new C()", value);
Assert.Equal("(new C()).F", GetChildren(root).Single().FullName); // documentation
root = FormatResult("A.B", value);
Assert.Equal("A.B.F", GetChildren(root).Single().FullName); // desirable
root = FormatResult("A::B", value);
Assert.Equal("(A::B).F", GetChildren(root).Single().FullName); // documentation
}
[Fact]
public void RootTrailingSemicolons()
{
var source = @"
class C
{
public int F;
}
";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(type.Instantiate());
var root = FormatResult("a;", value);
Assert.Equal("a.F", GetChildren(root).Single().FullName);
root = FormatResult("a + b;;", value);
Assert.Equal("(a + b).F", GetChildren(root).Single().FullName);
root = FormatResult(" M( ) ; ;", value);
Assert.Equal("M( ).F", GetChildren(root).Single().FullName);
}
[Fact]
public void RootMixedExtras()
{
var source = @"
class C
{
public int F;
}
";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(type.Instantiate());
// Semicolon, then comment.
var root = FormatResult("a; //", value);
Assert.Equal("a", root.FullName);
// Comment, then semicolon.
root = FormatResult("a // ;", value);
Assert.Equal("a", root.FullName);
// Semicolon, then format specifier.
root = FormatResult("a;, ac", value);
Assert.Equal("a, ac", root.FullName);
// Format specifier, then semicolon.
root = FormatResult("a, ac;", value);
Assert.Equal("a, ac", root.FullName);
// Comment, then format specifier.
root = FormatResult("a//, ac", value);
Assert.Equal("a", root.FullName);
// Format specifier, then comment.
root = FormatResult("a, ac //", value);
Assert.Equal("a, ac", root.FullName);
// Everything.
root = FormatResult("/*A*/ a /*B*/ + /*C*/ b /*D*/ ; ; , ac /*E*/, raw // ;, hidden", value);
Assert.Equal("a + b, ac, raw", root.FullName);
}
[Fact, WorkItem(1022165, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1022165")]
public void Keywords_Root()
{
var source = @"
class C
{
void M()
{
int @namespace = 3;
}
}
";
var assembly = GetAssembly(source);
var value = CreateDkmClrValue(3);
var root = FormatResult("@namespace", value);
Verify(root,
EvalResult("@namespace", "3", "int", "@namespace"));
value = CreateDkmClrValue(assembly.GetType("C").Instantiate());
root = FormatResult("this", value);
Verify(root,
EvalResult("this", "{C}", "C", "this"));
// Verify that keywords aren't escaped by the ResultProvider at the
// root level (we would never expect to see "namespace" passed as a
// resultName, but this check verifies that we leave them "as is").
root = FormatResult("namespace", CreateDkmClrValue(new object()));
Verify(root,
EvalResult("namespace", "{object}", "object", "namespace"));
}
[Fact]
public void Keywords_RuntimeType()
{
var source = @"
public class @struct
{
}
public class @namespace : @struct
{
@struct m = new @if();
}
public class @if : @struct
{
}
";
var assembly = GetAssembly(source);
var type = assembly.GetType("namespace");
var declaredType = assembly.GetType("struct");
var value = CreateDkmClrValue(type.Instantiate(), type);
var root = FormatResult("o", value, new DkmClrType((TypeImpl)declaredType));
Verify(GetChildren(root),
EvalResult("m", "{if}", "struct {if}", "((@namespace)o).m", DkmEvaluationResultFlags.None));
}
[Fact]
public void Keywords_ProxyType()
{
var source = @"
using System.Diagnostics;
[DebuggerTypeProxy(typeof(@class))]
public class @struct
{
public bool @true = false;
}
public class @class
{
public bool @false = true;
public @class(@struct s) { }
}
";
var assembly = GetAssembly(source);
var value = CreateDkmClrValue(assembly.GetType("struct").Instantiate());
var root = FormatResult("o", value);
var children = GetChildren(root);
Verify(children,
EvalResult("@false", "true", "bool", "new @class(o).@false", DkmEvaluationResultFlags.Boolean | DkmEvaluationResultFlags.BooleanTrue),
EvalResult("Raw View", null, "", "o, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
var grandChildren = GetChildren(children.Last());
Verify(grandChildren,
EvalResult("@true", "false", "bool", "o.@true", DkmEvaluationResultFlags.Boolean));
}
[Fact]
public void Keywords_MemberAccess()
{
var source = @"
public class @struct
{
public int @true;
}
";
var assembly = GetAssembly(source);
var value = CreateDkmClrValue(assembly.GetType("struct").Instantiate());
var root = FormatResult("o", value);
Verify(GetChildren(root),
EvalResult("@true", "0", "int", "o.@true"));
}
[Fact]
public void Keywords_StaticMembers()
{
var source = @"
public class @struct
{
public static int @true;
}
";
var assembly = GetAssembly(source);
var value = CreateDkmClrValue(assembly.GetType("struct").Instantiate());
var root = FormatResult("o", value);
var children = GetChildren(root);
Verify(children,
EvalResult("Static members", null, "", "@struct", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
Verify(GetChildren(children.Single()),
EvalResult("@true", "0", "int", "@struct.@true", DkmEvaluationResultFlags.None, DkmEvaluationResultCategory.Data, DkmEvaluationResultAccessType.Public));
}
[Fact]
public void Keywords_ExplicitInterfaceImplementation()
{
var source = @"
namespace @namespace
{
public interface @interface<T>
{
int @return { get; set; }
}
public class @class : @interface<@class>
{
int @interface<@class>.@return { get; set; }
}
}
";
var assembly = GetAssembly(source);
var value = CreateDkmClrValue(assembly.GetType("namespace.class").Instantiate());
var root = FormatResult("instance", value);
Verify(GetChildren(root),
EvalResult("@namespace.@interface<@namespace.@class>.@return", "0", "int", "((@namespace.@interface<@namespace.@class>)instance).@return"));
}
[Fact]
public void MangledNames_CastRequired()
{
var il = @"
.class public auto ansi beforefieldinit '<>Mangled' extends [mscorlib]System.Object
{
.field public int32 x
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
.class public auto ansi beforefieldinit 'NotMangled' extends '<>Mangled'
{
.field public int32 x
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
ldarg.0
call instance void '<>Mangled'::.ctor()
ret
}
}
";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var assembly = ReflectionUtilities.Load(assemblyBytes);
var value = CreateDkmClrValue(assembly.GetType("NotMangled").Instantiate());
var root = FormatResult("o", value);
Verify(GetChildren(root),
EvalResult("x (<>Mangled)", "0", "int", null),
EvalResult("x", "0", "int", "o.x"));
}
[Fact]
public void MangledNames_StaticMembers()
{
var il = @"
.class public auto ansi beforefieldinit '<>Mangled' extends [mscorlib]System.Object
{
.field public static int32 x
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
.class public auto ansi beforefieldinit 'NotMangled' extends '<>Mangled'
{
.field public static int32 y
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
ldarg.0
call instance void '<>Mangled'::.ctor()
ret
}
}
";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var assembly = ReflectionUtilities.Load(assemblyBytes);
var baseValue = CreateDkmClrValue(assembly.GetType("<>Mangled").Instantiate());
var root = FormatResult("o", baseValue);
var children = GetChildren(root);
Verify(children,
EvalResult("Static members", null, "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
Verify(GetChildren(children.Single()),
EvalResult("x", "0", "int", null));
var derivedValue = CreateDkmClrValue(assembly.GetType("NotMangled").Instantiate());
root = FormatResult("o", derivedValue);
children = GetChildren(root);
Verify(children,
EvalResult("Static members", null, "", "NotMangled", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
Verify(GetChildren(children.Single()),
EvalResult("x", "0", "int", null, DkmEvaluationResultFlags.None, DkmEvaluationResultCategory.Data, DkmEvaluationResultAccessType.Public),
EvalResult("y", "0", "int", "NotMangled.y", DkmEvaluationResultFlags.None, DkmEvaluationResultCategory.Data, DkmEvaluationResultAccessType.Public));
}
[Fact]
public void MangledNames_ExplicitInterfaceImplementation()
{
var il = @"
.class interface public abstract auto ansi 'abstract.I<>Mangled'
{
.method public hidebysig newslot specialname abstract virtual
instance int32 get_P() cil managed
{
}
.property instance int32 P()
{
.get instance int32 'abstract.I<>Mangled'::get_P()
}
} // end of class 'abstract.I<>Mangled'
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
implements 'abstract.I<>Mangled'
{
.method private hidebysig newslot specialname virtual final
instance int32 'abstract.I<>Mangled.get_P'() cil managed
{
.override 'abstract.I<>Mangled'::get_P
ldc.i4.1
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance int32 'abstract.I<>Mangled.P'()
{
.get instance int32 C::'abstract.I<>Mangled.get_P'()
}
.property instance int32 P()
{
.get instance int32 C::'abstract.I<>Mangled.get_P'()
}
} // end of class C
";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var assembly = ReflectionUtilities.Load(assemblyBytes);
var value = CreateDkmClrValue(assembly.GetType("C").Instantiate());
var root = FormatResult("instance", value);
Verify(GetChildren(root),
EvalResult("P", "1", "int", "instance.P", DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Property, DkmEvaluationResultAccessType.Private),
EvalResult("abstract.I<>Mangled.P", "1", "int", null, DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Property, DkmEvaluationResultAccessType.Private));
}
[Fact]
public void MangledNames_ArrayElement()
{
var il = @"
.class public auto ansi beforefieldinit '<>Mangled'
extends [mscorlib]System.Object
{
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
.class public auto ansi beforefieldinit NotMangled
extends [mscorlib]System.Object
{
.field public class [mscorlib]System.Collections.Generic.IEnumerable`1<class '<>Mangled'> 'array'
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
ldc.i4.1
newarr '<>Mangled'
stfld class [mscorlib]System.Collections.Generic.IEnumerable`1<class '<>Mangled'> NotMangled::'array'
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var assembly = ReflectionUtilities.Load(assemblyBytes);
var value = CreateDkmClrValue(assembly.GetType("NotMangled").Instantiate());
var root = FormatResult("o", value);
var children = GetChildren(root);
Verify(children,
EvalResult("array", "{<>Mangled[1]}", "System.Collections.Generic.IEnumerable<<>Mangled> {<>Mangled[]}", "o.array", DkmEvaluationResultFlags.Expandable));
Verify(GetChildren(children.Single()),
EvalResult("[0]", "null", "<>Mangled", null));
}
[Fact]
public void MangledNames_Namespace()
{
var il = @"
.class public auto ansi beforefieldinit '<>Mangled.C' extends [mscorlib]System.Object
{
.field public static int32 x
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var assembly = ReflectionUtilities.Load(assemblyBytes);
var baseValue = CreateDkmClrValue(assembly.GetType("<>Mangled.C").Instantiate());
var root = FormatResult("o", baseValue);
var children = GetChildren(root);
Verify(children,
EvalResult("Static members", null, "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
Verify(GetChildren(children.Single()),
EvalResult("x", "0", "int", null));
}
[Fact]
public void MangledNames_PointerDereference()
{
var il = @"
.class public auto ansi beforefieldinit '<>Mangled'
extends [mscorlib]System.Object
{
.field private static int32* p
.method assembly hidebysig specialname rtspecialname
instance void .ctor(int64 arg) cil managed
{
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0008: ldarg.1
IL_0009: conv.u
IL_000a: stsfld int32* '<>Mangled'::p
IL_0010: ret
}
} // end of class '<>Mangled'
";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var assembly = ReflectionUtilities.Load(assemblyBytes);
unsafe
{
int i = 4;
long p = (long)&i;
var type = assembly.GetType("<>Mangled");
var rootExpr = "m";
var value = CreateDkmClrValue(type.Instantiate(p));
var evalResult = FormatResult(rootExpr, value);
Verify(evalResult,
EvalResult(rootExpr, "{<>Mangled}", "<>Mangled", rootExpr, DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("Static members", null, "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
children = GetChildren(children.Single());
Verify(children,
EvalResult("p", PointerToString(new IntPtr(p)), "int*", null, DkmEvaluationResultFlags.Expandable));
children = GetChildren(children.Single());
Verify(children,
EvalResult("*p", "4", "int", null));
}
}
[Fact]
public void MangledNames_DebuggerTypeProxy()
{
var il = @"
.class public auto ansi beforefieldinit Type
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Diagnostics.DebuggerTypeProxyAttribute::.ctor(class [mscorlib]System.Type)
= {type('<>Mangled')}
.field public bool x
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
ldc.i4.0
stfld bool Type::x
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
} // end of method Type::.ctor
} // end of class Type
.class public auto ansi beforefieldinit '<>Mangled'
extends [mscorlib]System.Object
{
.field public bool y
.method public hidebysig specialname rtspecialname
instance void .ctor(class Type s) cil managed
{
ldarg.0
ldc.i4.1
stfld bool '<>Mangled'::y
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
} // end of method '<>Mangled'::.ctor
} // end of class '<>Mangled'
";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var assembly = ReflectionUtilities.Load(assemblyBytes);
var value = CreateDkmClrValue(assembly.GetType("Type").Instantiate());
var root = FormatResult("o", value);
var children = GetChildren(root);
Verify(children,
EvalResult("y", "true", "bool", null, DkmEvaluationResultFlags.Boolean | DkmEvaluationResultFlags.BooleanTrue),
EvalResult("Raw View", null, "", "o, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
var grandChildren = GetChildren(children.Last());
Verify(grandChildren,
EvalResult("x", "false", "bool", "o.x", DkmEvaluationResultFlags.Boolean));
}
[Fact]
public void GenericTypeWithoutBacktick()
{
var il = @"
.class public auto ansi beforefieldinit C<T> extends [mscorlib]System.Object
{
.field public static int32 'x'
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var assembly = ReflectionUtilities.Load(assemblyBytes);
var value = CreateDkmClrValue(assembly.GetType("C").MakeGenericType(typeof(int)).Instantiate());
var root = FormatResult("o", value);
var children = GetChildren(root);
Verify(children,
EvalResult("Static members", null, "", "C<int>", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
Verify(GetChildren(children.Single()),
EvalResult("x", "0", "int", "C<int>.x"));
}
[Fact]
public void BackTick_NonGenericType()
{
var il = @"
.class public auto ansi beforefieldinit 'C`1' extends [mscorlib]System.Object
{
.field public static int32 'x'
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var assembly = ReflectionUtilities.Load(assemblyBytes);
var value = CreateDkmClrValue(assembly.GetType("C`1").Instantiate());
var root = FormatResult("o", value);
var children = GetChildren(root);
Verify(children,
EvalResult("Static members", null, "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
Verify(GetChildren(children.Single()),
EvalResult("x", "0", "int", null));
}
[Fact]
public void BackTick_GenericType()
{
var il = @"
.class public auto ansi beforefieldinit 'C`1'<T> extends [mscorlib]System.Object
{
.field public static int32 'x'
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var assembly = ReflectionUtilities.Load(assemblyBytes);
var value = CreateDkmClrValue(assembly.GetType("C`1").MakeGenericType(typeof(int)).Instantiate());
var root = FormatResult("o", value);
var children = GetChildren(root);
Verify(children,
EvalResult("Static members", null, "", "C<int>", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
Verify(GetChildren(children.Single()),
EvalResult("x", "0", "int", "C<int>.x"));
}
[Fact]
public void BackTick_Member()
{
// IL doesn't support using generic methods as property accessors so
// there's no way to test a "legitimate" backtick in a member name.
var il = @"
.class public auto ansi beforefieldinit C extends [mscorlib]System.Object
{
.field public static int32 'x`1'
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var assembly = ReflectionUtilities.Load(assemblyBytes);
var value = CreateDkmClrValue(assembly.GetType("C").Instantiate());
var root = FormatResult("o", value);
var children = GetChildren(root);
Verify(children,
EvalResult("Static members", null, "", "C", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
Verify(GetChildren(children.Single()),
EvalResult("x`1", "0", "int", fullName: null));
}
[Fact]
public void BackTick_FirstCharacter()
{
var il = @"
.class public auto ansi beforefieldinit '`1'<T> extends [mscorlib]System.Object
{
.field public static int32 'x'
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var assembly = ReflectionUtilities.Load(assemblyBytes);
var value = CreateDkmClrValue(assembly.GetType("`1").MakeGenericType(typeof(int)).Instantiate());
var root = FormatResult("o", value);
var children = GetChildren(root);
Verify(children,
EvalResult("Static members", null, "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
Verify(GetChildren(children.Single()),
EvalResult("x", "0", "int", fullName: null));
}
}
}
| 35.526128 | 183 | 0.611607 | [
"Apache-2.0"
] | AArnott/roslyn | src/ExpressionEvaluator/CSharp/Test/ResultProvider/FullNameTests.cs | 29,913 | C# |
using System;
namespace Battle.Actor
{
public class Animator : IComponent
{
public Animator()
{
}
public void Start()
{
throw new NotImplementedException();
}
public void Update()
{
throw new NotImplementedException();
}
}
}
| 14.125 | 48 | 0.492625 | [
"Apache-2.0"
] | mumuyu66/ml-angents-workspace | my_ml_angents/Assets/Scripts/LittleBattle/Module/Battle/Actor/Components/Animator.cs | 341 | C# |
using Orchard.ContentManagement.Handlers;
using Orchard.ContentManagement;
using Orchard.CRM.Dashboard.Models;
namespace Orchard.CRM.Dashboard.Handlers
{
public class SidebarHandler : ContentHandler
{
public SidebarHandler(IContentManager contentManager)
{
OnPublished<CoverWidgetPart>((context, part) =>
{
if (part.TargetContentItemId != default(int)) {
return;
}
if (string.IsNullOrEmpty(part.ContentType))
{
part.TargetContentItemId = default(int);
return;
}
if (part.TargetContentItemId == default(int))
{
var contentItem = contentManager.Create(part.ContentType, VersionOptions.Draft);
part.TargetContentItemId = contentItem.Id;
contentManager.Publish(contentItem);
}
});
}
}
} | 30.515152 | 100 | 0.540218 | [
"MIT"
] | AccentureRapid/OrchardCollaboration | src/Orchard.Web/Modules/Orchard.CRM.Dashboard/Handlers/SidebarHandler.cs | 1,009 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.