content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
namespace Dragon.Samples.WepApi.DomainModels
{
/// <summary>
/// MyTestResponse数据实体
/// </summary>
public class MyTestResponse
{
/// <summary>
/// Id主键
/// </summary>
public int Id { get; set; }
/// <summary>
/// 名称
/// </summary>
public string NameTest { get; set; }
/// <summary>
/// 我的地址
/// </summary>
public string MyAddress { get; set; }
}
}
| 19.583333 | 45 | 0.465957 | [
"MIT"
] | T-Manson/Dragon | Samples/Dragon.Samples.WepApi/DomainModels/MyTestResponse.cs | 494 | C# |
using System;
namespace StoryTeller.UserInterface.Eventing
{
public class FilteredListener<T> : IListener<T>
{
private readonly Action<T> _action;
private readonly Func<T, bool> _filter;
public FilteredListener(Func<T, bool> filter, Action<T> action)
{
_filter = filter;
_action = action;
}
#region IListener<T> Members
public void Handle(T message)
{
if (_filter(message)) _action(message);
}
#endregion
}
} | 22.6 | 72 | 0.552212 | [
"Apache-2.0"
] | DarthFubuMVC/storyteller | src/StoryTeller.UserInterface/Eventing/FilteredListener.cs | 565 | C# |
// ==========================================================================
// Notifo.io
// ==========================================================================
// Copyright (c) Sebastian Stehle
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using MongoDB.Driver;
namespace Notifo.Infrastructure.MongoDb
{
public class MongoDbStore<T> : MongoDbRepository<T> where T : MongoDbEntity
{
public MongoDbStore(IMongoDatabase database)
: base(database)
{
}
protected async Task<T?> GetDocumentAsync(string id,
CancellationToken ct)
{
Guard.NotNullOrEmpty(id, nameof(id));
var existing =
await Collection.Find(x => x.DocId == id)
.FirstOrDefaultAsync(ct);
return existing;
}
protected async Task UpsertDocumentAsync(string id, T value, string? oldEtag,
CancellationToken ct)
{
Guard.NotNullOrEmpty(id, nameof(id));
Guard.NotNull(value, nameof(value));
try
{
if (!string.IsNullOrWhiteSpace(oldEtag))
{
await Collection.ReplaceOneAsync(x => x.DocId == id && x.Etag == oldEtag, value, UpsertReplace, ct);
}
else
{
await Collection.ReplaceOneAsync(x => x.DocId == id, value, UpsertReplace, ct);
}
}
catch (MongoWriteException ex)
{
if (ex.WriteError.Category == ServerErrorCategory.DuplicateKey)
{
if (oldEtag != null)
{
var existingVersion =
await Collection.Find(x => x.DocId == id).Only(x => x.DocId, x => x.Etag)
.FirstOrDefaultAsync(ct);
if (existingVersion != null)
{
throw new InconsistentStateException(existingVersion["e"].AsString, oldEtag, ex);
}
}
throw new UniqueConstraintException();
}
else
{
throw;
}
}
}
public Task DeleteAsync(string id,
CancellationToken ct)
{
Guard.NotNullOrEmpty(id, nameof(id));
return Collection.DeleteOneAsync(x => x.DocId == id, ct);
}
}
}
| 32.243902 | 120 | 0.431921 | [
"MIT"
] | golfstrom/notifo | backend/src/Notifo.Infrastructure/MongoDb/MongoDbStore.cs | 2,646 | C# |
/* Copyright (c) 2010 Robert Adams
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of the copyright holder may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
namespace LookingGlass.Renderer.OGL {
public interface IViewOGL {
}
}
| 53.466667 | 88 | 0.758728 | [
"BSD-3-Clause"
] | Misterblue/LookingGlass-Viewer | src/LookingGlass.Renderer.OGL/IViewOGL.cs | 1,606 | C# |
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using SharpDX.DXGI;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// Describes how data will be displayed to the screen.
/// </summary>
/// <msdn-id>bb173075</msdn-id>
/// <unmanaged>DXGI_SWAP_CHAIN_DESC</unmanaged>
/// <unmanaged-short>DXGI_SWAP_CHAIN_DESC</unmanaged-short>
public class PresentationParameters
{
#region Fields
/// <summary>
/// A <strong><see cref="SharpDX.DXGI.Format" /></strong> structure describing the display format.
/// </summary>
/// <msdn-id>bb173075</msdn-id>
/// <unmanaged>DXGI_MODE_DESC BufferDesc</unmanaged>
/// <unmanaged-short>DXGI_MODE_DESC BufferDesc</unmanaged-short>
public PixelFormat BackBufferFormat;
/// <summary>
/// A value that describes the resolution height.
/// </summary>
/// <msdn-id>bb173075</msdn-id>
/// <unmanaged>DXGI_MODE_DESC BufferDesc</unmanaged>
/// <unmanaged-short>DXGI_MODE_DESC BufferDesc</unmanaged-short>
public int BackBufferHeight;
/// <summary>
/// A value that describes the resolution width.
/// </summary>
/// <msdn-id>bb173075</msdn-id>
/// <unmanaged>DXGI_MODE_DESC BufferDesc</unmanaged>
/// <unmanaged-short>DXGI_MODE_DESC BufferDesc</unmanaged-short>
public int BackBufferWidth;
/// <summary>
/// Gets or sets the depth stencil format
/// </summary>
public DepthFormat DepthStencilFormat;
/// <summary>
/// A Window object. See remarks.
/// </summary>
/// <remarks>
/// A window object is platform dependent:
/// <ul>
/// <li>On Windows Desktop: This could a low level window/control handle (IntPtr), or directly a Winform Control object.</li>
/// <li>On Windows Metro: This could be SwapChainBackgroundPanel object.</li>
/// </ul>
/// </remarks>
public object DeviceWindowHandle;
/// <summary>
/// A member of the <see cref="SharpDX.DXGI.SwapChainFlags" />
/// enumerated type that describes options for swap-chain behavior.
/// </summary>
/// <msdn-id>bb173075</msdn-id>
/// <unmanaged>DXGI_SWAP_CHAIN_FLAG Flags</unmanaged>
/// <unmanaged-short>DXGI_SWAP_CHAIN_FLAG Flags</unmanaged-short>
public SwapChainFlags Flags;
/// <summary>
/// Gets or sets a value indicating whether the application is in full screen mode.
/// </summary>
public bool IsFullScreen;
/// <summary>
/// Gets or sets a value indicating the number of sample locations during multisampling.
/// </summary>
public MSAALevel MultiSampleCount;
/// <summary>
/// Gets or sets the maximum rate at which the swap chain's back buffers can be presented to the front buffer.
/// </summary>
public PresentInterval PresentationInterval;
/// <summary>
/// A <see cref="SharpDX.DXGI.Rational" /> structure describing the refresh rate in hertz
/// </summary>
/// <msdn-id>bb173064</msdn-id>
/// <unmanaged>DXGI_RATIONAL RefreshRate</unmanaged>
/// <unmanaged-short>DXGI_RATIONAL RefreshRate</unmanaged-short>
public Rational RefreshRate;
/// <summary>
/// <p>A member of the DXGI_USAGE enumerated type that describes the surface usage and CPU access options for the back buffer. The back buffer can be used for shader input or render-target output.</p>
/// </summary>
/// <msdn-id>bb173075</msdn-id>
/// <unmanaged>DXGI_USAGE_ENUM BufferUsage</unmanaged>
/// <unmanaged-short>DXGI_USAGE_ENUM BufferUsage</unmanaged-short>
public Usage RenderTargetUsage;
/// <summary>
/// The output (monitor) index to use when switching to fullscreen mode. Doesn't have any effect when windowed mode is used.
/// </summary>
public int PreferredFullScreenOutputIndex;
#endregion
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="PresentationParameters" /> class with default values.
/// </summary>
public PresentationParameters()
{
BackBufferWidth = 800;
BackBufferHeight = 480;
BackBufferFormat = PixelFormat.R8G8B8A8.UNorm;
PresentationInterval = PresentInterval.Immediate;
DepthStencilFormat = DepthFormat.Depth24Stencil8;
MultiSampleCount = MSAALevel.None;
IsFullScreen = false;
RefreshRate = new Rational(60, 1); // by default
RenderTargetUsage = Usage.BackBuffer | Usage.RenderTargetOutput;
Flags = SwapChainFlags.AllowModeSwitch;
}
/// <summary>
/// Initializes a new instance of the <see cref="PresentationParameters" /> class with <see cref="PixelFormat.R8G8B8A8.UNorm"/>.
/// </summary>
/// <param name="backBufferWidth">Width of the back buffer.</param>
/// <param name="backBufferHeight">Height of the back buffer.</param>
/// <param name="deviceWindowHandle">The device window handle.</param>
public PresentationParameters(int backBufferWidth, int backBufferHeight, object deviceWindowHandle)
: this(backBufferWidth, backBufferHeight, deviceWindowHandle, PixelFormat.R8G8B8A8.UNorm)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="PresentationParameters" /> class.
/// </summary>
/// <param name="backBufferWidth">Width of the back buffer.</param>
/// <param name="backBufferHeight">Height of the back buffer.</param>
/// <param name="deviceWindowHandle">The device window handle.</param>
/// <param name="backBufferFormat">The back buffer format.</param>
public PresentationParameters(int backBufferWidth, int backBufferHeight, object deviceWindowHandle, PixelFormat backBufferFormat)
: this()
{
BackBufferWidth = backBufferWidth;
BackBufferHeight = backBufferHeight;
DeviceWindowHandle = deviceWindowHandle;
BackBufferFormat = backBufferFormat;
}
#endregion
#region Methods
public PresentationParameters Clone()
{
return (PresentationParameters)MemberwiseClone();
}
#endregion
}
} | 42.716667 | 211 | 0.642346 | [
"MIT"
] | shoelzer/SharpDX | Source/Toolkit/SharpDX.Toolkit.Graphics/PresentationParameters.cs | 7,691 | C# |
using System;
namespace RangeSafety
{
internal static class Utils
{
//keeps angles in the range 0 to 360
internal static double ClampDegrees360(double angle)
{
angle = angle % 360.0;
if (angle < 0) return angle + 360.0;
else return angle;
}
//keeps angles in the range -180 to 180
internal static double ClampDegrees180(double angle)
{
angle = ClampDegrees360(angle);
if (angle > 180) angle -= 360;
return angle;
}
internal static double DegreeToRadian(double angle)
{
return Math.PI * angle / 180.0;
}
internal static double RadianToDegree(double angle)
{
return angle * (180.0 / Math.PI);
}
}
}
| 24.176471 | 60 | 0.536496 | [
"MIT"
] | dgeastman/RangeSafety | Source/Utils.cs | 824 | C# |
namespace SimulOP
{
public interface IFluidoOPI
{
IMaterialFluidoOPI Material { get; }
}
}
| 14 | 44 | 0.625 | [
"MIT"
] | rafaelterras/SimulOp | SimulOP/SimulOP/Interfaces/IFluidoOPI.cs | 114 | C# |
namespace IdentityUtils.Demos.Api.Models
{
public class LoginModel
{
public string Username { get; set; }
public string Password { get; set; }
}
} | 21.875 | 44 | 0.622857 | [
"MIT"
] | intellegens-hr/utils-identity | dotnetcore/IdentityUtils.Demos.Api/Models/LoginModel.cs | 177 | 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 opsworks-2013-02-18.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.OpsWorks.Model
{
/// <summary>
/// Container for the parameters to the DescribeInstances operation.
/// Requests a description of a set of instances.
///
/// <note>
/// <para>
/// This call accepts only one resource-identifying parameter.
/// </para>
/// </note>
/// <para>
/// <b>Required Permissions</b>: To use this action, an IAM user must have a Show, Deploy,
/// or Manage permissions level for the stack, or an attached policy that explicitly grants
/// permissions. For more information about user permissions, see <a href="https://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html">Managing
/// User Permissions</a>.
/// </para>
/// </summary>
public partial class DescribeInstancesRequest : AmazonOpsWorksRequest
{
private List<string> _instanceIds = new List<string>();
private string _layerId;
private string _stackId;
/// <summary>
/// Gets and sets the property InstanceIds.
/// <para>
/// An array of instance IDs to be described. If you use this parameter, <code>DescribeInstances</code>
/// returns a description of the specified instances. Otherwise, it returns a description
/// of every instance.
/// </para>
/// </summary>
public List<string> InstanceIds
{
get { return this._instanceIds; }
set { this._instanceIds = value; }
}
// Check to see if InstanceIds property is set
internal bool IsSetInstanceIds()
{
return this._instanceIds != null && this._instanceIds.Count > 0;
}
/// <summary>
/// Gets and sets the property LayerId.
/// <para>
/// A layer ID. If you use this parameter, <code>DescribeInstances</code> returns descriptions
/// of the instances associated with the specified layer.
/// </para>
/// </summary>
public string LayerId
{
get { return this._layerId; }
set { this._layerId = value; }
}
// Check to see if LayerId property is set
internal bool IsSetLayerId()
{
return this._layerId != null;
}
/// <summary>
/// Gets and sets the property StackId.
/// <para>
/// A stack ID. If you use this parameter, <code>DescribeInstances</code> returns descriptions
/// of the instances associated with the specified stack.
/// </para>
/// </summary>
public string StackId
{
get { return this._stackId; }
set { this._stackId = value; }
}
// Check to see if StackId property is set
internal bool IsSetStackId()
{
return this._stackId != null;
}
}
} | 34.651786 | 172 | 0.598557 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/OpsWorks/Generated/Model/DescribeInstancesRequest.cs | 3,881 | C# |
// The MIT License (MIT)
//
// Copyright (c) Andrew Armstrong/FacticiusVir 2018
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// This file was automatically generated and should not be edited directly.
namespace SharpVk
{
/// <summary>
/// Bitmask specifying which aspects of an image are included in a view.
/// </summary>
[System.Flags]
public enum ImageAspectFlags
{
/// <summary>
///
/// </summary>
None = 0,
/// <summary>
///
/// </summary>
Color = 1 << 0,
/// <summary>
///
/// </summary>
Depth = 1 << 1,
/// <summary>
///
/// </summary>
Stencil = 1 << 2,
/// <summary>
///
/// </summary>
Metadata = 1 << 3,
/// <summary>
///
/// </summary>
MemoryPlane0 = 1 << 7,
/// <summary>
///
/// </summary>
MemoryPlane1 = 1 << 8,
/// <summary>
///
/// </summary>
MemoryPlane2 = 1 << 9,
/// <summary>
///
/// </summary>
MemoryPlane3 = 1 << 10,
}
}
| 28.911392 | 81 | 0.563923 | [
"MIT"
] | sebastianulm/SharpVk | src/SharpVk/ImageAspectFlags.gen.cs | 2,284 | C# |
namespace BMSF.WPF.Utilities.Converters
{
using System;
using System.Globalization;
using System.Windows.Data;
public class IsZeroOrNullConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return true;
if (value is decimal)
return (decimal) value == 0.00m;
if (value is int)
return (int) value == 0.00m;
if (value is long)
return (long) value == 0.00m;
if (value is short)
return (short) value == 0.00m;
if (value is string)
return (string) value == "";
throw new NotSupportedException();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
} | 31.806452 | 103 | 0.549696 | [
"MIT"
] | nickguletskii/BMSF | BMSF.WPF.Utilities/Converters/IsZeroOrNullConverter.cs | 988 | C# |
namespace Raiding
{
public class Druid : BaseHero
{
private const int BASE_POWER = 80;
public Druid(string name) : base(name, BASE_POWER)
{
}
public override string CastAbility()
{
return $"{nameof(Druid)} - {this.Name} healed for {this.Power}";
}
}
}
| 19.333333 | 76 | 0.517241 | [
"MIT"
] | dinikolaeva/OOP-CSharp | OOP-CSharp/08.Polymorphism-Exe/03.Raiding/Druid.cs | 350 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using HangfireSample.Business.Models;
using HangfireSample.Business.Services.Interfaces;
using Microsoft.AspNetCore.Mvc;
namespace HangfireSample.Api.Controllers
{
[Route("api/comments")]
public class CommentController : Controller
{
private readonly ICommentService _commentService;
public CommentController(ICommentService commentService) => _commentService = commentService;
/// <summary>
/// Get all comments
/// GET api/comments
/// </summary>
/// <returns></returns>
[HttpGet]
public async Task<ActionResult<IEnumerable<Comment>>> Get()
{
return Ok(await _commentService.GetAllComments());
}
/// <summary>
/// Get a comment by Id
///
/// GET api/comments/5
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet("{id}")]
public async Task<ActionResult<Comment>> Get(int id)
{
return Ok(await _commentService.GetCommentById(id));
}
}
} | 28.725 | 101 | 0.607485 | [
"MIT"
] | XeNz/HangfireSample | HangfireSample/Api/Controllers/CommentController.cs | 1,151 | C# |
using IdentityServer4.Admin.Domain.Core.Commands;
using System;
using System.Collections.Generic;
using System.Text;
namespace IdentityServer4.Admin.Domain.Commands.Client.Secret
{
public abstract class ClientSecretCommand : Command
{
public int Id { get; protected set; }
public string ClientId { get; protected set; }
public string Description { get; protected set; }
public string Value { get; protected set; }
public DateTime? Expiration { get; protected set; }
public int HashType { get; protected set; } = 0;
public string Type { get; protected set; }
}
}
| 33.263158 | 61 | 0.683544 | [
"MIT"
] | dotnetcore-group/IdentityServer4.Admin | src/IdentityServer4.Admin.Domain/Commands/Client/Secret/ClientSecretCommand.cs | 634 | C# |
using System;
namespace SharpCifs.Smb
{
// Token: 0x020000A2 RID: 162
internal class SmbComTreeDisconnect : ServerMessageBlock
{
// Token: 0x060004B5 RID: 1205 RVA: 0x00016F7D File Offset: 0x0001517D
public SmbComTreeDisconnect()
{
this.Command = 113;
}
// Token: 0x060004B6 RID: 1206 RVA: 0x00016F90 File Offset: 0x00015190
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
// Token: 0x060004B7 RID: 1207 RVA: 0x00016FA4 File Offset: 0x000151A4
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
// Token: 0x060004B8 RID: 1208 RVA: 0x00016FB8 File Offset: 0x000151B8
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
// Token: 0x060004B9 RID: 1209 RVA: 0x00016FCC File Offset: 0x000151CC
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
// Token: 0x060004BA RID: 1210 RVA: 0x00016FE0 File Offset: 0x000151E0
public override string ToString()
{
return "SmbComTreeDisconnect[" + base.ToString() + "]";
}
}
}
| 26.4 | 85 | 0.693603 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 0x727/metasploit-framework | external/source/Scanner/smb/SharpCifs.shack2.SmbClient/Smb/SmbComTreeDisconnect.cs | 1,190 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.239
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
//
// This code was auto-generated by Microsoft.Silverlight.Phone.ServiceReference, version 3.7.0.0
//
namespace WCEmergency.Bing.Geocode {
using System.Runtime.Serialization;
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="RequestBase", Namespace="http://dev.virtualearth.net/webservices/v1/common")]
[System.Runtime.Serialization.KnownTypeAttribute(typeof(WCEmergency.Bing.Geocode.ReverseGeocodeRequest))]
[System.Runtime.Serialization.KnownTypeAttribute(typeof(WCEmergency.Bing.Geocode.GeocodeRequest))]
public partial class RequestBase : object, System.ComponentModel.INotifyPropertyChanged {
private Microsoft.Phone.Controls.Maps.Credentials CredentialsField;
private string CultureField;
private WCEmergency.Bing.Geocode.ExecutionOptions ExecutionOptionsField;
private WCEmergency.Bing.Geocode.UserProfile UserProfileField;
[System.Runtime.Serialization.DataMemberAttribute()]
public Microsoft.Phone.Controls.Maps.Credentials Credentials {
get {
return this.CredentialsField;
}
set {
if ((object.ReferenceEquals(this.CredentialsField, value) != true)) {
this.CredentialsField = value;
this.RaisePropertyChanged("Credentials");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string Culture {
get {
return this.CultureField;
}
set {
if ((object.ReferenceEquals(this.CultureField, value) != true)) {
this.CultureField = value;
this.RaisePropertyChanged("Culture");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public WCEmergency.Bing.Geocode.ExecutionOptions ExecutionOptions {
get {
return this.ExecutionOptionsField;
}
set {
if ((object.ReferenceEquals(this.ExecutionOptionsField, value) != true)) {
this.ExecutionOptionsField = value;
this.RaisePropertyChanged("ExecutionOptions");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public WCEmergency.Bing.Geocode.UserProfile UserProfile {
get {
return this.UserProfileField;
}
set {
if ((object.ReferenceEquals(this.UserProfileField, value) != true)) {
this.UserProfileField = value;
this.RaisePropertyChanged("UserProfile");
}
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="ExecutionOptions", Namespace="http://dev.virtualearth.net/webservices/v1/common")]
public partial class ExecutionOptions : object, System.ComponentModel.INotifyPropertyChanged {
private bool SuppressFaultsField;
[System.Runtime.Serialization.DataMemberAttribute()]
public bool SuppressFaults {
get {
return this.SuppressFaultsField;
}
set {
if ((this.SuppressFaultsField.Equals(value) != true)) {
this.SuppressFaultsField = value;
this.RaisePropertyChanged("SuppressFaults");
}
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="UserProfile", Namespace="http://dev.virtualearth.net/webservices/v1/common")]
[System.Runtime.Serialization.KnownTypeAttribute(typeof(Microsoft.Phone.Controls.Maps.Platform.Rectangle))]
[System.Runtime.Serialization.KnownTypeAttribute(typeof(WCEmergency.Bing.Geocode.Circle))]
[System.Runtime.Serialization.KnownTypeAttribute(typeof(WCEmergency.Bing.Geocode.Polygon))]
public partial class UserProfile : object, System.ComponentModel.INotifyPropertyChanged {
private WCEmergency.Bing.Geocode.Heading CurrentHeadingField;
private WCEmergency.Bing.Geocode.UserLocation CurrentLocationField;
private WCEmergency.Bing.Geocode.DeviceType DeviceTypeField;
private WCEmergency.Bing.Geocode.DistanceUnit DistanceUnitField;
private string IPAddressField;
private Microsoft.Phone.Controls.Maps.Platform.ShapeBase MapViewField;
private WCEmergency.Bing.Geocode.SizeOfint ScreenSizeField;
[System.Runtime.Serialization.DataMemberAttribute()]
public WCEmergency.Bing.Geocode.Heading CurrentHeading {
get {
return this.CurrentHeadingField;
}
set {
if ((object.ReferenceEquals(this.CurrentHeadingField, value) != true)) {
this.CurrentHeadingField = value;
this.RaisePropertyChanged("CurrentHeading");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public WCEmergency.Bing.Geocode.UserLocation CurrentLocation {
get {
return this.CurrentLocationField;
}
set {
if ((object.ReferenceEquals(this.CurrentLocationField, value) != true)) {
this.CurrentLocationField = value;
this.RaisePropertyChanged("CurrentLocation");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public WCEmergency.Bing.Geocode.DeviceType DeviceType {
get {
return this.DeviceTypeField;
}
set {
if ((this.DeviceTypeField.Equals(value) != true)) {
this.DeviceTypeField = value;
this.RaisePropertyChanged("DeviceType");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public WCEmergency.Bing.Geocode.DistanceUnit DistanceUnit {
get {
return this.DistanceUnitField;
}
set {
if ((this.DistanceUnitField.Equals(value) != true)) {
this.DistanceUnitField = value;
this.RaisePropertyChanged("DistanceUnit");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string IPAddress {
get {
return this.IPAddressField;
}
set {
if ((object.ReferenceEquals(this.IPAddressField, value) != true)) {
this.IPAddressField = value;
this.RaisePropertyChanged("IPAddress");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public Microsoft.Phone.Controls.Maps.Platform.ShapeBase MapView {
get {
return this.MapViewField;
}
set {
if ((object.ReferenceEquals(this.MapViewField, value) != true)) {
this.MapViewField = value;
this.RaisePropertyChanged("MapView");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public WCEmergency.Bing.Geocode.SizeOfint ScreenSize {
get {
return this.ScreenSizeField;
}
set {
if ((object.ReferenceEquals(this.ScreenSizeField, value) != true)) {
this.ScreenSizeField = value;
this.RaisePropertyChanged("ScreenSize");
}
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="ReverseGeocodeRequest", Namespace="http://dev.virtualearth.net/webservices/v1/geocode")]
[System.Runtime.Serialization.KnownTypeAttribute(typeof(WCEmergency.Bing.Geocode.GeocodeLocation))]
[System.Runtime.Serialization.KnownTypeAttribute(typeof(WCEmergency.Bing.Geocode.UserLocation))]
public partial class ReverseGeocodeRequest : WCEmergency.Bing.Geocode.RequestBase {
private Microsoft.Phone.Controls.Maps.Platform.Location LocationField;
[System.Runtime.Serialization.DataMemberAttribute()]
public Microsoft.Phone.Controls.Maps.Platform.Location Location {
get {
return this.LocationField;
}
set {
if ((object.ReferenceEquals(this.LocationField, value) != true)) {
this.LocationField = value;
this.RaisePropertyChanged("Location");
}
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="GeocodeRequest", Namespace="http://dev.virtualearth.net/webservices/v1/geocode")]
public partial class GeocodeRequest : WCEmergency.Bing.Geocode.RequestBase {
private WCEmergency.Bing.Geocode.Address AddressField;
private WCEmergency.Bing.Geocode.GeocodeOptions OptionsField;
private string QueryField;
[System.Runtime.Serialization.DataMemberAttribute()]
public WCEmergency.Bing.Geocode.Address Address {
get {
return this.AddressField;
}
set {
if ((object.ReferenceEquals(this.AddressField, value) != true)) {
this.AddressField = value;
this.RaisePropertyChanged("Address");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public WCEmergency.Bing.Geocode.GeocodeOptions Options {
get {
return this.OptionsField;
}
set {
if ((object.ReferenceEquals(this.OptionsField, value) != true)) {
this.OptionsField = value;
this.RaisePropertyChanged("Options");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string Query {
get {
return this.QueryField;
}
set {
if ((object.ReferenceEquals(this.QueryField, value) != true)) {
this.QueryField = value;
this.RaisePropertyChanged("Query");
}
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="Address", Namespace="http://dev.virtualearth.net/webservices/v1/common")]
public partial class Address : object, System.ComponentModel.INotifyPropertyChanged {
private string AddressLineField;
private string AdminDistrictField;
private string CountryRegionField;
private string DistrictField;
private string FormattedAddressField;
private string LocalityField;
private string PostalCodeField;
private string PostalTownField;
[System.Runtime.Serialization.DataMemberAttribute()]
public string AddressLine {
get {
return this.AddressLineField;
}
set {
if ((object.ReferenceEquals(this.AddressLineField, value) != true)) {
this.AddressLineField = value;
this.RaisePropertyChanged("AddressLine");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string AdminDistrict {
get {
return this.AdminDistrictField;
}
set {
if ((object.ReferenceEquals(this.AdminDistrictField, value) != true)) {
this.AdminDistrictField = value;
this.RaisePropertyChanged("AdminDistrict");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string CountryRegion {
get {
return this.CountryRegionField;
}
set {
if ((object.ReferenceEquals(this.CountryRegionField, value) != true)) {
this.CountryRegionField = value;
this.RaisePropertyChanged("CountryRegion");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string District {
get {
return this.DistrictField;
}
set {
if ((object.ReferenceEquals(this.DistrictField, value) != true)) {
this.DistrictField = value;
this.RaisePropertyChanged("District");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string FormattedAddress {
get {
return this.FormattedAddressField;
}
set {
if ((object.ReferenceEquals(this.FormattedAddressField, value) != true)) {
this.FormattedAddressField = value;
this.RaisePropertyChanged("FormattedAddress");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string Locality {
get {
return this.LocalityField;
}
set {
if ((object.ReferenceEquals(this.LocalityField, value) != true)) {
this.LocalityField = value;
this.RaisePropertyChanged("Locality");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string PostalCode {
get {
return this.PostalCodeField;
}
set {
if ((object.ReferenceEquals(this.PostalCodeField, value) != true)) {
this.PostalCodeField = value;
this.RaisePropertyChanged("PostalCode");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string PostalTown {
get {
return this.PostalTownField;
}
set {
if ((object.ReferenceEquals(this.PostalTownField, value) != true)) {
this.PostalTownField = value;
this.RaisePropertyChanged("PostalTown");
}
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="GeocodeOptions", Namespace="http://dev.virtualearth.net/webservices/v1/geocode")]
public partial class GeocodeOptions : object, System.ComponentModel.INotifyPropertyChanged {
private System.Nullable<int> CountField;
private System.Collections.ObjectModel.ObservableCollection<WCEmergency.Bing.Geocode.FilterBase> FiltersField;
[System.Runtime.Serialization.DataMemberAttribute()]
public System.Nullable<int> Count {
get {
return this.CountField;
}
set {
if ((this.CountField.Equals(value) != true)) {
this.CountField = value;
this.RaisePropertyChanged("Count");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public System.Collections.ObjectModel.ObservableCollection<WCEmergency.Bing.Geocode.FilterBase> Filters {
get {
return this.FiltersField;
}
set {
if ((object.ReferenceEquals(this.FiltersField, value) != true)) {
this.FiltersField = value;
this.RaisePropertyChanged("Filters");
}
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="Heading", Namespace="http://dev.virtualearth.net/webservices/v1/common")]
public partial class Heading : object, System.ComponentModel.INotifyPropertyChanged {
private double OrientationField;
[System.Runtime.Serialization.DataMemberAttribute()]
public double Orientation {
get {
return this.OrientationField;
}
set {
if ((this.OrientationField.Equals(value) != true)) {
this.OrientationField = value;
this.RaisePropertyChanged("Orientation");
}
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="UserLocation", Namespace="http://dev.virtualearth.net/webservices/v1/common")]
public partial class UserLocation : Microsoft.Phone.Controls.Maps.Platform.Location, System.ComponentModel.INotifyPropertyChanged {
private WCEmergency.Bing.Geocode.Confidence ConfidenceField;
[System.Runtime.Serialization.DataMemberAttribute()]
public WCEmergency.Bing.Geocode.Confidence Confidence {
get {
return this.ConfidenceField;
}
set {
if ((this.ConfidenceField.Equals(value) != true)) {
this.ConfidenceField = value;
this.RaisePropertyChanged("Confidence");
}
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="SizeOfint", Namespace="http://dev.virtualearth.net/webservices/v1/common")]
public partial class SizeOfint : object, System.ComponentModel.INotifyPropertyChanged {
private int HeightField;
private int WidthField;
[System.Runtime.Serialization.DataMemberAttribute()]
public int Height {
get {
return this.HeightField;
}
set {
if ((this.HeightField.Equals(value) != true)) {
this.HeightField = value;
this.RaisePropertyChanged("Height");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public int Width {
get {
return this.WidthField;
}
set {
if ((this.WidthField.Equals(value) != true)) {
this.WidthField = value;
this.RaisePropertyChanged("Width");
}
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="Circle", Namespace="http://dev.virtualearth.net/webservices/v1/common")]
[System.Runtime.Serialization.KnownTypeAttribute(typeof(WCEmergency.Bing.Geocode.GeocodeLocation))]
[System.Runtime.Serialization.KnownTypeAttribute(typeof(WCEmergency.Bing.Geocode.UserLocation))]
public partial class Circle : Microsoft.Phone.Controls.Maps.Platform.ShapeBase, System.ComponentModel.INotifyPropertyChanged {
private Microsoft.Phone.Controls.Maps.Platform.Location CenterField;
private WCEmergency.Bing.Geocode.DistanceUnit DistanceUnitField;
private double RadiusField;
[System.Runtime.Serialization.DataMemberAttribute()]
public Microsoft.Phone.Controls.Maps.Platform.Location Center {
get {
return this.CenterField;
}
set {
if ((object.ReferenceEquals(this.CenterField, value) != true)) {
this.CenterField = value;
this.RaisePropertyChanged("Center");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public WCEmergency.Bing.Geocode.DistanceUnit DistanceUnit {
get {
return this.DistanceUnitField;
}
set {
if ((this.DistanceUnitField.Equals(value) != true)) {
this.DistanceUnitField = value;
this.RaisePropertyChanged("DistanceUnit");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public double Radius {
get {
return this.RadiusField;
}
set {
if ((this.RadiusField.Equals(value) != true)) {
this.RadiusField = value;
this.RaisePropertyChanged("Radius");
}
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="Polygon", Namespace="http://dev.virtualearth.net/webservices/v1/common")]
public partial class Polygon : Microsoft.Phone.Controls.Maps.Platform.ShapeBase, System.ComponentModel.INotifyPropertyChanged {
private System.Collections.ObjectModel.ObservableCollection<Microsoft.Phone.Controls.Maps.Platform.Location> VerticesField;
[System.Runtime.Serialization.DataMemberAttribute()]
public System.Collections.ObjectModel.ObservableCollection<Microsoft.Phone.Controls.Maps.Platform.Location> Vertices {
get {
return this.VerticesField;
}
set {
if ((object.ReferenceEquals(this.VerticesField, value) != true)) {
this.VerticesField = value;
this.RaisePropertyChanged("Vertices");
}
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="DeviceType", Namespace="http://dev.virtualearth.net/webservices/v1/common")]
public enum DeviceType : int {
[System.Runtime.Serialization.EnumMemberAttribute()]
Desktop = 0,
[System.Runtime.Serialization.EnumMemberAttribute()]
Mobile = 1,
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="DistanceUnit", Namespace="http://dev.virtualearth.net/webservices/v1/common")]
public enum DistanceUnit : int {
[System.Runtime.Serialization.EnumMemberAttribute()]
Kilometer = 0,
[System.Runtime.Serialization.EnumMemberAttribute()]
Mile = 1,
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="Confidence", Namespace="http://dev.virtualearth.net/webservices/v1/common")]
public enum Confidence : int {
[System.Runtime.Serialization.EnumMemberAttribute()]
High = 0,
[System.Runtime.Serialization.EnumMemberAttribute()]
Medium = 1,
[System.Runtime.Serialization.EnumMemberAttribute()]
Low = 2,
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="GeocodeLocation", Namespace="http://dev.virtualearth.net/webservices/v1/common")]
public partial class GeocodeLocation : Microsoft.Phone.Controls.Maps.Platform.Location, System.ComponentModel.INotifyPropertyChanged {
private string CalculationMethodField;
[System.Runtime.Serialization.DataMemberAttribute()]
public string CalculationMethod {
get {
return this.CalculationMethodField;
}
set {
if ((object.ReferenceEquals(this.CalculationMethodField, value) != true)) {
this.CalculationMethodField = value;
this.RaisePropertyChanged("CalculationMethod");
}
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="FilterBase", Namespace="http://dev.virtualearth.net/webservices/v1/geocode")]
[System.Runtime.Serialization.KnownTypeAttribute(typeof(WCEmergency.Bing.Geocode.ConfidenceFilter))]
public partial class FilterBase : object, System.ComponentModel.INotifyPropertyChanged {
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="ConfidenceFilter", Namespace="http://dev.virtualearth.net/webservices/v1/geocode")]
public partial class ConfidenceFilter : WCEmergency.Bing.Geocode.FilterBase {
private WCEmergency.Bing.Geocode.Confidence MinimumConfidenceField;
[System.Runtime.Serialization.DataMemberAttribute()]
public WCEmergency.Bing.Geocode.Confidence MinimumConfidence {
get {
return this.MinimumConfidenceField;
}
set {
if ((this.MinimumConfidenceField.Equals(value) != true)) {
this.MinimumConfidenceField = value;
this.RaisePropertyChanged("MinimumConfidence");
}
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="ResponseBase", Namespace="http://dev.virtualearth.net/webservices/v1/common")]
[System.Runtime.Serialization.KnownTypeAttribute(typeof(WCEmergency.Bing.Geocode.GeocodeResponse))]
public partial class ResponseBase : object, System.ComponentModel.INotifyPropertyChanged {
private System.Uri BrandLogoUriField;
private WCEmergency.Bing.Geocode.ResponseSummary ResponseSummaryField;
[System.Runtime.Serialization.DataMemberAttribute()]
public System.Uri BrandLogoUri {
get {
return this.BrandLogoUriField;
}
set {
if ((object.ReferenceEquals(this.BrandLogoUriField, value) != true)) {
this.BrandLogoUriField = value;
this.RaisePropertyChanged("BrandLogoUri");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public WCEmergency.Bing.Geocode.ResponseSummary ResponseSummary {
get {
return this.ResponseSummaryField;
}
set {
if ((object.ReferenceEquals(this.ResponseSummaryField, value) != true)) {
this.ResponseSummaryField = value;
this.RaisePropertyChanged("ResponseSummary");
}
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="ResponseSummary", Namespace="http://dev.virtualearth.net/webservices/v1/common")]
public partial class ResponseSummary : object, System.ComponentModel.INotifyPropertyChanged {
private WCEmergency.Bing.Geocode.AuthenticationResultCode AuthenticationResultCodeField;
private string CopyrightField;
private string FaultReasonField;
private WCEmergency.Bing.Geocode.ResponseStatusCode StatusCodeField;
private string TraceIdField;
[System.Runtime.Serialization.DataMemberAttribute()]
public WCEmergency.Bing.Geocode.AuthenticationResultCode AuthenticationResultCode {
get {
return this.AuthenticationResultCodeField;
}
set {
if ((this.AuthenticationResultCodeField.Equals(value) != true)) {
this.AuthenticationResultCodeField = value;
this.RaisePropertyChanged("AuthenticationResultCode");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string Copyright {
get {
return this.CopyrightField;
}
set {
if ((object.ReferenceEquals(this.CopyrightField, value) != true)) {
this.CopyrightField = value;
this.RaisePropertyChanged("Copyright");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string FaultReason {
get {
return this.FaultReasonField;
}
set {
if ((object.ReferenceEquals(this.FaultReasonField, value) != true)) {
this.FaultReasonField = value;
this.RaisePropertyChanged("FaultReason");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public WCEmergency.Bing.Geocode.ResponseStatusCode StatusCode {
get {
return this.StatusCodeField;
}
set {
if ((this.StatusCodeField.Equals(value) != true)) {
this.StatusCodeField = value;
this.RaisePropertyChanged("StatusCode");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string TraceId {
get {
return this.TraceIdField;
}
set {
if ((object.ReferenceEquals(this.TraceIdField, value) != true)) {
this.TraceIdField = value;
this.RaisePropertyChanged("TraceId");
}
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="GeocodeResponse", Namespace="http://dev.virtualearth.net/webservices/v1/geocode")]
public partial class GeocodeResponse : WCEmergency.Bing.Geocode.ResponseBase {
private System.Collections.ObjectModel.ObservableCollection<WCEmergency.Bing.Geocode.GeocodeResult> ResultsField;
[System.Runtime.Serialization.DataMemberAttribute()]
public System.Collections.ObjectModel.ObservableCollection<WCEmergency.Bing.Geocode.GeocodeResult> Results {
get {
return this.ResultsField;
}
set {
if ((object.ReferenceEquals(this.ResultsField, value) != true)) {
this.ResultsField = value;
this.RaisePropertyChanged("Results");
}
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="GeocodeResult", Namespace="http://dev.virtualearth.net/webservices/v1/common")]
[System.Runtime.Serialization.KnownTypeAttribute(typeof(WCEmergency.Bing.Geocode.GeocodeLocation))]
[System.Runtime.Serialization.KnownTypeAttribute(typeof(WCEmergency.Bing.Geocode.UserLocation))]
public partial class GeocodeResult : object, System.ComponentModel.INotifyPropertyChanged {
private WCEmergency.Bing.Geocode.Address AddressField;
private Microsoft.Phone.Controls.Maps.Platform.Rectangle BestViewField;
private WCEmergency.Bing.Geocode.Confidence ConfidenceField;
private string DisplayNameField;
private string EntityTypeField;
private System.Collections.ObjectModel.ObservableCollection<WCEmergency.Bing.Geocode.GeocodeLocation> LocationsField;
private System.Collections.ObjectModel.ObservableCollection<string> MatchCodesField;
[System.Runtime.Serialization.DataMemberAttribute()]
public WCEmergency.Bing.Geocode.Address Address {
get {
return this.AddressField;
}
set {
if ((object.ReferenceEquals(this.AddressField, value) != true)) {
this.AddressField = value;
this.RaisePropertyChanged("Address");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public Microsoft.Phone.Controls.Maps.Platform.Rectangle BestView {
get {
return this.BestViewField;
}
set {
if ((object.ReferenceEquals(this.BestViewField, value) != true)) {
this.BestViewField = value;
this.RaisePropertyChanged("BestView");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public WCEmergency.Bing.Geocode.Confidence Confidence {
get {
return this.ConfidenceField;
}
set {
if ((this.ConfidenceField.Equals(value) != true)) {
this.ConfidenceField = value;
this.RaisePropertyChanged("Confidence");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string DisplayName {
get {
return this.DisplayNameField;
}
set {
if ((object.ReferenceEquals(this.DisplayNameField, value) != true)) {
this.DisplayNameField = value;
this.RaisePropertyChanged("DisplayName");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string EntityType {
get {
return this.EntityTypeField;
}
set {
if ((object.ReferenceEquals(this.EntityTypeField, value) != true)) {
this.EntityTypeField = value;
this.RaisePropertyChanged("EntityType");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public System.Collections.ObjectModel.ObservableCollection<WCEmergency.Bing.Geocode.GeocodeLocation> Locations {
get {
return this.LocationsField;
}
set {
if ((object.ReferenceEquals(this.LocationsField, value) != true)) {
this.LocationsField = value;
this.RaisePropertyChanged("Locations");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public System.Collections.ObjectModel.ObservableCollection<string> MatchCodes {
get {
return this.MatchCodesField;
}
set {
if ((object.ReferenceEquals(this.MatchCodesField, value) != true)) {
this.MatchCodesField = value;
this.RaisePropertyChanged("MatchCodes");
}
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="AuthenticationResultCode", Namespace="http://dev.virtualearth.net/webservices/v1/common")]
public enum AuthenticationResultCode : int {
[System.Runtime.Serialization.EnumMemberAttribute()]
None = 0,
[System.Runtime.Serialization.EnumMemberAttribute()]
NoCredentials = 1,
[System.Runtime.Serialization.EnumMemberAttribute()]
ValidCredentials = 2,
[System.Runtime.Serialization.EnumMemberAttribute()]
InvalidCredentials = 3,
[System.Runtime.Serialization.EnumMemberAttribute()]
CredentialsExpired = 4,
[System.Runtime.Serialization.EnumMemberAttribute()]
NotAuthorized = 7,
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="ResponseStatusCode", Namespace="http://dev.virtualearth.net/webservices/v1/common")]
public enum ResponseStatusCode : int {
[System.Runtime.Serialization.EnumMemberAttribute()]
Success = 0,
[System.Runtime.Serialization.EnumMemberAttribute()]
BadRequest = 1,
[System.Runtime.Serialization.EnumMemberAttribute()]
ServerError = 2,
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(Namespace="http://dev.virtualearth.net/webservices/v1/geocode/contracts", ConfigurationName="Bing.Geocode.IGeocodeService")]
public interface IGeocodeService {
[System.ServiceModel.OperationContractAttribute(AsyncPattern=true, Action="http://dev.virtualearth.net/webservices/v1/geocode/contracts/IGeocodeService/Geoc" +
"ode", ReplyAction="http://dev.virtualearth.net/webservices/v1/geocode/contracts/IGeocodeService/Geoc" +
"odeResponse")]
[System.ServiceModel.FaultContractAttribute(typeof(WCEmergency.Bing.Geocode.ResponseSummary), Action="http://dev.virtualearth.net/webservices/v1/geocode/contracts/IGeocodeService/Geoc" +
"odeResponseSummaryFault", Name="ResponseSummary", Namespace="http://dev.virtualearth.net/webservices/v1/common")]
System.IAsyncResult BeginGeocode(WCEmergency.Bing.Geocode.GeocodeRequest request, System.AsyncCallback callback, object asyncState);
WCEmergency.Bing.Geocode.GeocodeResponse EndGeocode(System.IAsyncResult result);
[System.ServiceModel.OperationContractAttribute(AsyncPattern=true, Action="http://dev.virtualearth.net/webservices/v1/geocode/contracts/IGeocodeService/Reve" +
"rseGeocode", ReplyAction="http://dev.virtualearth.net/webservices/v1/geocode/contracts/IGeocodeService/Reve" +
"rseGeocodeResponse")]
[System.ServiceModel.FaultContractAttribute(typeof(WCEmergency.Bing.Geocode.ResponseSummary), Action="http://dev.virtualearth.net/webservices/v1/geocode/contracts/IGeocodeService/Reve" +
"rseGeocodeResponseSummaryFault", Name="ResponseSummary", Namespace="http://dev.virtualearth.net/webservices/v1/common")]
System.IAsyncResult BeginReverseGeocode(WCEmergency.Bing.Geocode.ReverseGeocodeRequest request, System.AsyncCallback callback, object asyncState);
WCEmergency.Bing.Geocode.GeocodeResponse EndReverseGeocode(System.IAsyncResult result);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public interface IGeocodeServiceChannel : WCEmergency.Bing.Geocode.IGeocodeService, System.ServiceModel.IClientChannel {
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public partial class GeocodeCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
public GeocodeCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
public WCEmergency.Bing.Geocode.GeocodeResponse Result {
get {
base.RaiseExceptionIfNecessary();
return ((WCEmergency.Bing.Geocode.GeocodeResponse)(this.results[0]));
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public partial class ReverseGeocodeCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
public ReverseGeocodeCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
public WCEmergency.Bing.Geocode.GeocodeResponse Result {
get {
base.RaiseExceptionIfNecessary();
return ((WCEmergency.Bing.Geocode.GeocodeResponse)(this.results[0]));
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public partial class GeocodeServiceClient : System.ServiceModel.ClientBase<WCEmergency.Bing.Geocode.IGeocodeService>, WCEmergency.Bing.Geocode.IGeocodeService {
private BeginOperationDelegate onBeginGeocodeDelegate;
private EndOperationDelegate onEndGeocodeDelegate;
private System.Threading.SendOrPostCallback onGeocodeCompletedDelegate;
private BeginOperationDelegate onBeginReverseGeocodeDelegate;
private EndOperationDelegate onEndReverseGeocodeDelegate;
private System.Threading.SendOrPostCallback onReverseGeocodeCompletedDelegate;
private BeginOperationDelegate onBeginOpenDelegate;
private EndOperationDelegate onEndOpenDelegate;
private System.Threading.SendOrPostCallback onOpenCompletedDelegate;
private BeginOperationDelegate onBeginCloseDelegate;
private EndOperationDelegate onEndCloseDelegate;
private System.Threading.SendOrPostCallback onCloseCompletedDelegate;
public GeocodeServiceClient() {
}
public GeocodeServiceClient(string endpointConfigurationName) :
base(endpointConfigurationName) {
}
public GeocodeServiceClient(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress) {
}
public GeocodeServiceClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress) {
}
public GeocodeServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
base(binding, remoteAddress) {
}
public System.Net.CookieContainer CookieContainer {
get {
System.ServiceModel.Channels.IHttpCookieContainerManager httpCookieContainerManager = this.InnerChannel.GetProperty<System.ServiceModel.Channels.IHttpCookieContainerManager>();
if ((httpCookieContainerManager != null)) {
return httpCookieContainerManager.CookieContainer;
}
else {
return null;
}
}
set {
System.ServiceModel.Channels.IHttpCookieContainerManager httpCookieContainerManager = this.InnerChannel.GetProperty<System.ServiceModel.Channels.IHttpCookieContainerManager>();
if ((httpCookieContainerManager != null)) {
httpCookieContainerManager.CookieContainer = value;
}
else {
throw new System.InvalidOperationException("Unable to set the CookieContainer. Please make sure the binding contains an HttpC" +
"ookieContainerBindingElement.");
}
}
}
public event System.EventHandler<GeocodeCompletedEventArgs> GeocodeCompleted;
public event System.EventHandler<ReverseGeocodeCompletedEventArgs> ReverseGeocodeCompleted;
public event System.EventHandler<System.ComponentModel.AsyncCompletedEventArgs> OpenCompleted;
public event System.EventHandler<System.ComponentModel.AsyncCompletedEventArgs> CloseCompleted;
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
System.IAsyncResult WCEmergency.Bing.Geocode.IGeocodeService.BeginGeocode(WCEmergency.Bing.Geocode.GeocodeRequest request, System.AsyncCallback callback, object asyncState) {
return base.Channel.BeginGeocode(request, callback, asyncState);
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
WCEmergency.Bing.Geocode.GeocodeResponse WCEmergency.Bing.Geocode.IGeocodeService.EndGeocode(System.IAsyncResult result) {
return base.Channel.EndGeocode(result);
}
private System.IAsyncResult OnBeginGeocode(object[] inValues, System.AsyncCallback callback, object asyncState) {
WCEmergency.Bing.Geocode.GeocodeRequest request = ((WCEmergency.Bing.Geocode.GeocodeRequest)(inValues[0]));
return ((WCEmergency.Bing.Geocode.IGeocodeService)(this)).BeginGeocode(request, callback, asyncState);
}
private object[] OnEndGeocode(System.IAsyncResult result) {
WCEmergency.Bing.Geocode.GeocodeResponse retVal = ((WCEmergency.Bing.Geocode.IGeocodeService)(this)).EndGeocode(result);
return new object[] {
retVal};
}
private void OnGeocodeCompleted(object state) {
if ((this.GeocodeCompleted != null)) {
InvokeAsyncCompletedEventArgs e = ((InvokeAsyncCompletedEventArgs)(state));
this.GeocodeCompleted(this, new GeocodeCompletedEventArgs(e.Results, e.Error, e.Cancelled, e.UserState));
}
}
public void GeocodeAsync(WCEmergency.Bing.Geocode.GeocodeRequest request) {
this.GeocodeAsync(request, null);
}
public void GeocodeAsync(WCEmergency.Bing.Geocode.GeocodeRequest request, object userState) {
if ((this.onBeginGeocodeDelegate == null)) {
this.onBeginGeocodeDelegate = new BeginOperationDelegate(this.OnBeginGeocode);
}
if ((this.onEndGeocodeDelegate == null)) {
this.onEndGeocodeDelegate = new EndOperationDelegate(this.OnEndGeocode);
}
if ((this.onGeocodeCompletedDelegate == null)) {
this.onGeocodeCompletedDelegate = new System.Threading.SendOrPostCallback(this.OnGeocodeCompleted);
}
base.InvokeAsync(this.onBeginGeocodeDelegate, new object[] {
request}, this.onEndGeocodeDelegate, this.onGeocodeCompletedDelegate, userState);
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
System.IAsyncResult WCEmergency.Bing.Geocode.IGeocodeService.BeginReverseGeocode(WCEmergency.Bing.Geocode.ReverseGeocodeRequest request, System.AsyncCallback callback, object asyncState) {
return base.Channel.BeginReverseGeocode(request, callback, asyncState);
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
WCEmergency.Bing.Geocode.GeocodeResponse WCEmergency.Bing.Geocode.IGeocodeService.EndReverseGeocode(System.IAsyncResult result) {
return base.Channel.EndReverseGeocode(result);
}
private System.IAsyncResult OnBeginReverseGeocode(object[] inValues, System.AsyncCallback callback, object asyncState) {
WCEmergency.Bing.Geocode.ReverseGeocodeRequest request = ((WCEmergency.Bing.Geocode.ReverseGeocodeRequest)(inValues[0]));
return ((WCEmergency.Bing.Geocode.IGeocodeService)(this)).BeginReverseGeocode(request, callback, asyncState);
}
private object[] OnEndReverseGeocode(System.IAsyncResult result) {
WCEmergency.Bing.Geocode.GeocodeResponse retVal = ((WCEmergency.Bing.Geocode.IGeocodeService)(this)).EndReverseGeocode(result);
return new object[] {
retVal};
}
private void OnReverseGeocodeCompleted(object state) {
if ((this.ReverseGeocodeCompleted != null)) {
InvokeAsyncCompletedEventArgs e = ((InvokeAsyncCompletedEventArgs)(state));
this.ReverseGeocodeCompleted(this, new ReverseGeocodeCompletedEventArgs(e.Results, e.Error, e.Cancelled, e.UserState));
}
}
public void ReverseGeocodeAsync(WCEmergency.Bing.Geocode.ReverseGeocodeRequest request) {
this.ReverseGeocodeAsync(request, null);
}
public void ReverseGeocodeAsync(WCEmergency.Bing.Geocode.ReverseGeocodeRequest request, object userState) {
if ((this.onBeginReverseGeocodeDelegate == null)) {
this.onBeginReverseGeocodeDelegate = new BeginOperationDelegate(this.OnBeginReverseGeocode);
}
if ((this.onEndReverseGeocodeDelegate == null)) {
this.onEndReverseGeocodeDelegate = new EndOperationDelegate(this.OnEndReverseGeocode);
}
if ((this.onReverseGeocodeCompletedDelegate == null)) {
this.onReverseGeocodeCompletedDelegate = new System.Threading.SendOrPostCallback(this.OnReverseGeocodeCompleted);
}
base.InvokeAsync(this.onBeginReverseGeocodeDelegate, new object[] {
request}, this.onEndReverseGeocodeDelegate, this.onReverseGeocodeCompletedDelegate, userState);
}
private System.IAsyncResult OnBeginOpen(object[] inValues, System.AsyncCallback callback, object asyncState) {
return ((System.ServiceModel.ICommunicationObject)(this)).BeginOpen(callback, asyncState);
}
private object[] OnEndOpen(System.IAsyncResult result) {
((System.ServiceModel.ICommunicationObject)(this)).EndOpen(result);
return null;
}
private void OnOpenCompleted(object state) {
if ((this.OpenCompleted != null)) {
InvokeAsyncCompletedEventArgs e = ((InvokeAsyncCompletedEventArgs)(state));
this.OpenCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(e.Error, e.Cancelled, e.UserState));
}
}
public void OpenAsync() {
this.OpenAsync(null);
}
public void OpenAsync(object userState) {
if ((this.onBeginOpenDelegate == null)) {
this.onBeginOpenDelegate = new BeginOperationDelegate(this.OnBeginOpen);
}
if ((this.onEndOpenDelegate == null)) {
this.onEndOpenDelegate = new EndOperationDelegate(this.OnEndOpen);
}
if ((this.onOpenCompletedDelegate == null)) {
this.onOpenCompletedDelegate = new System.Threading.SendOrPostCallback(this.OnOpenCompleted);
}
base.InvokeAsync(this.onBeginOpenDelegate, null, this.onEndOpenDelegate, this.onOpenCompletedDelegate, userState);
}
private System.IAsyncResult OnBeginClose(object[] inValues, System.AsyncCallback callback, object asyncState) {
return ((System.ServiceModel.ICommunicationObject)(this)).BeginClose(callback, asyncState);
}
private object[] OnEndClose(System.IAsyncResult result) {
((System.ServiceModel.ICommunicationObject)(this)).EndClose(result);
return null;
}
private void OnCloseCompleted(object state) {
if ((this.CloseCompleted != null)) {
InvokeAsyncCompletedEventArgs e = ((InvokeAsyncCompletedEventArgs)(state));
this.CloseCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(e.Error, e.Cancelled, e.UserState));
}
}
public void CloseAsync() {
this.CloseAsync(null);
}
public void CloseAsync(object userState) {
if ((this.onBeginCloseDelegate == null)) {
this.onBeginCloseDelegate = new BeginOperationDelegate(this.OnBeginClose);
}
if ((this.onEndCloseDelegate == null)) {
this.onEndCloseDelegate = new EndOperationDelegate(this.OnEndClose);
}
if ((this.onCloseCompletedDelegate == null)) {
this.onCloseCompletedDelegate = new System.Threading.SendOrPostCallback(this.OnCloseCompleted);
}
base.InvokeAsync(this.onBeginCloseDelegate, null, this.onEndCloseDelegate, this.onCloseCompletedDelegate, userState);
}
protected override WCEmergency.Bing.Geocode.IGeocodeService CreateChannel() {
return new GeocodeServiceClientChannel(this);
}
private class GeocodeServiceClientChannel : ChannelBase<WCEmergency.Bing.Geocode.IGeocodeService>, WCEmergency.Bing.Geocode.IGeocodeService {
public GeocodeServiceClientChannel(System.ServiceModel.ClientBase<WCEmergency.Bing.Geocode.IGeocodeService> client) :
base(client) {
}
public System.IAsyncResult BeginGeocode(WCEmergency.Bing.Geocode.GeocodeRequest request, System.AsyncCallback callback, object asyncState) {
object[] _args = new object[1];
_args[0] = request;
System.IAsyncResult _result = base.BeginInvoke("Geocode", _args, callback, asyncState);
return _result;
}
public WCEmergency.Bing.Geocode.GeocodeResponse EndGeocode(System.IAsyncResult result) {
object[] _args = new object[0];
WCEmergency.Bing.Geocode.GeocodeResponse _result = ((WCEmergency.Bing.Geocode.GeocodeResponse)(base.EndInvoke("Geocode", _args, result)));
return _result;
}
public System.IAsyncResult BeginReverseGeocode(WCEmergency.Bing.Geocode.ReverseGeocodeRequest request, System.AsyncCallback callback, object asyncState) {
object[] _args = new object[1];
_args[0] = request;
System.IAsyncResult _result = base.BeginInvoke("ReverseGeocode", _args, callback, asyncState);
return _result;
}
public WCEmergency.Bing.Geocode.GeocodeResponse EndReverseGeocode(System.IAsyncResult result) {
object[] _args = new object[0];
WCEmergency.Bing.Geocode.GeocodeResponse _result = ((WCEmergency.Bing.Geocode.GeocodeResponse)(base.EndInvoke("ReverseGeocode", _args, result)));
return _result;
}
}
}
}
| 45.35989 | 197 | 0.606823 | [
"MIT"
] | andriybuday/hakaton-wp7-mobile | SS-Mobile-One/WCEmergency/WCEmergency/Service References/Bing.Geocode/Reference.cs | 66,046 | C# |
// Copyright (c) 2017 Trevor Redfern
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
namespace Tests.Shops
{
using Xunit;
using SilverNeedle.Equipment;
using SilverNeedle.Shops;
public class ArmorShopTests : RequiresDataFiles
{
[Fact]
public void ProvidesACollectionOfArmor()
{
var shop = new ArmorShop();
var armors = shop.GetInventory<IArmor>();
Assert.NotEmpty(armors);
}
[Fact]
public void ProvidesSomeMasterworkArmor()
{
var shop = new ArmorShop();
var armors = shop.GetInventory();
var mwkArmors = shop.GetInventory<MasterworkArmor>();
Assert.NotEmpty(armors);
Assert.NotEmpty(mwkArmors);
}
}
} | 26.0625 | 65 | 0.594724 | [
"MIT"
] | shortlegstudio/silverneedle-web | silverneedle-tests/Shops/ArmorShopTests.cs | 834 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RobinKarp
{
public class KMP
{
private static void GetNextVal(string str, int[] next)
{
int i = 0;
int j = -1;
next[0] = -1;
while (i < str.Length - 1)
{
if (j == -1 || str[i] == str[j])
{
i++;
j++;
next[i] = j;
}
else
{
j = next[j];
}
}
}
public static int KMPSearch(string source, string pattern)
{
int i, j;
int[] next = new int[pattern.Length];
GetNextVal(pattern, next);
i = 0;
j = 0;
while (i < source.Length && j < pattern.Length)
{
if (j == -1 || source[i] == pattern[j])
{
++i;
++j;
}
else
{
j = next[j];
}
}
if (j == pattern.Length)
return i - pattern.Length;
return -1;
}
}
}
| 23.5 | 66 | 0.336626 | [
"MIT"
] | lizhen325/MIT-Data-Structures-And-Algorithms | MIT/RobinKarp/RobinKarp/KMP.cs | 1,318 | C# |
// Copyright (c) .NET Core Community. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
namespace DotNetCore.CAP.Internal
{
/// <summary>
/// A context for consumers, it used to be provider wrapper of method description and received message.
/// </summary>
public class ConsumerContext
{
/// <summary>
/// create a new instance of <see cref="ConsumerContext" /> .
/// </summary>
/// <param name="descriptor">consumer method descriptor. </param>
/// <param name="message"> received message.</param>
public ConsumerContext(ConsumerExecutorDescriptor descriptor, MessageContext message)
{
ConsumerDescriptor = descriptor ?? throw new ArgumentNullException(nameof(descriptor));
DeliverMessage = message ?? throw new ArgumentNullException(nameof(message));
}
/// <summary>
/// a descriptor of consumer information need to be performed.
/// </summary>
public ConsumerExecutorDescriptor ConsumerDescriptor { get; }
/// <summary>
/// consumer received message.
/// </summary>
public MessageContext DeliverMessage { get; }
}
} | 37.647059 | 107 | 0.645313 | [
"MIT"
] | CoolMoonGG/CAP | src/DotNetCore.CAP/Internal/ConsumerContext.cs | 1,282 | C# |
using System;
namespace Valle.GtkUtilidades
{
public enum FormatosNumericos { F_entero, F_Decimal, F_IP };
public enum AccionesNumerico { AC_Anular, AC_Aceptar, AC_BtnPulsado };
public delegate void OnSalirNumerico(AccionesNumerico accion, String numero);
public partial class TecladoNumerico : FormularioBase
{
public TecladoNumerico (FormatosNumericos formatoTeclado, String titulo)
{
this.init ();
LblTituloBase = lblTitulo;
Titulo = titulo;
this.lblDisplay.Font = new System.Drawing.Font(this.lblDisplay.Font.FontFamily,20f);
this.lblDisplay.ColorDeFono = System.Drawing.Color.White;
salirNumerico = null;
formato = formatoTeclado;
if (formato== FormatosNumericos.F_entero)
this.btnComa.Sensitive = false;
}
public String Numero
{
set { this.lblDisplay.Texto = value; }
get { return lblDisplay.Texto == null ? "0" : lblDisplay.Texto; }
}
private AccionesNumerico accion;
public AccionesNumerico Accion
{
get { return accion; }
}
private FormatosNumericos formato;
public FormatosNumericos Formato
{
set { formato = value;
if (formato== FormatosNumericos.F_entero)
this.btnComa.Sensitive = false;
else
this.btnComa.Sensitive = true;
}
}
public event OnSalirNumerico salirNumerico;
private void BtnNumerico_Click(object sender, EventArgs e)
{
PulsadoRecientemente = true;
string tecla = (((Gtk.Button)sender).Child as Gtk.Label).Text;
switch(tecla){
case ".":
if(formato!= FormatosNumericos.F_IP){
if(!this.Numero.Contains(tecla)){
Numero += ",";
}
}else{
Numero+=".";
}
break;
default:
Numero += tecla;
break;
}
}
private void btnAceptar_Click(object sender, EventArgs e)
{
accion = AccionesNumerico.AC_Aceptar;
if (salirNumerico != null) { salirNumerico(accion, this.lblDisplay.Texto); }
this.CerrarFormulario();
}
private void OnBtnSalir(object sender, EventArgs e)
{
accion = AccionesNumerico.AC_Anular;
if (salirNumerico != null) { salirNumerico(accion, null); }
this.CerrarFormulario();
}
private void btnBackSp_Click(object sender, EventArgs e)
{
PulsadoRecientemente = true;
if (this.Numero.Length > 1)
Numero = Numero.Remove(Numero.Length - 1);
else
Numero = "";
}
protected virtual void OnBtnBorrar (object sender, System.EventArgs e)
{
Numero = "";
}
}
}
| 28.925926 | 88 | 0.532971 | [
"Apache-2.0"
] | vallemrv/valletpv | Valle.Library/Valle.GtkUtilidades/Valle.GtkUtilidades/Formularios/TecladoNumerico.cs | 3,124 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Schema;
/// <summary>
/// Utility functions for reading/writing BXDJ files
/// </summary>
public partial class BXDJSkeleton
{
#region XSD Markup
/// <summary>
/// The XSD markup to ensure valid document reading.
/// </summary>
private const string BXDJ_XSD_3_0 =
@"
<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<!-- definition of simple elements -->
<xs:element name='ParentID' type='xs:integer'/>
<xs:element name='ModelFileName' type='xs:string'/>
<xs:element name='ModelID' type='xs:string'/>
<xs:element name='X' type='xs:decimal'/>
<xs:element name='Y' type='xs:decimal'/>
<xs:element name='Z' type='xs:decimal'/>
<xs:element name='AngularLowLimit' type='xs:decimal'/>
<xs:element name='AngularHighLimit' type='xs:decimal'/>
<xs:element name='LinearStartLimit' type='xs:decimal'/>
<xs:element name='LinearEndLimit' type='xs:decimal'/>
<xs:element name='LinearLowLimit' type='xs:decimal'/>
<xs:element name='LinearUpperLimit' type='xs:decimal'/>
<xs:element name='CurrentLinearPosition' type='xs:decimal'/>
<xs:element name='CurrentAngularPosition' type='xs:decimal'/>
<xs:element name='WidthMM' type='xs:decimal'/>
<xs:element name='PressurePSI' type='xs:decimal'/>
<xs:element name='WheelRadius' type='xs:decimal'/>
<xs:element name='WheelWidth' type='xs:decimal'/>
<xs:element name='ForwardAsympSlip' type='xs:decimal'/>
<xs:element name='ForwardAsympValue' type='xs:decimal'/>
<xs:element name='ForwardExtremeSlip' type='xs:decimal'/>
<xs:element name='ForwardExtremeValue' type='xs:decimal'/>
<xs:element name='SideAsympSlip' type='xs:decimal'/>
<xs:element name='SideAsympValue' type='xs:decimal'/>
<xs:element name='SideExtremeSlip' type='xs:decimal'/>
<xs:element name='SideExtremeValue' type='xs:decimal'/>
<xs:element name='IsDriveWheel' type='xs:boolean'/>
<xs:element name='PortA' type='xs:integer'/>
<xs:element name='PortB' type='xs:integer'/>
<xs:element name='InputGear' type='xs:double'/>
<xs:element name='OutputGear' type='xs:double'/>
<xs:element name='LowerLimit' type='xs:float'/>
<xs:element name='UpperLimit' type='xs:float'/>
<xs:element name='Coefficient' type='xs:decimal'/>
<xs:element name='SensorModule' type='xs:integer'/>
<xs:element name='SensorPort' type='xs:integer'/>
<xs:element name='UseSecondarySource' type='xs:boolean'/>
<xs:element name='ElevatorType'>
<xs:simpleType>
<xs:restriction base='xs:string'>
<xs:enumeration value='NOT_MULTI'/>
<xs:enumeration value='CASCADING_STAGE_1'/>
<xs:enumeration value='CASCADING_STAGE_2'/>
<xs:enumeration value='CONTINUOUS_STAGE_1'/>
<xs:enumeration value='CONTINUOUS_STAGE_2'/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name='DriveType'>
<xs:simpleType>
<xs:restriction base='xs:string'>
<xs:enumeration value='MOTOR'/>
<xs:enumeration value='SERVO'/>
<xs:enumeration value='WORM_SCREW'/>
<xs:enumeration value='BUMPER_PNEUMATIC'/>
<xs:enumeration value='RELAY_PNEUMATIC'/>
<xs:enumeration value='DUAL_MOTOR'/>
<xs:enumeration value='ELEVATOR'/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name='SignalType'>
<xs:simpleType>
<xs:restriction base='xs:string'>
<xs:enumeration value='CAN'/>
<xs:enumeration value='PWM'/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name='WheelType'>
<xs:simpleType>
<xs:restriction base='xs:string'>
<xs:enumeration value='NOT_A_WHEEL'/>
<xs:enumeration value='NORMAL'/>
<xs:enumeration value='OMNI'/>
<xs:enumeration value='MECANUM'/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name='SensorType'>
<xs:simpleType>
<xs:restriction base='xs:string'>
<xs:enumeration value='LIMIT'/>
<xs:enumeration value='ENCODER'/>
<xs:enumeration value='POTENTIOMETER'/>
<xs:enumeration value='LIMIT_HALL'/>
<xs:enumeration value='ACCELEROMETER'/>
<xs:enumeration value='MAGNETOMETER'/>
<xs:enumeration value='GYRO'/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<!-- definition of attributes -->
<xs:attribute name='GUID' type='xs:string'/>
<xs:attribute name='VectorID' type='xs:string'/>
<xs:attribute name='DriverMetaID' type='xs:integer'/>
<xs:attribute name='Version'>
<xs:simpleType>
<xs:restriction base='xs:string'>
<xs:pattern value='3\.0\.\d+'/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<!-- definition of complex elements -->
<xs:element name='BXDVector3'>
<xs:complexType>
<xs:sequence>
<xs:element ref='X'/>
<xs:element ref='Y'/>
<xs:element ref='Z'/>
</xs:sequence>
<xs:attribute ref='VectorID' use='required'/>
</xs:complexType>
</xs:element>
<xs:element name='BallJoint'>
<xs:complexType>
<xs:sequence>
<xs:element ref='BXDVector3'/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name='CylindricalJoint'>
<xs:complexType>
<xs:sequence>
<xs:element ref='BXDVector3' minOccurs='2' maxOccurs='2'/>
<xs:element ref='AngularLowLimit' minOccurs='0' maxOccurs='1'/>
<xs:element ref='AngularHighLimit' minOccurs='0' maxOccurs='1'/>
<xs:element ref='LinearStartLimit' minOccurs='0' maxOccurs='1'/>
<xs:element ref='LinearEndLimit' minOccurs='0' maxOccurs='1'/>
<xs:element ref='CurrentLinearPosition'/>
<xs:element ref='CurrentAngularPosition'/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name='LinearJoint'>
<xs:complexType>
<xs:sequence>
<xs:element ref='BXDVector3' minOccurs='2' maxOccurs='2'/>
<xs:element ref='LinearLowLimit' minOccurs='0' maxOccurs='1'/>
<xs:element ref='LinearUpperLimit' minOccurs='0' maxOccurs='1'/>
<xs:element ref='CurrentLinearPosition'/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name='PlanarJoint'>
<xs:complexType>
<xs:sequence>
<xs:element ref='BXDVector3' minOccurs='2' maxOccurs='2'/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name='RotationalJoint'>
<xs:complexType>
<xs:sequence>
<xs:element ref='BXDVector3' minOccurs='2' maxOccurs='2'/>
<xs:element ref='AngularLowLimit' minOccurs='0' maxOccurs='1'/>
<xs:element ref='AngularHighLimit' minOccurs='0' maxOccurs='1'/>
<xs:element ref='CurrentAngularPosition'/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name='ElevatorDriverMeta'>
<xs:complexType>
<xs:sequence>
<xs:element ref='ElevatorType'/>
</xs:sequence>
<xs:attribute ref='DriverMetaID' use='required'/>
</xs:complexType>
</xs:element>
<xs:element name='PneumaticDriverMeta'>
<xs:complexType>
<xs:sequence>
<xs:element ref='WidthMM'/>
<xs:element ref='PressurePSI'/>
</xs:sequence>
<xs:attribute ref='DriverMetaID' use='required'/>
</xs:complexType>
</xs:element>
<xs:element name='WheelDriverMeta'>
<xs:complexType>
<xs:sequence>
<xs:element ref='WheelType'/>
<xs:element ref='WheelRadius'/>
<xs:element ref='WheelWidth'/>
<xs:element ref='BXDVector3'/>
<xs:element ref='ForwardAsympSlip'/>
<xs:element ref='ForwardAsympValue'/>
<xs:element ref='ForwardExtremeSlip'/>
<xs:element ref='ForwardExtremeValue'/>
<xs:element ref='SideAsympSlip'/>
<xs:element ref='SideAsympValue'/>
<xs:element ref='SideExtremeSlip'/>
<xs:element ref='SideExtremeValue'/>
<xs:element ref='IsDriveWheel'/>
</xs:sequence>
<xs:attribute ref='DriverMetaID' use='required'/>
</xs:complexType>
</xs:element>
<xs:element name='JointDriver'>
<xs:complexType>
<xs:sequence>
<xs:element ref='DriveType'/>
<xs:element ref='PortA'/>
<xs:element ref='PortB'/>
<xs:element ref='InputGear'/>
<xs:element ref='OutputGear'/>
<xs:element ref='LowerLimit'/>
<xs:element ref='UpperLimit'/>
<xs:element ref='SignalType'/>
<xs:choice maxOccurs='unbounded' minOccurs='0'>
<xs:element ref='ElevatorDriverMeta'/>
<xs:element ref='PneumaticDriverMeta'/>
<xs:element ref='WheelDriverMeta'/>
</xs:choice>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name='Polynomial'>
<xs:complexType>
<xs:sequence>
<xs:element ref='Coefficient' maxOccurs='unbounded' minOccurs='0'/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name='RobotSensor'>
<xs:complexType>
<xs:sequence>
<xs:element ref='SensorType'/>
<xs:element ref='SensorModule'/>
<xs:element ref='SensorPort'/>
<xs:element ref='Polynomial'/>
<xs:element ref='UseSecondarySource'/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name='Node'>
<xs:complexType>
<xs:sequence>
<xs:element ref='ParentID'/>
<xs:element ref='ModelFileName'/>
<xs:element ref='ModelID'/>
<xs:choice maxOccurs='1' minOccurs='0'>
<xs:element ref='BallJoint'/>
<xs:element ref='CylindricalJoint'/>
<xs:element ref='LinearJoint'/>
<xs:element ref='PlanarJoint'/>
<xs:element ref='RotationalJoint'/>
</xs:choice>
<xs:element ref='JointDriver' minOccurs='0' maxOccurs='1'/>
<xs:element ref='RobotSensor' minOccurs='0' maxOccurs='unbounded'/>
</xs:sequence>
<xs:attribute ref='GUID' use='required'/>
</xs:complexType>
</xs:element>
<xs:element name='BXDJ'>
<xs:complexType>
<xs:sequence>
<xs:element ref='Node' minOccurs='0' maxOccurs='unbounded'/>
</xs:sequence>
<xs:attribute ref='Version' use='required'/>
</xs:complexType>
</xs:element>
</xs:schema>";
#endregion
/// <summary>
/// Reads the skeleton contained in the XML BXDJ file specified and
/// returns the corresponding RigidNode_Base.
/// </summary>
/// <param name="path"></param>
/// <param name="useValidation"></param>
private static RigidNode_Base ReadSkeleton_3_0(string path, bool useValidation = true)
{
RigidNode_Base root = null;
List<RigidNode_Base> nodes = new List<RigidNode_Base>();
XmlReaderSettings settings = new XmlReaderSettings();
if (useValidation)
{
settings.Schemas.Add(XmlSchema.Read(new StringReader(BXDJ_XSD_3_0), null));
settings.ValidationType = ValidationType.Schema;
}
else
{
settings.ValidationType = ValidationType.None;
}
XmlReader reader = XmlReader.Create(path, settings);
try
{
foreach (string name in IOUtilities.AllElements(reader))
{
switch (name)
{
case "Node":
// Reads the current element as a node.
ReadNode_3_0(reader.ReadSubtree(), nodes, ref root);
break;
}
}
}
catch (Exception)// A variety of exceptions can take place if the file is invalid, but we will always want to return null.
{
// If the file is invalid, return null.
return null;
}
finally
{
// Closes the reader.
reader.Close();
}
return nodes[0];
}
/// <summary>
/// Reads a RigidNode_Base with the given reader, list of nodes, and root node reference.
/// </summary>
/// <param name="reader"></param>
/// <param name="nodes"></param>
/// <param name="root"></param>
private static void ReadNode_3_0(XmlReader reader, List<RigidNode_Base> nodes, ref RigidNode_Base root)
{
int parentID = -1;
foreach (string name in IOUtilities.AllElements(reader))
{
switch (name)
{
case "Node":
// Adds a new node to the list of RigidNode_Bases.
nodes.Add(RigidNode_Base.NODE_FACTORY(new Guid(reader["GUID"])));
break;
case "ParentID":
// Stores this ID for later use.
parentID = reader.ReadElementContentAsInt();
if (parentID == -1) // If this is the root...
root = nodes[nodes.Count - 1];
break;
case "ModelFileName":
// Assigns the ModelFileName property to the ModelFileName element value.
nodes[nodes.Count - 1].ModelFileName = reader.ReadElementContentAsString();
break;
case "ModelID":
// Assigns the ModelFullID property to the ModelID element value.
nodes[nodes.Count - 1].ModelFullID = reader.ReadElementContentAsString();
break;
case "BallJoint":
// Reads the current element as a BallJoint.
nodes[parentID].AddChild(ReadBallJoint_3_0(reader.ReadSubtree()), nodes[nodes.Count - 1]);
break;
case "CylindricalJoint":
// Reads the current element as a CylindricalJoint.
nodes[parentID].AddChild(ReadCylindricalJoint_3_0(reader.ReadSubtree()), nodes[nodes.Count - 1]);
break;
case "LinearJoint":
// Reads the current element as a LinearJoint.
nodes[parentID].AddChild(ReadLinearJoint_3_0(reader.ReadSubtree()), nodes[nodes.Count - 1]);
break;
case "PlanarJoint":
// Reads the current element as a PlanarJoint.
nodes[parentID].AddChild(ReadPlanarJoint_3_0(reader.ReadSubtree()), nodes[nodes.Count - 1]);
break;
case "RotationalJoint":
// Reads the current elemenet as a RotationalJoint.
nodes[parentID].AddChild(ReadRotationalJoint_3_0(reader.ReadSubtree()), nodes[nodes.Count - 1]);
break;
case "JointDriver":
// Add a joint driver to the skeletal joint of the current node.
nodes[nodes.Count - 1].GetSkeletalJoint().cDriver = ReadJointDriver_3_0(reader.ReadSubtree());
break;
case "RobotSensor":
nodes[nodes.Count - 1].GetSkeletalJoint().attachedSensors.Add(ReadRobotSensor_3_0(reader.ReadSubtree()));
break;
}
}
}
/// <summary>
/// Reads a BallJoint_Base from the given XmlReader.
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
private static BallJoint_Base ReadBallJoint_3_0(XmlReader reader)
{
// Create a new BallJoint_Base.
BallJoint_Base ballJoint = (BallJoint_Base)SkeletalJoint_Base.JOINT_FACTORY(SkeletalJointType.BALL);
foreach (string name in IOUtilities.AllElements(reader))
{
switch (name)
{
case "BXDVector3":
// Read the BXDVector3 as the basePoint.
ballJoint.basePoint = ReadBXDVector3_3_0(reader.ReadSubtree());
break;
}
}
return ballJoint;
}
/// <summary>
/// Reads a CylindricalJoint_Base from the given XmlReader.
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
private static CylindricalJoint_Base ReadCylindricalJoint_3_0(XmlReader reader)
{
// Create a new CylindricalJoint_Base.
CylindricalJoint_Base cylindricalJoint = (CylindricalJoint_Base)SkeletalJoint_Base.JOINT_FACTORY(SkeletalJointType.CYLINDRICAL);
foreach (string name in IOUtilities.AllElements(reader))
{
switch (name)
{
case "BXDVector3":
switch (reader["VectorID"])
{
case "BasePoint":
// Assign the BXDVector3 to the basePoint.
cylindricalJoint.basePoint = ReadBXDVector3_3_0(reader.ReadSubtree());
break;
case "Axis":
// Assign the BXDVector3 to the axis.
cylindricalJoint.axis = ReadBXDVector3_3_0(reader.ReadSubtree());
break;
}
break;
case "AngularLowLimit":
// Assign a value to the angularLimitLow.
cylindricalJoint.hasAngularLimit = true;
cylindricalJoint.angularLimitLow = float.Parse(reader.ReadElementContentAsString());
break;
case "AngularHighLimit":
// Assign a value to the angularLimitHigh.
cylindricalJoint.angularLimitHigh = float.Parse(reader.ReadElementContentAsString());
break;
case "LinearStartLimit":
// Assign a value to the linearLimitStart.
cylindricalJoint.hasLinearStartLimit = true;
cylindricalJoint.linearLimitStart = float.Parse(reader.ReadElementContentAsString());
break;
case "LinearEndLimit":
// Assign a value to the linearLimitEnd.
cylindricalJoint.hasLinearEndLimit = true;
cylindricalJoint.linearLimitEnd = float.Parse(reader.ReadElementContentAsString());
break;
case "CurrentLinearPosition":
// Assign a value to the currentLinearPosition.
cylindricalJoint.currentLinearPosition = float.Parse(reader.ReadElementContentAsString());
break;
case "CurrentAngularPosition":
// Assign a value to the currentAngularPosition.
cylindricalJoint.currentAngularPosition = float.Parse(reader.ReadElementContentAsString());
break;
}
}
return cylindricalJoint;
}
/// <summary>
/// Reads a LinearJoint_Base from the given XmlReader.
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
private static LinearJoint_Base ReadLinearJoint_3_0(XmlReader reader)
{
// Create a new LinearJoint_Base.
LinearJoint_Base linearJoint = (LinearJoint_Base)SkeletalJoint_Base.JOINT_FACTORY(SkeletalJointType.LINEAR);
foreach (string name in IOUtilities.AllElements(reader))
{
switch (name)
{
case "BXDVector3":
switch (reader["VectorID"])
{
case "BasePoint":
// Assign the BXDVector3 to the basePoint.
linearJoint.basePoint = ReadBXDVector3_3_0(reader.ReadSubtree());
break;
case "Axis":
// Assign the BXDVector3 to the axis.
linearJoint.axis = ReadBXDVector3_3_0(reader.ReadSubtree());
break;
}
break;
case "LinearLowLimit":
// Assign a value to the linearLimitLow.
linearJoint.hasLowerLimit = true;
linearJoint.linearLimitLow = float.Parse(reader.ReadElementContentAsString());
break;
case "LinearUpperLimit":
// Assign a value to the linearLimitHigh.
linearJoint.hasUpperLimit = true;
linearJoint.linearLimitHigh = float.Parse(reader.ReadElementContentAsString());
break;
case "CurrentLinearPosition":
// Assign a value to the currentLinearPosition.
linearJoint.currentLinearPosition = float.Parse(reader.ReadElementContentAsString());
break;
}
}
return linearJoint;
}
/// <summary>
/// Reads a PlanarJoint_Base from the given XmlReader.
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
private static PlanarJoint_Base ReadPlanarJoint_3_0(XmlReader reader)
{
// Create a new PlanarJoint_Base.
PlanarJoint_Base planarJoint = (PlanarJoint_Base)SkeletalJoint_Base.JOINT_FACTORY(SkeletalJointType.PLANAR);
foreach (string name in IOUtilities.AllElements(reader))
{
switch (name)
{
case "BXDVector3":
switch (reader["VectorID"])
{
case "Normal":
// Assign the BXDVector3 to the normal.
planarJoint.normal = ReadBXDVector3_3_0(reader.ReadSubtree());
break;
case "BasePoint":
// Assign the BXDVector3 to the basePoint.s
planarJoint.basePoint = ReadBXDVector3_3_0(reader.ReadSubtree());
break;
}
break;
}
}
return planarJoint;
}
/// <summary>
/// Reads a RotationalJoint_Base from the given XmlReader.
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
private static RotationalJoint_Base ReadRotationalJoint_3_0(XmlReader reader)
{
// Create a new RotationalJoint_Base.
RotationalJoint_Base rotationalJoint = (RotationalJoint_Base)SkeletalJoint_Base.JOINT_FACTORY(SkeletalJointType.ROTATIONAL);
foreach (string name in IOUtilities.AllElements(reader))
{
switch (name)
{
case "BXDVector3":
switch (reader["VectorID"])
{
case "BasePoint":
// Read the BXDVector3 as the basePoint.
rotationalJoint.basePoint = ReadBXDVector3_3_0(reader.ReadSubtree());
break;
case "Axis":
// Read the BXDVector3 as the axis.
rotationalJoint.axis = ReadBXDVector3_3_0(reader.ReadSubtree());
break;
}
break;
case "AngularLowLimit":
// Assign the current element value to angularLimitLow.
rotationalJoint.hasAngularLimit = true;
rotationalJoint.angularLimitLow = float.Parse(reader.ReadElementContentAsString());
break;
case "AngularHighLimit":
// Assign the current element value to angularLimitHigh.
rotationalJoint.angularLimitHigh = float.Parse(reader.ReadElementContentAsString());
break;
case "CurrentAngularPosition":
// Assign the current element value to currentAngularPosition.
rotationalJoint.currentAngularPosition = float.Parse(reader.ReadElementContentAsString());
break;
}
}
return rotationalJoint;
}
/// <summary>
/// Reads a BXDVector3 with the given XmlReader and returns the reading.
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
private static BXDVector3 ReadBXDVector3_3_0(XmlReader reader)
{
BXDVector3 vec = new BXDVector3();
foreach (string name in IOUtilities.AllElements(reader))
{
switch (name)
{
case "X":
// Assign the x value.
vec.x = float.Parse(reader.ReadElementContentAsString());
break;
case "Y":
// Assign the y value.
vec.y = float.Parse(reader.ReadElementContentAsString());
break;
case "Z":
// Assign the z value.
vec.z = float.Parse(reader.ReadElementContentAsString());
break;
}
}
return vec;
}
/// <summary>
/// Reads a JointDriver from the given XmlReader.
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
private static JointDriver ReadJointDriver_3_0(XmlReader reader)
{
JointDriver driver = null;
foreach (string name in IOUtilities.AllElements(reader))
{
switch (name)
{
case "DriveType":
// Initialize the driver.
driver = new JointDriver((JointDriverType)Enum.Parse(typeof(JointDriverType), reader.ReadElementContentAsString()));
break;
case "PortA":// mismatched naming so we can keep backwards compatibility
// Assign a value to portA.
driver.port1 = reader.ReadElementContentAsInt();
break;
case "PortB":
// Assign a value to port2.
driver.port2 = reader.ReadElementContentAsInt();
break;
case "InputGear":
// Assign a value to InputGear
driver.InputGear = reader.ReadElementContentAsDouble();
break;
case "OutputGear":
// Assign a value to OutputGear
driver.OutputGear = reader.ReadElementContentAsDouble();
break;
case "LowerLimit":
// Assign a value to the lowerLimit.
driver.lowerLimit = float.Parse(reader.ReadElementContentAsString());
break;
case "UpperLimit":
// Assign a value to the upperLimit.
driver.upperLimit = float.Parse(reader.ReadElementContentAsString());
break;
case "SignalType":
// Assign a value to isCan.
driver.isCan = reader.ReadElementContentAsString().Equals("CAN") ? true : false;
break;
case "ElevatorDriverMeta":
// Add an ElevatorDriverMeta.
driver.AddInfo(ReadElevatorDriverMeta_3_0(reader.ReadSubtree()));
break;
case "PneumaticDriverMeta":
// Add a PneumaticsDriverMeta.
driver.AddInfo(ReadPneumaticDriverMeta_3_0(reader.ReadSubtree()));
break;
case "WheelDriverMeta":
// Add a WheelDriverMeta.
driver.AddInfo(ReadWheelDriverMeta_3_0(reader.ReadSubtree()));
break;
}
}
return driver;
}
/// <summary>
/// Reads an ElevatorDriverMeta from the given XmlReader.
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
private static ElevatorDriverMeta ReadElevatorDriverMeta_3_0(XmlReader reader)
{
// Create a new ElevatorDriveMeta.
ElevatorDriverMeta elevatorDriverMeta = new ElevatorDriverMeta();
foreach (string name in IOUtilities.AllElements(reader))
{
switch (name)
{
case "ElevatorType":
// Assign the type to the current element value.
elevatorDriverMeta.type = (ElevatorType)Enum.Parse(typeof(ElevatorType), reader.ReadElementContentAsString());
break;
}
}
return elevatorDriverMeta;
}
/// <summary>
/// Reads a PneumaticDriverMeta from the given XmlReader.
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
private static PneumaticDriverMeta ReadPneumaticDriverMeta_3_0(XmlReader reader)
{
// Create a new pneumaticDriverMeta.
PneumaticDriverMeta pneumaticDriverMeta = new PneumaticDriverMeta();
foreach (string name in IOUtilities.AllElements(reader))
{
switch (name)
{
case "WidthMM":
// Assign the current element value to widthMM.
pneumaticDriverMeta.widthMM = reader.ReadElementContentAsInt();
break;
case "PressurePSI":
// Assign the current element value to pressurePSI.
pneumaticDriverMeta.pressurePSI = float.Parse(reader.ReadElementContentAsString());
break;
}
}
return pneumaticDriverMeta;
}
/// <summary>
/// Reads a WheelDriverMeta from the given XmlReader.
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
private static WheelDriverMeta ReadWheelDriverMeta_3_0(XmlReader reader)
{
// Create new WheelDriveMeta.
WheelDriverMeta wheelDriverMeta = new WheelDriverMeta();
foreach (string name in IOUtilities.AllElements(reader))
{
switch (name)
{
case "WheelType":
// Assign a value to the type.
wheelDriverMeta.type = (WheelType)Enum.Parse(typeof(WheelType), reader.ReadElementContentAsString());
break;
case "WheelRadius":
// Assign a value to the radius.
wheelDriverMeta.radius = float.Parse(reader.ReadElementContentAsString());
break;
case "WheelWidth":
// Assign a value to the width.
wheelDriverMeta.width = float.Parse(reader.ReadElementContentAsString());
break;
case "BXDVector3":
// Assign a value to the center.
wheelDriverMeta.center = ReadBXDVector3_3_0(reader.ReadSubtree());
break;
case "ForwardAsympSlip":
// Assign a value to the forwardAsympSlip.
wheelDriverMeta.forwardAsympSlip = float.Parse(reader.ReadElementContentAsString());
break;
case "ForwardAsympValue":
// Assign a value to the forwardAsympValue.
wheelDriverMeta.forwardAsympValue = float.Parse(reader.ReadElementContentAsString());
break;
case "ForwardExtremeSlip":
// Assign a value to the forwardExtremeSlip.
wheelDriverMeta.forwardExtremeSlip = float.Parse(reader.ReadElementContentAsString());
break;
case "ForwardExtremeValue":
// Assign a value to the forwardExtremeValue.
wheelDriverMeta.forwardExtremeValue = float.Parse(reader.ReadElementContentAsString());
break;
case "SideAsympSlip":
// Assign a value to the sideAsympSlip.
wheelDriverMeta.sideAsympSlip = float.Parse(reader.ReadElementContentAsString());
break;
case "SideAsympValue":
// Assign a value to the sideAsympValue.
wheelDriverMeta.sideAsympValue = float.Parse(reader.ReadElementContentAsString());
break;
case "SideExtremeSlip":
// Assign a value to the sideExtremeSlip.
wheelDriverMeta.sideExtremeSlip = float.Parse(reader.ReadElementContentAsString());
break;
case "SideExtremeValue":
// Assign a value to the sideExtremeValue.
wheelDriverMeta.sideExtremeValue = float.Parse(reader.ReadElementContentAsString());
break;
case "IsDriveWheel":
// Assign a value to isDriveWheel.
wheelDriverMeta.isDriveWheel = reader.ReadElementContentAsBoolean();
break;
}
}
return wheelDriverMeta;
}
/// <summary>
/// Read a RobotSensor from the given XmlReader.
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
private static RobotSensor ReadRobotSensor_3_0(XmlReader reader)
{
RobotSensor robotSensor = null;
foreach (string name in IOUtilities.AllElements(reader))
{
switch (name)
{
case "SensorType":
// Initialize the RobotSensor.
robotSensor = new RobotSensor((RobotSensorType)Enum.Parse(typeof(RobotSensorType), reader.ReadElementContentAsString()));
break;
case "SensorModule":
// Assign a value to the module.
short m = (short)reader.ReadElementContentAsInt();
break;
case "SensorPort":
// Assign a value to the port.
short s = (short)reader.ReadElementContentAsInt();
break;
case "Polynomial":
// Create a polynomial and assign it to the equation.
Polynomial e = ReadPolynomial_3_0(reader.ReadSubtree());
break;
case "UseSecondarySource":
// Assign a value to useSecondarySource.
reader.ReadElementContentAsBoolean();
break;
}
}
return robotSensor;
}
/// <summary>
/// Reads a Polynomial from the given XmlReader.
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
private static Polynomial ReadPolynomial_3_0(XmlReader reader)
{
// Initialize a list of floats.
List<float> coeff = new List<float>();
foreach (string name in IOUtilities.AllElements(reader))
{
switch (name)
{
case "Coefficient":
// Add a new coefficient to the list of floats.
coeff.Add(float.Parse(reader.ReadElementContentAsString()));
break;
}
}
// Convert the list of floats to a Polynomial.
return new Polynomial(coeff.ToArray());
}
} | 42.00444 | 141 | 0.521984 | [
"Apache-2.0"
] | HiceS/synthesis | exporters/Aardvark-Libraries/SimulatorFileIO/IO/BXDJ/BXDJReader_3_0.cs | 37,848 | C# |
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.AuditLogging.EntityFrameworkCore;
using Volo.Abp.BackgroundJobs.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.SqlServer;
using Volo.Abp.FeatureManagement.EntityFrameworkCore;
using Volo.Abp.Identity.EntityFrameworkCore;
using Volo.Abp.IdentityServer.EntityFrameworkCore;
using Volo.Abp.Modularity;
using Volo.Abp.PermissionManagement.EntityFrameworkCore;
using Volo.Abp.SettingManagement.EntityFrameworkCore;
using Volo.Abp.TenantManagement.EntityFrameworkCore;
namespace PDFGenius.EntityFrameworkCore
{
[DependsOn(
typeof(PDFGeniusDomainModule),
typeof(AbpIdentityEntityFrameworkCoreModule),
typeof(AbpIdentityServerEntityFrameworkCoreModule),
typeof(AbpPermissionManagementEntityFrameworkCoreModule),
typeof(AbpSettingManagementEntityFrameworkCoreModule),
typeof(AbpEntityFrameworkCoreSqlServerModule),
typeof(AbpBackgroundJobsEntityFrameworkCoreModule),
typeof(AbpAuditLoggingEntityFrameworkCoreModule),
typeof(AbpTenantManagementEntityFrameworkCoreModule),
typeof(AbpFeatureManagementEntityFrameworkCoreModule)
)]
public class PDFGeniusEntityFrameworkCoreModule : AbpModule
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
context.Services.AddAbpDbContext<PDFGeniusDbContext>(options =>
{
/* Remove "includeAllEntities: true" to create
* default repositories only for aggregate roots */
options.AddDefaultRepositories(includeAllEntities: true);
});
Configure<AbpDbContextOptions>(options =>
{
/* The main point to change your DBMS.
* See also PDFGeniusMigrationsDbContextFactory for EF Core tooling. */
options.UseSqlServer();
});
}
}
}
| 41.291667 | 87 | 0.733098 | [
"Apache-2.0"
] | edenprairie/PDFGenius | aspnet-core/src/PDFGenius.EntityFrameworkCore/EntityFrameworkCore/PDFGeniusEntityFrameworkCoreModule.cs | 1,984 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Basketee.API.DTOs.Orders
{
public class OutForDeliveryResponse : ResponseDto
{
public OutForDeliveryDto order_details { get; set; }
}
}
| 19.533333 | 60 | 0.720137 | [
"MIT"
] | eworkart/Basketee | Basketee.API.ServicesLib/DTOs/Orders/OutForDeliveryResponse.cs | 295 | C# |
using Newtonsoft.Json;
namespace ExchangeSharp
{
public sealed partial class ExchangeNDAXAPI
{
class SendOrderResponse
{
[JsonProperty("errormsg")]
public string ErrorMsg { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("OrderId")]
public int OrderId { get; set; }
}
}
}
| 18.777778 | 44 | 0.683432 | [
"MIT"
] | AllTerrainDeveloper/ExchangeSharp | src/ExchangeSharp/API/Exchanges/NDAX/Models/SendOrderResponse.cs | 338 | C# |
using DSharp4Webhook.Core.Embed.Subtypes;
namespace DSharp4Webhook.Core.Embed
{
/// <summary>
/// Author of embed.
/// </summary>
public interface IEmbedAuthor : IIconable, IUrlable
{
/// <summary>
/// Name of author.
/// </summary>
public string? Name { get; }
}
}
| 20.6875 | 55 | 0.555891 | [
"MIT"
] | iRebbok/DSharp4Webhook | src/DSharp4Webhook/Core/Interfaces/Discord/Embed/IEmbedAuthor.cs | 331 | C# |
// <auto-generated />
namespace JoinRpg.Dal.Impl.Migrations
{
using System.CodeDom.Compiler;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
using System.Resources;
[GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")]
public sealed partial class ProjectPlugins : IMigrationMetadata
{
private readonly ResourceManager Resources = new ResourceManager(typeof(ProjectPlugins));
string IMigrationMetadata.Id
{
get { return "201606092055571_ProjectPlugins"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return Resources.GetString("Target"); }
}
}
}
| 27.666667 | 97 | 0.624096 | [
"MIT"
] | FulcrumVlsM/joinrpg-net | JoinRpg.Dal.Impl/Migrations/201606092055571_ProjectPlugins.Designer.cs | 830 | C# |
using System;
using Microsoft.Extensions.CommandLineUtils;
namespace Company.ConsoleApplication1.Hello
{
/// Example of a root command. Typically just prints the list of the nested commands
internal class RootCommand : IRootCommand
{
private readonly IHelloCommand[] _commands;
public RootCommand(IHelloCommand[] commands)
{
_commands = commands;
}
private int Run(CommandLineApplication command)
{
command.ShowHelp();
return 0;
}
public string Name => "hello";
public Action<CommandLineApplication> Configure() => command =>
{
command.Description = "A group of commands that say hello";
command.HelpOption("-?|-h|--help");
command.OnExecute(() => Run(command));
foreach(var nestedCommand in _commands)
{
command.Command(nestedCommand.Name, nestedCommand.Configure());
}
};
}
} | 29.828571 | 89 | 0.57567 | [
"MIT"
] | lazyWombat/console-command-template | src/Content/Hello/RootCommand.cs | 1,044 | C# |
/**
* Copyright 2018 IBM Corp. 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.
* 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 Newtonsoft.Json;
namespace IBM.WatsonDeveloperCloud.NaturalLanguageUnderstanding.v1.Model
{
/// <summary>
/// Whether or not to analyze content for general concepts that are referenced or alluded to.
/// </summary>
public class ConceptsOptions : BaseModel
{
/// <summary>
/// Maximum number of concepts to return.
/// </summary>
/// <value>
/// Maximum number of concepts to return.
/// </value>
[JsonProperty("limit", NullValueHandling = NullValueHandling.Ignore)]
public long? Limit { get; set; }
}
}
| 31.684211 | 97 | 0.686047 | [
"Apache-2.0"
] | johnpisg/dotnet-standard-sdk | src/IBM.WatsonDeveloperCloud.NaturalLanguageUnderstanding.v1/Model/ConceptsOptions.cs | 1,204 | C# |
using System.Collections.Generic;
using System.Linq;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Tests.Loggers;
using Xunit;
using Xunit.Abstractions;
namespace BenchmarkDotNet.IntegrationTests
{
public class PriorityTests : BenchmarkTestExecutor
{
public PriorityTests(ITestOutputHelper output) : base(output) { }
[Fact]
public void ParamsSupportPropertyWithPublicSetter()
{
var logger = new OutputLogger(Output);
var config = CreateSimpleConfig(logger);
var summary = CanExecute<PriorityBenchmark>(config);
var columns = summary.Table.Columns;
var aColumn = columns.First(col => col.Header == "A");
var bColumn = columns.First(col => col.Header == "b");
var cColumn = columns.First(col => col.Header == "c");
var dColumn = columns.First(col => col.Header == "d");
var eColumn = columns.First(col => col.Header == "E");
var fColumn = columns.First(col => col.Header == "F");
Assert.NotNull(aColumn);
Assert.NotNull(bColumn);
Assert.NotNull(cColumn);
Assert.NotNull(dColumn);
Assert.NotNull(eColumn);
Assert.NotNull(fColumn);
Assert.True(aColumn.OriginalColumn.PriorityInCategory == -100);
Assert.True(bColumn.OriginalColumn.PriorityInCategory == -10);
Assert.True(cColumn.OriginalColumn.PriorityInCategory == 0);
Assert.True(dColumn.OriginalColumn.PriorityInCategory == 0);
Assert.True(eColumn.OriginalColumn.PriorityInCategory == 10);
Assert.True(fColumn.OriginalColumn.PriorityInCategory == 50);
Assert.True(aColumn.Index < bColumn.Index);
Assert.True(bColumn.Index < cColumn.Index);
Assert.True(cColumn.Index < dColumn.Index);
Assert.True(dColumn.Index < eColumn.Index);
Assert.True(eColumn.Index < fColumn.Index);
}
public class PriorityBenchmark
{
[Params(100, Priority = -100)]
public int A { get; set; }
[ParamsSource(nameof(NumberParams), Priority = 50)]
public int F { get; set; }
[ParamsAllValues(Priority = 10)]
public bool E;
[Arguments(5, Priority = -10)]
[Arguments(10)]
[Arguments(20)]
[Benchmark]
public int OneArgument(int b) => E ? A + b : F;
[Benchmark]
[ArgumentsSource(nameof(NumberArguments))]
public int ManyArguments(int c, int d) => E ? A + c + d : F;
public IEnumerable<object[]> NumberArguments()
{
yield return new object[] { 1, 2 };
}
public IEnumerable<int> NumberParams => new int[]
{
50
};
}
}
} | 35.682927 | 75 | 0.574504 | [
"MIT"
] | AndyAyersMS/BenchmarkDotNet | tests/BenchmarkDotNet.IntegrationTests/PriorityTests.cs | 2,928 | C# |
namespace Fortnox.SDK.Search
{
public class TermsOfPaymentSearch : BaseSearch
{
[SearchParameter("sortby")]
public Sort.By.TermsOfPayment? SortBy { get; set; }
[SearchParameter("filter")]
public Filter.TermsOfPayment? FilterBy { get; set; }
}
}
| 19.142857 | 54 | 0.69403 | [
"Unlicense",
"MIT"
] | LukasLonnroth/csharp-api-sdk | FortnoxSDK/Search/TermsOfPaymentSearch.cs | 268 | C# |
using System.Collections.Generic;
namespace EplanDevice
{
/// <summary>
/// Технологическое устройство - дискретный выход.
/// </summary>
sealed public class DO : IODevice
{
public DO(string name, string eplanName, string description,
int deviceNumber, string objectName, int objectNumber) : base(name,
eplanName, description, deviceNumber, objectName, objectNumber)
{
dSubType = DeviceSubType.NONE;
dType = DeviceType.DO;
}
public override string SetSubType(string subtype)
{
base.SetSubType(subtype);
string errStr = string.Empty;
switch (subtype)
{
case "DO_VIRT":
break;
case "DO":
case "":
dSubType = DeviceSubType.DO;
DO.Add(new IOChannel("DO", -1, -1, -1, ""));
break;
default:
errStr = string.Format("\"{0}\" - неверный тип" +
" (пустая строка, DO, DO_VIRT).\n",
Name);
break;
}
return errStr;
}
public override string GetDeviceSubTypeStr(DeviceType dt,
DeviceSubType dst)
{
switch (dt)
{
case DeviceType.DO:
switch (dst)
{
case DeviceSubType.DO:
return "DO";
case DeviceSubType.DO_VIRT:
return "DO_VIRT";
}
break;
}
return string.Empty;
}
public override Dictionary<string, int> GetDeviceProperties(
DeviceType dt, DeviceSubType dst)
{
switch (dt)
{
case DeviceType.DO:
return new Dictionary<string, int>()
{
{Tag.ST, 1},
{Tag.M, 1},
};
}
return null;
}
}
}
| 27.148148 | 79 | 0.420646 | [
"MIT"
] | KirillGutyrchik/EasyEPLANner | src/Device/IODevices/DO.cs | 2,264 | C# |
using AndreasReitberger.Enum;
using Newtonsoft.Json;
using System;
namespace AndreasReitberger.Models
{
public partial class KlipperStatusHeaterBed
{
#region Properties
[JsonProperty("temperature")]
public double? Temperature { get; set; }
[JsonProperty("target")]
public double? Target { get; set; }
[JsonProperty("power")]
public double? Power { get; set; }
[JsonIgnore]
public bool CanUpdateTarget { get; set; } = false;
[JsonIgnore]
public KlipperToolState State { get => GetCurrentState(); }
#endregion
#region Methods
KlipperToolState GetCurrentState()
{
try
{
if (Target == null || Temperature == null)
return KlipperToolState.Idle;
return Target <= 0
? KlipperToolState.Idle
: Target > Temperature && Math.Abs(Convert.ToDouble(Target - Temperature)) > 2 ? KlipperToolState.Heating : KlipperToolState.Ready;
}
catch (Exception)
{
return KlipperToolState.Error;
}
}
#endregion
#region Overrides
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
#endregion
}
}
| 25.703704 | 151 | 0.54755 | [
"Apache-2.0"
] | AndreasReitberger/KlipperRestApiSharp | source/KlipperSharpWebApi/KlipperSharpWebApi/Models/PrinterStatus/KlipperStatusHeaterBed.cs | 1,390 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Capstone.Models
{
public class Park
{
public int ParkId { get; set; }
public string ParkName { get; set; }
public string Location { get; set; }
public DateTime EstablishDate { get; set; }
public int Area { get; set; }
public int AnnualVisitorCount { get; set; }
public string Description { get; set; }
}
}
| 26.05 | 52 | 0.614203 | [
"MIT"
] | NateOsterfeld/National-Parks-Reservation-CLI | Capstone/Models/Park.cs | 523 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.ViewManagement;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace Fibaro_Cortana_Voice_Commands
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
ApplicationView.PreferredLaunchViewSize = new Size(1000, 1000);
ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.PreferredLaunchViewSize;
}
private void Button_Click(System.Object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["TurnOnMainLights"].DynamicInvoke();
}
private void LightsOffClick(object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["TurnOffMainLights"].DynamicInvoke();
}
private void dimhigh(object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["IncreaseMainLights"].DynamicInvoke();
}
private void dimlow(object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["DecreaseMainLights"].DynamicInvoke();
}
private void mainlow(object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["MainLightsLow"].DynamicInvoke();
}
private void mainmed(object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["MainLightsMedium"].DynamicInvoke();
}
private void dinon(object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["TurnOnDinningLights"].DynamicInvoke();
}
private void dinoff(object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["TurnOffDinningLights"].DynamicInvoke();
}
private void dinhigh(object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["IncreaseDinningLights"].DynamicInvoke();
}
private void dinlow(object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["DecreaseDinningLights"].DynamicInvoke();
}
private void dinninglow(object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["DinningLightsLow"].DynamicInvoke();
}
private void dinningmed(object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["DinningLightsMedium"].DynamicInvoke();
}
private void balcon(System.Object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["TurnOnBalconyLights"].DynamicInvoke();
}
private void balcoff(System.Object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["TurnOffBalconyLights"].DynamicInvoke();
}
private void balhigh(System.Object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["IncreaseBalconyLights"].DynamicInvoke();
}
private void balow(System.Object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["DecreaseBalconyLights"].DynamicInvoke();
}
private void balconylow(System.Object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["BalconyLightsLow"].DynamicInvoke();
}
private void balconymedium(System.Object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["BalconyMainMedium"].DynamicInvoke();
}
private void hallon(object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["TurnOnHallLights"].DynamicInvoke();
}
private void halloff(object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["TurnOffHallLights"].DynamicInvoke();
}
private void halhigh(object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["IncreaseHallLights"].DynamicInvoke();
}
private void hallow(object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["DecreaseHallLights"].DynamicInvoke();
}
private void hallwaylow(object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["HallLightsLow"].DynamicInvoke();
}
private void hallwaymedium(object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["HallLightsMedium"].DynamicInvoke();
}
private void sideon(object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["TurnOnSideLight"].DynamicInvoke();
}
private void sideoff(object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["TurnOffSideLight"].DynamicInvoke();
}
private void vison(object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["TurnOnVisitorLights"].DynamicInvoke();
}
private void visoff(object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["TurnOffVisitorLights"].DynamicInvoke();
}
private void vishigh(object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["IncreaseVisitorLights"].DynamicInvoke();
}
private void vislow(object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["DecreaseVisitorLights"].DynamicInvoke();
}
private void visitorlor(object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["VisitorLightsLow"].DynamicInvoke();
}
private void visitormedium(object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["VisitorLightsMedium"].DynamicInvoke();
}
private void bathon(System.Object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["TurnOnBathroomLights"].DynamicInvoke();
}
private void bathoff(System.Object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["TurnOffBathroomLights"].DynamicInvoke();
}
private void bathihg(System.Object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["IncreaseBathroomLights"].DynamicInvoke();
}
private void bathlow(System.Object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["DecreaseBathroomLights"].DynamicInvoke();
}
private void bathroomlow(System.Object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["BathroomLightsLow"].DynamicInvoke();
}
private void bathroomedium(System.Object sender, RoutedEventArgs e)
{
CortanaFibaroVoice.vcdLookup["BathroomLightsMedium"].DynamicInvoke();
}
private void SettingsPage1(object sender, RoutedEventArgs e)
{
//Open Popup
settingsPopup.IsOpen = true;
}
}
}
| 32.181435 | 112 | 0.649272 | [
"MIT"
] | evkapsal/Fibaro-Cortana-Voice-Commands | Fibaro Cortana Voice Commands/MainPage.xaml.cs | 7,629 | C# |
using ECUniqueChar;
using System;
using Xunit;
namespace ECUniqueChar_unittesting
{
public class UnitTest1
{
//test happy case unique
[Fact]
public void TestHappyPass()
{
string testString1 = "abc";
bool testAnswer1 = Program.UniqueChara(testString1);
Assert.True(testAnswer1);
}
//test happy fail that there is duplicate
[Fact]
public void TestHappyFail()
{
string testString2 = "abcabc";
bool testAnswer2 = Program.UniqueChara(testString2);
Assert.False(testAnswer2);
}
//test caps
[Fact]
public void TestCaps()
{
string testString3 = "Aa";
bool testAnswer3 = Program.UniqueChara(testString3);
Assert.False(testAnswer3);
}
//test empty string
[Fact]
public void TestEmptyString()
{
string testString4 = "";
bool testAnswer4 = Program.UniqueChara(testString4);
Assert.False(testAnswer4);
}
}
}
| 22.38 | 64 | 0.547811 | [
"MIT"
] | JulieLy8619/Data-Structures-and-Algorithms | Challenges/ECUniqueChar/ECUniqueChar-unittesting/UnitTest1.cs | 1,119 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the kinesis-video-media-2017-09-30.normal.json service model.
*/
using System;
using System.Net;
using Amazon.Runtime;
namespace Amazon.KinesisVideoMedia.Model
{
///<summary>
/// KinesisVideoMedia exception
/// </summary>
#if !PCL && !NETSTANDARD
[Serializable]
#endif
public class ConnectionLimitExceededException : AmazonKinesisVideoMediaException
{
/// <summary>
/// Constructs a new ConnectionLimitExceededException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public ConnectionLimitExceededException(string message)
: base(message) {}
/// <summary>
/// Construct instance of ConnectionLimitExceededException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public ConnectionLimitExceededException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of ConnectionLimitExceededException
/// </summary>
/// <param name="innerException"></param>
public ConnectionLimitExceededException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of ConnectionLimitExceededException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public ConnectionLimitExceededException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of ConnectionLimitExceededException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public ConnectionLimitExceededException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !PCL && !NETSTANDARD
/// <summary>
/// Constructs a new instance of the ConnectionLimitExceededException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected ConnectionLimitExceededException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
#endif
}
} | 44.443299 | 178 | 0.65994 | [
"Apache-2.0"
] | FoxBearBear/aws-sdk-net | sdk/src/Services/KinesisVideoMedia/Generated/Model/ConnectionLimitExceededException.cs | 4,311 | C# |
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(IzdavanjeFaktura.Startup))]
namespace IzdavanjeFaktura
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
| 18.8 | 66 | 0.663121 | [
"MIT"
] | jkvakaric/IzdavanjeFaktura | IzdavanjeFaktura/Startup.cs | 284 | C# |
using Google.Apis.Sheets.v4.Data;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace BusinessLogic
{
public interface ISheetsHandler
{
Task<bool> AppendAsync(ValueRange values, string range);
Task<bool> CopyTemplateAsync(string sheetName);
Task<bool> DeleteAsync(List<string> cellsToDelete);
Task<bool> DeleteSheetAsync(string sheetName);
Task<bool> NewSheetAsync(string sheetName);
Task<IList<IList<object>>> ReadAsync(string readRange);
Task<List<string>> SheetsList();
Task<bool> WriteAsync(string rangeLow, string rangeHigh, IList<IList<object>> insertStrings);
}
} | 37.222222 | 101 | 0.714925 | [
"MIT"
] | Malia-Labor/TestBot | BusinessLogic/ISheetsHandler.cs | 672 | C# |
using Justin.AspNetCore.ModAuthPubTkt;
using Microsoft.AspNetCore.Builder;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.Builder
{
public static class BuilderExtensions
{
public static IApplicationBuilder UseModAuthPubTkt(this IApplicationBuilder builder, ModAuthPubTktAuthenticationOptions options)
{
return builder.UseMiddleware<ModAuthPubTktMiddleware>(Options.Create(options));
}
}
}
| 29.263158 | 136 | 0.776978 | [
"MIT"
] | jusbuc2k/dotnet_mod_auth_pubtkt | src/Justin.AspNetCore.ModAuthPubTkt/BuilderExtensions.cs | 558 | C# |
using Gedcom4Sharp.Models.Gedcom.Base;
using Gedcom4Sharp.Models.Gedcom.Enums;
namespace Gedcom4Sharp.Models.Gedcom
{
public class IndividualEvent : AbstractEvent
{
public FamilyChild Family { get; set; }
public IndividualEventType Type { get; set; }
}
} | 25.818182 | 53 | 0.714789 | [
"MIT"
] | ThomasPe/Gedcom4Sharp | Gedcom4Sharp/Models/Gedcom/IndividualEvent.cs | 286 | C# |
#region Licence
/* The MIT License (MIT)
Copyright © 2014 Ian Cooper <ian_hammond_cooper@yahoo.co.uk>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#endregion
using System;
using System.Linq;
using Paramore.Brighter.Logging;
using Paramore.Brighter.MessagingGateway.RESTMS.Exceptions;
using Paramore.Brighter.MessagingGateway.RESTMS.Model;
namespace Paramore.Brighter.MessagingGateway.RESTMS
{
internal class Pipe
{
private static readonly Lazy<ILog> _logger = new Lazy<ILog>(LogProvider.For<Pipe>);
private readonly RestMSMessageGateway _gateway;
private readonly Join _join;
public string PipeUri { get; private set; }
public Pipe(RestMsMessageConsumer gateway, Feed feed)
{
_gateway = gateway;
_join = new Join(gateway, feed);
}
public void EnsurePipeExists(string pipeTitle, string routingKey, RestMSDomain domain)
{
_logger.Value.DebugFormat("Checking for existence of the pipe {0} on the RestMS server: {1}", pipeTitle, _gateway.Configuration.RestMS.Uri.AbsoluteUri);
var pipeExists = PipeExists(pipeTitle, domain);
if (!pipeExists)
{
domain = CreatePipe(domain.Href, pipeTitle);
if (domain == null || !domain.Pipes.Any(dp => dp.Title == pipeTitle))
{
throw new RestMSClientException(string.Format("Unable to create pipe {0} on the default domain; see log for errors", pipeTitle));
}
_join.CreateJoin(domain.Pipes.First(p => p.Title == pipeTitle).Href, routingKey);
}
PipeUri = domain.Pipes.First(dp => dp.Title == pipeTitle).Href;
}
public RestMSPipe GetPipe()
{
/*TODO: Optimize this by using a repository approach with the repository checking for modification
through etag and serving existing version if not modified and grabbing new version if changed*/
_logger.Value.DebugFormat("Getting the pipe from the RestMS server: {0}", PipeUri);
var client = _gateway.Client();
try
{
var response = client.GetAsync(PipeUri).Result;
response.EnsureSuccessStatusCode();
return _gateway.ParseResponse<RestMSPipe>(response);
}
catch (AggregateException ae)
{
foreach (var exception in ae.Flatten().InnerExceptions)
{
_logger.Value.ErrorFormat("Threw exception getting Pipe {0} from RestMS Server {1}", PipeUri, exception.Message);
}
throw new RestMSClientException("Error retrieving the domain from the RestMS server, see log for details");
}
}
private RestMSDomain CreatePipe(string domainUri, string title)
{
_logger.Value.DebugFormat("Creating the pipe {0} on the RestMS server: {1}", title, _gateway.Configuration.RestMS.Uri.AbsoluteUri);
var client = _gateway.Client();
try
{
var response = client.SendAsync(_gateway.CreateRequest(
domainUri, _gateway.CreateEntityBody(
new RestMSPipeNew
{
Type = "Default",
Title = title
})
)
)
.Result;
response.EnsureSuccessStatusCode();
return _gateway.ParseResponse<RestMSDomain>(response);
}
catch (AggregateException ae)
{
foreach (var exception in ae.Flatten().InnerExceptions)
{
_logger.Value.ErrorFormat("Threw exception adding Pipe {0} to RestMS Server {1}", title, exception.Message);
}
throw new RestMSClientException(string.Format("Error adding the Feed {0} to the RestMS server, see log for details", title));
}
}
private bool PipeExists(string pipeTitle, RestMSDomain domain)
{
return domain?.Pipes != null && domain.Pipes.Any(p => p.Title == pipeTitle);
}
}
}
| 40.523077 | 164 | 0.624525 | [
"MIT"
] | DevJonny/Brighter | src/Paramore.Brighter.MessagingGateway.RESTMS/Pipe.cs | 5,279 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using Moq;
using NUnit.Framework;
namespace Litle.Sdk.Test.Unit
{
[TestFixture]
internal class TestLitleOnline
{
private LitleOnline litle;
private IDictionary<string, StringBuilder> _memoryStreams;
[TestFixtureSetUp]
public void SetUpLitle()
{
_memoryStreams = new Dictionary<string, StringBuilder>();
litle = new LitleOnline(_memoryStreams);
}
[Test]
public void TestAuth()
{
var authorization = new authorization();
authorization.reportGroup = "Planets";
authorization.orderId = "12344";
authorization.amount = 106;
authorization.orderSource = orderSourceType.ecommerce;
var card = new cardType();
card.type = methodOfPaymentTypeEnum.VI;
card.number = "4100000000000002";
card.expDate = "1210";
authorization.card = card;
var mock = new Mock<Communications>(_memoryStreams);
mock.Setup(
Communications =>
Communications.HttpPost(
It.IsRegex(
".*<litleOnlineRequest.*<authorization.*<card>.*<number>4100000000000002</number>.*</card>.*</authorization>.*",
RegexOptions.Singleline), It.IsAny<Dictionary<string, string>>()))
.Returns(
"<litleOnlineResponse version='8.10' response='0' message='Valid Format' xmlns='http://www.litle.com/schema'><authorizationResponse><litleTxnId>123</litleTxnId></authorizationResponse></litleOnlineResponse>");
var mockedCommunication = mock.Object;
litle.setCommunication(mockedCommunication);
var authorize = litle.Authorize(authorization);
Assert.AreEqual(123, authorize.litleTxnId);
}
[Test]
public void testAuthReversal()
{
var authreversal = new authReversal();
authreversal.litleTxnId = 12345678000;
authreversal.amount = 106;
authreversal.payPalNotes = "Notes";
var mock = new Mock<Communications>(_memoryStreams);
mock.Setup(
Communications =>
Communications.HttpPost(
It.IsRegex(
".*?<litleOnlineRequest.*?<authReversal.*?<litleTxnId>12345678000</litleTxnId>.*?</authReversal>.*?",
RegexOptions.Singleline), It.IsAny<Dictionary<string, string>>()))
.Returns(
"<litleOnlineResponse version='8.10' response='0' message='Valid Format' xmlns='http://www.litle.com/schema'><authReversalResponse><litleTxnId>123</litleTxnId></authReversalResponse></litleOnlineResponse>");
var mockedCommunication = mock.Object;
litle.setCommunication(mockedCommunication);
var authreversalresponse = litle.AuthReversal(authreversal);
Assert.AreEqual(123, authreversalresponse.litleTxnId);
}
[Test]
public void testCapture()
{
var caputure = new capture();
caputure.litleTxnId = 123456000;
caputure.amount = 106;
caputure.payPalNotes = "Notes";
var mock = new Mock<Communications>(_memoryStreams);
mock.Setup(
Communications =>
Communications.HttpPost(
It.IsRegex(
".*?<litleOnlineRequest.*?<capture.*?<litleTxnId>123456000</litleTxnId>.*?</capture>.*?",
RegexOptions.Singleline), It.IsAny<Dictionary<string, string>>()))
.Returns(
"<litleOnlineResponse version='8.10' response='0' message='Valid Format' xmlns='http://www.litle.com/schema'><captureResponse><litleTxnId>123</litleTxnId></captureResponse></litleOnlineResponse>");
var mockedCommunication = mock.Object;
litle.setCommunication(mockedCommunication);
var captureresponse = litle.Capture(caputure);
Assert.AreEqual(123, captureresponse.litleTxnId);
}
[Test]
public void testCaptureGivenAuth()
{
var capturegivenauth = new captureGivenAuth();
capturegivenauth.orderId = "12344";
capturegivenauth.amount = 106;
var authinfo = new authInformation();
authinfo.authDate = new DateTime(2002, 10, 9);
authinfo.authCode = "543216";
authinfo.authAmount = 12345;
capturegivenauth.authInformation = authinfo;
capturegivenauth.orderSource = orderSourceType.ecommerce;
var card = new cardType();
card.type = methodOfPaymentTypeEnum.VI;
card.number = "4100000000000001";
card.expDate = "1210";
capturegivenauth.card = card;
var mock = new Mock<Communications>(_memoryStreams);
mock.Setup(
Communications =>
Communications.HttpPost(
It.IsRegex(
".*?<litleOnlineRequest.*?<captureGivenAuth.*?<card>.*?<number>4100000000000001</number>.*?</card>.*?</captureGivenAuth>.*?",
RegexOptions.Singleline), It.IsAny<Dictionary<string, string>>()))
.Returns(
"<litleOnlineResponse version='8.10' response='0' message='Valid Format' xmlns='http://www.litle.com/schema'><captureGivenAuthResponse><litleTxnId>123</litleTxnId></captureGivenAuthResponse></litleOnlineResponse>");
var mockedCommunication = mock.Object;
litle.setCommunication(mockedCommunication);
var caputregivenauthresponse = litle.CaptureGivenAuth(capturegivenauth);
Assert.AreEqual(123, caputregivenauthresponse.litleTxnId);
}
[Test]
public void testCredit()
{
var credit = new credit();
credit.orderId = "12344";
credit.amount = 106;
credit.orderSource = orderSourceType.ecommerce;
var card = new cardType();
card.type = methodOfPaymentTypeEnum.VI;
card.number = "4100000000000001";
card.expDate = "1210";
credit.card = card;
var mock = new Mock<Communications>(_memoryStreams);
mock.Setup(
Communications =>
Communications.HttpPost(
It.IsRegex(
".*?<litleOnlineRequest.*?<credit.*?<card>.*?<number>4100000000000001</number>.*?</card>.*?</credit>.*?",
RegexOptions.Singleline), It.IsAny<Dictionary<string, string>>()))
.Returns(
"<litleOnlineResponse version='8.10' response='0' message='Valid Format' xmlns='http://www.litle.com/schema'><creditResponse><litleTxnId>123</litleTxnId></creditResponse></litleOnlineResponse>");
var mockedCommunication = mock.Object;
litle.setCommunication(mockedCommunication);
var creditresponse = litle.Credit(credit);
Assert.AreEqual(123, creditresponse.litleTxnId);
}
[Test]
public void testEcheckCredit()
{
var echeckcredit = new echeckCredit();
echeckcredit.amount = 12;
echeckcredit.litleTxnId = 123456789101112;
var mock = new Mock<Communications>(_memoryStreams);
mock.Setup(
Communications =>
Communications.HttpPost(
It.IsRegex(
".*?<litleOnlineRequest.*?<echeckCredit.*?<litleTxnId>123456789101112</litleTxnId>.*?</echeckCredit>.*?",
RegexOptions.Singleline), It.IsAny<Dictionary<string, string>>()))
.Returns(
"<litleOnlineResponse version='8.10' response='0' message='Valid Format' xmlns='http://www.litle.com/schema'><echeckCreditResponse><litleTxnId>123</litleTxnId></echeckCreditResponse></litleOnlineResponse>");
var mockedCommunication = mock.Object;
litle.setCommunication(mockedCommunication);
var echeckcreditresponse = litle.EcheckCredit(echeckcredit);
Assert.AreEqual(123, echeckcreditresponse.litleTxnId);
}
[Test]
public void testEcheckRedeposit()
{
var echeckredeposit = new echeckRedeposit();
echeckredeposit.litleTxnId = 123456;
var mock = new Mock<Communications>(_memoryStreams);
mock.Setup(
Communications =>
Communications.HttpPost(
It.IsRegex(
".*?<litleOnlineRequest.*?<echeckRedeposit.*?<litleTxnId>123456</litleTxnId>.*?</echeckRedeposit>.*?",
RegexOptions.Singleline), It.IsAny<Dictionary<string, string>>()))
.Returns(
"<litleOnlineResponse version='8.10' response='0' message='Valid Format' xmlns='http://www.litle.com/schema'><echeckRedepositResponse><litleTxnId>123</litleTxnId></echeckRedepositResponse></litleOnlineResponse>");
var mockedCommunication = mock.Object;
litle.setCommunication(mockedCommunication);
var echeckredepositresponse = litle.EcheckRedeposit(echeckredeposit);
Assert.AreEqual(123, echeckredepositresponse.litleTxnId);
}
[Test]
public void testEcheckSale()
{
var echecksale = new echeckSale();
echecksale.orderId = "12345";
echecksale.amount = 123456;
echecksale.orderSource = orderSourceType.ecommerce;
var echeck = new echeckType();
echeck.accType = echeckAccountTypeEnum.Checking;
echeck.accNum = "12345657890";
echeck.routingNum = "123456789";
echeck.checkNum = "123455";
echecksale.echeck = echeck;
var contact = new contact();
contact.name = "Bob";
contact.city = "lowell";
contact.state = "MA";
contact.email = "litle.com";
echecksale.billToAddress = contact;
var mock = new Mock<Communications>(_memoryStreams);
mock.Setup(
Communications =>
Communications.HttpPost(
It.IsRegex(
".*?<litleOnlineRequest.*?<echeckSale.*?<echeck>.*?<accNum>12345657890</accNum>.*?</echeck>.*?</echeckSale>.*?",
RegexOptions.Singleline), It.IsAny<Dictionary<string, string>>()))
.Returns(
"<litleOnlineResponse version='8.10' response='0' message='Valid Format' xmlns='http://www.litle.com/schema'><echeckSalesResponse><litleTxnId>123</litleTxnId></echeckSalesResponse></litleOnlineResponse>");
var mockedCommunication = mock.Object;
litle.setCommunication(mockedCommunication);
var echecksaleresponse = litle.EcheckSale(echecksale);
Assert.AreEqual(123, echecksaleresponse.litleTxnId);
}
[Test]
public void testEcheckVerification()
{
var echeckverification = new echeckVerification();
echeckverification.orderId = "12345";
echeckverification.amount = 123456;
echeckverification.orderSource = orderSourceType.ecommerce;
var echeck = new echeckType();
echeck.accType = echeckAccountTypeEnum.Checking;
echeck.accNum = "12345657890";
echeck.routingNum = "123456789";
echeck.checkNum = "123455";
echeckverification.echeck = echeck;
var contact = new contact();
contact.name = "Bob";
contact.city = "lowell";
contact.state = "MA";
contact.email = "litle.com";
echeckverification.billToAddress = contact;
var mock = new Mock<Communications>(_memoryStreams);
mock.Setup(
Communications =>
Communications.HttpPost(
It.IsRegex(
".*?<litleOnlineRequest.*?<echeckVerification.*?<echeck>.*?<accNum>12345657890</accNum>.*?</echeck>.*?</echeckVerification>.*?",
RegexOptions.Singleline), It.IsAny<Dictionary<string, string>>()))
.Returns(
"<litleOnlineResponse version='8.10' response='0' message='Valid Format' xmlns='http://www.litle.com/schema'><echeckVerificationResponse><litleTxnId>123</litleTxnId></echeckVerificationResponse></litleOnlineResponse>");
var mockedCommunication = mock.Object;
litle.setCommunication(mockedCommunication);
var echeckverificaitonresponse = litle.EcheckVerification(echeckverification);
Assert.AreEqual(123, echeckverificaitonresponse.litleTxnId);
}
[Test]
public void testForceCapture()
{
var forcecapture = new forceCapture();
forcecapture.orderId = "12344";
forcecapture.amount = 106;
forcecapture.orderSource = orderSourceType.ecommerce;
var card = new cardType();
card.type = methodOfPaymentTypeEnum.VI;
card.number = "4100000000000001";
card.expDate = "1210";
forcecapture.card = card;
var mock = new Mock<Communications>(_memoryStreams);
mock.Setup(
Communications =>
Communications.HttpPost(
It.IsRegex(
".*?<litleOnlineRequest.*?<forceCapture.*?<card>.*?<number>4100000000000001</number>.*?</card>.*?</forceCapture>.*?",
RegexOptions.Singleline), It.IsAny<Dictionary<string, string>>()))
.Returns(
"<litleOnlineResponse version='8.10' response='0' message='Valid Format' xmlns='http://www.litle.com/schema'><forceCaptureResponse><litleTxnId>123</litleTxnId></forceCaptureResponse></litleOnlineResponse>");
var mockedCommunication = mock.Object;
litle.setCommunication(mockedCommunication);
var forcecaptureresponse = litle.ForceCapture(forcecapture);
Assert.AreEqual(123, forcecaptureresponse.litleTxnId);
}
[Test]
public void testSale()
{
var sale = new sale();
sale.orderId = "12344";
sale.amount = 106;
sale.orderSource = orderSourceType.ecommerce;
var card = new cardType();
card.type = methodOfPaymentTypeEnum.VI;
card.number = "4100000000000002";
card.expDate = "1210";
sale.card = card;
var mock = new Mock<Communications>(_memoryStreams);
mock.Setup(
Communications =>
Communications.HttpPost(
It.IsRegex(
".*?<litleOnlineRequest.*?<sale.*?<card>.*?<number>4100000000000002</number>.*?</card>.*?</sale>.*?",
RegexOptions.Singleline), It.IsAny<Dictionary<string, string>>()))
.Returns(
"<litleOnlineResponse version='8.10' response='0' message='Valid Format' xmlns='http://www.litle.com/schema'><saleResponse><litleTxnId>123</litleTxnId></saleResponse></litleOnlineResponse>");
var mockedCommunication = mock.Object;
litle.setCommunication(mockedCommunication);
var saleresponse = litle.Sale(sale);
Assert.AreEqual(123, saleresponse.litleTxnId);
}
[Test]
public void testToken()
{
var token = new registerTokenRequestType();
token.orderId = "12344";
token.accountNumber = "1233456789103801";
var mock = new Mock<Communications>(_memoryStreams);
mock.Setup(
Communications =>
Communications.HttpPost(
It.IsRegex(
".*?<litleOnlineRequest.*?<registerTokenRequest.*?<accountNumber>1233456789103801</accountNumber>.*?</registerTokenRequest>.*?",
RegexOptions.Singleline), It.IsAny<Dictionary<string, string>>()))
.Returns(
"<litleOnlineResponse version='8.10' response='0' message='Valid Format' xmlns='http://www.litle.com/schema'><registerTokenResponse><litleTxnId>123</litleTxnId></registerTokenResponse></litleOnlineResponse>");
var mockedCommunication = mock.Object;
litle.setCommunication(mockedCommunication);
var registertokenresponse = litle.RegisterToken(token);
Assert.AreEqual(123, registertokenresponse.litleTxnId);
Assert.IsNull(registertokenresponse.type);
}
[Test]
public void testActivate()
{
var activate = new activate();
activate.orderId = "2";
activate.orderSource = orderSourceType.ecommerce;
activate.card = new cardType();
var mock = new Mock<Communications>(_memoryStreams);
mock.Setup(
Communications =>
Communications.HttpPost(
It.IsRegex(".*?<litleOnlineRequest.*?<activate.*?<orderId>2</orderId>.*?</activate>.*?",
RegexOptions.Singleline), It.IsAny<Dictionary<string, string>>()))
.Returns(
"<litleOnlineResponse version='8.21' response='0' message='Valid Format' xmlns='http://www.litle.com/schema'><activateResponse><litleTxnId>123</litleTxnId></activateResponse></litleOnlineResponse>");
var mockedCommunication = mock.Object;
litle.setCommunication(mockedCommunication);
var activateResponse = litle.Activate(activate);
Assert.AreEqual("123", activateResponse.litleTxnId);
}
[Test]
public void testDeactivate()
{
var deactivate = new deactivate();
deactivate.orderId = "2";
deactivate.orderSource = orderSourceType.ecommerce;
deactivate.card = new cardType();
var mock = new Mock<Communications>(_memoryStreams);
mock.Setup(
Communications =>
Communications.HttpPost(
It.IsRegex(".*?<litleOnlineRequest.*?<deactivate.*?<orderId>2</orderId>.*?</deactivate>.*?",
RegexOptions.Singleline), It.IsAny<Dictionary<string, string>>()))
.Returns(
"<litleOnlineResponse version='8.21' response='0' message='Valid Format' xmlns='http://www.litle.com/schema'><deactivateResponse><litleTxnId>123</litleTxnId></deactivateResponse></litleOnlineResponse>");
var mockedCommunication = mock.Object;
litle.setCommunication(mockedCommunication);
var deactivateResponse = litle.Deactivate(deactivate);
Assert.AreEqual("123", deactivateResponse.litleTxnId);
}
[Test]
public void testLoad()
{
var load = new load();
load.orderId = "2";
load.orderSource = orderSourceType.ecommerce;
load.card = new cardType();
var mock = new Mock<Communications>(_memoryStreams);
mock.Setup(
Communications =>
Communications.HttpPost(
It.IsRegex(".*?<litleOnlineRequest.*?<load.*?<orderId>2</orderId>.*?</load>.*?",
RegexOptions.Singleline), It.IsAny<Dictionary<string, string>>()))
.Returns(
"<litleOnlineResponse version='8.21' response='0' message='Valid Format' xmlns='http://www.litle.com/schema'><loadResponse><litleTxnId>123</litleTxnId></loadResponse></litleOnlineResponse>");
var mockedCommunication = mock.Object;
litle.setCommunication(mockedCommunication);
var loadResponse = litle.Load(load);
Assert.AreEqual("123", loadResponse.litleTxnId);
}
[Test]
public void testUnload()
{
var unload = new unload();
unload.orderId = "2";
unload.orderSource = orderSourceType.ecommerce;
unload.card = new cardType();
var mock = new Mock<Communications>(_memoryStreams);
mock.Setup(
Communications =>
Communications.HttpPost(
It.IsRegex(".*?<litleOnlineRequest.*?<unload.*?<orderId>2</orderId>.*?</unload>.*?",
RegexOptions.Singleline), It.IsAny<Dictionary<string, string>>()))
.Returns(
"<litleOnlineResponse version='8.21' response='0' message='Valid Format' xmlns='http://www.litle.com/schema'><unloadResponse><litleTxnId>123</litleTxnId></unloadResponse></litleOnlineResponse>");
var mockedCommunication = mock.Object;
litle.setCommunication(mockedCommunication);
var unloadResponse = litle.Unload(unload);
Assert.AreEqual("123", unloadResponse.litleTxnId);
}
[Test]
public void testBalanceInquiry()
{
var balanceInquiry = new balanceInquiry();
balanceInquiry.orderId = "2";
balanceInquiry.orderSource = orderSourceType.ecommerce;
balanceInquiry.card = new cardType();
var mock = new Mock<Communications>(_memoryStreams);
mock.Setup(
Communications =>
Communications.HttpPost(
It.IsRegex(
".*?<litleOnlineRequest.*?<balanceInquiry.*?<orderId>2</orderId>.*?</balanceInquiry>.*?",
RegexOptions.Singleline), It.IsAny<Dictionary<string, string>>()))
.Returns(
"<litleOnlineResponse version='8.21' response='0' message='Valid Format' xmlns='http://www.litle.com/schema'><balanceInquiryResponse><litleTxnId>123</litleTxnId></balanceInquiryResponse></litleOnlineResponse>");
var mockedCommunication = mock.Object;
litle.setCommunication(mockedCommunication);
var balanceInquiryResponse = litle.BalanceInquiry(balanceInquiry);
Assert.AreEqual("123", balanceInquiryResponse.litleTxnId);
}
[Test]
public void testCreatePlan()
{
var createPlan = new createPlan();
createPlan.planCode = "theCode";
var mock = new Mock<Communications>(_memoryStreams);
mock.Setup(
Communications =>
Communications.HttpPost(
It.IsRegex(
".*?<litleOnlineRequest.*?<createPlan.*?<planCode>theCode</planCode>.*?</createPlan>.*?",
RegexOptions.Singleline), It.IsAny<Dictionary<string, string>>()))
.Returns(
"<litleOnlineResponse version='8.21' response='0' message='Valid Format' xmlns='http://www.litle.com/schema'><createPlanResponse><planCode>theCode</planCode></createPlanResponse></litleOnlineResponse>");
var mockedCommunication = mock.Object;
litle.setCommunication(mockedCommunication);
var createPlanResponse = litle.CreatePlan(createPlan);
Assert.AreEqual("theCode", createPlanResponse.planCode);
}
[Test]
public void testUpdatePlan()
{
var updatePlan = new updatePlan();
updatePlan.planCode = "theCode";
var mock = new Mock<Communications>(_memoryStreams);
mock.Setup(
Communications =>
Communications.HttpPost(
It.IsRegex(
".*?<litleOnlineRequest.*?<updatePlan.*?<planCode>theCode</planCode>.*?</updatePlan>.*?",
RegexOptions.Singleline), It.IsAny<Dictionary<string, string>>()))
.Returns(
"<litleOnlineResponse version='8.21' response='0' message='Valid Format' xmlns='http://www.litle.com/schema'><updatePlanResponse><planCode>theCode</planCode></updatePlanResponse></litleOnlineResponse>");
var mockedCommunication = mock.Object;
litle.setCommunication(mockedCommunication);
var updatePlanResponse = litle.UpdatePlan(updatePlan);
Assert.AreEqual("theCode", updatePlanResponse.planCode);
}
[Test]
public void testLitleOnlineException()
{
var authorization = new authorization();
authorization.reportGroup = "Planets";
authorization.orderId = "12344";
authorization.amount = 106;
authorization.orderSource = orderSourceType.ecommerce;
var card = new cardType();
card.type = methodOfPaymentTypeEnum.VI;
card.number = "4100000000000002";
card.expDate = "1210";
authorization.card = card;
var mock = new Mock<Communications>(_memoryStreams);
mock.Setup(
Communications =>
Communications.HttpPost(
It.IsRegex(
".*?<litleOnlineRequest.*?<authorization.*?<card>.*?<number>4100000000000002</number>.*?</card>.*?</authorization>.*?",
RegexOptions.Singleline), It.IsAny<Dictionary<string, string>>()))
.Returns(
"<litleOnlineResponse version='8.10' response='1' message='Error validating xml data against the schema' xmlns='http://www.litle.com/schema'><authorizationResponse><litleTxnId>123</litleTxnId></authorizationResponse></litleOnlineResponse>");
var mockedCommunication = mock.Object;
litle.setCommunication(mockedCommunication);
try
{
litle.Authorize(authorization);
}
catch (LitleOnlineException e)
{
Assert.AreEqual("Error validating xml data against the schema", e.Message);
}
}
[Test]
public void testInvalidOperationException()
{
var authorization = new authorization();
authorization.reportGroup = "Planets";
authorization.orderId = "12344";
authorization.amount = 106;
authorization.orderSource = orderSourceType.ecommerce;
var card = new cardType();
card.type = methodOfPaymentTypeEnum.VI;
card.number = "4100000000000002";
card.expDate = "1210";
authorization.card = card;
var mock = new Mock<Communications>(_memoryStreams);
mock.Setup(
Communications =>
Communications.HttpPost(
It.IsRegex(
".*?<litleOnlineRequest.*?<authorization.*?<card>.*?<number>4100000000000002</number>.*?</card>.*?</authorization>.*?",
RegexOptions.Singleline), It.IsAny<Dictionary<string, string>>()))
.Returns("no xml");
var mockedCommunication = mock.Object;
litle.setCommunication(mockedCommunication);
try
{
litle.Authorize(authorization);
}
catch (LitleOnlineException e)
{
Assert.AreEqual("Error validating xml data against the schema", e.Message);
}
}
[Test]
public void testDefaultReportGroup()
{
var authorization = new authorization();
authorization.orderId = "12344";
authorization.amount = 106;
authorization.orderSource = orderSourceType.ecommerce;
var card = new cardType();
card.type = methodOfPaymentTypeEnum.VI;
card.number = "4100000000000002";
card.expDate = "1210";
authorization.card = card;
var mock = new Mock<Communications>(_memoryStreams);
mock.Setup(
Communications =>
Communications.HttpPost(
It.IsRegex(
".*?<litleOnlineRequest.*?<authorization.*? reportGroup=\"Default Report Group\">.*?<card>.*?<number>4100000000000002</number>.*?</card>.*?</authorization>.*?",
RegexOptions.Singleline), It.IsAny<Dictionary<string, string>>()))
.Returns(
"<litleOnlineResponse version='8.10' response='0' message='Valid Format' xmlns='http://www.litle.com/schema'><authorizationResponse reportGroup='Default Report Group'></authorizationResponse></litleOnlineResponse>");
var mockedCommunication = mock.Object;
litle.setCommunication(mockedCommunication);
var authorize = litle.Authorize(authorization);
Assert.AreEqual("Default Report Group", authorize.reportGroup);
}
[Test]
public void testSetMerchantSdk()
{
}
}
}
| 45.207317 | 261 | 0.575803 | [
"MIT"
] | Coverdell/litle-sdk-for-dotNet | LitleSdkForNet/LitleSdkForNetTest/Unit/TestLitleOnline.cs | 29,658 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.ComponentModel; // Win32Exception
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.IO.Pipes;
using System.Management.Automation.Internal;
using System.Management.Automation.Remoting;
using System.Management.Automation.Remoting.Client;
using System.Management.Automation.Tracing;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Threading;
using Microsoft.Win32.SafeHandles;
using Dbg = System.Management.Automation.Diagnostics;
using WSManAuthenticationMechanism = System.Management.Automation.Remoting.Client.WSManNativeApi.WSManAuthenticationMechanism;
// ReSharper disable CheckNamespace
namespace System.Management.Automation.Runspaces
// ReSharper restore CheckNamespace
{
/// <summary>
/// Different Authentication Mechanisms supported by New-Runspace command to connect
/// to remote server.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags")]
[SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")]
public enum AuthenticationMechanism
{
/// <summary>
/// Use the default authentication (as defined by the underlying protocol)
/// for establishing a remote connection.
/// </summary>
Default = 0x0,
/// <summary>
/// Use Basic authentication for establishing a remote connection.
/// </summary>
Basic = 0x1,
/// <summary>
/// Use Negotiate authentication for establishing a remote connection.
/// </summary>
Negotiate = 0x2,
/// <summary>
/// Use Negotiate authentication for establishing a remote connection.
/// Allow implicit credentials for Negotiate.
/// </summary>
NegotiateWithImplicitCredential = 0x3,
/// <summary>
/// Use CredSSP authentication for establishing a remote connection.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Credssp")]
Credssp = 0x4,
/// <summary>
/// Use Digest authentication mechanism. Digest authentication operates much
/// like Basic authentication. However, unlike Basic authentication, Digest authentication
/// transmits credentials across the network as a hash value, also known as a message digest.
/// The user name and password cannot be deciphered from the hash value. Conversely, Basic
/// authentication sends a Base 64 encoded password, essentially in clear text, across the
/// network.
/// </summary>
Digest = 0x5,
/// <summary>
/// Use Kerberos authentication for establishing a remote connection.
/// </summary>
Kerberos = 0x6,
}
/// <summary>
/// Specify the type of access mode that should be
/// used when creating a session configuration.
/// </summary>
public enum PSSessionConfigurationAccessMode
{
/// <summary>
/// Disable the configuration.
/// </summary>
Disabled = 0,
/// <summary>
/// Allow local access.
/// </summary>
Local = 1,
/// <summary>
/// Default allow remote access.
/// </summary>
Remote = 2,
}
/// <summary>
/// WSManTransportManager supports disconnected PowerShell sessions.
/// When a remote PS session server is in disconnected state, output
/// from the running command pipeline is cached on the server. This
/// enum determines what the server does when the cache is full.
/// </summary>
public enum OutputBufferingMode
{
/// <summary>
/// No output buffering mode specified. Output buffering mode on server will
/// default to Block if a new session is created, or will retain its current
/// mode for non-creation scenarios (e.g., disconnect/connect operations).
/// </summary>
None = 0,
/// <summary>
/// Command pipeline execution continues, excess output is dropped in FIFO manner.
/// </summary>
Drop = 1,
/// <summary>
/// Command pipeline execution on server is blocked until session is reconnected.
/// </summary>
Block = 2
}
/// <summary>
/// Class which defines connection path to a remote runspace
/// that needs to be created. Transport specific connection
/// paths will be derived from this.
/// </summary>
public abstract class RunspaceConnectionInfo
{
#region Public Properties
/// <summary>
/// Name of the computer.
/// </summary>
public abstract string ComputerName { get; set; }
/// <summary>
/// Credential used for the connection.
/// </summary>
public abstract PSCredential Credential { get; set; }
/// <summary>
/// Authentication mechanism to use while connecting to the server.
/// </summary>
public abstract AuthenticationMechanism AuthenticationMechanism { get; set; }
/// <summary>
/// ThumbPrint of a certificate used for connecting to a remote machine.
/// When this is specified, you dont need to supply credential and authentication
/// mechanism.
/// </summary>
public abstract string CertificateThumbprint { get; set; }
/// <summary>
/// Culture that the remote session should use.
/// </summary>
public CultureInfo Culture
{
get
{
return _culture;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
_culture = value;
}
}
private CultureInfo _culture = CultureInfo.CurrentCulture;
/// <summary>
/// UI culture that the remote session should use.
/// </summary>
public CultureInfo UICulture
{
get
{
return _uiCulture;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
_uiCulture = value;
}
}
private CultureInfo _uiCulture = CultureInfo.CurrentUICulture;
/// <summary>
/// The duration (in ms) for which PowerShell remoting waits before timing out on a connection to a remote machine.
/// Simply put, the timeout for a remote runspace creation.
/// The administrator would like to tweak this timeout depending on whether
/// he/she is connecting to a machine in the data center or across a slow WAN.
/// </summary>
public int OpenTimeout
{
get
{
return _openTimeout;
}
set
{
_openTimeout = value;
if (this is WSManConnectionInfo && _openTimeout == DefaultTimeout)
{
_openTimeout = DefaultOpenTimeout;
}
else if (this is WSManConnectionInfo && _openTimeout == InfiniteTimeout)
{
// this timeout value gets passed to a
// timer associated with the session
// data structure handler state machine.
// The timer constructor will throw an exception
// for any value greater than Int32.MaxValue
// hence this is the maximum possible limit
_openTimeout = Int32.MaxValue;
}
}
}
private int _openTimeout = DefaultOpenTimeout;
internal const int DefaultOpenTimeout = 3 * 60 * 1000; // 3 minutes
internal const int DefaultTimeout = -1;
internal const int InfiniteTimeout = 0;
/// <summary>
/// The duration (in ms) for which PowerShell should wait before it times out on cancel operations
/// (close runspace or stop powershell). For instance, when the user hits ctrl-C,
/// New-PSSession cmdlet tries to call a stop on all remote runspaces which are in the Opening state.
/// The administrator wouldn't mind waiting for 15 seconds, but this should be time bound and of a shorter duration.
/// A high timeout here like 3 minutes will give the administrator a feeling that the PowerShell client is not responding.
/// </summary>
public int CancelTimeout { get; set; } = defaultCancelTimeout;
internal const int defaultCancelTimeout = BaseTransportManager.ClientCloseTimeoutMs;
/// <summary>
/// The duration for which PowerShell remoting waits before timing out
/// for any operation. The user would like to tweak this timeout
/// depending on whether he/she is connecting to a machine in the data
/// center or across a slow WAN.
///
/// Default: 3*60*1000 == 3minutes.
/// </summary>
public int OperationTimeout { get; set; } = BaseTransportManager.ClientDefaultOperationTimeoutMs;
/// <summary>
/// The duration (in ms) for which a Runspace on server needs to wait before it declares the client dead and closes itself down.
/// This is especially important as these values may have to be configured differently for enterprise administration
/// and exchange scenarios.
/// </summary>
public int IdleTimeout { get; set; } = DefaultIdleTimeout;
internal const int DefaultIdleTimeout = BaseTransportManager.UseServerDefaultIdleTimeout;
/// <summary>
/// The maximum allowed idle timeout duration (in ms) that can be set on a Runspace. This is a read-only property
/// that is set once the Runspace is successfully created and opened.
/// </summary>
public int MaxIdleTimeout { get; internal set; } = Int32.MaxValue;
/// <summary>
/// Populates session options from a PSSessionOption instance.
/// </summary>
/// <param name="options"></param>
public virtual void SetSessionOptions(PSSessionOption options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (options.Culture != null)
{
this.Culture = options.Culture;
}
if (options.UICulture != null)
{
this.UICulture = options.UICulture;
}
_openTimeout = TimeSpanToTimeOutMs(options.OpenTimeout);
CancelTimeout = TimeSpanToTimeOutMs(options.CancelTimeout);
OperationTimeout = TimeSpanToTimeOutMs(options.OperationTimeout);
// Special case for idle timeout. A value of milliseconds == -1
// (BaseTransportManager.UseServerDefaultIdleTimeout) is allowed for
// specifying the default value on the server.
IdleTimeout = (options.IdleTimeout.TotalMilliseconds >= BaseTransportManager.UseServerDefaultIdleTimeout &&
options.IdleTimeout.TotalMilliseconds < int.MaxValue)
? (int)(options.IdleTimeout.TotalMilliseconds) : int.MaxValue;
}
#endregion Public Properties
#region Internal Methods
internal int TimeSpanToTimeOutMs(TimeSpan t)
{
if ((t.TotalMilliseconds > int.MaxValue) || (t == TimeSpan.MaxValue) || (t.TotalMilliseconds < 0))
{
return int.MaxValue;
}
else
{
return (int)(t.TotalMilliseconds);
}
}
/// <summary>
/// Creates the appropriate client session transportmanager.
/// </summary>
/// <param name="instanceId">Runspace/Pool instance Id.</param>
/// <param name="sessionName">Session name.</param>
/// <param name="cryptoHelper">PSRemotingCryptoHelper.</param>
internal virtual BaseClientSessionTransportManager CreateClientSessionTransportManager(
Guid instanceId,
string sessionName,
PSRemotingCryptoHelper cryptoHelper)
{
throw new PSNotImplementedException();
}
/// <summary>
/// Create a copy of the connection info object.
/// </summary>
/// <returns>Copy of the connection info object.</returns>
internal virtual RunspaceConnectionInfo InternalCopy()
{
throw new PSNotImplementedException();
}
/// <summary>
/// Validates port number is in range.
/// </summary>
/// <param name="port">Port number to validate.</param>
internal virtual void ValidatePortInRange(int port)
{
if ((port < MinPort || port > MaxPort))
{
string message =
PSRemotingErrorInvariants.FormatResourceString(
RemotingErrorIdStrings.PortIsOutOfRange, port);
ArgumentException e = new ArgumentException(message);
throw e;
}
}
#endregion
#region Constants
/// <summary>
/// Maximum value for port.
/// </summary>
protected const int MaxPort = 0xFFFF;
/// <summary>
/// Minimum value for port.
/// </summary>
protected const int MinPort = 0;
#endregion
}
/// <summary>
/// Class which defines path to a remote runspace that
/// need to be created.
/// </summary>
public sealed class WSManConnectionInfo : RunspaceConnectionInfo
{
#region Public Properties
/// <summary>
/// Uri associated with this connection path.
/// </summary>
public Uri ConnectionUri
{
get
{
return _connectionUri;
}
set
{
if (value == null)
{
throw PSTraceSource.NewArgumentNullException("value");
}
UpdateUri(value);
}
}
/// <summary>
/// Name of the computer.
/// </summary>
public override string ComputerName
{
get
{
return _computerName;
}
set
{
// null or empty value allowed
ConstructUri(_scheme, value, null, _appName);
}
}
/// <summary>
/// Scheme used for connection.
/// </summary>
public string Scheme
{
get
{
return _scheme;
}
set
{
// null or empty value allowed
ConstructUri(value, _computerName, null, _appName);
}
}
/// <summary>
/// Port in which to connect.
/// </summary>
public int Port
{
get
{
return ConnectionUri.Port;
}
set
{
ConstructUri(_scheme, _computerName, value, _appName);
}
}
/// <summary>
/// AppName which identifies the connection
/// end point in the machine.
/// </summary>
public string AppName
{
get
{
return _appName;
}
set
{
// null or empty value allowed
ConstructUri(_scheme, _computerName, null, value);
}
}
/// <summary>
/// Credential used for the connection.
/// </summary>
public override PSCredential Credential
{
get
{
return _credential;
}
set
{
// null or empty value allowed
_credential = value;
}
}
/// <summary>
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Scope = "member", Target = "System.Management.Automation.Runspaces.WSManConnectionInfo.#ShellUri")]
public string ShellUri
{
get
{
return _shellUri;
}
set
{
_shellUri = ResolveShellUri(value);
}
}
/// <summary>
/// Authentication mechanism to use while connecting to the server.
/// </summary>
public override AuthenticationMechanism AuthenticationMechanism
{
get
{
switch (WSManAuthenticationMechanism)
{
case WSManAuthenticationMechanism.WSMAN_FLAG_DEFAULT_AUTHENTICATION:
return AuthenticationMechanism.Default;
case WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_BASIC:
return AuthenticationMechanism.Basic;
case WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_CREDSSP:
return AuthenticationMechanism.Credssp;
case WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_NEGOTIATE:
if (AllowImplicitCredentialForNegotiate)
{
return AuthenticationMechanism.NegotiateWithImplicitCredential;
}
return AuthenticationMechanism.Negotiate;
case WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_DIGEST:
return AuthenticationMechanism.Digest;
case WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_KERBEROS:
return AuthenticationMechanism.Kerberos;
default:
Dbg.Assert(false, "Invalid authentication mechanism detected.");
return AuthenticationMechanism.Default;
}
}
set
{
switch (value)
{
case AuthenticationMechanism.Default:
WSManAuthenticationMechanism = WSManAuthenticationMechanism.WSMAN_FLAG_DEFAULT_AUTHENTICATION;
break;
case AuthenticationMechanism.Basic:
WSManAuthenticationMechanism = WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_BASIC;
break;
case AuthenticationMechanism.Negotiate:
WSManAuthenticationMechanism = WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_NEGOTIATE;
break;
case AuthenticationMechanism.NegotiateWithImplicitCredential:
WSManAuthenticationMechanism = WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_NEGOTIATE;
AllowImplicitCredentialForNegotiate = true;
break;
case AuthenticationMechanism.Credssp:
WSManAuthenticationMechanism = WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_CREDSSP;
break;
case AuthenticationMechanism.Digest:
WSManAuthenticationMechanism = WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_DIGEST;
break;
case AuthenticationMechanism.Kerberos:
WSManAuthenticationMechanism = WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_KERBEROS;
break;
default:
throw new PSNotSupportedException();
}
ValidateSpecifiedAuthentication();
}
}
/// <summary>
/// AuthenticationMechanism converted to WSManAuthenticationMechanism type.
/// This is internal.
/// </summary>
internal WSManAuthenticationMechanism WSManAuthenticationMechanism { get; private set; } = WSManAuthenticationMechanism.WSMAN_FLAG_DEFAULT_AUTHENTICATION;
/// <summary>
/// Allow default credentials for Negotiate.
/// </summary>
internal bool AllowImplicitCredentialForNegotiate { get; private set; }
/// <summary>
/// Returns the actual port property value and not the ConnectionUri port.
/// Internal only.
/// </summary>
internal int PortSetting { get; private set; } = -1;
/// <summary>
/// ThumbPrint of a certificate used for connecting to a remote machine.
/// When this is specified, you dont need to supply credential and authentication
/// mechanism.
/// </summary>
public override string CertificateThumbprint
{
get
{
return _thumbPrint;
}
set
{
if (value == null)
{
throw PSTraceSource.NewArgumentNullException("value");
}
_thumbPrint = value;
}
}
/// <summary>
/// Maximum uri redirection count.
/// </summary>
public int MaximumConnectionRedirectionCount { get; set; }
internal const int defaultMaximumConnectionRedirectionCount = 5;
/// <summary>
/// Total data (in bytes) that can be received from a remote machine
/// targeted towards a command. If null, then the size is unlimited.
/// Default is unlimited data.
/// </summary>
public int? MaximumReceivedDataSizePerCommand { get; set; }
/// <summary>
/// Maximum size (in bytes) of a deserialized object received from a remote machine.
/// If null, then the size is unlimited. Default is unlimited object size.
/// </summary>
public int? MaximumReceivedObjectSize { get; set; }
/// <summary>
/// If true, underlying WSMan infrastructure will compress data sent on the network.
/// If false, data will not be compressed. Compression improves performance by
/// reducing the amount of data sent on the network. Compression my require extra
/// memory consumption and CPU usage. In cases where available memory / CPU is less,
/// set this property to false.
/// By default the value of this property is "true".
/// </summary>
public bool UseCompression { get; set; } = true;
/// <summary>
/// If <see langword="true"/> then Operating System won't load the user profile (i.e. registry keys under HKCU) on the remote server
/// which can result in a faster session creation time. This option won't have any effect if the remote machine has
/// already loaded the profile (i.e. in another session).
/// </summary>
public bool NoMachineProfile { get; set; }
// BEGIN: Session Options
/// <summary>
/// By default, wsman uses IEConfig - the current user
/// Internet Explorer proxy settings for the current active network connection.
/// This option requires the user profile to be loaded, so the option can
/// be directly used when called within a process that is running under
/// an interactive user account identity; if the client application is running
/// under a user context different then the interactive user, the client
/// application has to explicitly load the user profile prior to using this option.
///
/// IMPORTANT: proxy configuration is supported for HTTPS only; for HTTP, the direct
/// connection to the server is used.
/// </summary>
public ProxyAccessType ProxyAccessType { get; set; } = ProxyAccessType.None;
/// <summary>
/// The following is the definition of the input parameter "ProxyAuthentication".
/// This parameter takes a set of authentication methods the user can select
/// from. The available options should be as follows:
/// - Negotiate: Use the default authentication (ad defined by the underlying
/// protocol) for establishing a remote connection.
/// - Basic: Use basic authentication for establishing a remote connection
/// - Digest: Use Digest authentication for establishing a remote connection.
/// </summary>
public AuthenticationMechanism ProxyAuthentication
{
get
{
return _proxyAuthentication;
}
set
{
switch (value)
{
case AuthenticationMechanism.Basic:
case AuthenticationMechanism.Negotiate:
case AuthenticationMechanism.Digest:
_proxyAuthentication = value;
break;
default:
string message = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.ProxyAmbiguousAuthentication,
value,
nameof(AuthenticationMechanism.Basic),
nameof(AuthenticationMechanism.Negotiate),
nameof(AuthenticationMechanism.Digest));
throw new ArgumentException(message);
}
}
}
/// <summary>
/// The following is the definition of the input parameter "ProxyCredential".
/// </summary>
public PSCredential ProxyCredential
{
get
{
return _proxyCredential;
}
set
{
if (ProxyAccessType == ProxyAccessType.None)
{
string message = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.ProxyCredentialWithoutAccess,
ProxyAccessType.None);
throw new ArgumentException(message);
}
_proxyCredential = value;
}
}
/// <summary>
/// When connecting over HTTPS, the client does not validate that the server
/// certificate is signed by a trusted certificate authority (CA). Use only when
/// the remote computer is trusted by other means, for example, if the remote
/// computer is part of a network that is physically secure and isolated or the
/// remote computer is listed as a trusted host in WinRM configuration.
/// </summary>
public bool SkipCACheck { get; set; }
/// <summary>
/// Indicates that certificate common name (CN) of the server need not match the
/// hostname of the server. Used only in remote operations using https. This
/// option should only be used for trusted machines.
/// </summary>
public bool SkipCNCheck { get; set; }
/// <summary>
/// Indicates that certificate common name (CN) of the server need not match the
/// hostname of the server. Used only in remote operations using https. This
/// option should only be used for trusted machines.
/// </summary>
public bool SkipRevocationCheck { get; set; }
/// <summary>
/// Specifies that no encryption will be used when doing remote operations over
/// http. Unencrypted traffic is not allowed by default and must be enabled in
/// the local configuration.
/// </summary>
public bool NoEncryption { get; set; }
/// <summary>
/// Indicates the request is encoded in UTF16 format rather than UTF8 format;
/// UTF8 is the default.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "UTF")]
public bool UseUTF16 { get; set; }
// END: Session Options
/// <summary>
/// Determines how server in disconnected state deals with cached output
/// data when the cache becomes filled.
/// </summary>
public OutputBufferingMode OutputBufferingMode { get; set; } = DefaultOutputBufferingMode;
/// <summary>
/// Uses Service Principal Name (SPN) along with the Port number during authentication.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SPN")]
public bool IncludePortInSPN { get; set; }
/// <summary>
/// When true and in loopback scenario (localhost) this enables creation of WSMan
/// host process with the user interactive token, allowing PowerShell script network access,
/// i.e., allows going off box. When this property is true and a PSSession is disconnected,
/// reconnection is allowed only if reconnecting from a PowerShell session on the same box.
/// </summary>
public bool EnableNetworkAccess { get; set; }
/// <summary>
/// Specifies the maximum number of connection retries if previous connection attempts fail
/// due to network issues.
/// </summary>
public int MaxConnectionRetryCount { get; set; } = DefaultMaxConnectionRetryCount;
#endregion Public Properties
#region Constructors
/// <summary>
/// Constructor used to create a WSManConnectionInfo.
/// </summary>
/// <param name="computerName">Computer to connect to.</param>
/// <param name="scheme">Scheme to be used for connection.</param>
/// <param name="port">Port to connect to.</param>
/// <param name="appName">Application end point to connect to.</param>
/// <param name="shellUri">remote shell to launch
/// on connection</param>
/// <param name="credential">credential to be used
/// for connection</param>
/// <param name="openTimeout">Timeout in milliseconds for open
/// call on Runspace to finish</param>
/// <exception cref="ArgumentException">Invalid
/// scheme or invalid port is specified</exception>
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", Scope = "member", Target = "System.Management.Automation.Runspaces.WSManConnectionInfo.#.ctor(System.String,System.String,System.Int32,System.String,System.String,System.Management.Automation.PSCredential,System.Int64,System.Int64)", MessageId = "4#")]
public WSManConnectionInfo(string scheme, string computerName, int port, string appName, string shellUri, PSCredential credential, int openTimeout)
{
Scheme = scheme;
ComputerName = computerName;
Port = port;
AppName = appName;
ShellUri = shellUri;
Credential = credential;
OpenTimeout = openTimeout;
}
/// <summary>
/// Constructor used to create a WSManConnectionInfo.
/// </summary>
/// <param name="computerName">Computer to connect to.</param>
/// <param name="scheme">Scheme to be used for connection.</param>
/// <param name="port">Port to connect to.</param>
/// <param name="appName">Application end point to connect to.</param>
/// <param name="shellUri">remote shell to launch
/// on connection</param>
/// <param name="credential">credential to be used
/// for connection</param>
/// <exception cref="ArgumentException">Invalid
/// scheme or invalid port is specified</exception>
/// <remarks>max server life timeout and open timeout are
/// default in this case</remarks>
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", Scope = "member", Target = "System.Management.Automation.Runspaces.WSManConnectionInfo.#.ctor(System.String,System.String,System.Int32,System.String,System.String,System.Management.Automation.PSCredential)", MessageId = "4#")]
public WSManConnectionInfo(
string scheme,
string computerName,
int port,
string appName,
string shellUri,
PSCredential credential)
: this(
scheme,
computerName,
port,
appName,
shellUri,
credential,
DefaultOpenTimeout)
{
}
/// <summary>
/// Constructor used to create a WSManConnectionInfo.
/// </summary>
/// <param name="useSsl"></param>
/// <param name="computerName"></param>
/// <param name="port"></param>
/// <param name="appName"></param>
/// <param name="shellUri"></param>
/// <param name="credential"></param>
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "4#")]
public WSManConnectionInfo(
bool useSsl,
string computerName,
int port,
string appName,
string shellUri,
PSCredential credential)
: this(
useSsl ? DefaultSslScheme : DefaultScheme,
computerName,
port,
appName,
shellUri,
credential)
{
}
/// <summary>
/// </summary>
/// <param name="useSsl"></param>
/// <param name="computerName"></param>
/// <param name="port"></param>
/// <param name="appName"></param>
/// <param name="shellUri"></param>
/// <param name="credential"></param>
/// <param name="openTimeout"></param>
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "4#")]
public WSManConnectionInfo(
bool useSsl,
string computerName,
int port,
string appName,
string shellUri,
PSCredential credential,
int openTimeout)
: this(
useSsl ? DefaultSslScheme : DefaultScheme,
computerName,
port,
appName,
shellUri,
credential,
openTimeout)
{
}
/// <summary>
/// Creates a WSManConnectionInfo for the following URI
/// and with the default credentials, default server
/// life time and default open timeout
/// http://localhost/
/// The default shellname Microsoft.PowerShell will be
/// used.
/// </summary>
public WSManConnectionInfo()
{
// ConstructUri(DefaultScheme, DefaultComputerName, DefaultPort, DefaultAppName);
UseDefaultWSManPort = true;
}
/// <summary>
/// Constructor to create a WSManConnectionInfo with a uri
/// and explicit credentials - server life time is
/// default and open timeout is default.
/// </summary>
/// <param name="uri">Uri of remote runspace.</param>
/// <param name="shellUri"></param>
/// <param name="credential">credentials to use to
/// connect to the remote runspace</param>
/// <exception cref="ArgumentException">When an
/// uri representing an invalid path is specified</exception>
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", Scope = "member", Target = "System.Management.Automation.Runspaces.WSManConnectionInfo.#.ctor(System.Uri,System.String,System.Management.Automation.PSCredential)", MessageId = "1#")]
public WSManConnectionInfo(Uri uri, string shellUri, PSCredential credential)
{
if (uri == null)
{
// if the uri is null..apply wsman default logic for port
// resolution..BUG 542726
ShellUri = shellUri;
Credential = credential;
UseDefaultWSManPort = true;
return;
}
if (!uri.IsAbsoluteUri)
{
throw new NotSupportedException(PSRemotingErrorInvariants.FormatResourceString
(RemotingErrorIdStrings.RelativeUriForRunspacePathNotSupported));
}
// This check is needed to make sure we connect to WSMan app in the
// default case (when user did not specify any appname) like
// http://localhost , http://127.0.0.1 etc.
if (uri.AbsolutePath.Equals("/", StringComparison.OrdinalIgnoreCase) &&
string.IsNullOrEmpty(uri.Query) && string.IsNullOrEmpty(uri.Fragment))
{
ConstructUri(uri.Scheme,
uri.Host,
uri.Port,
s_defaultAppName);
}
else
{
ConnectionUri = uri;
}
ShellUri = shellUri;
Credential = credential;
}
/// <summary>
/// Constructor used to create a WSManConnectionInfo. This constructor supports a certificate thumbprint to
/// be used while connecting to a remote machine instead of credential.
/// </summary>
/// <param name="uri">Uri of remote runspace.</param>
/// <param name="shellUri"></param>
/// <param name="certificateThumbprint">
/// A thumb print of the certificate to use while connecting to the remote machine.
/// </param>
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#")]
public WSManConnectionInfo(Uri uri, string shellUri, string certificateThumbprint)
: this(uri, shellUri, (PSCredential)null)
{
_thumbPrint = certificateThumbprint;
}
/// <summary>
/// Constructor to create a WSManConnectionInfo with a
/// uri specified and the default credentials,
/// default server life time and default open
/// timeout.
/// </summary>
/// <param name="uri">Uri of remote runspace.</param>
/// <exception cref="ArgumentException">When an
/// uri representing an invalid path is specified</exception>
public WSManConnectionInfo(Uri uri)
: this(uri, DefaultShellUri, DefaultCredential)
{
}
#endregion Constructors
#region Public Methods
/// <summary>
/// Populates session options from a PSSessionOption instance.
/// </summary>
/// <param name="options"></param>
/// <exception cref="ArgumentException">
/// 1. Proxy credential cannot be specified when proxy accesstype is None.
/// Either specify a valid proxy accesstype other than None or do not specify proxy credential.
/// </exception>
public override void SetSessionOptions(PSSessionOption options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if ((options.ProxyAccessType == ProxyAccessType.None) && (options.ProxyCredential != null))
{
string message = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.ProxyCredentialWithoutAccess,
ProxyAccessType.None);
throw new ArgumentException(message);
}
base.SetSessionOptions(options);
this.MaximumConnectionRedirectionCount =
options.MaximumConnectionRedirectionCount >= 0
? options.MaximumConnectionRedirectionCount : int.MaxValue;
this.MaximumReceivedDataSizePerCommand = options.MaximumReceivedDataSizePerCommand;
this.MaximumReceivedObjectSize = options.MaximumReceivedObjectSize;
this.UseCompression = !(options.NoCompression);
this.NoMachineProfile = options.NoMachineProfile;
ProxyAccessType = options.ProxyAccessType;
_proxyAuthentication = options.ProxyAuthentication;
_proxyCredential = options.ProxyCredential;
SkipCACheck = options.SkipCACheck;
SkipCNCheck = options.SkipCNCheck;
SkipRevocationCheck = options.SkipRevocationCheck;
NoEncryption = options.NoEncryption;
UseUTF16 = options.UseUTF16;
IncludePortInSPN = options.IncludePortInSPN;
OutputBufferingMode = options.OutputBufferingMode;
MaxConnectionRetryCount = options.MaxConnectionRetryCount;
}
/// <summary>
/// Shallow copy of the current instance.
/// </summary>
/// <returns>RunspaceConnectionInfo.</returns>
internal override RunspaceConnectionInfo InternalCopy()
{
return Copy();
}
/// <summary>
/// Does a shallow copy of the current instance.
/// </summary>
/// <returns></returns>
public WSManConnectionInfo Copy()
{
WSManConnectionInfo result = new WSManConnectionInfo();
result._connectionUri = _connectionUri;
result._computerName = _computerName;
result._scheme = _scheme;
result.PortSetting = PortSetting;
result._appName = _appName;
result._shellUri = _shellUri;
result._credential = _credential;
result.UseDefaultWSManPort = UseDefaultWSManPort;
result.WSManAuthenticationMechanism = WSManAuthenticationMechanism;
result.MaximumConnectionRedirectionCount = MaximumConnectionRedirectionCount;
result.MaximumReceivedDataSizePerCommand = MaximumReceivedDataSizePerCommand;
result.MaximumReceivedObjectSize = MaximumReceivedObjectSize;
result.OpenTimeout = this.OpenTimeout;
result.IdleTimeout = this.IdleTimeout;
result.MaxIdleTimeout = this.MaxIdleTimeout;
result.CancelTimeout = this.CancelTimeout;
result.OperationTimeout = base.OperationTimeout;
result.Culture = this.Culture;
result.UICulture = this.UICulture;
result._thumbPrint = _thumbPrint;
result.AllowImplicitCredentialForNegotiate = AllowImplicitCredentialForNegotiate;
result.UseCompression = UseCompression;
result.NoMachineProfile = NoMachineProfile;
result.ProxyAccessType = this.ProxyAccessType;
result._proxyAuthentication = this.ProxyAuthentication;
result._proxyCredential = this.ProxyCredential;
result.SkipCACheck = this.SkipCACheck;
result.SkipCNCheck = this.SkipCNCheck;
result.SkipRevocationCheck = this.SkipRevocationCheck;
result.NoEncryption = this.NoEncryption;
result.UseUTF16 = this.UseUTF16;
result.IncludePortInSPN = this.IncludePortInSPN;
result.EnableNetworkAccess = this.EnableNetworkAccess;
result.UseDefaultWSManPort = this.UseDefaultWSManPort;
result.OutputBufferingMode = OutputBufferingMode;
result.DisconnectedOn = this.DisconnectedOn;
result.ExpiresOn = this.ExpiresOn;
result.MaxConnectionRetryCount = this.MaxConnectionRetryCount;
return result;
}
/// <summary>
/// String for http scheme.
/// </summary>
public const string HttpScheme = "http";
/// <summary>
/// String for https scheme.
/// </summary>
public const string HttpsScheme = "https";
#endregion
#region Internal Methods
internal override BaseClientSessionTransportManager CreateClientSessionTransportManager(Guid instanceId, string sessionName, PSRemotingCryptoHelper cryptoHelper)
{
return new WSManClientSessionTransportManager(
instanceId,
this,
cryptoHelper,
sessionName);
}
#endregion
#region Private Methods
private static string ResolveShellUri(string shell)
{
string resolvedShellUri = shell;
if (string.IsNullOrEmpty(resolvedShellUri))
{
resolvedShellUri = DefaultShellUri;
}
if (!resolvedShellUri.Contains(WSManNativeApi.ResourceURIPrefix, StringComparison.OrdinalIgnoreCase))
{
resolvedShellUri = WSManNativeApi.ResourceURIPrefix + resolvedShellUri;
}
return resolvedShellUri;
}
/// <summary>
/// Converts <paramref name="rsCI"/> to a WSManConnectionInfo. If conversion succeeds extracts
/// the property..otherwise returns default value.
/// </summary>
/// <param name="rsCI"></param>
/// <param name="property"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
internal static T ExtractPropertyAsWsManConnectionInfo<T>(RunspaceConnectionInfo rsCI,
string property, T defaultValue)
{
if (!(rsCI is WSManConnectionInfo wsCI))
{
return defaultValue;
}
return (T)typeof(WSManConnectionInfo).GetProperty(property, typeof(T)).GetValue(wsCI, null);
}
internal void SetConnectionUri(Uri newUri)
{
Dbg.Assert(newUri != null, "newUri cannot be null.");
_connectionUri = newUri;
}
/// <summary>
/// Constructs a Uri from the supplied parameters.
/// </summary>
/// <param name="scheme"></param>
/// <param name="computerName"></param>
/// <param name="port">
/// Making the port nullable to make sure the UseDefaultWSManPort variable is protected and updated
/// only when Port is updated. Usages that dont update port, should use null for this parameter.
/// </param>
/// <param name="appName"></param>
/// <returns></returns>
internal void ConstructUri(string scheme, string computerName, int? port, string appName)
{
// Default scheme is http
_scheme = scheme;
if (string.IsNullOrEmpty(_scheme))
{
_scheme = DefaultScheme;
}
// Valid values for scheme are "http" and "https"
if (!(_scheme.Equals(HttpScheme, StringComparison.OrdinalIgnoreCase)
|| _scheme.Equals(HttpsScheme, StringComparison.OrdinalIgnoreCase)
|| _scheme.Equals(DefaultScheme, StringComparison.OrdinalIgnoreCase)))
{
string message =
PSRemotingErrorInvariants.FormatResourceString(
RemotingErrorIdStrings.InvalidSchemeValue, _scheme);
ArgumentException e = new ArgumentException(message);
throw e;
}
// default host is localhost
if (string.IsNullOrEmpty(computerName) || string.Equals(computerName, ".", StringComparison.OrdinalIgnoreCase))
{
_computerName = DefaultComputerName;
}
else
{
_computerName = computerName.Trim();
// According to RFC3513, an Ipv6 address in URI needs to be bracketed.
IPAddress ipAddress = null;
bool isIPAddress = IPAddress.TryParse(_computerName, out ipAddress);
if (isIPAddress && ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
{
if ((_computerName.Length == 0) || (_computerName[0] != '['))
{
_computerName = @"[" + _computerName + @"]";
}
}
}
PSEtwLog.LogAnalyticVerbose(PSEventId.ComputerName, PSOpcode.Method,
PSTask.CreateRunspace, PSKeyword.Runspace | PSKeyword.UseAlwaysAnalytic,
_computerName);
if (port.HasValue)
{
ValidatePortInRange(port.Value);
// resolve to default ports if required
if (port.Value == DefaultPort)
{
// this is needed so that the OriginalString on
// connection uri is fine
PortSetting = -1;
UseDefaultWSManPort = true;
}
else
{
PortSetting = port.Value;
UseDefaultWSManPort = false;
}
}
// default appname is WSMan
_appName = appName;
if (string.IsNullOrEmpty(_appName))
{
_appName = s_defaultAppName;
}
// construct Uri
UriBuilder uriBuilder = new UriBuilder(_scheme, _computerName,
PortSetting, _appName);
_connectionUri = uriBuilder.Uri;
}
/// <summary>
/// Returns connection string without the scheme portion.
/// </summary>
/// <param name="connectionUri">
/// The uri from which the string will be extracted
/// </param>
/// <param name="isSSLSpecified">
/// returns true if https scheme is specified
/// </param>
/// <returns>
/// returns connection string without the scheme portion.
/// </returns>
internal static string GetConnectionString(Uri connectionUri,
out bool isSSLSpecified)
{
isSSLSpecified =
connectionUri.Scheme.Equals(WSManConnectionInfo.HttpsScheme);
string result = connectionUri.OriginalString.TrimStart();
if (isSSLSpecified)
{
return result.Substring(WSManConnectionInfo.HttpsScheme.Length + 3);
}
else
{
return result.Substring(WSManConnectionInfo.HttpScheme.Length + 3);
}
}
/// <summary>
/// Used to resolve authentication from the parameters chosen by the user.
/// User has the following options:
/// 1. AuthMechanism + Credential
/// 2. CertificateThumbPrint
///
/// All the above are mutually exclusive.
/// </summary>
/// <exception cref="InvalidOperationException">
/// If there is ambiguity as specified above.
/// </exception>
private void ValidateSpecifiedAuthentication()
{
if ((WSManAuthenticationMechanism != WSManAuthenticationMechanism.WSMAN_FLAG_DEFAULT_AUTHENTICATION)
&& (_thumbPrint != null))
{
throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.NewRunspaceAmbiguousAuthentication,
"CertificateThumbPrint", this.AuthenticationMechanism.ToString());
}
}
private void UpdateUri(Uri uri)
{
if (!uri.IsAbsoluteUri)
{
throw new NotSupportedException(PSRemotingErrorInvariants.FormatResourceString
(RemotingErrorIdStrings.RelativeUriForRunspacePathNotSupported));
}
if (uri.OriginalString.LastIndexOf(':') >
uri.AbsoluteUri.IndexOf("//", StringComparison.Ordinal))
{
UseDefaultWSManPort = false;
}
// This check is needed to make sure we connect to WSMan app in the
// default case (when user did not specify any appname) like
// http://localhost , http://127.0.0.1 etc.
string appname;
if (uri.AbsolutePath.Equals("/", StringComparison.Ordinal) &&
string.IsNullOrEmpty(uri.Query) && string.IsNullOrEmpty(uri.Fragment))
{
appname = s_defaultAppName;
ConstructUri(uri.Scheme,
uri.Host,
uri.Port,
appname);
}
else
{
_connectionUri = uri;
_scheme = uri.Scheme;
_appName = uri.AbsolutePath;
PortSetting = uri.Port;
_computerName = uri.Host;
UseDefaultWSManPort = false;
}
}
#endregion Private Methods
#region Private Members
private string _scheme = HttpScheme;
private string _computerName = DefaultComputerName;
private string _appName = s_defaultAppName;
private Uri _connectionUri = new Uri(LocalHostUriString); // uri of this connection
private PSCredential _credential; // credentials to be used for this connection
private string _shellUri = DefaultShellUri; // shell thats specified by the user
private string _thumbPrint;
private AuthenticationMechanism _proxyAuthentication;
private PSCredential _proxyCredential;
#endregion Private Members
#region constants
/// <summary>
/// Default disconnected server output mode is set to None. This mode allows the
/// server to set the buffering mode to Block for new sessions and retain its
/// current mode during disconnect/connect operations.
/// </summary>
internal const OutputBufferingMode DefaultOutputBufferingMode = OutputBufferingMode.None;
/// <summary>
/// Default maximum connection retry count.
/// </summary>
internal const int DefaultMaxConnectionRetryCount = 5;
#if NOT_APPLY_PORT_DCR
private static string DEFAULT_SCHEME = HTTP_SCHEME;
internal static readonly string DEFAULT_SSL_SCHEME = HTTPS_SCHEME;
private static string DEFAULT_APP_NAME = "wsman";
/// <summary>
/// See below for explanation.
/// </summary>
internal bool UseDefaultWSManPort
{
get { return false; }
set { }
}
#else
private const string DefaultScheme = HttpScheme;
private const string DefaultSslScheme = HttpsScheme;
/// <summary>
/// Default appname. This is empty as WSMan configuration has support
/// for this. Look at
/// get-item WSMan:\localhost\Client\URLPrefix.
/// </summary>
private static readonly string s_defaultAppName = "/wsman";
/// <summary>
/// Default scheme.
/// As part of port DCR, WSMan changed the default ports
/// from 80,443 to 5985,5986 respectively no-SSL,SSL
/// connections. Since the standards say http,https use
/// 80,443 as defaults..we came up with new mechanism
/// to specify scheme as empty. For SSL, WSMan introduced
/// a new SessionOption. In order to make scheme empty
/// in the connection string passed to WSMan, we use
/// this internal boolean.
/// </summary>
internal bool UseDefaultWSManPort { get; set; }
#endif
/// <summary>
/// Default port for http scheme.
/// </summary>
private const int DefaultPortHttp = 80;
/// <summary>
/// Default port for https scheme.
/// </summary>
private const int DefaultPortHttps = 443;
/// <summary>
/// This is the default port value which when specified
/// results in the default port for the scheme to be
/// assumed.
/// </summary>
private const int DefaultPort = 0;
/// <summary>
/// Default remote host name.
/// </summary>
private const string DefaultComputerName = "localhost";
/// <summary>
/// String that represents the local host Uri.
/// </summary>
private const string LocalHostUriString = "http://localhost/wsman";
/// <summary>
/// Default value for shell.
/// </summary>
private const string DefaultShellUri = WSManNativeApi.ResourceURIPrefix + RemotingConstants.DefaultShellName;
/// <summary>
/// Default credentials - null indicates credentials of
/// current user.
/// </summary>
private const PSCredential DefaultCredential = null;
#endregion constants
#region Internal members
/// <summary>
/// Helper property that returns true when the connection has EnableNetworkAccess set
/// and the connection is localhost (loopback), i.e., not a network connection.
/// </summary>
/// <returns></returns>
internal bool IsLocalhostAndNetworkAccess
{
get
{
return (EnableNetworkAccess && // Interactive token requested
(Credential == null && // No credential provided
(ComputerName.Equals(DefaultComputerName, StringComparison.OrdinalIgnoreCase) || // Localhost computer name
!ComputerName.Contains('.')))); // Not FQDN computer name
}
}
/// <summary>
/// DisconnectedOn property applies to disconnnected runspaces.
/// This property is publicly exposed only through Runspace class.
/// </summary>
internal DateTime? DisconnectedOn
{
get;
set;
}
/// <summary>
/// ExpiresOn property applies to disconnnected runspaces.
/// This property is publicly exposed only through Runspace class.
/// </summary>
internal DateTime? ExpiresOn
{
get;
set;
}
/// <summary>
/// Helper method to reset DisconnectedOn/ExpiresOn properties to null.
/// </summary>
internal void NullDisconnectedExpiresOn()
{
this.DisconnectedOn = null;
this.ExpiresOn = null;
}
/// <summary>
/// Helper method to set the DisconnectedOn/ExpiresOn properties based
/// on current date/time and session idletimeout value.
/// </summary>
internal void SetDisconnectedExpiresOnToNow()
{
TimeSpan idleTimeoutTime = TimeSpan.FromSeconds(this.IdleTimeout / 1000);
DateTime now = DateTime.Now;
this.DisconnectedOn = now;
this.ExpiresOn = now.Add(idleTimeoutTime);
}
#endregion Internal members
}
/// <summary>
/// Class which is used to create an Out-Of-Process Runspace/RunspacePool.
/// This does not have a dependency on WSMan. *-Job cmdlets use Out-Of-Proc
/// Runspaces to support background jobs.
/// </summary>
internal sealed class NewProcessConnectionInfo : RunspaceConnectionInfo
{
#region Private Data
private PSCredential _credential;
private AuthenticationMechanism _authMechanism;
#endregion
#region Properties
/// <summary>
/// Script to run while starting the background process.
/// </summary>
public ScriptBlock InitializationScript { get; set; }
/// <summary>
/// On a 64bit machine, specifying true for this will launch a 32 bit process
/// for the background process.
/// </summary>
public bool RunAs32 { get; set; }
/// <summary>
/// Gets or sets an initial working directory for the powershell background process.
/// </summary>
public string WorkingDirectory { get; set; }
/// <summary>
/// Powershell version to execute the job in.
/// </summary>
public Version PSVersion { get; set; }
internal PowerShellProcessInstance Process { get; set; }
#endregion
#region Overrides
/// <summary>
/// Name of the computer. Will always be "localhost" to signify local machine.
/// </summary>
public override string ComputerName
{
get { return "localhost"; }
set { throw new NotImplementedException(); }
}
/// <summary>
/// Credential used for the connection.
/// </summary>
public override PSCredential Credential
{
get
{
return _credential;
}
set
{
_credential = value;
_authMechanism = AuthenticationMechanism.Default;
}
}
/// <summary>
/// Authentication mechanism to use while connecting to the server.
/// Only Default is supported.
/// </summary>
public override AuthenticationMechanism AuthenticationMechanism
{
get
{
return _authMechanism;
}
set
{
if (value != AuthenticationMechanism.Default)
{
throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.IPCSupportsOnlyDefaultAuth,
value.ToString(), nameof(AuthenticationMechanism.Default));
}
_authMechanism = value;
}
}
/// <summary>
/// ThumbPrint of a certificate used for connecting to a remote machine.
/// When this is specified, you dont need to supply credential and authentication
/// mechanism.
/// Will always be empty to signify that this is not supported.
/// </summary>
public override string CertificateThumbprint
{
get { return string.Empty; }
set { throw new NotImplementedException(); }
}
public NewProcessConnectionInfo Copy()
{
NewProcessConnectionInfo result = new NewProcessConnectionInfo(_credential);
result.AuthenticationMechanism = this.AuthenticationMechanism;
result.InitializationScript = this.InitializationScript;
result.WorkingDirectory = this.WorkingDirectory;
result.RunAs32 = this.RunAs32;
result.PSVersion = this.PSVersion;
result.Process = Process;
return result;
}
internal override RunspaceConnectionInfo InternalCopy()
{
return Copy();
}
internal override BaseClientSessionTransportManager CreateClientSessionTransportManager(Guid instanceId, string sessionName, PSRemotingCryptoHelper cryptoHelper)
{
return new OutOfProcessClientSessionTransportManager(
instanceId,
this,
cryptoHelper);
}
#endregion
#region Constructors
/// <summary>
/// Creates a connection info instance used to create a runspace on a different
/// process on the local machine.
/// </summary>
internal NewProcessConnectionInfo(PSCredential credential)
{
_credential = credential;
_authMechanism = AuthenticationMechanism.Default;
}
#endregion
}
/// <summary>
/// Class used to create an Out-Of-Process Runspace/RunspacePool between
/// two local processes using a named pipe for IPC.
/// This class does not have a dependency on WSMan and is used to implement
/// the PowerShell attach-to-process feature.
/// </summary>
public sealed class NamedPipeConnectionInfo : RunspaceConnectionInfo
{
#region Private Data
private PSCredential _credential;
private AuthenticationMechanism _authMechanism;
private string _appDomainName = string.Empty;
private const int _defaultOpenTimeout = 60000; /* 60 seconds. */
#endregion
#region Properties
/// <summary>
/// Process Id of process to attach to.
/// </summary>
public int ProcessId
{
get;
set;
}
/// <summary>
/// Optional application domain name. If not specified then the
/// default application domain is used.
/// </summary>
public string AppDomainName
{
get
{
return _appDomainName;
}
set
{
_appDomainName = value ?? string.Empty;
}
}
/// <summary>
/// Gets or sets the custom named pipe name to connect to. This is usually used in conjunction with pwsh -CustomPipeName.
/// </summary>
public string CustomPipeName
{
get;
set;
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="NamedPipeConnectionInfo"/> class.
/// </summary>
public NamedPipeConnectionInfo()
{
OpenTimeout = _defaultOpenTimeout;
}
/// <summary>
/// Initializes a new instance of the <see cref="NamedPipeConnectionInfo"/> class.
/// </summary>
/// <param name="processId">Process Id to connect to.</param>
public NamedPipeConnectionInfo(int processId)
: this(processId, string.Empty, _defaultOpenTimeout)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="NamedPipeConnectionInfo"/> class.
/// </summary>
/// <param name="processId">Process Id to connect to.</param>
/// <param name="appDomainName">Application domain name to connect to, or default AppDomain if blank.</param>
public NamedPipeConnectionInfo(int processId, string appDomainName)
: this(processId, appDomainName, _defaultOpenTimeout)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="NamedPipeConnectionInfo"/> class.
/// </summary>
/// <param name="processId">Process Id to connect to.</param>
/// <param name="appDomainName">Name of application domain to connect to. Connection is to default application domain if blank.</param>
/// <param name="openTimeout">Open time out in Milliseconds.</param>
public NamedPipeConnectionInfo(
int processId,
string appDomainName,
int openTimeout)
{
ProcessId = processId;
AppDomainName = appDomainName;
OpenTimeout = openTimeout;
}
/// <summary>
/// Initializes a new instance of the <see cref="NamedPipeConnectionInfo"/> class.
/// </summary>
/// <param name="customPipeName">Pipe name to connect to.</param>
public NamedPipeConnectionInfo(string customPipeName)
: this(customPipeName, _defaultOpenTimeout)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="NamedPipeConnectionInfo"/> class.
/// </summary>
/// <param name="customPipeName">Pipe name to connect to.</param>
/// <param name="openTimeout">Open time out in Milliseconds.</param>
public NamedPipeConnectionInfo(
string customPipeName,
int openTimeout)
{
if (customPipeName == null)
{
throw new PSArgumentNullException(nameof(customPipeName));
}
CustomPipeName = customPipeName;
OpenTimeout = openTimeout;
}
#endregion
#region Overrides
/// <summary>
/// Computer is always localhost.
/// </summary>
public override string ComputerName
{
get { return "localhost"; }
set { throw new NotImplementedException(); }
}
/// <summary>
/// Credential.
/// </summary>
public override PSCredential Credential
{
get
{
return _credential;
}
set
{
_credential = value;
_authMechanism = Runspaces.AuthenticationMechanism.Default;
}
}
/// <summary>
/// Authentication.
/// </summary>
public override AuthenticationMechanism AuthenticationMechanism
{
get
{
return _authMechanism;
}
set
{
if (value != Runspaces.AuthenticationMechanism.Default)
{
throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.IPCSupportsOnlyDefaultAuth,
value.ToString(), nameof(AuthenticationMechanism.Default));
}
_authMechanism = value;
}
}
/// <summary>
/// CertificateThumbprint.
/// </summary>
public override string CertificateThumbprint
{
get { return string.Empty; }
set { throw new NotImplementedException(); }
}
/// <summary>
/// Shallow copy of current instance.
/// </summary>
/// <returns>NamedPipeConnectionInfo.</returns>
internal override RunspaceConnectionInfo InternalCopy()
{
NamedPipeConnectionInfo newCopy = new NamedPipeConnectionInfo();
newCopy._authMechanism = this.AuthenticationMechanism;
newCopy._credential = this.Credential;
newCopy.ProcessId = this.ProcessId;
newCopy._appDomainName = _appDomainName;
newCopy.OpenTimeout = this.OpenTimeout;
newCopy.CustomPipeName = this.CustomPipeName;
return newCopy;
}
internal override BaseClientSessionTransportManager CreateClientSessionTransportManager(Guid instanceId, string sessionName, PSRemotingCryptoHelper cryptoHelper)
{
return new NamedPipeClientSessionTransportManager(
this,
instanceId,
cryptoHelper);
}
#endregion
}
/// <summary>
/// Class used to create a connection through an SSH.exe client to a remote host machine.
/// Connection information includes SSH target (user name and host machine) along with
/// client key used for key based user authorization.
/// </summary>
public sealed class SSHConnectionInfo : RunspaceConnectionInfo
{
#region Constants
/// <summary>
/// Default value for subsystem.
/// </summary>
private const string DefaultSubsystem = "powershell";
/// <summary>
/// Default value is infinite timeout.
/// </summary>
private const int DefaultConnectingTimeoutTime = Timeout.Infinite;
#endregion
#region Properties
/// <summary>
/// User Name.
/// </summary>
public string UserName
{
get;
private set;
}
/// <summary>
/// Key File Path.
/// </summary>
private string KeyFilePath
{
get;
set;
}
/// <summary>
/// Port for connection.
/// </summary>
private int Port
{
get;
set;
}
/// <summary>
/// Subsystem to use.
/// </summary>
private string Subsystem
{
get;
set;
}
/// <summary>
/// Gets or sets a time in milliseconds after which a connection attempt is terminated.
/// Default value (-1) never times out and a connection attempt waits indefinitely.
/// </summary>
public int ConnectingTimeout
{
get;
set;
}
#endregion
#region Constructors
/// <summary>
/// Constructor.
/// </summary>
private SSHConnectionInfo()
{ }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="userName">User Name.</param>
/// <param name="computerName">Computer Name.</param>
/// <param name="keyFilePath">Key File Path.</param>
public SSHConnectionInfo(
string userName,
string computerName,
string keyFilePath)
{
if (computerName == null) { throw new PSArgumentNullException(nameof(computerName)); }
UserName = userName;
ComputerName = computerName;
KeyFilePath = keyFilePath;
Port = 0;
Subsystem = DefaultSubsystem;
ConnectingTimeout = DefaultConnectingTimeoutTime;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="userName">User Name.</param>
/// <param name="computerName">Computer Name.</param>
/// <param name="keyFilePath">Key File Path.</param>
/// <param name="port">Port number for connection (default 22).</param>
public SSHConnectionInfo(
string userName,
string computerName,
string keyFilePath,
int port) : this(userName, computerName, keyFilePath)
{
ValidatePortInRange(port);
Port = port;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="userName">User Name.</param>
/// <param name="computerName">Computer Name.</param>
/// <param name="keyFilePath">Key File Path.</param>
/// <param name="port">Port number for connection (default 22).</param>
/// <param name="subsystem">Subsystem to use (default 'powershell').</param>
public SSHConnectionInfo(
string userName,
string computerName,
string keyFilePath,
int port,
string subsystem) : this(userName, computerName, keyFilePath, port)
{
Subsystem = string.IsNullOrEmpty(subsystem) ? DefaultSubsystem : subsystem;
}
/// <summary>
/// Initializes a new instance of SSHConnectionInfo.
/// </summary>
/// <param name="userName">Name of user.</param>
/// <param name="computerName">Name of computer.</param>
/// <param name="keyFilePath">Path of key file.</param>
/// <param name="port">Port number for connection (default 22).</param>
/// <param name="subsystem">Subsystem to use (default 'powershell').</param>
/// <param name="connectingTimeout">Timeout time for terminating connection attempt.</param>
public SSHConnectionInfo(
string userName,
string computerName,
string keyFilePath,
int port,
string subsystem,
int connectingTimeout) : this(userName, computerName, keyFilePath, port, subsystem)
{
ConnectingTimeout = connectingTimeout;
}
#endregion
#region Overrides
/// <summary>
/// Computer is always localhost.
/// </summary>
public override string ComputerName
{
get;
set;
}
/// <summary>
/// Credential.
/// </summary>
public override PSCredential Credential
{
get { return null; }
set { throw new NotImplementedException(); }
}
/// <summary>
/// Authentication.
/// </summary>
public override AuthenticationMechanism AuthenticationMechanism
{
get { return AuthenticationMechanism.Default; }
set { throw new NotImplementedException(); }
}
/// <summary>
/// CertificateThumbprint.
/// </summary>
public override string CertificateThumbprint
{
get { return string.Empty; }
set { throw new NotImplementedException(); }
}
/// <summary>
/// Shallow copy of current instance.
/// </summary>
/// <returns>NamedPipeConnectionInfo.</returns>
internal override RunspaceConnectionInfo InternalCopy()
{
SSHConnectionInfo newCopy = new SSHConnectionInfo();
newCopy.ComputerName = ComputerName;
newCopy.UserName = UserName;
newCopy.KeyFilePath = KeyFilePath;
newCopy.Port = Port;
newCopy.Subsystem = Subsystem;
newCopy.ConnectingTimeout = ConnectingTimeout;
return newCopy;
}
/// <summary>
/// CreateClientSessionTransportManager.
/// </summary>
/// <param name="instanceId"></param>
/// <param name="sessionName"></param>
/// <param name="cryptoHelper"></param>
/// <returns></returns>
internal override BaseClientSessionTransportManager CreateClientSessionTransportManager(Guid instanceId, string sessionName, PSRemotingCryptoHelper cryptoHelper)
{
return new SSHClientSessionTransportManager(
this,
instanceId,
cryptoHelper);
}
#endregion
#region Internal Methods
/// <summary>
/// StartSSHProcess.
/// </summary>
/// <returns></returns>
internal int StartSSHProcess(
out StreamWriter stdInWriterVar,
out StreamReader stdOutReaderVar,
out StreamReader stdErrReaderVar)
{
string filePath = string.Empty;
#if UNIX
const string sshCommand = "ssh";
#else
const string sshCommand = "ssh.exe";
#endif
var context = Runspaces.LocalPipeline.GetExecutionContextFromTLS();
if (context != null)
{
var cmdInfo = context.CommandDiscovery.LookupCommandInfo(sshCommand, CommandOrigin.Internal) as ApplicationInfo;
if (cmdInfo != null)
{
filePath = cmdInfo.Path;
}
}
// Create a local ssh process (client) that conects to a remote sshd process (server) using a 'powershell' subsystem.
//
// Local ssh invoked as:
// windows:
// ssh.exe [-i identity_file] [-l login_name] [-p port] -s <destination> <command>
// linux|macos:
// ssh [-i identity_file] [-l login_name] [-p port] -s <destination> <command>
// where <command> is interpreted as the subsystem due to the -s flag.
//
// Remote sshd configured for PowerShell Remoting Protocol (PSRP) over Secure Shell Protocol (SSH)
// by adding one of the following Subsystem directives to sshd_config on the remote machine:
// windows:
// Subsystem powershell C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -SSHServerMode -NoLogo -NoProfile
// Subsystem powershell C:\Program Files\PowerShell\6\pwsh.exe -SSHServerMode -NoLogo -NoProfile
// linux|macos:
// Subsystem powershell /usr/local/bin/pwsh -SSHServerMode -NoLogo -NoProfile
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(filePath);
// pass "-i identity_file" command line argument to ssh if KeyFilePath is set
// if KeyFilePath is not set, then ssh will use IdentityFile / IdentityAgent from ssh_config if defined else none by default
if (!string.IsNullOrEmpty(this.KeyFilePath))
{
if (!System.IO.File.Exists(this.KeyFilePath))
{
throw new FileNotFoundException(
StringUtil.Format(RemotingErrorIdStrings.KeyFileNotFound, this.KeyFilePath));
}
startInfo.ArgumentList.Add(string.Format(CultureInfo.InvariantCulture, @"-i ""{0}""", this.KeyFilePath));
}
// pass "-l login_name" command line argument to ssh if UserName is set
// if UserName is not set, then ssh will use User from ssh_config if defined else the environment user by default
if (!string.IsNullOrEmpty(this.UserName))
{
var parts = this.UserName.Split(Utils.Separators.Backslash);
if (parts.Length == 2)
{
// convert DOMAIN\user to user@DOMAIN
var domainName = parts[0];
var userName = parts[1];
startInfo.ArgumentList.Add(string.Format(CultureInfo.InvariantCulture, @"-l {0}@{1}", userName, domainName));
}
else
{
startInfo.ArgumentList.Add(string.Format(CultureInfo.InvariantCulture, @"-l {0}", this.UserName));
}
}
// pass "-p port" command line argument to ssh if Port is set
// if Port is not set, then ssh will use Port from ssh_config if defined else 22 by default
if (this.Port != 0)
{
startInfo.ArgumentList.Add(string.Format(CultureInfo.InvariantCulture, @"-p {0}", this.Port));
}
// pass "-s destination command" command line arguments to ssh where command is the subsystem to invoke on the destination
// note that ssh expects IPv6 addresses to not be enclosed in square brackets so trim them if present
startInfo.ArgumentList.Add(string.Format(CultureInfo.InvariantCulture, @"-s {0} {1}", this.ComputerName.TrimStart('[').TrimEnd(']'), this.Subsystem));
startInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(filePath);
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
return StartSSHProcessImpl(startInfo, out stdInWriterVar, out stdOutReaderVar, out stdErrReaderVar);
}
internal void KillSSHProcess(int pid)
{
KillSSHProcessImpl(pid);
}
#endregion
#region SSH Process Creation
#if UNIX
/// <summary>
/// Create a process through managed APIs and returns StdIn, StdOut, StdError reader/writers.
/// This works for Linux platforms and creates the SSH process in its own session which means
/// Ctrl+C signals will not propagate from parent (PowerShell) process to SSH process so that
/// PSRP handles them correctly.
/// </summary>
private static int StartSSHProcessImpl(
System.Diagnostics.ProcessStartInfo startInfo,
out StreamWriter stdInWriterVar,
out StreamReader stdOutReaderVar,
out StreamReader stdErrReaderVar)
{
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
StreamWriter stdInWriter = null;
StreamReader stdOutReader = null;
StreamReader stdErrReader = null;
int pid = StartSSHProcess(
startInfo,
ref stdInWriter,
ref stdOutReader,
ref stdErrReader);
stdInWriterVar = stdInWriter;
stdOutReaderVar = stdOutReader;
stdErrReaderVar = stdErrReader;
return pid;
}
private static void KillSSHProcessImpl(int pid)
{
// killing a zombie might or might not return ESRCH, so we ignore kill's return value
Platform.NonWindowsKillProcess(pid);
// block while waiting for process to die
// shouldn't take long after SIGKILL
Platform.NonWindowsWaitPid(pid, false);
}
#region UNIX Create Process
//
// This code is based on GitHub DotNet CoreFx
// It is specific to launching the SSH process for use in
// SSH based remoting, and is not intended to be general
// process creation code.
//
private const int StreamBufferSize = 4096;
private const int SUPPRESS_PROCESS_SIGINT = 0x00000001;
internal static int StartSSHProcess(
ProcessStartInfo startInfo,
ref StreamWriter standardInput,
ref StreamReader standardOutput,
ref StreamReader standardError)
{
if (startInfo.UseShellExecute)
{
throw new PSNotSupportedException();
}
string filename = startInfo.FileName;
string[] argv = ParseArgv(startInfo);
string[] envp = CopyEnvVariables(startInfo);
string cwd = !string.IsNullOrWhiteSpace(startInfo.WorkingDirectory) ? startInfo.WorkingDirectory : null;
// Invoke the shim fork/execve routine. It will create pipes for all requested
// redirects, fork a child process, map the pipe ends onto the appropriate stdin/stdout/stderr
// descriptors, and execve to execute the requested process. The shim implementation
// is used to fork/execve as executing managed code in a forked process is not safe (only
// the calling thread will transfer, thread IDs aren't stable across the fork, etc.)
int childPid, stdinFd, stdoutFd, stderrFd;
CreateProcess(
filename, argv, envp, cwd,
startInfo.RedirectStandardInput, startInfo.RedirectStandardOutput, startInfo.RedirectStandardError,
SUPPRESS_PROCESS_SIGINT, // Create SSH process to ignore SIGINT signals
out childPid,
out stdinFd, out stdoutFd, out stderrFd);
Debug.Assert(childPid >= 0, "Invalid process id");
// Configure the parent's ends of the redirection streams.
// We use UTF8 encoding without BOM by-default(instead of Console encoding as on Windows)
// as there is no good way to get this information from the native layer
// and we do not want to take dependency on Console contract.
if (startInfo.RedirectStandardInput)
{
Debug.Assert(stdinFd >= 0, "Invalid Fd");
standardInput = new StreamWriter(OpenStream(stdinFd, FileAccess.Write),
Utils.utf8NoBom, StreamBufferSize)
{ AutoFlush = true };
}
if (startInfo.RedirectStandardOutput)
{
Debug.Assert(stdoutFd >= 0, "Invalid Fd");
standardOutput = new StreamReader(OpenStream(stdoutFd, FileAccess.Read),
startInfo.StandardOutputEncoding ?? Utils.utf8NoBom, true, StreamBufferSize);
}
if (startInfo.RedirectStandardError)
{
Debug.Assert(stderrFd >= 0, "Invalid Fd");
standardError = new StreamReader(OpenStream(stderrFd, FileAccess.Read),
startInfo.StandardErrorEncoding ?? Utils.utf8NoBom, true, StreamBufferSize);
}
return childPid;
}
/// <summary>Opens a stream around the specified file descriptor and with the specified access.</summary>
/// <param name="fd">The file descriptor.</param>
/// <param name="access">The access mode.</param>
/// <returns>The opened stream.</returns>
private static FileStream OpenStream(int fd, FileAccess access)
{
Debug.Assert(fd >= 0, "Invalid Fd");
return new FileStream(
new SafeFileHandle((IntPtr)fd, ownsHandle: true),
access, StreamBufferSize, isAsync: false);
}
/// <summary>Copies environment variables from ProcessStartInfo </summary>
/// <param name="psi">ProcessStartInfo.</param>
/// <returns>String array of environment key/value pairs.</returns>
private static string[] CopyEnvVariables(ProcessStartInfo psi)
{
var envp = new string[psi.Environment.Count];
int index = 0;
foreach (var pair in psi.Environment)
{
envp[index++] = pair.Key + "=" + pair.Value;
}
return envp;
}
/// <summary>Converts the filename and arguments information from a ProcessStartInfo into an argv array.</summary>
/// <param name="psi">The ProcessStartInfo.</param>
/// <returns>The argv array.</returns>
private static string[] ParseArgv(ProcessStartInfo psi)
{
var argvList = new List<string>();
argvList.Add(psi.FileName);
var argsToParse = String.Join(" ", psi.ArgumentList).Trim();
var argsLength = argsToParse.Length;
for (int i = 0; i < argsLength; )
{
var iStart = i;
switch (argsToParse[i])
{
case '"':
// Special case for arguments within quotes
// Just return argument value within the quotes
while ((++i < argsLength) && argsToParse[i] != '"') { }
if (iStart < argsLength - 1)
{
iStart++;
}
break;
default:
// Common case for parsing arguments with space character delimiter
while ((++i < argsLength) && argsToParse[i] != ' ') { }
break;
}
argvList.Add(argsToParse.Substring(iStart, (i - iStart)));
while ((++i < argsLength) && argsToParse[i] == ' ') { }
}
return argvList.ToArray();
}
internal static unsafe void CreateProcess(
string filename, string[] argv, string[] envp, string cwd,
bool redirectStdin, bool redirectStdout, bool redirectStderr, int creationFlags,
out int lpChildPid, out int stdinFd, out int stdoutFd, out int stderrFd)
{
byte** argvPtr = null, envpPtr = null;
try
{
AllocNullTerminatedArray(argv, ref argvPtr);
AllocNullTerminatedArray(envp, ref envpPtr);
int result = ForkAndExecProcess(
filename, argvPtr, envpPtr, cwd,
redirectStdin ? 1 : 0, redirectStdout ? 1 : 0, redirectStderr ? 1 : 0, creationFlags,
out lpChildPid, out stdinFd, out stdoutFd, out stderrFd);
if (result != 0)
{
// Normally we'd simply make this method return the result of the native
// call and allow the caller to use GetLastWin32Error. However, we need
// to free the native arrays after calling the function, and doing so
// stomps on the runtime's captured last error. So we need to access the
// error here, and without SetLastWin32Error available, we can't propagate
// the error to the caller via the normal GetLastWin32Error mechanism. We could
// return 0 on success or the GetLastWin32Error value on failure, but that's
// technically ambiguous, in the case of a failure with a 0 errno. Simplest
// solution then is just to throw here the same exception the Process caller
// would have. This can be revisited if we ever have another call site.
throw new Win32Exception();
}
}
finally
{
FreeArray(envpPtr, envp.Length);
FreeArray(argvPtr, argv.Length);
}
}
private static unsafe void AllocNullTerminatedArray(string[] arr, ref byte** arrPtr)
{
int arrLength = arr.Length + 1; // +1 is for null termination
// Allocate the unmanaged array to hold each string pointer.
// It needs to have an extra element to null terminate the array.
arrPtr = (byte**)Marshal.AllocHGlobal(sizeof(IntPtr) * arrLength);
System.Diagnostics.Debug.Assert(arrPtr != null, "Invalid array ptr");
// Zero the memory so that if any of the individual string allocations fails,
// we can loop through the array to free any that succeeded.
// The last element will remain null.
for (int i = 0; i < arrLength; i++)
{
arrPtr[i] = null;
}
// Now copy each string to unmanaged memory referenced from the array.
// We need the data to be an unmanaged, null-terminated array of UTF8-encoded bytes.
for (int i = 0; i < arr.Length; i++)
{
byte[] byteArr = System.Text.Encoding.UTF8.GetBytes(arr[i]);
arrPtr[i] = (byte*)Marshal.AllocHGlobal(byteArr.Length + 1); // +1 for null termination
System.Diagnostics.Debug.Assert(arrPtr[i] != null, "Invalid array ptr");
Marshal.Copy(byteArr, 0, (IntPtr)arrPtr[i], byteArr.Length); // copy over the data from the managed byte array
arrPtr[i][byteArr.Length] = (byte)'\0'; // null terminate
}
}
private static unsafe void FreeArray(byte** arr, int length)
{
if (arr != null)
{
// Free each element of the array
for (int i = 0; i < length; i++)
{
if (arr[i] != null)
{
Marshal.FreeHGlobal((IntPtr)arr[i]);
arr[i] = null;
}
}
// And then the array itself
Marshal.FreeHGlobal((IntPtr)arr);
}
}
[DllImport("libpsl-native", CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern unsafe int ForkAndExecProcess(
string filename, byte** argv, byte** envp, string cwd,
int redirectStdin, int redirectStdout, int redirectStderr, int creationFlags,
out int lpChildPid, out int stdinFd, out int stdoutFd, out int stderrFd);
#endregion
#else
/// <summary>
/// Create a process through native Win32 APIs and return StdIn, StdOut, StdError reader/writers
/// This needs to be done via Win32 APIs because managed code creates anonymous synchronous pipes
/// for redirected StdIn/Out and SSH (and PSRP) require asynchronous (overlapped) pipes, which must
/// be through named pipes. Managed code for named pipes is unreliable and so this is done via
/// P-Invoking native APIs.
/// </summary>
private static int StartSSHProcessImpl(
System.Diagnostics.ProcessStartInfo startInfo,
out StreamWriter stdInWriterVar,
out StreamReader stdOutReaderVar,
out StreamReader stdErrReaderVar)
{
Exception ex = null;
System.Diagnostics.Process sshProcess = null;
//
// These std pipe handles are bound to managed Reader/Writer objects and returned to the transport
// manager object, which uses them for PSRP communication. The lifetime of these handles are then
// tied to the reader/writer objects which the transport is responsible for disposing (see
// SSHClientSessionTransportManger and the CloseConnection() method.
//
SafePipeHandle stdInPipeServer = null;
SafePipeHandle stdOutPipeServer = null;
SafePipeHandle stdErrPipeServer = null;
try
{
sshProcess = CreateProcessWithRedirectedStd(
startInfo,
out stdInPipeServer,
out stdOutPipeServer,
out stdErrPipeServer);
}
catch (InvalidOperationException e) { ex = e; }
catch (ArgumentException e) { ex = e; }
catch (FileNotFoundException e) { ex = e; }
catch (System.ComponentModel.Win32Exception e) { ex = e; }
if ((ex != null) ||
(sshProcess == null) ||
(sshProcess.HasExited))
{
throw new InvalidOperationException(
StringUtil.Format(RemotingErrorIdStrings.CannotStartSSHClient, (ex != null) ? ex.Message : string.Empty),
ex);
}
// Create the std in writer/readers needed for communication with ssh.exe.
stdInWriterVar = null;
stdOutReaderVar = null;
stdErrReaderVar = null;
try
{
stdInWriterVar = new StreamWriter(new NamedPipeServerStream(PipeDirection.Out, true, true, stdInPipeServer));
stdOutReaderVar = new StreamReader(new NamedPipeServerStream(PipeDirection.In, true, true, stdOutPipeServer));
stdErrReaderVar = new StreamReader(new NamedPipeServerStream(PipeDirection.In, true, true, stdErrPipeServer));
}
catch (Exception)
{
if (stdInWriterVar != null) { stdInWriterVar.Dispose(); } else { stdInPipeServer.Dispose(); }
if (stdOutReaderVar != null) { stdInWriterVar.Dispose(); } else { stdOutPipeServer.Dispose(); }
if (stdErrReaderVar != null) { stdInWriterVar.Dispose(); } else { stdErrPipeServer.Dispose(); }
throw;
}
return sshProcess.Id;
}
private static void KillSSHProcessImpl(int pid)
{
using (var sshProcess = System.Diagnostics.Process.GetProcessById(pid))
{
if ((sshProcess != null) && (sshProcess.Handle != IntPtr.Zero) && !sshProcess.HasExited)
{
sshProcess.Kill();
}
}
}
// Process creation flags
private const int CREATE_NEW_PROCESS_GROUP = 0x00000200;
private const int CREATE_SUSPENDED = 0x00000004;
/// <summary>
/// CreateProcessWithRedirectedStd.
/// </summary>
private static Process CreateProcessWithRedirectedStd(
ProcessStartInfo startInfo,
out SafePipeHandle stdInPipeServer,
out SafePipeHandle stdOutPipeServer,
out SafePipeHandle stdErrPipeServer)
{
//
// Create named (async) pipes for reading/writing to std.
//
stdInPipeServer = null;
stdOutPipeServer = null;
stdErrPipeServer = null;
SafePipeHandle stdInPipeClient = null;
SafePipeHandle stdOutPipeClient = null;
SafePipeHandle stdErrPipeClient = null;
string randomName = System.IO.Path.GetFileNameWithoutExtension(System.IO.Path.GetRandomFileName());
try
{
// Get default pipe security (Admin and current user access)
var securityDesc = RemoteSessionNamedPipeServer.GetServerPipeSecurity();
var stdInPipeName = @"\\.\pipe\StdIn" + randomName;
stdInPipeServer = CreateNamedPipe(stdInPipeName, securityDesc);
stdInPipeClient = GetNamedPipeHandle(stdInPipeName);
var stdOutPipeName = @"\\.\pipe\StdOut" + randomName;
stdOutPipeServer = CreateNamedPipe(stdOutPipeName, securityDesc);
stdOutPipeClient = GetNamedPipeHandle(stdOutPipeName);
var stdErrPipeName = @"\\.\pipe\StdErr" + randomName;
stdErrPipeServer = CreateNamedPipe(stdErrPipeName, securityDesc);
stdErrPipeClient = GetNamedPipeHandle(stdErrPipeName);
}
catch (Exception)
{
if (stdInPipeServer != null) { stdInPipeServer.Dispose(); }
if (stdInPipeClient != null) { stdInPipeClient.Dispose(); }
if (stdOutPipeServer != null) { stdOutPipeServer.Dispose(); }
if (stdOutPipeClient != null) { stdOutPipeClient.Dispose(); }
if (stdErrPipeServer != null) { stdErrPipeServer.Dispose(); }
if (stdErrPipeClient != null) { stdErrPipeClient.Dispose(); }
throw;
}
// Create process
PlatformInvokes.STARTUPINFO lpStartupInfo = new PlatformInvokes.STARTUPINFO();
PlatformInvokes.PROCESS_INFORMATION lpProcessInformation = new PlatformInvokes.PROCESS_INFORMATION();
int creationFlags = 0;
try
{
// Create process start command line with filename and argument list.
var cmdLine = string.Format(
CultureInfo.InvariantCulture,
@"""{0}"" {1}",
startInfo.FileName,
string.Join(' ', startInfo.ArgumentList));
lpStartupInfo.hStdInput = new SafeFileHandle(stdInPipeClient.DangerousGetHandle(), false);
lpStartupInfo.hStdOutput = new SafeFileHandle(stdOutPipeClient.DangerousGetHandle(), false);
lpStartupInfo.hStdError = new SafeFileHandle(stdErrPipeClient.DangerousGetHandle(), false);
lpStartupInfo.dwFlags = 0x100;
// No new window: Inherit the parent process's console window
creationFlags = 0x00000000;
// Create the new process in its own group, so that Ctrl+C is not sent to ssh.exe. We want to handle this
// control signal internally so that it can be passed via PSRP to the remote session.
creationFlags |= CREATE_NEW_PROCESS_GROUP;
// Create the new process suspended so we have a chance to get a corresponding Process object in case it terminates quickly.
creationFlags |= CREATE_SUSPENDED;
PlatformInvokes.SECURITY_ATTRIBUTES lpProcessAttributes = new PlatformInvokes.SECURITY_ATTRIBUTES();
PlatformInvokes.SECURITY_ATTRIBUTES lpThreadAttributes = new PlatformInvokes.SECURITY_ATTRIBUTES();
bool success = PlatformInvokes.CreateProcess(
null,
cmdLine,
lpProcessAttributes,
lpThreadAttributes,
true,
creationFlags,
IntPtr.Zero,
startInfo.WorkingDirectory,
lpStartupInfo,
lpProcessInformation);
if (!success)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
// At this point, we should have a suspended process. Get the .Net Process object, resume the process, and return.
Process result = Process.GetProcessById(lpProcessInformation.dwProcessId);
uint returnValue = PlatformInvokes.ResumeThread(lpProcessInformation.hThread);
if (returnValue == PlatformInvokes.RESUME_THREAD_FAILED)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
return result;
}
catch (Exception)
{
if (stdInPipeServer != null) { stdInPipeServer.Dispose(); }
if (stdInPipeClient != null) { stdInPipeClient.Dispose(); }
if (stdOutPipeServer != null) { stdOutPipeServer.Dispose(); }
if (stdOutPipeClient != null) { stdOutPipeClient.Dispose(); }
if (stdErrPipeServer != null) { stdErrPipeServer.Dispose(); }
if (stdErrPipeClient != null) { stdErrPipeClient.Dispose(); }
throw;
}
finally
{
lpProcessInformation.Dispose();
}
}
private static SafePipeHandle GetNamedPipeHandle(string pipeName)
{
// Get handle to pipe.
var fileHandle = PlatformInvokes.CreateFileW(
lpFileName: pipeName,
dwDesiredAccess: NamedPipeNative.GENERIC_READ | NamedPipeNative.GENERIC_WRITE,
dwShareMode: 0,
lpSecurityAttributes: new PlatformInvokes.SECURITY_ATTRIBUTES(), // Create an inheritable handle.
dwCreationDisposition: NamedPipeNative.OPEN_EXISTING,
dwFlagsAndAttributes: NamedPipeNative.FILE_FLAG_OVERLAPPED, // Open in asynchronous mode.
hTemplateFile: IntPtr.Zero);
int lastError = Marshal.GetLastWin32Error();
if (fileHandle == PlatformInvokes.INVALID_HANDLE_VALUE)
{
throw new System.ComponentModel.Win32Exception(lastError);
}
return new SafePipeHandle(fileHandle, true);
}
private static SafePipeHandle CreateNamedPipe(
string pipeName,
CommonSecurityDescriptor securityDesc)
{
// Create optional security attributes based on provided PipeSecurity.
NamedPipeNative.SECURITY_ATTRIBUTES securityAttributes = null;
GCHandle? securityDescHandle = null;
if (securityDesc != null)
{
byte[] securityDescBuffer = new byte[securityDesc.BinaryLength];
securityDesc.GetBinaryForm(securityDescBuffer, 0);
securityDescHandle = GCHandle.Alloc(securityDescBuffer, GCHandleType.Pinned);
securityAttributes = NamedPipeNative.GetSecurityAttributes(securityDescHandle.Value, true);
}
// Create async named pipe.
SafePipeHandle pipeHandle = NamedPipeNative.CreateNamedPipe(
pipeName,
NamedPipeNative.PIPE_ACCESS_DUPLEX | NamedPipeNative.FILE_FLAG_FIRST_PIPE_INSTANCE | NamedPipeNative.FILE_FLAG_OVERLAPPED,
NamedPipeNative.PIPE_TYPE_MESSAGE | NamedPipeNative.PIPE_READMODE_MESSAGE,
1,
32768,
32768,
0,
securityAttributes);
int lastError = Marshal.GetLastWin32Error();
if (securityDescHandle != null)
{
securityDescHandle.Value.Free();
}
if (pipeHandle.IsInvalid)
{
throw new Win32Exception(lastError);
}
return pipeHandle;
}
#endif
#endregion
}
/// <summary>
/// The class that contains connection information for a remote session between a local host
/// and VM. The local host can be a VM in nested scenario.
/// </summary>
public sealed class VMConnectionInfo : RunspaceConnectionInfo
{
#region Private Data
private AuthenticationMechanism _authMechanism;
private PSCredential _credential;
private const int _defaultOpenTimeout = 20000; /* 20 seconds. */
#endregion
#region Properties
/// <summary>
/// GUID of the target VM.
/// </summary>
public Guid VMGuid { get; set; }
/// <summary>
/// Configuration name of the VM session.
/// </summary>
public string ConfigurationName { get; set; }
#endregion
#region Overrides
/// <summary>
/// Authentication mechanism to use while connecting to the server.
/// Only Default is supported.
/// </summary>
public override AuthenticationMechanism AuthenticationMechanism
{
get
{
return _authMechanism;
}
set
{
if (value != AuthenticationMechanism.Default)
{
throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.IPCSupportsOnlyDefaultAuth,
value.ToString(), nameof(AuthenticationMechanism.Default));
}
_authMechanism = value;
}
}
/// <summary>
/// ThumbPrint of a certificate used for connecting to a remote machine.
/// When this is specified, you dont need to supply credential and authentication
/// mechanism.
/// Will always be null to signify that this is not supported.
/// </summary>
public override string CertificateThumbprint
{
get { return null; }
set { throw new NotImplementedException(); }
}
/// <summary>
/// Credential used for the connection.
/// </summary>
public override PSCredential Credential
{
get
{
return _credential;
}
set
{
_credential = value;
_authMechanism = AuthenticationMechanism.Default;
}
}
/// <summary>
/// Name of the target VM.
/// </summary>
public override string ComputerName { get; set; }
internal override RunspaceConnectionInfo InternalCopy()
{
VMConnectionInfo result = new VMConnectionInfo(Credential, VMGuid, ComputerName, ConfigurationName);
return result;
}
internal override BaseClientSessionTransportManager CreateClientSessionTransportManager(Guid instanceId, string sessionName, PSRemotingCryptoHelper cryptoHelper)
{
return new VMHyperVSocketClientSessionTransportManager(
this,
instanceId,
cryptoHelper,
VMGuid,
ConfigurationName);
}
#endregion
#region Constructors
/// <summary>
/// Creates a connection info instance used to create a runspace on target VM.
/// </summary>
internal VMConnectionInfo(
PSCredential credential,
Guid vmGuid,
string vmName,
string configurationName)
: base()
{
Credential = credential;
VMGuid = vmGuid;
ComputerName = vmName;
ConfigurationName = configurationName;
AuthenticationMechanism = AuthenticationMechanism.Default;
OpenTimeout = _defaultOpenTimeout;
}
#endregion
}
/// <summary>
/// The class that contains connection information for a remote session between a local
/// container host and container.
/// For Windows Server container, the transport is based on named pipe for now.
/// For Hyper-V container, the transport is based on Hyper-V socket.
/// </summary>
public sealed class ContainerConnectionInfo : RunspaceConnectionInfo
{
#region Private Data
private AuthenticationMechanism _authMechanism;
private PSCredential _credential;
private const int _defaultOpenTimeout = 20000; /* 20 seconds. */
#endregion
#region Properties
/// <summary>
/// ContainerProcess class instance.
/// </summary>
internal ContainerProcess ContainerProc { get; set; }
#endregion
#region Overrides
/// <summary>
/// Authentication mechanism to use while connecting to the server.
/// Only Default is supported.
/// </summary>
public override AuthenticationMechanism AuthenticationMechanism
{
get
{
return _authMechanism;
}
set
{
if (value != AuthenticationMechanism.Default)
{
throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.IPCSupportsOnlyDefaultAuth,
value.ToString(), nameof(AuthenticationMechanism.Default));
}
_authMechanism = value;
}
}
/// <summary>
/// ThumbPrint of a certificate used for connecting to a remote machine.
/// When this is specified, you dont need to supply credential and authentication
/// mechanism.
/// Will always be null to signify that this is not supported.
/// </summary>
public override string CertificateThumbprint
{
get { return null; }
set { throw new NotImplementedException(); }
}
/// <summary>
/// Credential used for the connection.
/// </summary>
public override PSCredential Credential
{
get
{
return _credential;
}
set
{
_credential = value;
_authMechanism = Runspaces.AuthenticationMechanism.Default;
}
}
/// <summary>
/// Name of the target container.
/// </summary>
public override string ComputerName
{
get { return ContainerProc.ContainerId; }
set { throw new PSNotSupportedException(); }
}
internal override RunspaceConnectionInfo InternalCopy()
{
ContainerConnectionInfo newCopy = new ContainerConnectionInfo(ContainerProc);
return newCopy;
}
internal override BaseClientSessionTransportManager CreateClientSessionTransportManager(Guid instanceId, string sessionName, PSRemotingCryptoHelper cryptoHelper)
{
if (ContainerProc.RuntimeId != Guid.Empty)
{
return new ContainerHyperVSocketClientSessionTransportManager(
this,
instanceId,
cryptoHelper,
ContainerProc.RuntimeId);
}
else
{
return new ContainerNamedPipeClientSessionTransportManager(
this,
instanceId,
cryptoHelper);
}
}
#endregion
#region Constructors
/// <summary>
/// Creates a connection info instance used to create a runspace on target container.
/// </summary>
internal ContainerConnectionInfo(
ContainerProcess containerProc)
: base()
{
ContainerProc = containerProc;
AuthenticationMechanism = AuthenticationMechanism.Default;
Credential = null;
OpenTimeout = _defaultOpenTimeout;
}
#endregion
#region Public methods
/// <summary>
/// Create ContainerConnectionInfo object based on container id.
/// </summary>
public static ContainerConnectionInfo CreateContainerConnectionInfo(
string containerId,
bool runAsAdmin,
string configurationName)
{
ContainerProcess containerProc = new ContainerProcess(containerId, null, 0, runAsAdmin, configurationName);
return new ContainerConnectionInfo(containerProc);
}
/// <summary>
/// Create process inside container.
/// </summary>
public void CreateContainerProcess()
{
ContainerProc.CreateContainerProcess();
}
/// <summary>
/// Terminate process inside container.
/// </summary>
public bool TerminateContainerProcess()
{
return ContainerProc.TerminateContainerProcess();
}
#endregion
}
/// <summary>
/// Class used to create/terminate process inside container, which can be either
/// Windows Server Container or Hyper-V container.
/// - Windows Server Container does not require Hyper-V.
/// - Hyper-V container requires Hyper-V and utility VM, which is different from normal VM.
/// </summary>
internal class ContainerProcess
{
#region Private Data
private const uint NoError = 0;
private const uint InvalidContainerId = 1;
private const uint ContainersFeatureNotEnabled = 2;
private const uint OtherError = 9999;
private const uint FileNotFoundHResult = 0x80070002;
// The list of executable to try in order
private static readonly string[] Executables = new string[] { "pwsh.exe", "powershell.exe" };
#endregion
#region Properties
/// <summary>
/// Gets or Sets, for Hyper-V container, the Guid of utility VM hosting Hyper-V container.
/// For Windows Server Container, it is empty.
/// </summary>
public Guid RuntimeId { get; set; }
/// <summary>
/// Gets or sets the OB root of the container.
/// </summary>
public string ContainerObRoot { get; set; }
/// <summary>
/// Gets or sets the ID of the container.
/// </summary>
public string ContainerId { get; set; }
/// <summary>
/// Gets or sets the process ID of the process created in container.
/// </summary>
internal int ProcessId { get; set; }
/// <summary>
/// Gets or sets whether the process in container should be launched as high privileged account
/// (RunAsAdmin being true) or low privileged account (RunAsAdmin being false).
/// </summary>
internal bool RunAsAdmin { get; set; } = false;
/// <summary>
/// Gets or sets the configuration name of the container session.
/// </summary>
internal string ConfigurationName { get; set; }
/// <summary>
/// Gets or sets whether the process in container has terminated.
/// </summary>
internal bool ProcessTerminated { get; set; } = false;
/// <summary>
/// Gets or sets the error code.
/// </summary>
internal uint ErrorCode { get; set; } = 0;
/// <summary>
/// Gets or sets the error message for other errors.
/// </summary>
internal string ErrorMessage { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the PowerShell executable being used to host the runspace.
/// </summary>
internal string Executable { get; set; } = string.Empty;
#endregion
#region Native HCS (i.e., host compute service) methods
[StructLayout(LayoutKind.Sequential)]
internal struct HCS_PROCESS_INFORMATION
{
/// <summary>
/// The process id.
/// </summary>
public uint ProcessId;
/// <summary>
/// Reserved.
/// </summary>
public uint Reserved;
/// <summary>
/// If created, standard input handle of the process.
/// </summary>
public IntPtr StdInput;
/// <summary>
/// If created, standard output handle of the process.
/// </summary>
public IntPtr StdOutput;
/// <summary>
/// If created, standard error handle of the process.
/// </summary>
public IntPtr StdError;
}
[DllImport(PinvokeDllNames.CreateProcessInComputeSystemDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern uint HcsOpenComputeSystem(
string id,
ref IntPtr computeSystem,
ref string result);
[DllImport(PinvokeDllNames.CreateProcessInComputeSystemDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern uint HcsGetComputeSystemProperties(
IntPtr computeSystem,
string propertyQuery,
ref string properties,
ref string result);
[DllImport(PinvokeDllNames.CreateProcessInComputeSystemDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern uint HcsCreateProcess(
IntPtr computeSystem,
string processParameters,
ref HCS_PROCESS_INFORMATION processInformation,
ref IntPtr process,
ref string result);
[DllImport(PinvokeDllNames.CreateProcessInComputeSystemDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern uint HcsOpenProcess(
IntPtr computeSystem,
int processId,
ref IntPtr process,
ref string result);
[DllImport(PinvokeDllNames.CreateProcessInComputeSystemDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern uint HcsTerminateProcess(
IntPtr process,
ref string result);
#endregion
#region Constructors
/// <summary>
/// Creates an instance used for PowerShell Direct for container.
/// </summary>
public ContainerProcess(string containerId, string containerObRoot, int processId, bool runAsAdmin, string configurationName)
{
this.ContainerId = containerId;
this.ContainerObRoot = containerObRoot;
this.ProcessId = processId;
this.RunAsAdmin = runAsAdmin;
this.ConfigurationName = configurationName;
Dbg.Assert(!string.IsNullOrEmpty(containerId), "containerId input cannot be empty.");
GetContainerProperties();
}
#endregion
#region Public methods
/// <summary>
/// Create process inside container.
/// </summary>
public void CreateContainerProcess()
{
RunOnMTAThread(CreateContainerProcessInternal);
//
// Report error. More error reporting will come later.
//
switch (ErrorCode)
{
case NoError:
break;
case InvalidContainerId:
throw new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.InvalidContainerId,
ContainerId));
case ContainersFeatureNotEnabled:
throw new PSInvalidOperationException(RemotingErrorIdStrings.ContainersFeatureNotEnabled);
// other errors caught with exception
case OtherError:
throw new PSInvalidOperationException(ErrorMessage);
// other errors caught without exception
default:
throw new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.CannotCreateProcessInContainer,
ContainerId,
Executable,
ErrorCode));
}
}
/// <summary>
/// Terminate process inside container.
/// </summary>
public bool TerminateContainerProcess()
{
RunOnMTAThread(TerminateContainerProcessInternal);
return ProcessTerminated;
}
/// <summary>
/// Get object root based on given container id.
/// </summary>
public void GetContainerProperties()
{
RunOnMTAThread(GetContainerPropertiesInternal);
//
// Report error.
//
switch (ErrorCode)
{
case NoError:
break;
case ContainersFeatureNotEnabled:
throw new PSInvalidOperationException(RemotingErrorIdStrings.ContainersFeatureNotEnabled);
case OtherError:
throw new PSInvalidOperationException(ErrorMessage);
}
}
#endregion
#region Private methods
/// <summary>
/// Dynamically load the Host Compute interop assemblies and return useful types.
/// </summary>
/// <param name="computeSystemPropertiesType">The HCS.Compute.System.Properties type.</param>
/// <param name="hostComputeInteropType">The Microsoft.HostCompute.Interop.HostComputeInterop type.</param>
private static void GetHostComputeInteropTypes(out Type computeSystemPropertiesType, out Type hostComputeInteropType)
{
Assembly schemaAssembly = Assembly.Load(new AssemblyName("Microsoft.HyperV.Schema, Version=10.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"));
// The type name was changed in newer version of Windows so we check for new one first,
// then fallback to previous type name to support older versions of Windows
computeSystemPropertiesType = schemaAssembly.GetType("HCS.Compute.System.Properties");
if (computeSystemPropertiesType == null)
{
computeSystemPropertiesType = schemaAssembly.GetType("Microsoft.HyperV.Schema.Compute.System.Properties");
if (computeSystemPropertiesType == null)
{
throw new PSInvalidOperationException(RemotingErrorIdStrings.CannotGetHostInteropTypes);
}
}
Assembly hostComputeInteropAssembly = Assembly.Load(new AssemblyName("Microsoft.HostCompute.Interop, Version=10.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"));
hostComputeInteropType = hostComputeInteropAssembly.GetType("Microsoft.HostCompute.Interop.HostComputeInterop");
if (hostComputeInteropType == null)
{
throw new PSInvalidOperationException(RemotingErrorIdStrings.CannotGetHostInteropTypes);
}
}
/// <summary>
/// Create process inside container.
/// </summary>
private void CreateContainerProcessInternal()
{
uint result;
string cmd;
int processId = 0;
uint error = 0;
//
// Check whether the given container id exists.
//
try
{
IntPtr ComputeSystem = IntPtr.Zero;
string resultString = string.Empty;
result = HcsOpenComputeSystem(ContainerId, ref ComputeSystem, ref resultString);
if (result != 0)
{
processId = 0;
error = InvalidContainerId;
}
else
{
//
// Hyper-V container (i.e., RuntimeId is not empty) uses Hyper-V socket transport.
// Windows Server container (i.e., RuntimeId is empty) uses named pipe transport for now.
// This code executes `pwsh.exe` as it exists in the container which currently is
// expected to be PowerShell 6+ as it's inbox in the container.
// If `pwsh.exe` does not exist, fall back to `powershell.exe` which is Windows PowerShell.
//
foreach (string executableToTry in Executables)
{
cmd = GetContainerProcessCommand(executableToTry);
HCS_PROCESS_INFORMATION ProcessInformation = new HCS_PROCESS_INFORMATION();
IntPtr Process = IntPtr.Zero;
//
// Create PowerShell process inside the container.
//
result = HcsCreateProcess(ComputeSystem, cmd, ref ProcessInformation, ref Process, ref resultString);
if (result == 0)
{
processId = Convert.ToInt32(ProcessInformation.ProcessId);
// Reset error to 0 in case this is not the first iteration of the loop.
error = 0;
// the process was started, exit the loop.
break;
}
else if (result == FileNotFoundHResult)
{
// "The system cannot find the file specified", try the next one
// or exit the loop of none are left to try.
// Set the process and error information in case we exit the loop.
processId = 0;
error = result;
continue;
}
else
{
processId = 0;
error = result;
// the executable was found but did not work
// exit the loop with the error state.
break;
}
}
}
}
catch (Exception e)
{
if (e is FileNotFoundException || e is FileLoadException)
{
//
// The ComputeSystemExists call depends on the existence of microsoft.hostcompute.interop.dll,
// which requires Containers feature to be enabled. In case Containers feature is
// not enabled, we need to output a corresponding error message to inform user.
//
ProcessId = 0;
ErrorCode = ContainersFeatureNotEnabled;
return;
}
else
{
ProcessId = 0;
ErrorCode = OtherError;
ErrorMessage = GetErrorMessageFromException(e);
return;
}
}
ProcessId = processId;
ErrorCode = error;
}
/// <summary>
/// Get Command to launch container process based on instance properties.
/// </summary>
/// <param name="executable">The name of the executable to use in the command.</param>
/// <returns>The command to launch the container process.</returns>
private string GetContainerProcessCommand(string executable)
{
Executable = executable;
return string.Format(
System.Globalization.CultureInfo.InvariantCulture,
@"{{""CommandLine"": ""{0} {1} -NoLogo {2}"",""RestrictedToken"": {3}}}",
Executable,
(RuntimeId != Guid.Empty) ? "-SocketServerMode -NoProfile" : "-NamedPipeServerMode",
string.IsNullOrEmpty(ConfigurationName) ? string.Empty : string.Concat("-Config ", ConfigurationName),
RunAsAdmin ? "false" : "true");
}
/// <summary>
/// Terminate the process inside container.
/// </summary>
private void TerminateContainerProcessInternal()
{
IntPtr ComputeSystem = IntPtr.Zero;
string resultString = string.Empty;
IntPtr process = IntPtr.Zero;
ProcessTerminated = false;
if (HcsOpenComputeSystem(ContainerId, ref ComputeSystem, ref resultString) == 0)
{
if (HcsOpenProcess(ComputeSystem, ProcessId, ref process, ref resultString) == 0)
{
if (HcsTerminateProcess(process, ref resultString) == 0)
{
ProcessTerminated = true;
}
}
}
}
/// <summary>
/// Get object root based on given container id.
/// </summary>
private void GetContainerPropertiesInternal()
{
try
{
IntPtr ComputeSystem = IntPtr.Zero;
string resultString = string.Empty;
if (HcsOpenComputeSystem(ContainerId, ref ComputeSystem, ref resultString) == 0)
{
Type computeSystemPropertiesType;
Type hostComputeInteropType;
GetHostComputeInteropTypes(out computeSystemPropertiesType, out hostComputeInteropType);
MethodInfo getComputeSystemPropertiesInfo = hostComputeInteropType.GetMethod("HcsGetComputeSystemProperties");
var computeSystemPropertiesHandle = getComputeSystemPropertiesInfo.Invoke(null, new object[] { ComputeSystem });
// Since Hyper-V changed this from a property to a field, we can optimize for newest Windows to see if it's a field,
// otherwise we fall back to old code to be compatible with older versions of Windows
var fieldInfo = computeSystemPropertiesType.GetField("RuntimeId");
if (fieldInfo != null)
{
RuntimeId = (Guid)fieldInfo.GetValue(computeSystemPropertiesHandle);
}
else
{
var propertyInfo = computeSystemPropertiesType.GetProperty("RuntimeId");
if (propertyInfo == null)
{
throw new PSInvalidOperationException(RemotingErrorIdStrings.CannotGetHostInteropTypes);
}
RuntimeId = (Guid)propertyInfo.GetValue(computeSystemPropertiesHandle);
}
//
// Get container object root for Windows Server container.
//
if (RuntimeId == Guid.Empty)
{
// Since Hyper-V changed this from a property to a field, we can optimize for newest Windows to see if it's a field,
// otherwise we fall back to old code to be compatible with older versions of Windows
var obRootFieldInfo = computeSystemPropertiesType.GetField("ObRoot");
if (obRootFieldInfo != null)
{
ContainerObRoot = obRootFieldInfo.GetValue(computeSystemPropertiesHandle) as string;
}
else
{
var obRootPropertyInfo = computeSystemPropertiesType.GetProperty("ObRoot");
if (obRootPropertyInfo != null)
{
ContainerObRoot = obRootPropertyInfo.GetValue(computeSystemPropertiesHandle) as string;
}
}
if (ContainerObRoot == null)
{
throw new PSInvalidOperationException(RemotingErrorIdStrings.CannotGetHostInteropTypes);
}
}
}
}
catch (FileNotFoundException)
{
ErrorCode = ContainersFeatureNotEnabled;
}
catch (FileLoadException)
{
ErrorCode = ContainersFeatureNotEnabled;
}
catch (Exception e)
{
if (e.InnerException != null &&
StringComparer.Ordinal.Equals(
e.InnerException.GetType().FullName,
"Microsoft.HostCompute.Interop.ObjectNotFoundException"))
{
ErrorCode = InvalidContainerId;
}
else
{
ErrorCode = OtherError;
ErrorMessage = GetErrorMessageFromException(e);
}
}
}
/// <summary>
/// Run some tasks on MTA thread if needed.
/// </summary>
private static void RunOnMTAThread(ThreadStart threadProc)
{
if (Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA)
{
threadProc();
}
else
{
Thread executionThread = new Thread(new ThreadStart(threadProc));
executionThread.SetApartmentState(ApartmentState.MTA);
executionThread.Start();
executionThread.Join();
}
}
/// <summary>
/// Get error message from the thrown exception.
/// </summary>
private static string GetErrorMessageFromException(Exception e)
{
string errorMessage = e.Message;
if (e.InnerException != null)
{
errorMessage += " " + e.InnerException.Message;
}
return errorMessage;
}
#endregion
}
}
| 37.961834 | 339 | 0.565989 | [
"MIT"
] | 10088/PowerShell | src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs | 138,257 | C# |
// Copyright (c) 2019-2020 Faber Leonardo. All Rights Reserved. Faber.reach@gmail.com
/*===================================================================================
CameraTranslations.cs
====================================================================================*/
namespace Vultaik.Physics
{
public enum CameraTranslations
{
None,
UseDelta,
UseSlowDelta,
Quick,
}
}
| 21.7 | 86 | 0.382488 | [
"MIT"
] | FaberSan/Zeckoxe | Src/Vultaik.Toolkit/Physics/CameraTranslations.cs | 436 | C# |
/* Copyright 2010-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
namespace MongoDB.Shared
{
internal class CanonicalEquatableClass : IEquatable<CanonicalEquatableClass>
{
// private fields
private int _x;
private int _y;
// constructors
/// <summary>
/// Initializes a new instance of the <see cref="CanonicalEquatableClass"/> class.
/// </summary>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
public CanonicalEquatableClass(int x, int y)
{
_x = y;
_y = y;
}
// public operators
/// <summary>
/// Determines whether two <see cref="CanonicalEquatableClass"/> instances are equal.
/// </summary>
/// <param name="lhs">The LHS.</param>
/// <param name="rhs">The RHS.</param>
/// <returns>
/// <c>true</c> if the left hand side is equal to the right hand side; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(CanonicalEquatableClass lhs, CanonicalEquatableClass rhs)
{
return object.Equals(lhs, rhs); // handles lhs == null correctly
}
/// <summary>
/// Determines whether two <see cref="CanonicalEquatableClass"/> instances are not equal.
/// </summary>
/// <param name="lhs">The LHS.</param>
/// <param name="rhs">The RHS.</param>
/// <returns>
/// <c>true</c> if the left hand side is not equal to the right hand side; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(CanonicalEquatableClass lhs, CanonicalEquatableClass rhs)
{
return !(lhs == rhs);
}
// public methods
/// <summary>
/// Determines whether the specified <see cref="CanonicalEquatableClass" /> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="CanonicalEquatableClass" /> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="CanonicalEquatableClass" /> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public bool Equals(CanonicalEquatableClass obj)
{
return Equals((object)obj); // handles obj == null correctly
}
/// <summary>
/// Determines whether the specified <see cref="System.Object" /> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
// actual work done here (in virtual Equals) to handle inheritance
// use ReferenceEquals consistently because sometimes using == can lead to recursion loops
// make sure to use GetType instead of typeof in case derived classes are involved
if (object.ReferenceEquals(obj, null) || GetType() != obj.GetType()) { return false; }
var rhs = (CanonicalEquatableClass)obj;
return // be sure x and y implement ==, otherwise use Equals
_x == rhs._x &&
_y == rhs._y;
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
return new Hasher()
.Hash(_x)
.Hash(_y)
.GetHashCode();
}
}
}
| 39.482143 | 133 | 0.585482 | [
"MIT"
] | 13294029724/ET | Server/ThirdParty/MongoDBDriver/MongoDB.Shared/CanonicalEquatableClass.cs | 4,424 | C# |
using System;
namespace Orkester
{
public class Log : ILog
{
public Log()
{
}
public bool IsEnabled
{
get; set;
}
public void RaiseExecutionEnded(IExecution e)
{
if (this.IsEnabled)
{
ExecutionEnded?.Invoke(this, e);
}
}
public void RaiseExecutionFailed(IExecution e)
{
if (this.IsEnabled)
{
ExecutionFailed?.Invoke(this, e);
}
}
public void RaiseExecutionRequested(IExecution e)
{
if (this.IsEnabled)
{
ExecutionRequested?.Invoke(this, e);
}
}
public void RaiseExecutionStarted(IExecution e)
{
if (this.IsEnabled)
{
ExecutionStarted?.Invoke(this, e);
}
}
public event EventHandler<IExecution> ExecutionEnded;
public event EventHandler<IExecution> ExecutionFailed;
public event EventHandler<IExecution> ExecutionRequested;
public event EventHandler<IExecution> ExecutionStarted;
}
}
| 15.465517 | 59 | 0.67893 | [
"MIT"
] | aloisdeniel/Orkester | Sources/Orkester/Log.cs | 899 | C# |
using System.Text;
using Bing.Printer.Factories;
namespace Bing.Printer.EscPos
{
/// <summary>
/// Esc/Pos 打印机
/// </summary>
public class EscPosPrinter : PrinterBase<IEscPosPrinter>, IEscPosPrinter
{
/// <summary>
/// 创建打印命令
/// </summary>
protected override IPrintCommand CreatePrintCommand() =>
new PrintCommand(PrintPaperFactory.GetOrCreate(PrintPaper), Encoding.GetEncoding("GB18030"));
}
}
| 25.888889 | 105 | 0.641631 | [
"MIT"
] | bing-framework/Bing.Printer | src/Bing.Printer.EscPos/EscPosPrinter.cs | 486 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace ScrambleSquaresPuzzleSolver
{
public class Graphic
{
public string Name { get; set; }
public bool IsFront { get; set; }
}
}
| 17.769231 | 41 | 0.666667 | [
"Apache-2.0"
] | jessefugitt/scramble-squares-puzzle-solver | Graphic.cs | 233 | C# |
using ElsasCharms.BL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ElsasCharms.WebAdmin.Controllers
{
[Authorize]
public class ProductosController : Controller
{
ProductosBL _productosBL;
CategoriasBL _categoriasBL;
public ProductosController()
{
_productosBL = new ProductosBL();
_categoriasBL = new CategoriasBL();
}
// GET: Productos
public ActionResult Index()
{
var listadeProductos = _productosBL.ObtenerProductos();
return View(listadeProductos);
}
public ActionResult Crear()
{
var nuevoProducto = new Producto();
var categorias = _categoriasBL.ObtenerCategorias();
ViewBag.CategoriaId = new SelectList(categorias, "Id", "Descripcion");
return View(nuevoProducto);
}
[HttpPost]
public ActionResult Crear(Producto producto, HttpPostedFileBase imagen)
{
if (ModelState.IsValid)
{
if (producto.CategoriaId == 0)
{
ModelState.AddModelError("CategoriaId", "Seleccione una categoría");
return View(producto);
}
if (imagen != null)
{
producto.UrlImagen = GuardarImagen(imagen);
}
_productosBL.GuardarProducto(producto);
return RedirectToAction("Index");
}
var categorias = _categoriasBL.ObtenerCategorias();
ViewBag.CategoriaId = new SelectList(categorias, "Id", "Descripcion", producto.CategoriaId);
return View(producto);
}
public ActionResult Editar(int id)
{
var producto = _productosBL.ObtenerProducto(id);
var categorias = _categoriasBL.ObtenerCategorias();
ViewBag.CategoriaId = new SelectList(categorias, "Id", "Descripcion", producto.CategoriaId);
return View(producto);
}
[HttpPost]
public ActionResult Editar(Producto producto, HttpPostedFileBase imagen)
{
if (ModelState.IsValid)
{
if (producto.CategoriaId == 0)
{
ModelState.AddModelError("CategoriaId", "Seleccione una categoría");
return View(producto);
}
if (imagen != null)
{
producto.UrlImagen = GuardarImagen(imagen);
}
_productosBL.GuardarProducto(producto);
return RedirectToAction("Index");
}
var categorias = _categoriasBL.ObtenerCategorias();
ViewBag.CategoriaId = new SelectList(categorias, "Id", "Descripcion");
return View(producto);
}
public ActionResult Detalle(int id)
{
var producto = _productosBL.ObtenerProducto(id);
var categorias = _categoriasBL.ObtenerCategorias();
return View(producto);
}
public ActionResult Eliminar(int id)
{
var producto = _productosBL.ObtenerProducto(id);
var categorias = _categoriasBL.ObtenerCategorias();
return View(producto);
}
[HttpPost]
public ActionResult Eliminar(Producto producto)
{
_productosBL.EliminarProducto(producto.Id);
return RedirectToAction("Index");
}
private string GuardarImagen(HttpPostedFileBase imagen)
{
string path = Server.MapPath("~/Imagenes/" + imagen.FileName);
imagen.SaveAs(path);
return "/Imagenes/" + imagen.FileName;
}
}
} | 28.143885 | 104 | 0.551892 | [
"MIT"
] | DanielaVH/Elsas_Charms | Elsas_Charms/ElsasCharms.WebAdmin/Controllers/ProductosController.cs | 3,916 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the snowball-2016-06-30.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Snowball.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Snowball.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for Address Object
/// </summary>
public class AddressUnmarshaller : IUnmarshaller<Address, XmlUnmarshallerContext>, IUnmarshaller<Address, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
Address IUnmarshaller<Address, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public Address Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
Address unmarshalledObject = new Address();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("AddressId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.AddressId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("City", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.City = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Company", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Company = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Country", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Country = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Landmark", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Landmark = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Name", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Name = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("PhoneNumber", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.PhoneNumber = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("PostalCode", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.PostalCode = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("PrefectureOrDistrict", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.PrefectureOrDistrict = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("StateOrProvince", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.StateOrProvince = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Street1", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Street1 = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Street2", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Street2 = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Street3", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Street3 = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static AddressUnmarshaller _instance = new AddressUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static AddressUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 39.426829 | 134 | 0.566811 | [
"Apache-2.0"
] | Bynder/aws-sdk-net | sdk/src/Services/Snowball/Generated/Model/Internal/MarshallTransformations/AddressUnmarshaller.cs | 6,466 | C# |
using System;
using System.Reflection;
namespace lab_53_API_Northwind_Demo.Areas.HelpPage.ModelDescriptions
{
public interface IModelDocumentationProvider
{
string GetDocumentation(MemberInfo member);
string GetDocumentation(Type type);
}
} | 22.5 | 68 | 0.762963 | [
"MIT"
] | jordanbenbelaid/2020-01-C-Sharp-Labs | Labs/lab_53_API_Northwind_Demo/Areas/HelpPage/ModelDescriptions/IModelDocumentationProvider.cs | 270 | C# |
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;
namespace AutoLazy.Fody
{
internal static class TypeExtensions
{
const MethodAttributes _staticConstructorAttributes
= MethodAttributes.Private
| MethodAttributes.HideBySig
| MethodAttributes.SpecialName
| MethodAttributes.RTSpecialName
| MethodAttributes.Static;
public static MethodDefinition GetOrCreateStaticConstructor(this TypeDefinition type)
{
var cctor = type.GetStaticConstructor();
if (cctor != null) return cctor;
cctor = new MethodDefinition(".cctor", _staticConstructorAttributes, type.Module.ImportReference(typeof(void)));
type.Methods.Add(cctor);
var il = cctor.Body.GetILProcessor();
il.Emit(OpCodes.Ret);
return cctor;
}
}
}
| 32.107143 | 124 | 0.641824 | [
"Apache-2.0"
] | dougbenham/AutoLazy | src/AutoLazy.Fody/TypeExtensions.cs | 901 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Messerli.Utility.Extension;
using Xunit;
namespace Messerli.Utility.Test.Extension
{
public sealed class TypeExtensionTest
{
[Theory]
[InlineData(typeof(IQueryable))]
[InlineData(typeof(IQueryable<>))]
[InlineData(typeof(IQueryable<object>))]
[InlineData(typeof(IQueryable<int>))]
[InlineData(typeof(IQueryable<Type>))]
public void QueryableIsQueryable(Type type)
{
Assert.True(type.IsQueryable());
}
[Theory]
[InlineData(typeof(IEnumerable))]
[InlineData(typeof(IEnumerable<>))]
[InlineData(typeof(IEnumerable<object>))]
[InlineData(typeof(IEnumerable<int>))]
[InlineData(typeof(IEnumerable<Type>))]
public void EnumerableIsEnumerable(Type type)
{
Assert.True(type.IsEnumerable());
}
}
}
| 27.742857 | 53 | 0.637487 | [
"Apache-2.0",
"MIT"
] | messerli-informatik-ag/utility | Utility.Test/Extension/TypeExtensionTest.cs | 973 | C# |
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
namespace PSModule
{
/*
* runType=<Alm/FileSystem/LoadRunner>
almServerUrl=http://<server>:<port>/qcbin
almUserName=<user>
almPassword=<password>
almDomain=<domain>
almProject=<project>
almRunMode=<RUN_LOCAL/RUN_REMOTE/RUN_PLANNED_HOST>
almTimeout=<-1>/<numberOfSeconds>
almRunHost=<hostname>
TestSet<number starting at 1>=<testSet>/<AlmFolder>
Test<number starting at 1>=<testFolderPath>/<a Path ContainingTestFolders>/<mtbFilePath>
*/
public class LauncherParamsBuilder
{
private string secretkey = "EncriptionPass4Java";
private readonly List<string> requiredParameters = new List<string> { "almRunHost", "almPassword" };
private Dictionary<string, string> properties = new Dictionary<string, string>();
public Dictionary<string, string> GetProperties()
{
return properties;
}
public void SetRunType(RunType runType)
{
SetParamValue("runType", runType.ToString());
}
public void SetAlmServerUrl(string almServerUrl)
{
SetParamValue("almServerUrl", almServerUrl);
}
public void SetAlmUserName(string almUserName)
{
SetParamValue("almUserName", almUserName);
}
public void SetAlmPassword(string almPassword)
{
string encAlmPass;
try
{
encAlmPass = EncryptParameter(almPassword);
SetParamValue("almPassword", encAlmPass);
}
catch
{
}
}
public void SetAlmDomain(string almDomain)
{
SetParamValue("almDomain", almDomain);
}
public void SetAlmProject(string almProject)
{
SetParamValue("almProject", almProject);
}
public void SetAlmRunMode(AlmRunMode almRunMode)
{
properties.Add("almRunMode", almRunMode != AlmRunMode.RUN_NONE ? almRunMode.ToString() : "");
}
public void SetAlmTimeout(string almTimeout)
{
string paramToSet = "-1";
if (!string.IsNullOrEmpty(almTimeout))
{
paramToSet = almTimeout;
}
SetParamValue("almTimeout", paramToSet);
}
public void SetTimeslotDuration(string timeslotDuration)
{
SetParamValue("timeslotDuration", timeslotDuration);
}
public void SetTestSet(int index, string testSet)
{
SetParamValue("TestSet" + index, testSet);
}
public void SetTestSetID(string testID)
{
SetParamValue("TestSetID", testID);
}
public void SetTestRunType(RunTestType testType)
{
properties.Add("RunTestType", testType.ToString());
}
private void SetParamValue(string v, int testID)
{
throw new NotImplementedException();
}
public void SetAlmTestSet(string testSets)
{
SetParamValue("almTestSets", testSets);
}
public void SetAlmRunHost(string host)
{
SetParamValue("almRunHost", host);
}
public void SetTest(int index, string test)
{
SetParamValue("Test" + index, test);
}
public void SetDeploymentAction(string deploymentAction)
{
SetParamValue("DeploymentAction", deploymentAction);
}
public void SetDeployedEnvironmentName(string deploymentEnvironmentName)
{
SetParamValue("DeploymentEnvironmentName", deploymentEnvironmentName);
}
public void SetDeprovisioningAction(string deprovisioningAction)
{
SetParamValue("DeprovisioningAction", deprovisioningAction);
}
public void SetFileSystemPassword(string oriPass)
{
string encPass;
try
{
encPass = EncryptParameter(oriPass);
SetParamValue("MobilePassword", encPass);
}
catch
{
}
}
public void SetPerScenarioTimeOut(string perScenarioTimeOut)
{
string paramToSet = "-1";
if (!string.IsNullOrEmpty(perScenarioTimeOut))
{
paramToSet = perScenarioTimeOut;
}
SetParamValue("PerScenarioTimeOut", paramToSet);
}
public void setServerUrl(String serverUrl)
{
SetParamValue("MobileHostAddress", serverUrl);
}
public void setUserName(String username)
{
SetParamValue("MobileUserName", username);
}
public void setProxyHost(String proxyHost)
{
SetParamValue("proxyHost", proxyHost);
}
public void setProxyPort(String proxyPort)
{
SetParamValue("proxyPort", proxyPort);
}
#region mobile
public void SetMobileInfo(String mobileInfo)
{
SetParamValue("mobileinfo", mobileInfo);
}
public void setMobileUseSSL(int type)
{
SetParamValue("MobileUseSSL", type.ToString());
}
public void setMobileUseProxy(int proxy)
{
SetParamValue("MobileUseProxy", proxy.ToString());
}
public void setMobileProxyType(int type)
{
SetParamValue("MobileProxyType", type.ToString());
}
public void setMobileProxySetting_Address(String proxyAddress)
{
SetParamValue("MobileProxySetting_Address", proxyAddress);
}
public void SetMobileProxySetting_Authentication(int authentication)
{
SetParamValue("MobileProxySetting_Authentication", authentication.ToString());
}
public void SetMobileProxySetting_UserName(string proxyUserName)
{
SetParamValue("MobileProxySetting_UserName", proxyUserName);
}
public void SetMobileProxySetting_Password(string proxyPassword)
{
string proxyPass;
try
{
proxyPass = EncryptParameter(proxyPassword);
SetParamValue("MobileProxySetting_Password", proxyPass);
}
catch
{
}
}
#endregion
private void SetParamValue(string paramName, string paramValue)
{
if (string.IsNullOrEmpty(paramValue))
{
if (!requiredParameters.Contains(paramName))
properties.Remove(paramName);
else
properties.Add(paramName, "");
}
else
{
properties.Add(paramName, paramValue);
}
}
private string EncryptParameter(string parameter)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = CipherMode.CBC;
rijndaelCipher.Padding = PaddingMode.PKCS7;
rijndaelCipher.KeySize = 0x80;
rijndaelCipher.BlockSize = 0x80;
byte[] pwdBytes = Encoding.UTF8.GetBytes(secretkey);
byte[] keyBytes = new byte[0x10];
int len = pwdBytes.Length;
if (len > keyBytes.Length)
{
len = keyBytes.Length;
}
Array.Copy(pwdBytes, keyBytes, len);
rijndaelCipher.Key = keyBytes;
rijndaelCipher.IV = keyBytes;
ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
byte[] plainText = Encoding.UTF8.GetBytes(parameter);
return Convert.ToBase64String(transform.TransformFinalBlock(plainText, 0, plainText.Length));
}
}
}
| 29.714286 | 109 | 0.551082 | [
"Apache-2.0"
] | abdousmi/ADM-TFS-Extension | PSModule/LauncherParamsBuilder.cs | 8,322 | C# |
using GiGraph.Dot.Entities.Attributes.Properties.Common.Font;
using GiGraph.Dot.Entities.Attributes.Properties.Common.Hyperlink;
using GiGraph.Dot.Entities.Attributes.Properties.Common.SvgStyleSheet;
using GiGraph.Dot.Entities.Edges.Attributes;
using GiGraph.Dot.Entities.Edges.Endpoints.Attributes;
using GiGraph.Dot.Entities.Labels;
using GiGraph.Dot.Types.Colors;
using GiGraph.Dot.Types.Edges;
using GiGraph.Dot.Types.EscapeString;
using GiGraph.Dot.Types.Styling;
namespace GiGraph.Dot.Entities.Edges.Collections
{
public partial class DotEdgeCollection : IDotEdgeRootAttributes
{
/// <inheritdoc cref="IDotEdgeRootAttributes.Head" />
public DotEdgeHeadAttributes Head => Attributes.Implementation.Head;
/// <inheritdoc cref="IDotEdgeRootAttributes.Tail" />
public DotEdgeTailAttributes Tail => Attributes.Implementation.Tail;
/// <inheritdoc cref="IDotEdgeRootAttributes.Font" />
public DotFontAttributes Font => Attributes.Implementation.Font;
/// <inheritdoc cref="IDotEdgeRootAttributes.EndpointLabels" />
public DotEdgeEndpointLabelsAttributes EndpointLabels => Attributes.Implementation.EndpointLabels;
/// <inheritdoc cref="IDotEdgeRootAttributes.EdgeHyperlink" />
public DotEdgeHyperlinkAttributes EdgeHyperlink => Attributes.Implementation.EdgeHyperlink;
/// <inheritdoc cref="IDotEdgeRootAttributes.LabelHyperlink" />
public DotEdgeLabelHyperlinkAttributes LabelHyperlink => Attributes.Implementation.LabelHyperlink;
/// <inheritdoc cref="IDotEdgeRootAttributes.Style" />
public DotEdgeStyleAttributeOptions Style => Attributes.Implementation.Style;
/// <inheritdoc cref="IDotEdgeRootAttributes.SvgStyleSheet" />
public DotSvgStyleSheetAttributes SvgStyleSheet => Attributes.Implementation.SvgStyleSheet;
/// <inheritdoc cref="IDotEdgeRootAttributes.Hyperlink" />
public DotHyperlinkAttributes Hyperlink => Attributes.Implementation.Hyperlink;
DotStyles? IDotEdgeAttributes.Style
{
get => ((IDotEdgeAttributes) Attributes.Implementation).Style;
set => ((IDotEdgeAttributes) Attributes.Implementation).Style = value;
}
/// <inheritdoc cref="IDotEdgeAttributes.Label" />
public virtual DotLabel Label
{
get => Attributes.Implementation.Label;
set => Attributes.Implementation.Label = value;
}
/// <inheritdoc cref="IDotEdgeAttributes.ExternalLabel" />
public virtual DotLabel ExternalLabel
{
get => Attributes.Implementation.ExternalLabel;
set => Attributes.Implementation.ExternalLabel = value;
}
/// <inheritdoc cref="IDotEdgeAttributes.AllowLabelFloat" />
public virtual bool? AllowLabelFloat
{
get => Attributes.Implementation.AllowLabelFloat;
set => Attributes.Implementation.AllowLabelFloat = value;
}
/// <inheritdoc cref="IDotEdgeAttributes.MinLength" />
public virtual int? MinLength
{
get => Attributes.Implementation.MinLength;
set => Attributes.Implementation.MinLength = value;
}
/// <inheritdoc cref="IDotEdgeAttributes.Length" />
public virtual double? Length
{
get => Attributes.Implementation.Length;
set => Attributes.Implementation.Length = value;
}
/// <inheritdoc cref="IDotEdgeAttributes.Weight" />
public virtual double? Weight
{
get => Attributes.Implementation.Weight;
set => Attributes.Implementation.Weight = value;
}
/// <inheritdoc cref="IDotEdgeAttributes.Tooltip" />
public virtual DotEscapeString Tooltip
{
get => Attributes.Implementation.Tooltip;
set => Attributes.Implementation.Tooltip = value;
}
/// <inheritdoc cref="IDotEdgeAttributes.Color" />
public virtual DotColorDefinition Color
{
get => Attributes.Implementation.Color;
set => Attributes.Implementation.Color = value;
}
/// <inheritdoc cref="IDotEdgeAttributes.FillColor" />
public virtual DotColorDefinition FillColor
{
get => Attributes.Implementation.FillColor;
set => Attributes.Implementation.FillColor = value;
}
/// <inheritdoc cref="IDotEdgeAttributes.ColorScheme" />
public virtual string ColorScheme
{
get => Attributes.Implementation.ColorScheme;
set => Attributes.Implementation.ColorScheme = value;
}
/// <inheritdoc cref="IDotEdgeAttributes.Width" />
public virtual double? Width
{
get => Attributes.Implementation.Width;
set => Attributes.Implementation.Width = value;
}
/// <inheritdoc cref="IDotEdgeAttributes.ArrowheadScale" />
public virtual double? ArrowheadScale
{
get => Attributes.Implementation.ArrowheadScale;
set => Attributes.Implementation.ArrowheadScale = value;
}
/// <inheritdoc cref="IDotEdgeAttributes.Directions" />
public virtual DotEdgeDirections? Directions
{
get => Attributes.Implementation.Directions;
set => Attributes.Implementation.Directions = value;
}
/// <inheritdoc cref="IDotEdgeAttributes.AttachLabel" />
public virtual bool? AttachLabel
{
get => Attributes.Implementation.AttachLabel;
set => Attributes.Implementation.AttachLabel = value;
}
/// <inheritdoc cref="IDotEdgeAttributes.Constrain" />
public virtual bool? Constrain
{
get => Attributes.Implementation.Constrain;
set => Attributes.Implementation.Constrain = value;
}
/// <inheritdoc cref="IDotEdgeAttributes.Comment" />
public virtual string Comment
{
get => Attributes.Implementation.Comment;
set => Attributes.Implementation.Comment = value;
}
/// <inheritdoc cref="IDotEdgeAttributes.ObjectId" />
public virtual DotEscapeString ObjectId
{
get => Attributes.Implementation.ObjectId;
set => Attributes.Implementation.ObjectId = value;
}
}
} | 38.136095 | 106 | 0.653064 | [
"MIT"
] | mariusz-schimke/GiGraph | src/GiGraph.Dot.Entities/Edges/Collections/DotEdgeCollection.Attributes.cs | 6,447 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using JetBrains.Annotations;
using TypeScript.Net.Types;
namespace TypeScript.Net.Parsing
{
/// <summary>
/// Helper class for visiting nodes.
/// </summary>
/// <remarks>
/// In typescript codebase similar functionality resides in parser.ts.
/// </remarks>
public static class NodeWalker
{
/// <summary>
/// Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
/// stored in properties. If a <paramref name="cbNode"/> callback is specified, it is invoked for embedded arrays; otherwise,
/// embedded arrays are flattened and the <paramref name="cbNode"/> callback is invoked for each element. If a callback returns
/// a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
/// </summary>
public static T ForEachChild<T>(INode node, Func<INode /*node*/, T> cbNode) where T : class
{
if (node == null)
{
return default(T);
}
return ForEachChild(node, cbNode, (n, func) => func(n));
}
/// <summary>
/// Invokes a callback for each child of the given node. The <paramref name="cbNode"/> callback is invoked for all child nodes
/// stored in properties. If a <paramref name="cbNode"/> callback is specified, it is invoked for embedded arrays; otherwise,
/// embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns
/// a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
/// </summary>
public static TResult ForEachChild<TResult, TState>(INode node, TState state, Func<INode /*node*/, TState, TResult> cbNode) where TResult : class
{
if (node == null)
{
return default(TResult);
}
// Using pooled list of children to avoid iterator allocation.
using (var listWrapper = ObjectPools.NodeListPool.GetInstance())
{
var list = listWrapper.Instance;
DoGetChildren(node, list);
foreach (var child in list)
{
foreach (var c in child)
{
var result = cbNode(c, state);
if (result != null)
{
return result;
}
}
}
}
return default(TResult);
}
/// <summary>
/// Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
/// stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise,
/// embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns
/// a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
/// </summary>
public static void ForEachChild<TState>(INode node, TState state, Action<INode /*node*/, TState> cbNode)
{
if (node == null)
{
return;
}
// Using pooled list of children to avoid iterator allocation.
using (var listWrapper = ObjectPools.NodeListPool.GetInstance())
{
var list = listWrapper.Instance;
DoGetChildren(node, list);
foreach (var child in list)
{
foreach (var c in child)
{
cbNode(c, state);
}
}
}
}
/// <summary>
/// Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
/// stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise,
/// embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns
/// a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
/// </summary>
public static bool ForEachChild(INode node, Func<INode /*node*/, bool> cbNode)
{
// Using state explicitely to avoid closure allocation
return ForEachChild(node, cbNode, (n, cb) => cb(n) ? Bool.True : Bool.False);
}
/// <summary>
/// Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
/// stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise,
/// embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns
/// a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
/// </summary>
public static bool ForEachChild<TState>(INode node, TState state, Func<INode, TState, bool> cbNode)
{
// Using state explicitely to avoid closure allocation
return ForEachChild(node, (state, cbNode), (n, tup) => tup.cbNode(n, tup.state) ? Bool.True : Bool.False);
}
/// <summary>
/// Traverses the tree specified by <paramref name="root"/> recursively.
/// Returns non-null value provided by the call to <paramref name="func"/>.
/// </summary>
public static T ForEachChildRecursively<T>(INode root, Func<INode /*node*/, T> func, bool recurseThroughIdentifiers = false) where T : class
{
foreach (var n in TraverseBreadthFirstAndSelf(root, recurseThroughIdentifiers))
{
if (ReferenceEquals(n, root))
{
continue;
}
var r = func(n);
if (r != null)
{
return r;
}
}
return default(T);
}
/// <summary>
/// Helper function for traversing recursive data structures in non-recursive fashion.
/// </summary>
internal static IEnumerable<INode> TraverseBreadthFirstAndSelf(INode item, Func<INode, ThreadLocalPooledObjectWrapper<List<NodeOrNodeArray>>> childSelector)
{
// Using queue to get depth first left to right traversal. Stack would give right to left traversal.
var queue = new Queue<INode>();
queue.Enqueue(item);
while (queue.Count > 0)
{
var next = queue.Dequeue();
yield return next;
using (var listWrapper = childSelector(next))
{
foreach (var n in listWrapper.Instance)
{
foreach (var c in n)
{
queue.Enqueue(c);
}
}
}
}
}
/// <summary>
/// Traverses <paramref name="node"/> and its children in depth-first manner
/// </summary>
public static void TraverseDepthFirstAndSelfInOrder(INode node, Func<INode, bool> predicate, System.Threading.CancellationToken token, bool recurseThroughIdentifiers = false)
{
TraverseDepthFirstAndSelfInOrderLocal(node, recurseThroughIdentifiers);
bool TraverseDepthFirstAndSelfInOrderLocal(INode localNode, bool recurse)
{
bool needToContinue = predicate(localNode);
if (needToContinue && !token.IsCancellationRequested)
{
using (var listWrapper = GetChildrenFast(localNode, recurse))
{
foreach (var c in listWrapper.Instance)
{
foreach (var n in c)
{
needToContinue = TraverseDepthFirstAndSelfInOrderLocal(n, recurseThroughIdentifiers);
if (!needToContinue)
{
break;
}
}
}
}
}
return true;
}
}
/// <summary>
/// Helper function for traversing recursive data structures in non-recursive fashion.
/// </summary>
internal static IEnumerable<INode> TraverseDepthFirstAndSelfInOrder(INode item, Func<INode, ThreadLocalPooledObjectWrapper<List<NodeOrNodeArray>>> childSelector)
{
// Using stack to get depth first left to right traversal. Queue would give right to left traversal.
var stack = new Stack<INode>();
stack.Push(item);
while (stack.Count > 0)
{
var next = stack.Pop();
yield return next;
using (var listWrapper = childSelector(next))
{
foreach (var n in listWrapper.Instance)
{
foreach (var c in n)
{
stack.Push(c);
}
}
}
}
}
/// <summary>
/// Traverses <paramref name="node"/> and its children in depth-first manner
/// </summary>
public static IEnumerable<INode> TraverseBreadthFirstAndSelf(INode node, bool recurseThroughIdentifiers = false)
{
return TraverseBreadthFirstAndSelf(node, n => GetChildrenFast(n, recurseThroughIdentifiers));
}
/// <summary>
/// Returns child nodes for specified <paramref name="node"/>.
/// </summary>
/// <remarks>
/// This method returns just immediate children. To traverse all the nodes recursively, use <see cref="TraverseBreadthFirstAndSelf(INode, bool)"/>.
/// </remarks>
public static IEnumerable<INode> GetChildren(INode node)
{
// Using pooled list of children to avoid iterator allocation.
using (var listWrapper = ObjectPools.NodeListPool.GetInstance())
{
var list = listWrapper.Instance;
DoGetChildren(node, list);
foreach (var child in list)
{
foreach (var c in child)
{
yield return c;
}
}
}
}
/// <summary>
/// Allocation-free version of <see cref="GetChildren"/> method.
/// </summary>
public static ThreadLocalPooledObjectWrapper<List<NodeOrNodeArray>> GetChildrenFast(INode node, bool recurseThroughIdentifiers = false)
{
var wrapper = ObjectPools.NodeListPool.GetInstance();
DoGetChildren(node, wrapper.Instance, recurseThroughIdentifiers);
return wrapper;
}
private static NodeOrNodeArray Node([CanBeNull]INode node)
{
return new NodeOrNodeArray(node);
}
private static NodeOrNodeArray Nodes([NotNull]INodeArray<INode> nodes)
{
return new NodeOrNodeArray(nodes);
}
private static void DoGetChildren(INode node, List<NodeOrNodeArray> nodes, bool recurseThroughIdentifiers = false)
{
if (node == null)
{
return;
}
switch (node.Kind)
{
case SyntaxKind.QualifiedName:
{
var concreteNode = node.Cast<IQualifiedName>();
nodes.Add(Node(concreteNode.Left));
nodes.Add(Node(concreteNode.Right));
break;
}
case SyntaxKind.TypeParameter:
{
var concreteNode = node.Cast<ITypeParameterDeclaration>();
nodes.Add(Node(concreteNode.Name));
nodes.Add(Node(concreteNode.Constraint));
nodes.Add(Node(concreteNode.Expression));
break;
}
case SyntaxKind.ShorthandPropertyAssignment:
{
var concreteNode = node.Cast<IShorthandPropertyAssignment>();
nodes.Add(Nodes(node.Decorators));
nodes.Add(Nodes(node.Modifiers));
nodes.Add(Node(concreteNode.Name));
nodes.Add(Node(concreteNode.QuestionToken.ValueOrDefault));
nodes.Add(Node(concreteNode.EqualsToken.ValueOrDefault));
nodes.Add(Node(concreteNode.ObjectAssignmentInitializer));
break;
}
case SyntaxKind.Parameter:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.PropertySignature:
case SyntaxKind.PropertyAssignment:
case SyntaxKind.VariableDeclaration:
case SyntaxKind.BindingElement:
{
var concreteNode = node.Cast<IVariableLikeDeclaration>();
nodes.Add(Nodes(node.Decorators));
nodes.Add(Nodes(node.Modifiers));
nodes.Add(Node(concreteNode.PropertyName));
nodes.Add(Node(concreteNode.DotDotDotToken.ValueOrDefault));
nodes.Add(Node(concreteNode.Name));
nodes.Add(Node(concreteNode.QuestionToken.ValueOrDefault));
nodes.Add(Node(concreteNode.Type));
nodes.Add(Node(concreteNode.Initializer));
break;
}
case SyntaxKind.FunctionType:
case SyntaxKind.ConstructorType:
case SyntaxKind.CallSignature:
case SyntaxKind.ConstructSignature:
case SyntaxKind.IndexSignature:
{
var concreteNode = node.Cast<ISignatureDeclaration>();
nodes.Add(Nodes(node.Decorators));
nodes.Add(Nodes(node.Modifiers));
nodes.Add(Nodes(concreteNode.TypeParameters ?? NodeArray.Empty<ITypeParameterDeclaration>()));
nodes.Add(Nodes(concreteNode.Parameters));
nodes.Add(Node(concreteNode.Type));
break;
}
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
case SyntaxKind.Constructor:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.FunctionExpression:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.ArrowFunction:
{
var concreteNode = node.Cast<IFunctionLikeDeclaration>();
nodes.Add(Nodes(node.Decorators));
nodes.Add(Nodes(node.Modifiers));
nodes.Add(Node(concreteNode.AsteriskToken.ValueOrDefault));
nodes.Add(Node(concreteNode.Name));
nodes.Add(Node(concreteNode.QuestionToken.ValueOrDefault));
nodes.Add(Nodes(concreteNode.TypeParameters ?? NodeArray.Empty<ITypeParameterDeclaration>()));
nodes.Add(Nodes(concreteNode.Parameters));
nodes.Add(Node(concreteNode.Type));
nodes.Add(Node(node.As<IArrowFunction>()?.EqualsGreaterThanToken));
nodes.Add(Node(concreteNode.Body));
break;
}
case SyntaxKind.TypeReference:
{
var concreteNode = node.Cast<ITypeReferenceNode>();
nodes.Add(Node(concreteNode.TypeName));
nodes.Add(Nodes(concreteNode.TypeArguments ?? NodeArray.Empty<ITypeNode>()));
break;
}
case SyntaxKind.TypePredicate:
{
var concreteNode = node.Cast<ITypePredicateNode>();
nodes.Add(Node(concreteNode.ParameterName));
nodes.Add(Node(concreteNode.Type));
break;
}
case SyntaxKind.TypeQuery:
nodes.Add(Node(node.Cast<ITypeQueryNode>().ExprName));
break;
case SyntaxKind.TypeLiteral:
nodes.Add(Nodes(node.Cast<ITypeLiteralNode>().Members));
break;
case SyntaxKind.ArrayType:
nodes.Add(Node(node.Cast<IArrayTypeNode>().ElementType));
break;
case SyntaxKind.TupleType:
nodes.Add(Nodes(node.Cast<ITupleTypeNode>().ElementTypes));
break;
case SyntaxKind.UnionType:
case SyntaxKind.IntersectionType:
nodes.Add(Nodes(node.Cast<IUnionOrIntersectionTypeNode>().Types));
break;
case SyntaxKind.ParenthesizedType:
nodes.Add(Node(node.Cast<IParenthesizedTypeNode>().Type));
break;
case SyntaxKind.ObjectBindingPattern:
case SyntaxKind.ArrayBindingPattern:
nodes.Add(Nodes(node.Cast<IBindingPattern>().Elements));
break;
case SyntaxKind.ArrayLiteralExpression:
nodes.Add(Nodes(node.Cast<IArrayLiteralExpression>().Elements));
break;
case SyntaxKind.ObjectLiteralExpression:
nodes.Add(Nodes(node.Cast<IObjectLiteralExpression>().Properties));
break;
case SyntaxKind.PropertyAccessExpression:
{
var concreteNode = node.Cast<IPropertyAccessExpression>();
nodes.Add(Node(concreteNode.Expression));
nodes.Add(Node(concreteNode.DotToken));
nodes.Add(Node(concreteNode.Name));
break;
}
case SyntaxKind.ElementAccessExpression:
{
var concreteNode = node.Cast<IElementAccessExpression>();
nodes.Add(Node(concreteNode.Expression));
nodes.Add(Node(concreteNode.ArgumentExpression));
break;
}
case SyntaxKind.CallExpression:
case SyntaxKind.NewExpression:
{
var concreteNode = node.Cast<ICallExpression>();
nodes.Add(Node(concreteNode.Expression));
nodes.Add(Nodes(concreteNode.TypeArguments));
nodes.Add(Nodes(concreteNode.Arguments));
break;
}
case SyntaxKind.TaggedTemplateExpression:
{
var concreteNode = node.Cast<ITaggedTemplateExpression>();
nodes.Add(Node(concreteNode.Tag));
nodes.Add(Node(concreteNode.TemplateExpression));
break;
}
case SyntaxKind.TypeAssertionExpression:
{
var concreteNode = node.Cast<ITypeAssertion>();
nodes.Add(Node(concreteNode.Type));
nodes.Add(Node(concreteNode.Expression));
break;
}
case SyntaxKind.ParenthesizedExpression:
nodes.Add(Node(node.Cast<IParenthesizedExpression>().Expression));
break;
case SyntaxKind.DeleteExpression:
nodes.Add(Node(node.Cast<IDeleteExpression>().Expression));
break;
case SyntaxKind.TypeOfExpression:
nodes.Add(Node(node.Cast<ITypeOfExpression>().Expression));
break;
case SyntaxKind.VoidExpression:
nodes.Add(Node(node.Cast<IVoidExpression>().Expression));
break;
case SyntaxKind.PrefixUnaryExpression:
nodes.Add(Node(node.Cast<IPrefixUnaryExpression>().Operand));
break;
case SyntaxKind.YieldExpression:
{
var concreteExpression = node.Cast<IYieldExpression>();
nodes.Add(Node(concreteExpression.AsteriskToken));
nodes.Add(Node(concreteExpression.Expression));
break;
}
case SyntaxKind.AwaitExpression:
nodes.Add(Node(node.Cast<IAwaitExpression>().Expression));
break;
case SyntaxKind.PostfixUnaryExpression:
nodes.Add(Node(node.Cast<IPostfixUnaryExpression>().Operand));
break;
case SyntaxKind.BinaryExpression:
{
var concreteNode = node.Cast<IBinaryExpression>();
nodes.Add(Node(concreteNode.Left));
nodes.Add(Node(concreteNode.OperatorToken));
nodes.Add(Node(concreteNode.Right));
break;
}
case SyntaxKind.AsExpression:
{
var concreteNode = node.Cast<IAsExpression>();
nodes.Add(Node(concreteNode.Expression));
nodes.Add(Node(concreteNode.Type));
break;
}
case SyntaxKind.ConditionalExpression:
{
var concreteNode = node.Cast<IConditionalExpression>();
nodes.Add(Node(concreteNode.Condition));
nodes.Add(Node(concreteNode.QuestionToken));
nodes.Add(Node(concreteNode.WhenTrue));
nodes.Add(Node(concreteNode.ColonToken));
nodes.Add(Node(concreteNode.WhenFalse));
break;
}
case SyntaxKind.SwitchExpression:
{
var concreteNode = node.Cast<ISwitchExpression>();
nodes.Add(Node(concreteNode.Expression));
foreach (var clause in concreteNode.Clauses)
{
nodes.Add(Node(clause));
}
break;
}
case SyntaxKind.SwitchExpressionClause:
{
var concreteNode = node.Cast<ISwitchExpressionClause>();
if (!concreteNode.IsDefaultFallthrough)
{
nodes.Add(Node(concreteNode.Match));
}
nodes.Add(Node(concreteNode.Expression));
break;
}
case SyntaxKind.SpreadElementExpression:
nodes.Add(Node(node.Cast<ISpreadElementExpression>().Expression));
break;
case SyntaxKind.Block:
case SyntaxKind.ModuleBlock:
nodes.Add(Nodes(node.Cast<IBlock>().Statements));
break;
case SyntaxKind.SourceFile:
nodes.Add(Nodes(node.Cast<ISourceFile>().Statements));
nodes.Add(Node(node.Cast<ISourceFile>().EndOfFileToken));
break;
case SyntaxKind.VariableStatement:
nodes.Add(Nodes(node.Decorators));
nodes.Add(Nodes(node.Modifiers));
nodes.Add(Node(node.Cast<IVariableStatement>().DeclarationList));
break;
case SyntaxKind.VariableDeclarationList:
nodes.Add(Nodes(node.Cast<IVariableDeclarationList>().Declarations));
break;
case SyntaxKind.ExpressionStatement:
nodes.Add(Node(node.Cast<IExpressionStatement>().Expression));
break;
case SyntaxKind.IfStatement:
{
var concreteNode = node.Cast<IIfStatement>();
nodes.Add(Node(concreteNode.Expression));
nodes.Add(Node(concreteNode.ThenStatement));
nodes.Add(Node(concreteNode.ElseStatement.ValueOrDefault));
break;
}
case SyntaxKind.DoStatement:
{
var concreteNode = node.Cast<IDoStatement>();
nodes.Add(Node(concreteNode.Statement));
nodes.Add(Node(concreteNode.Expression));
break;
}
case SyntaxKind.WhileStatement:
{
var concreteNode = node.Cast<IWhileStatement>();
nodes.Add(Node(concreteNode.Expression));
nodes.Add(Node(concreteNode.Statement));
break;
}
case SyntaxKind.ForStatement:
{
var concreteNode = node.Cast<IForStatement>();
nodes.Add(Node(concreteNode.Initializer));
nodes.Add(Node(concreteNode.Condition));
nodes.Add(Node(concreteNode.Incrementor));
nodes.Add(Node(concreteNode.Statement));
break;
}
case SyntaxKind.ForInStatement:
{
var concreteNode = node.Cast<IForInStatement>();
nodes.Add(Node(concreteNode.Initializer));
nodes.Add(Node(concreteNode.Expression));
nodes.Add(Node(concreteNode.Statement));
break;
}
case SyntaxKind.ForOfStatement:
{
var concreteNode = node.Cast<IForOfStatement>();
nodes.Add(Node(concreteNode.Initializer));
nodes.Add(Node(concreteNode.Expression));
nodes.Add(Node(concreteNode.Statement));
break;
}
case SyntaxKind.ContinueStatement:
case SyntaxKind.BreakStatement:
nodes.Add(Node(node.Cast<IBreakOrContinueStatement>().Label));
break;
case SyntaxKind.ReturnStatement:
nodes.Add(Node(node.Cast<IReturnStatement>().Expression));
break;
case SyntaxKind.WithStatement:
{
var concreteNode = node.Cast<IWithStatement>();
nodes.Add(Node(concreteNode.Expression));
nodes.Add(Node(concreteNode.Statement));
break;
}
case SyntaxKind.SwitchStatement:
{
var concreteNode = node.Cast<ISwitchStatement>();
nodes.Add(Node(concreteNode.Expression));
nodes.Add(Node(concreteNode.CaseBlock));
break;
}
case SyntaxKind.CaseBlock:
nodes.Add(Nodes(node.Cast<ICaseBlock>().Clauses));
break;
case SyntaxKind.CaseClause:
{
var concreteNode = node.Cast<ICaseClause>();
nodes.Add(Node(concreteNode.Expression));
nodes.Add(Nodes(concreteNode.Statements));
break;
}
case SyntaxKind.DefaultClause:
nodes.Add(Nodes(node.Cast<IDefaultClause>().Statements));
break;
case SyntaxKind.LabeledStatement:
{
var concreteNode = node.Cast<ILabeledStatement>();
nodes.Add(Node(concreteNode.Label));
nodes.Add(Node(concreteNode.Statement));
break;
}
case SyntaxKind.ThrowStatement:
nodes.Add(Node(node.Cast<IThrowStatement>().Expression));
break;
case SyntaxKind.TryStatement:
{
var concreteNode = node.Cast<ITryStatement>();
nodes.Add(Node(concreteNode.TryBlock));
nodes.Add(Node(concreteNode.CatchClause));
nodes.Add(Node(concreteNode.FinallyBlock));
break;
}
case SyntaxKind.CatchClause:
{
var concreteNode = node.Cast<ICatchClause>();
nodes.Add(Node(concreteNode.VariableDeclaration));
nodes.Add(Node(concreteNode.Block));
break;
}
case SyntaxKind.Decorator:
nodes.Add(Node(node.Cast<IDecorator>().Expression));
break;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.ClassExpression:
{
var concreteNode = node.Cast<IClassLikeDeclaration>();
nodes.Add(Nodes(node.Decorators));
nodes.Add(Nodes(node.Modifiers));
nodes.Add(Node(concreteNode.Name));
nodes.Add(Nodes(concreteNode.TypeParameters));
nodes.Add(Nodes(concreteNode.HeritageClauses));
nodes.Add(Nodes(concreteNode.Members));
break;
}
case SyntaxKind.InterfaceDeclaration:
{
var concreteNode = node.Cast<IInterfaceDeclaration>();
nodes.Add(Nodes(node.Decorators));
nodes.Add(Nodes(node.Modifiers));
nodes.Add(Node(concreteNode.Name));
nodes.Add(Nodes(concreteNode.TypeParameters));
nodes.Add(Nodes(concreteNode.HeritageClauses));
nodes.Add(Nodes(concreteNode.Members));
break;
}
case SyntaxKind.TypeAliasDeclaration:
{
var concreteNode = node.Cast<ITypeAliasDeclaration>();
nodes.Add(Nodes(node.Decorators));
nodes.Add(Nodes(node.Modifiers));
nodes.Add(Node(concreteNode.Name));
nodes.Add(Nodes(concreteNode.TypeParameters));
nodes.Add(Node(concreteNode.Type));
break;
}
case SyntaxKind.EnumDeclaration:
{
var concreteNode = node.Cast<IEnumDeclaration>();
nodes.Add(Nodes(node.Decorators));
nodes.Add(Nodes(node.Modifiers));
nodes.Add(Node(concreteNode.Name));
nodes.Add(Nodes(concreteNode.Members));
break;
}
case SyntaxKind.EnumMember:
{
var concreteNode = node.Cast<IEnumMember>();
nodes.Add(Nodes(node.Decorators));
nodes.Add(Node(concreteNode.Name));
nodes.Add(Node(concreteNode.Initializer.ValueOrDefault));
break;
}
case SyntaxKind.ModuleDeclaration:
{
var concreteNode = node.Cast<IModuleDeclaration>();
nodes.Add(Nodes(node.Decorators));
nodes.Add(Nodes(node.Modifiers));
nodes.Add(Node(concreteNode.Name));
nodes.Add(Node(concreteNode.Body));
break;
}
case SyntaxKind.ImportEqualsDeclaration:
{
var concreteNode = node.Cast<IImportEqualsDeclaration>();
nodes.Add(Nodes(node.Decorators));
nodes.Add(Nodes(node.Modifiers));
nodes.Add(Node(concreteNode.Name));
nodes.Add(Node(concreteNode.ModuleReference));
break;
}
case SyntaxKind.ImportDeclaration:
{
var concreteNode = node.Cast<IImportDeclaration>();
nodes.Add(Nodes(node.Decorators));
nodes.Add(Nodes(node.Modifiers));
nodes.Add(Node(concreteNode.ImportClause));
nodes.Add(Node(concreteNode.ModuleSpecifier));
break;
}
case SyntaxKind.ImportClause:
{
var concreteNode = node.Cast<IImportClause>();
nodes.Add(Node(concreteNode.Name));
nodes.Add(Node(concreteNode.NamedBindings));
break;
}
case SyntaxKind.NamespaceImport:
nodes.Add(Node(node.Cast<INamespaceImport>().Name));
break;
case SyntaxKind.NamedImports:
nodes.Add(Nodes(node.Cast<INamedImports>().Elements));
break;
case SyntaxKind.NamedExports:
nodes.Add(Nodes(node.Cast<INamedExports>().Elements));
break;
case SyntaxKind.ExportDeclaration:
{
var concreteNode = node.Cast<IExportDeclaration>();
nodes.Add(Nodes(node.Decorators));
nodes.Add(Nodes(node.Modifiers));
nodes.Add(Node(concreteNode.ExportClause));
nodes.Add(Node(concreteNode.ModuleSpecifier));
break;
}
case SyntaxKind.ImportSpecifier:
{
var concreteNode = node.Cast<IImportSpecifier>();
nodes.Add(Node(concreteNode.PropertyName));
nodes.Add(Node(concreteNode.Name));
break;
}
case SyntaxKind.ExportSpecifier:
{
var concreteNode = node.Cast<IExportSpecifier>();
nodes.Add(Node(concreteNode.PropertyName));
nodes.Add(Node(concreteNode.Name));
break;
}
case SyntaxKind.ExportAssignment:
{
nodes.Add(Nodes(node.Decorators));
nodes.Add(Nodes(node.Modifiers));
nodes.Add(Node(node.Cast<IExportAssignment>().Expression));
break;
}
case SyntaxKind.TemplateExpression:
{
var concreteNode = node.Cast<ITemplateExpression>();
nodes.Add(Node(concreteNode.Head));
nodes.Add(Nodes(concreteNode.TemplateSpans));
break;
}
case SyntaxKind.TemplateSpan:
{
var concreteNode = node.Cast<ITemplateSpan>();
nodes.Add(Node(concreteNode.Expression));
nodes.Add(Node(concreteNode.Literal));
break;
}
case SyntaxKind.ComputedPropertyName:
nodes.Add(Node(node.Cast<IComputedPropertyName>().Expression));
break;
case SyntaxKind.HeritageClause:
nodes.Add(Nodes(node.Cast<IHeritageClause>().Types));
break;
case SyntaxKind.ExpressionWithTypeArguments:
{
var concreteNode = node.Cast<IExpressionWithTypeArguments>();
nodes.Add(Node(concreteNode.Expression));
nodes.Add(Nodes(concreteNode.TypeArguments));
break;
}
case SyntaxKind.ExternalModuleReference:
nodes.Add(Node(node.Cast<IExternalModuleReference>().Expression));
break;
case SyntaxKind.MissingDeclaration:
nodes.Add(Nodes(node.Decorators));
break;
case SyntaxKind.Identifier:
{
if (recurseThroughIdentifiers)
{
var declarationName = node.TryCast<DelegatingUnionNode>();
if (declarationName != null)
{
nodes.Add(Node(declarationName.Node));
}
}
break;
}
case SyntaxKind.StringLiteralType:
// DScript-specific: decorators on string literal types
nodes.Add(Nodes(node.Decorators));
break;
}
}
/// <summary>
/// Union type that models Node | Node[].
/// </summary>
public readonly struct NodeOrNodeArray
{
/// <nodoc />
public NodeOrNodeArrayEnumerator GetEnumerator()
{
return new NodeOrNodeArrayEnumerator(this);
}
/// <nodoc />
public readonly INode Node;
/// <nodoc />
public readonly INodeArray<INode> Nodes;
/// <nodoc />
public NodeOrNodeArray(INode node)
: this()
{
Node = node;
}
/// <nodoc />
public NodeOrNodeArray(INodeArray<INode> nodes)
: this()
{
Nodes = nodes;
}
/// <summary>
/// Nested iterator to avoid enumerator allocation when the client code uses foreach over the current type instance.
/// </summary>
public struct NodeOrNodeArrayEnumerator
{
private readonly NodeOrNodeArray m_parent;
private int m_index;
private readonly int m_count;
/// <nodoc />
public NodeOrNodeArrayEnumerator(NodeOrNodeArray parent)
{
m_parent = parent;
m_index = 0;
// if both Node and Nodes are null, then the 'count' is 0.
// if the parent.Node is not null, then the 'count' is 1.
// otherwise the cound is equals to parent.Nodes.Count
m_count = parent.Nodes != null ? parent.Nodes.Count : parent.Node != null ? 1 : 0;
}
/// <nodoc />
[CanBeNull]
public INode Current
{
get { return m_parent.Nodes != null ? m_parent.Nodes[m_index - 1] : m_parent.Node; }
}
/// <nodoc />
public bool MoveNext()
{
return m_index++ < m_count;
}
}
}
}
}
| 44.319328 | 183 | 0.474095 | [
"MIT"
] | BearerPipelineTest/BuildXL | Public/Src/FrontEnd/TypeScript.Net/TypeScript.Net/Parsing/NodeWalker.cs | 42,192 | C# |
using CharlieBackend.Core.DTO.Dashboard;
using Swashbuckle.AspNetCore.Filters;
using System;
using System.Collections.Generic;
namespace CharlieBackend.Api.SwaggerExamples.DashboardController
{
/// <summary>
/// Class for example data on SwaggerUI, that is complete copy of parental class
/// with response data grouped in different way
/// </summary>
public class StudentClassbookResultDto : StudentsClassbookResultDto
{
}
class StudentClassbookResponse : IExamplesProvider<StudentClassbookResultDto>
{
public StudentClassbookResultDto GetExamples()
{
return new StudentClassbookResultDto
{
StudentsMarks = new List<StudentMarkDto>
{
new StudentMarkDto
{
Student = "Erik Brown",
StudentId = 155,
Course = "Naturalism",
StudentGroup = "PZ-19-1",
LessonId = 345,
LessonDate = new DateTime(2017, 5, 21),
StudentMark = 5,
},
new StudentMarkDto
{
Student = "Erik Brown",
StudentId = 155,
Course = "Naturalism",
StudentGroup = "PZ-12-1",
LessonId = 345,
LessonDate = new DateTime(2017, 5, 21),
StudentMark = 11,
},
new StudentMarkDto
{
Student = "Erik Brown",
StudentId = 155,
Course = "Capitalism",
StudentGroup = "PZ-33-4",
LessonId = 345,
LessonDate = new DateTime(2017, 5, 21),
StudentMark = 8,
},
},
StudentsPresences = new List<StudentVisitDto>
{
new StudentVisitDto
{
Student = "Erik Brown",
StudentId = 155,
Course = "Naturalism",
StudentGroup = "PZ-19-1",
LessonId = 345,
LessonDate = new DateTime(2017, 5, 21),
Presence = false
},
new StudentVisitDto
{
Student = "Erik Brown",
StudentId = 155,
Course = "Naturalism",
StudentGroup = "PZ-12-1",
LessonId = 345,
LessonDate = new DateTime(2017, 5, 21),
Presence = false
},
new StudentVisitDto
{
Student = "Erik Brown",
StudentId = 155,
Course = "Capitalism",
StudentGroup = "PZ-33-4",
LessonId = 345,
LessonDate = new DateTime(2017, 5, 21),
Presence = false
}
}
};
}
}
}
| 36.074468 | 84 | 0.396638 | [
"MIT"
] | Maks0123/WhatBackend | CharlieBackend.Api/SwaggerExamples/DashboardController/StudentClassbookResponse.cs | 3,393 | C# |
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlTypes;
using System.Diagnostics;
using Microsoft.SqlTools.Utility;
namespace Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts
{
/// <summary>
/// Wrapper around a DbColumn, which provides extra functionality, but can be used as a
/// regular DbColumn
/// </summary>
public class DbColumnWrapper : DbColumn
{
#region Constants
/// <summary>
/// All types supported by the server, stored as a hash set to provide O(1) lookup
/// </summary>
private static readonly HashSet<string> AllServerDataTypes = new HashSet<string>
{
"bigint",
"binary",
"bit",
"char",
"datetime",
"decimal",
"float",
"image",
"int",
"money",
"nchar",
"ntext",
"nvarchar",
"real",
"uniqueidentifier",
"smalldatetime",
"smallint",
"smallmoney",
"text",
"timestamp",
"tinyint",
"varbinary",
"varchar",
"sql_variant",
"xml",
"date",
"time",
"datetimeoffset",
"datetime2"
};
private const string SqlXmlDataTypeName = "xml";
private const string DbTypeXmlDataTypeName = "DBTYPE_XML";
private const string UnknownTypeName = "unknown";
#endregion
/// <summary>
/// Constructor for a DbColumnWrapper
/// </summary>
/// <remarks>Most of this logic is taken from SSMS ColumnInfo class</remarks>
/// <param name="column">The column we're wrapping around</param>
public DbColumnWrapper(DbColumn column)
{
// Set all the fields for the base
AllowDBNull = column.AllowDBNull;
BaseCatalogName = column.BaseCatalogName;
BaseColumnName = column.BaseColumnName;
BaseSchemaName = column.BaseSchemaName;
BaseServerName = column.BaseServerName;
BaseTableName = column.BaseTableName;
ColumnOrdinal = column.ColumnOrdinal;
ColumnSize = column.ColumnSize;
IsAliased = column.IsAliased;
IsAutoIncrement = column.IsAutoIncrement;
IsExpression = column.IsExpression;
IsHidden = column.IsHidden;
IsIdentity = column.IsIdentity;
IsKey = column.IsKey;
IsLong = column.IsLong;
IsReadOnly = column.IsReadOnly;
IsUnique = column.IsUnique;
NumericPrecision = column.NumericPrecision;
NumericScale = column.NumericScale;
UdtAssemblyQualifiedName = column.UdtAssemblyQualifiedName;
DataType = column.DataType;
DataTypeName = column.DataTypeName.ToLowerInvariant();
DetermineSqlDbType();
AddNameAndDataFields(column.ColumnName);
if (IsUdt)
{
// udtassemblyqualifiedname property is used to find if the datatype is of hierarchyid assembly type
// Internally hiearchyid is sqlbinary so providerspecific type and type is changed to sqlbinarytype
object assemblyQualifiedName = column.UdtAssemblyQualifiedName;
const string hierarchyId = "MICROSOFT.SQLSERVER.TYPES.SQLHIERARCHYID";
if (assemblyQualifiedName != null
&& assemblyQualifiedName.ToString().StartsWith(hierarchyId, StringComparison.OrdinalIgnoreCase))
{
DataType = typeof(SqlBinary);
}
else
{
DataType = typeof(byte[]);
}
}
else
{
DataType = column.DataType;
}
}
public DbColumnWrapper(ColumnInfo columnInfo)
{
DataTypeName = columnInfo.DataTypeName.ToLowerInvariant();
DetermineSqlDbType();
DataType = TypeConvertor.ToNetType(this.SqlDbType);
if (DataType == typeof(String))
{
this.ColumnSize = int.MaxValue;
}
AddNameAndDataFields(columnInfo.Name);
}
/// <summary>
/// Default constructor, used for deserializing JSON RPC only
/// </summary>
public DbColumnWrapper()
{
}
#region Properties
/// <summary>
/// Whether or not the column is bytes
/// </summary>
public bool IsBytes { get; private set; }
/// <summary>
/// Whether or not the column is a character type
/// </summary>
public bool IsChars { get; private set; }
/// <summary>
/// Whether or not the column is a SqlVariant type
/// </summary>
public bool IsSqlVariant { get; private set; }
/// <summary>
/// Whether or not the column is a user-defined type
/// </summary>
public bool IsUdt { get; private set; }
/// <summary>
/// Whether or not the column is XML
/// </summary>
public bool IsXml { get; set; }
/// <summary>
/// Whether or not the column is JSON
/// </summary>
public bool IsJson { get; set; }
/// <summary>
/// The SqlDbType of the column, for use in a SqlParameter
/// </summary>
public SqlDbType SqlDbType { get; private set; }
/// <summary>
/// Whther this is a HierarchyId column
/// </summary>
public bool IsHierarchyId { get; set; }
/// <summary>
/// Whether or not the column is an XML Reader type.
/// </summary>
/// <remarks>
/// Logic taken from SSDT determination of whether a column is a SQL XML type. It may not
/// be possible to have XML readers from .NET Core SqlClient.
/// </remarks>
public bool IsSqlXmlType => DataTypeName.Equals(SqlXmlDataTypeName, StringComparison.OrdinalIgnoreCase) ||
DataTypeName.Equals(DbTypeXmlDataTypeName, StringComparison.OrdinalIgnoreCase) ||
DataType == typeof(System.Xml.XmlReader);
/// <summary>
/// Whether or not the column is an unknown type
/// </summary>
/// <remarks>
/// Logic taken from SSDT determination of unknown columns. It may not even be possible to
/// have "unknown" column types with the .NET Core SqlClient.
/// </remarks>
public bool IsUnknownType => DataType == typeof(object) &&
DataTypeName.Equals(UnknownTypeName, StringComparison.OrdinalIgnoreCase);
/// <summary>
/// Whether or not the column can be updated, based on whether it's an auto increment
/// column, is an XML reader column, and if it's read only.
/// </summary>
/// <remarks>
/// Logic taken from SSDT determination of updatable columns
/// Special treatment for HierarchyId since we are using an Expression for HierarchyId column and expression column is readonly.
/// </remarks>
public bool IsUpdatable => (!IsAutoIncrement.HasTrue() &&
!IsReadOnly.HasTrue() &&
!IsSqlXmlType) || IsHierarchyId;
#endregion
private void DetermineSqlDbType()
{
// Determine the SqlDbType
SqlDbType type;
if (Enum.TryParse(DataTypeName, true, out type))
{
SqlDbType = type;
}
else
{
switch (DataTypeName)
{
case "numeric":
SqlDbType = SqlDbType.Decimal;
break;
case "sql_variant":
SqlDbType = SqlDbType.Variant;
break;
case "timestamp":
SqlDbType = SqlDbType.VarBinary;
break;
case "sysname":
SqlDbType = SqlDbType.NVarChar;
break;
default:
SqlDbType = DataTypeName.EndsWith(".sys.hierarchyid") ? SqlDbType.Binary : SqlDbType.Udt;
break;
}
}
}
private void AddNameAndDataFields(string columnName)
{
// We want the display name for the column to always exist
ColumnName = string.IsNullOrEmpty(columnName)
? SR.QueryServiceColumnNull
: columnName;
switch (DataTypeName)
{
case "varchar":
case "nvarchar":
IsChars = true;
Debug.Assert(ColumnSize.HasValue);
if (ColumnSize.Value == int.MaxValue)
{
//For Yukon, special case nvarchar(max) with column name == "Microsoft SQL Server 2005 XML Showplan" -
//assume it is an XML showplan.
//Please note this field must be in sync with a similar field defined in QESQLBatch.cs.
//This is not the best fix that we could do but we are trying to minimize code impact
//at this point. Post Yukon we should review this code again and avoid
//hard-coding special column name in multiple places.
const string yukonXmlShowPlanColumn = "Microsoft SQL Server 2005 XML Showplan";
if (columnName == yukonXmlShowPlanColumn)
{
// Indicate that this is xml to apply the right size limit
// Note we leave chars type as well to use the right retrieval mechanism.
IsXml = true;
}
IsLong = true;
}
break;
case "text":
case "ntext":
IsChars = true;
IsLong = true;
break;
case "xml":
IsXml = true;
IsLong = true;
break;
case "binary":
case "image":
IsBytes = true;
IsLong = true;
break;
case "varbinary":
case "rowversion":
IsBytes = true;
Debug.Assert(ColumnSize.HasValue);
if (ColumnSize.Value == int.MaxValue)
{
IsLong = true;
}
break;
case "sql_variant":
IsSqlVariant = true;
break;
default:
if (!AllServerDataTypes.Contains(DataTypeName))
{
// treat all UDT's as long/bytes data types to prevent the CLR from attempting
// to load the UDT assembly into our process to call ToString() on the object.
IsUdt = true;
IsBytes = true;
IsLong = true;
}
break;
}
}
}
/// <summary>
/// Convert a base data type to another base data type
/// </summary>
public sealed class TypeConvertor
{
private static Dictionary<SqlDbType,Type> _typeMap = new Dictionary<SqlDbType,Type>();
static TypeConvertor()
{
_typeMap[SqlDbType.BigInt] = typeof(Int64);
_typeMap[SqlDbType.Binary] = typeof(Byte);
_typeMap[SqlDbType.Bit] = typeof(Boolean);
_typeMap[SqlDbType.Char] = typeof(String);
_typeMap[SqlDbType.DateTime] = typeof(DateTime);
_typeMap[SqlDbType.Decimal] = typeof(Decimal);
_typeMap[SqlDbType.Float] = typeof(Double);
_typeMap[SqlDbType.Image] = typeof(Byte[]);
_typeMap[SqlDbType.Int] = typeof(Int32);
_typeMap[SqlDbType.Money] = typeof(Decimal);
_typeMap[SqlDbType.NChar] = typeof(String);
_typeMap[SqlDbType.NChar] = typeof(String);
_typeMap[SqlDbType.NChar] = typeof(String);
_typeMap[SqlDbType.NText] = typeof(String);
_typeMap[SqlDbType.NVarChar] = typeof(String);
_typeMap[SqlDbType.Real] = typeof(Single);
_typeMap[SqlDbType.UniqueIdentifier] = typeof(Guid);
_typeMap[SqlDbType.SmallDateTime] = typeof(DateTime);
_typeMap[SqlDbType.SmallInt] = typeof(Int16);
_typeMap[SqlDbType.SmallMoney] = typeof(Decimal);
_typeMap[SqlDbType.Text] = typeof(String);
_typeMap[SqlDbType.Timestamp] = typeof(Byte[]);
_typeMap[SqlDbType.TinyInt] = typeof(Byte);
_typeMap[SqlDbType.VarBinary] = typeof(Byte[]);
_typeMap[SqlDbType.VarChar] = typeof(String);
_typeMap[SqlDbType.Variant] = typeof(Object);
// Note: treating as string
_typeMap[SqlDbType.Xml] = typeof(String);
_typeMap[SqlDbType.TinyInt] = typeof(Byte);
_typeMap[SqlDbType.TinyInt] = typeof(Byte);
_typeMap[SqlDbType.TinyInt] = typeof(Byte);
_typeMap[SqlDbType.TinyInt] = typeof(Byte);
}
private TypeConvertor()
{
}
/// <summary>
/// Convert TSQL type to .Net data type
/// </summary>
/// <param name="sqlDbType"></param>
/// <returns></returns>
public static Type ToNetType(SqlDbType sqlDbType)
{
Type netType;
if (!_typeMap.TryGetValue(sqlDbType, out netType))
{
netType = typeof(String);
}
return netType;
}
}
}
| 36.875318 | 136 | 0.520908 | [
"MIT"
] | KevinRansom/sqltoolsservice | src/Microsoft.SqlTools.ServiceLayer/QueryExecution/Contracts/DbColumnWrapper.cs | 14,494 | C# |
namespace Application.Common;
public interface ISessionService
{
ValueTask ClearAsync(CancellationToken? cancellationToken = null);
ValueTask<T> GetItemAsync<T>(string key, CancellationToken? cancellationToken = null);
ValueTask<string> GetItemAsStringAsync(
string key,
CancellationToken? cancellationToken = null);
// ValueTask<string> KeyAsync(int index, CancellationToken? cancellationToken = null);
ValueTask<bool> ContainKeyAsync(string key, CancellationToken? cancellationToken = null);
ValueTask<int> LengthAsync(CancellationToken? cancellationToken = null);
ValueTask RemoveItemAsync(string key, CancellationToken? cancellationToken = null);
ValueTask SetItemAsync<T>(string key, T data, CancellationToken? cancellationToken = null);
ValueTask SetItemAsStringAsync(
string key,
string data,
CancellationToken? cancellationToken = null);
//event EventHandler<ChangingEventArgs> Changing;
//event EventHandler<ChangedEventArgs> Changed;
} | 32.5 | 95 | 0.752885 | [
"MIT"
] | cmedianu/OraEmp | Application/Common/ISessionService.cs | 1,040 | C# |
namespace SineAndSoul
{
partial class SettingsWindow
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.SettingsCancelButton = new System.Windows.Forms.Button();
this.OKButton = new System.Windows.Forms.Button();
this.ImportCSVGroupBox = new System.Windows.Forms.GroupBox();
this.label3 = new System.Windows.Forms.Label();
this.FrequenciesPerLineNumeric = new System.Windows.Forms.NumericUpDown();
this.DecimalMarkTextBox = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.DelimiterTextBox = new System.Windows.Forms.TextBox();
this.AudioGroupBox = new System.Windows.Forms.GroupBox();
this.label4 = new System.Windows.Forms.Label();
this.LatencyNumeric = new System.Windows.Forms.NumericUpDown();
this.ResetButton = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.label6 = new System.Windows.Forms.Label();
this.BaseOctaveNumeric = new System.Windows.Forms.NumericUpDown();
this.BaseNoteComboBox = new System.Windows.Forms.ComboBox();
this.label5 = new System.Windows.Forms.Label();
this.MidiGroupBox = new System.Windows.Forms.GroupBox();
this.label7 = new System.Windows.Forms.Label();
this.MidiDevicesComboBox = new System.Windows.Forms.ComboBox();
this.ImportCSVGroupBox.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.FrequenciesPerLineNumeric)).BeginInit();
this.AudioGroupBox.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.LatencyNumeric)).BeginInit();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.BaseOctaveNumeric)).BeginInit();
this.MidiGroupBox.SuspendLayout();
this.SuspendLayout();
//
// SettingsCancelButton
//
this.SettingsCancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.SettingsCancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.SettingsCancelButton.Location = new System.Drawing.Point(345, 236);
this.SettingsCancelButton.Name = "SettingsCancelButton";
this.SettingsCancelButton.Size = new System.Drawing.Size(75, 23);
this.SettingsCancelButton.TabIndex = 8;
this.SettingsCancelButton.Text = "Cancel";
this.SettingsCancelButton.UseVisualStyleBackColor = true;
this.SettingsCancelButton.Click += new System.EventHandler(this.SettingsCancelButton_Click);
//
// OKButton
//
this.OKButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.OKButton.Location = new System.Drawing.Point(264, 236);
this.OKButton.Name = "OKButton";
this.OKButton.Size = new System.Drawing.Size(75, 23);
this.OKButton.TabIndex = 7;
this.OKButton.Text = "Save";
this.OKButton.UseVisualStyleBackColor = true;
this.OKButton.Click += new System.EventHandler(this.OKButton_Click);
//
// ImportCSVGroupBox
//
this.ImportCSVGroupBox.Controls.Add(this.label3);
this.ImportCSVGroupBox.Controls.Add(this.FrequenciesPerLineNumeric);
this.ImportCSVGroupBox.Controls.Add(this.DecimalMarkTextBox);
this.ImportCSVGroupBox.Controls.Add(this.label2);
this.ImportCSVGroupBox.Controls.Add(this.label1);
this.ImportCSVGroupBox.Controls.Add(this.DelimiterTextBox);
this.ImportCSVGroupBox.Location = new System.Drawing.Point(12, 12);
this.ImportCSVGroupBox.Name = "ImportCSVGroupBox";
this.ImportCSVGroupBox.Size = new System.Drawing.Size(200, 114);
this.ImportCSVGroupBox.TabIndex = 0;
this.ImportCSVGroupBox.TabStop = false;
this.ImportCSVGroupBox.Text = "Import CSV";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(21, 80);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(102, 13);
this.label3.TabIndex = 0;
this.label3.Text = "Frequencies per line";
//
// FrequenciesPerLineNumeric
//
this.FrequenciesPerLineNumeric.Location = new System.Drawing.Point(129, 78);
this.FrequenciesPerLineNumeric.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.FrequenciesPerLineNumeric.Name = "FrequenciesPerLineNumeric";
this.FrequenciesPerLineNumeric.Size = new System.Drawing.Size(56, 20);
this.FrequenciesPerLineNumeric.TabIndex = 3;
this.FrequenciesPerLineNumeric.Value = new decimal(new int[] {
1,
0,
0,
0});
//
// DecimalMarkTextBox
//
this.DecimalMarkTextBox.Location = new System.Drawing.Point(129, 50);
this.DecimalMarkTextBox.MaxLength = 1;
this.DecimalMarkTextBox.Name = "DecimalMarkTextBox";
this.DecimalMarkTextBox.Size = new System.Drawing.Size(31, 20);
this.DecimalMarkTextBox.TabIndex = 2;
this.DecimalMarkTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(21, 53);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(71, 13);
this.label2.TabIndex = 0;
this.label2.Text = "Decimal mark";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(21, 27);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(70, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Field delimiter";
//
// DelimiterTextBox
//
this.DelimiterTextBox.Location = new System.Drawing.Point(129, 24);
this.DelimiterTextBox.MaxLength = 1;
this.DelimiterTextBox.Name = "DelimiterTextBox";
this.DelimiterTextBox.Size = new System.Drawing.Size(31, 20);
this.DelimiterTextBox.TabIndex = 1;
this.DelimiterTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// AudioGroupBox
//
this.AudioGroupBox.Controls.Add(this.label4);
this.AudioGroupBox.Controls.Add(this.LatencyNumeric);
this.AudioGroupBox.Location = new System.Drawing.Point(220, 12);
this.AudioGroupBox.Name = "AudioGroupBox";
this.AudioGroupBox.Size = new System.Drawing.Size(200, 66);
this.AudioGroupBox.TabIndex = 0;
this.AudioGroupBox.TabStop = false;
this.AudioGroupBox.Text = "Audio";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(21, 27);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(67, 13);
this.label4.TabIndex = 0;
this.label4.Text = "Latency (ms)";
//
// LatencyNumeric
//
this.LatencyNumeric.Location = new System.Drawing.Point(94, 25);
this.LatencyNumeric.Maximum = new decimal(new int[] {
10000,
0,
0,
0});
this.LatencyNumeric.Name = "LatencyNumeric";
this.LatencyNumeric.Size = new System.Drawing.Size(91, 20);
this.LatencyNumeric.TabIndex = 4;
//
// ResetButton
//
this.ResetButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.ResetButton.Location = new System.Drawing.Point(12, 235);
this.ResetButton.Name = "ResetButton";
this.ResetButton.Size = new System.Drawing.Size(110, 23);
this.ResetButton.TabIndex = 6;
this.ResetButton.Text = "Restore default";
this.ResetButton.UseVisualStyleBackColor = true;
this.ResetButton.Click += new System.EventHandler(this.ResetButton_Click);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.label6);
this.groupBox1.Controls.Add(this.BaseOctaveNumeric);
this.groupBox1.Controls.Add(this.BaseNoteComboBox);
this.groupBox1.Controls.Add(this.label5);
this.groupBox1.Location = new System.Drawing.Point(12, 133);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(200, 87);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Base note";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(24, 52);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(42, 13);
this.label6.TabIndex = 3;
this.label6.Text = "Octave";
//
// BaseOctaveNumeric
//
this.BaseOctaveNumeric.Location = new System.Drawing.Point(72, 50);
this.BaseOctaveNumeric.Maximum = new decimal(new int[] {
9,
0,
0,
0});
this.BaseOctaveNumeric.Minimum = new decimal(new int[] {
1,
0,
0,
-2147483648});
this.BaseOctaveNumeric.Name = "BaseOctaveNumeric";
this.BaseOctaveNumeric.Size = new System.Drawing.Size(58, 20);
this.BaseOctaveNumeric.TabIndex = 2;
//
// BaseNoteComboBox
//
this.BaseNoteComboBox.FormattingEnabled = true;
this.BaseNoteComboBox.Items.AddRange(new object[] {
"C",
"C#",
"D",
"Eb",
"E",
"F",
"F#",
"G",
"G#",
"A",
"Bb",
"B"});
this.BaseNoteComboBox.Location = new System.Drawing.Point(72, 22);
this.BaseNoteComboBox.Name = "BaseNoteComboBox";
this.BaseNoteComboBox.Size = new System.Drawing.Size(58, 21);
this.BaseNoteComboBox.TabIndex = 1;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(24, 25);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(30, 13);
this.label5.TabIndex = 0;
this.label5.Text = "Note";
//
// MidiGroupBox
//
this.MidiGroupBox.Controls.Add(this.MidiDevicesComboBox);
this.MidiGroupBox.Controls.Add(this.label7);
this.MidiGroupBox.Location = new System.Drawing.Point(220, 85);
this.MidiGroupBox.Name = "MidiGroupBox";
this.MidiGroupBox.Size = new System.Drawing.Size(200, 64);
this.MidiGroupBox.TabIndex = 0;
this.MidiGroupBox.TabStop = false;
this.MidiGroupBox.Text = "MIDI";
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(21, 27);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(41, 13);
this.label7.TabIndex = 0;
this.label7.Text = "Device";
//
// MidiDevicesComboBox
//
this.MidiDevicesComboBox.FormattingEnabled = true;
this.MidiDevicesComboBox.Location = new System.Drawing.Point(68, 24);
this.MidiDevicesComboBox.Name = "MidiDevicesComboBox";
this.MidiDevicesComboBox.Size = new System.Drawing.Size(117, 21);
this.MidiDevicesComboBox.TabIndex = 5;
//
// SettingsWindow
//
this.AcceptButton = this.OKButton;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.SettingsCancelButton;
this.ClientSize = new System.Drawing.Size(432, 271);
this.Controls.Add(this.MidiGroupBox);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.ResetButton);
this.Controls.Add(this.AudioGroupBox);
this.Controls.Add(this.ImportCSVGroupBox);
this.Controls.Add(this.OKButton);
this.Controls.Add(this.SettingsCancelButton);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "SettingsWindow";
this.Text = "Settings";
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.SettingsWindow_FormClosed);
this.ImportCSVGroupBox.ResumeLayout(false);
this.ImportCSVGroupBox.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.FrequenciesPerLineNumeric)).EndInit();
this.AudioGroupBox.ResumeLayout(false);
this.AudioGroupBox.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.LatencyNumeric)).EndInit();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.BaseOctaveNumeric)).EndInit();
this.MidiGroupBox.ResumeLayout(false);
this.MidiGroupBox.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button SettingsCancelButton;
private System.Windows.Forms.Button OKButton;
private System.Windows.Forms.GroupBox ImportCSVGroupBox;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox DelimiterTextBox;
private System.Windows.Forms.TextBox DecimalMarkTextBox;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.NumericUpDown FrequenciesPerLineNumeric;
private System.Windows.Forms.GroupBox AudioGroupBox;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.NumericUpDown LatencyNumeric;
private System.Windows.Forms.Button ResetButton;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.ComboBox BaseNoteComboBox;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.NumericUpDown BaseOctaveNumeric;
private System.Windows.Forms.GroupBox MidiGroupBox;
private System.Windows.Forms.ComboBox MidiDevicesComboBox;
private System.Windows.Forms.Label label7;
}
} | 46.804469 | 171 | 0.593578 | [
"MIT"
] | nissafors/SineAndSoul | SettingsWindow.Designer.cs | 16,758 | C# |
/*
* Copyright (C) 2017 - 2020. Autumn Beauchesne. All rights reserved.
* Author: Autumn Beauchesne
* Date: 28 Nov 2018
*
* File: FourCC.Unity.cs
* Purpose: Unity-specific.
*/
#if UNITY_EDITOR
#define ALLOW_REGISTRY
#endif // UNITY_EDITOR
using System;
using System.Diagnostics;
using System.Reflection;
using UnityEngine;
#if UNITY_EDITOR
using System.Collections.Generic;
using UnityEditor;
#endif // UNITY_EDITOR
namespace BeauData
{
public partial struct FourCC : IEquatable<FourCC>, IComparable<FourCC>
{
#if UNITY_EDITOR && ALLOW_REGISTRY
[CustomPropertyDrawer(typeof(FourCC), true)]
[CustomPropertyDrawer(typeof(FourCCSelectorAttribute), true)]
private class Editor : PropertyDrawer
{
private const int VALUE_WIDTH = 80;
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
CachedSelectionList list = null;
FourCCSelectorAttribute selector = this.attribute as FourCCSelectorAttribute;
bool bShowDebug = true;
if (selector != null)
{
list = GetList(selector);
bShowDebug = selector.ShowDebug;
}
SerializedProperty valueProp = property.FindPropertyRelative("m_Value");
Rect labelRect = position;
Rect indentedRect = EditorGUI.IndentedRect(labelRect);
label = EditorGUI.BeginProperty(labelRect, label, property);
if (!string.IsNullOrEmpty(label.text))
{
labelRect.width = EditorGUIUtility.labelWidth;
indentedRect.x = labelRect.xMax;
indentedRect.width = position.xMax - indentedRect.xMin;
EditorGUI.LabelField(labelRect, label);
}
int prevIndent = EditorGUI.indentLevel;
{
EditorGUI.indentLevel = 0;
Rect fieldRect = indentedRect;
if (bShowDebug)
{
fieldRect.width -= VALUE_WIDTH;
}
if (list != null)
{
DropdownInput(fieldRect, list, valueProp);
}
else
{
StringInput(fieldRect, valueProp);
}
if (bShowDebug)
{
Rect valueRect = indentedRect;
valueRect.x += valueRect.width - VALUE_WIDTH;
valueRect.width = VALUE_WIDTH;
ValueDisplay(valueRect, valueProp);
}
}
EditorGUI.indentLevel = prevIndent;
EditorGUI.EndProperty();
}
#region Displays
private void DropdownInput(Rect inRect, CachedSelectionList inList, SerializedProperty inProperty)
{
int currentValueIndex;
if (inProperty.hasMultipleDifferentValues)
currentValueIndex = -1;
else
currentValueIndex = inList.GetContentIndex(new FourCC(inProperty.intValue));
EditorGUI.BeginChangeCheck();
int nextValueIndex = EditorGUI.Popup(inRect, currentValueIndex, inList.Contents());
if (EditorGUI.EndChangeCheck() && currentValueIndex != nextValueIndex)
inProperty.intValue = (int) inList.GetValue(nextValueIndex);
}
private void StringInput(Rect inRect, SerializedProperty inProperty)
{
string currentValue;
if (inProperty.hasMultipleDifferentValues)
{
currentValue = "[multiple]";
}
else
{
try
{
currentValue = FourCC.Stringify(inProperty.intValue, true);
}
catch
{
currentValue = "[invalid]";
}
}
EditorGUI.BeginChangeCheck();
string nextValue = EditorGUI.DelayedTextField(inRect, currentValue);
if (EditorGUI.EndChangeCheck() && currentValue != nextValue)
{
FourCC parsedValue;
bool bSuccess = FourCC.TryParse(nextValue, out parsedValue);
if (!bSuccess)
UnityEngine.Debug.LogErrorFormat("[FourCC] Unable to parse value '{0}' as a FourCC", nextValue);
else
inProperty.intValue = (int) parsedValue;
}
}
private void ValueDisplay(Rect inRect, SerializedProperty inProperty)
{
string display;
if (inProperty.hasMultipleDifferentValues)
display = "[multiple]";
else
display = "0x" + inProperty.intValue.ToString("X8");
EditorGUI.LabelField(inRect, display, EditorStyles.centeredGreyMiniLabel);
}
#endregion // Displays
#region Cached Lists
static private Dictionary<Type, CachedSelectionList> s_CachedLists = new Dictionary<Type, CachedSelectionList>();
static private CachedSelectionList GetList(FourCCSelectorAttribute inSelector)
{
CachedSelectionList list;
Type cachingType = inSelector.GetCachingType();
if (cachingType != null)
{
if (!s_CachedLists.TryGetValue(cachingType, out list))
{
list = new CachedSelectionList(inSelector);
s_CachedLists.Add(cachingType, list);
}
return list;
}
else
{
return new CachedSelectionList(inSelector);
}
}
#endregion // Cached Lists
}
private class CachedSelectionList
{
private GUIContent[] m_Content;
private FourCC[] m_Options;
public GUIContent[] Contents() { return m_Content; }
public CachedSelectionList() { }
public CachedSelectionList(FourCCSelectorAttribute inSelector)
{
List<Registry> registries = new List<Registry>();
foreach (var type in inSelector.Types)
{
Registry r = GetRegistry(type, false, true);
if (r != null)
registries.Add(r);
}
if (registries.Count == 0)
{
m_Options = new FourCC[] { FourCC.Zero };
m_Content = new GUIContent[] { new GUIContent("[empty]") };
}
else
{
List<RegistryEntry> entries = new List<RegistryEntry>();
foreach (var registry in registries)
{
registry.CopyEntries(entries);
}
entries.Sort();
m_Options = new FourCC[entries.Count + 1];
m_Content = new GUIContent[entries.Count + 1];
m_Options[0] = FourCC.Zero;
m_Content[0] = new GUIContent("[empty]");
for (int i = 0; i < entries.Count; ++i)
{
m_Options[i + 1] = entries[i].Value;
m_Content[i + 1] = new GUIContent(entries[i].Display, entries[i].Tooltip);
}
}
}
public int GetContentIndex(FourCC inValue)
{
for (int i = m_Options.Length - 1; i >= 0; --i)
{
if (m_Options[i] == inValue)
return i;
}
return -1;
}
public FourCC GetValue(int inIndex)
{
if (inIndex < 0 || inIndex >= m_Options.Length)
return FourCC.Zero;
return m_Options[inIndex];
}
}
#endif // UNITY_EDITOR && ALLOW_REGISTRY
}
[Conditional("UNITY_EDITOR")]
[AttributeUsage(AttributeTargets.Field | AttributeTargets.ReturnValue | AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)]
public class FourCCSelectorAttribute : PropertyAttribute
{
#if UNITY_EDITOR
internal readonly Type[] Types;
internal bool ShowDebug { get; set; }
internal Type GetCachingType()
{
return ShouldCacheList() ? GetType() : null;
}
#endif // UNITY_EDITOR
public FourCCSelectorAttribute(Type inType)
{
#if UNITY_EDITOR
Types = new Type[] { inType };
ShowDebug = false;
#endif // UNITY_EDITOR
}
public FourCCSelectorAttribute(bool inbShowDebug, Type inType)
{
#if UNITY_EDITOR
Types = new Type[] { inType };
ShowDebug = inbShowDebug;
#endif // UNITY_EDITOR
}
public FourCCSelectorAttribute(Type inFirstType, params Type[] inTypes)
{
#if UNITY_EDITOR
Types = new Type[1 + inTypes.Length];
Types[0] = inFirstType;
Array.Copy(inTypes, 0, Types, 1, inTypes.Length);
ShowDebug = false;
#endif // UNITY_EDITOR
}
public FourCCSelectorAttribute(bool inbShowDebug, Type inFirstType, params Type[] inTypes)
{
#if UNITY_EDITOR
Types = new Type[1 + inTypes.Length];
Types[0] = inFirstType;
Array.Copy(inTypes, 0, Types, 1, inTypes.Length);
ShowDebug = inbShowDebug;
#endif // UNITY_EDITOR
}
protected virtual bool ShouldCacheList()
{
return false;
}
}
} | 33.483871 | 145 | 0.49894 | [
"MIT"
] | BeauPrime/BeauData | Assets/BeauData/Structs/FourCC/FourCC.Unity.cs | 10,380 | 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 comprehend-2017-11-27.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Comprehend.Model
{
/// <summary>
/// Returns the code for the dominant language in the input text and the level of confidence
/// that Amazon Comprehend has in the accuracy of the detection.
/// </summary>
public partial class DominantLanguage
{
private string _languageCode;
private float? _score;
/// <summary>
/// Gets and sets the property LanguageCode.
/// <para>
/// The RFC 5646 language code for the dominant language. For more information about RFC
/// 5646, see <a href="https://tools.ietf.org/html/rfc5646">Tags for Identifying Languages</a>
/// on the <i>IETF Tools</i> web site.
/// </para>
/// </summary>
[AWSProperty(Min=1)]
public string LanguageCode
{
get { return this._languageCode; }
set { this._languageCode = value; }
}
// Check to see if LanguageCode property is set
internal bool IsSetLanguageCode()
{
return this._languageCode != null;
}
/// <summary>
/// Gets and sets the property Score.
/// <para>
/// The level of confidence that Amazon Comprehend has in the accuracy of the detection.
/// </para>
/// </summary>
public float Score
{
get { return this._score.GetValueOrDefault(); }
set { this._score = value; }
}
// Check to see if Score property is set
internal bool IsSetScore()
{
return this._score.HasValue;
}
}
} | 32.275 | 109 | 0.607668 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/Comprehend/Generated/Model/DominantLanguage.cs | 2,582 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using GoNorth.Data.Exporting;
using GoNorth.Services.Export.ExportSnippets;
using GoNorth.Services.Export.Placeholder.ScribanRenderingEngine.RenderingObjects;
using GoNorth.Services.Export.Placeholder.ScribanRenderingEngine.Util;
using Microsoft.Extensions.Localization;
using Scriban;
using Scriban.Runtime;
namespace GoNorth.Services.Export.Placeholder.ScribanRenderingEngine.ValueCollector
{
/// <summary>
/// Class to collect export snippet function data for Scriban value collectors
/// </summary>
public class ExportSnippetFunctionValueCollector : BaseScribanValueCollector
{
/// <summary>
/// Localizer Factory
/// </summary>
private readonly IStringLocalizerFactory _localizerFactory;
/// <summary>
/// Constructor
/// </summary>
/// <param name="localizerFactory">Localizer Factory</param>
public ExportSnippetFunctionValueCollector(IStringLocalizerFactory localizerFactory)
{
_localizerFactory = localizerFactory;
}
/// <summary>
/// Returns true if the value collector is valid for a given template type
/// </summary>
/// <param name="templateType">Template type</param>
/// <returns>True if the value collector is valid, else false</returns>
public override bool IsValidForTemplateType(TemplateType templateType)
{
return templateType == TemplateType.ObjectExportSnippetFunction;
}
/// <summary>
/// Collects the values for an export
/// </summary>
/// <param name="templateType">Template type</param>
/// <param name="parsedTemplate">Parsed scriban template</param>
/// <param name="scriptObject">Scriban script object to fill</param>
/// <param name="data">Export Data</param>
/// <returns>Task</returns>
public override Task CollectValues(TemplateType templateType, Template parsedTemplate, ScriptObject scriptObject, ExportObjectData data)
{
ExportSnippetFunction inputFunction = data.ExportData[ExportConstants.ExportDataObject] as ExportSnippetFunction;
if(inputFunction == null)
{
return Task.CompletedTask;
}
scriptObject.AddOrUpdate(ExportConstants.ScribanExportSnippetFunctionObjectKey, new ScribanExportSnippetFunction(inputFunction));
return Task.CompletedTask;
}
/// <summary>
/// Returns the Export Template Placeholders for a Template Type
/// </summary>
/// <param name="templateType">Template Type</param>
/// <returns>Export Template Placeholder</returns>
public override List<ExportTemplatePlaceholder> GetExportTemplatePlaceholdersForType(TemplateType templateType)
{
List<ExportTemplatePlaceholder> exportPlaceholders = new List<ExportTemplatePlaceholder>();
if(templateType != TemplateType.ObjectExportSnippetFunction)
{
return exportPlaceholders;
}
exportPlaceholders.AddRange(ScribanPlaceholderGenerator.GetPlaceholdersForObject<ScribanExportSnippetFunction>(_localizerFactory, ExportConstants.ScribanExportSnippetFunctionObjectKey));
return exportPlaceholders;
}
}
} | 43.17284 | 199 | 0.668001 | [
"MIT"
] | Dyescape/GoNorth | Services/Export/Placeholder/ScribanRenderingEngine/ValueCollector/ExportSnippetFunctionValueCollector.cs | 3,497 | C# |
using Omnikeeper.Entity.AttributeValues;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
namespace Omnikeeper.Base.Entity
{
public class EffectiveTrait
{
public readonly Guid CIID;
public readonly ITrait UnderlyingTrait;
public readonly IImmutableDictionary<string, MergedCIAttribute> TraitAttributes;
public readonly IImmutableDictionary<string, IEnumerable<MergedRelation>> OutgoingTraitRelations;
public readonly IImmutableDictionary<string, IEnumerable<MergedRelation>> IncomingTraitRelations;
public EffectiveTrait(Guid ciid, ITrait underlyingTrait,
IDictionary<string, MergedCIAttribute> traitAttributes,
IDictionary<string, IEnumerable<MergedRelation>> outgoingTraitRelations,
IDictionary<string, IEnumerable<MergedRelation>> incomingTraitRelations
)
{
CIID = ciid;
UnderlyingTrait = underlyingTrait;
TraitAttributes = traitAttributes.ToImmutableDictionary();
OutgoingTraitRelations = outgoingTraitRelations.ToImmutableDictionary();
IncomingTraitRelations = incomingTraitRelations.ToImmutableDictionary();
}
}
public static class EffectiveTraitExtensions
{
public static IEnumerable<(string attributeName, IAttributeValue attributeValue)> ExtractIDAttributeValueTuples(this EffectiveTrait effectiveTrait)
{
var idTraitAttributes = effectiveTrait.UnderlyingTrait.RequiredAttributes.Where(ra => ra.AttributeTemplate.IsID.GetValueOrDefault(false));
foreach(var idTraitAttribute in idTraitAttributes)
{
var ta = effectiveTrait.TraitAttributes[idTraitAttribute.Identifier];
yield return (ta.Attribute.Name, ta.Attribute.Value);
}
}
public static IAttributeValue? ExtractAttributeValueByTraitAttributeIdentifier(this EffectiveTrait effectiveTrait, string traitAttributeIdentifier)
{
return effectiveTrait.TraitAttributes[traitAttributeIdentifier]?.Attribute.Value;
}
// returns all changeset IDs that contribute to this effective trait
public static ISet<Guid> GetRelevantChangesetIDs(this EffectiveTrait effectiveTrait)
{
return effectiveTrait.TraitAttributes.Select(ta => ta.Value.Attribute.ChangesetID)
.Union(effectiveTrait.OutgoingTraitRelations.SelectMany(or => or.Value.Select(o => o.Relation.ChangesetID)))
.Union(effectiveTrait.IncomingTraitRelations.SelectMany(or => or.Value.Select(o => o.Relation.ChangesetID)))
.ToHashSet();
}
}
}
| 46.355932 | 155 | 0.715174 | [
"Apache-2.0"
] | max-bytes/omnikeeper | backend/Omnikeeper.Base/Entity/EffectiveTrait.cs | 2,737 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace _8.CustomComparatorE
{
class Program
{
static void Main(string[] args)
{
int[] numbersToSort = Console.ReadLine()
.Split(" ", StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
Func<int, int, int> sortFunc = (x, y) => x.CompareTo(y);
Action<int[], int[]> printNumbers = (x, y) => Console.WriteLine($"{string.Join(" ", x)} {string.Join(" ", y)}");
int[] evenNumbers = numbersToSort.Where(x => x % 2 == 0).ToArray();
int[] oddNumbers = numbersToSort.Where(x => x % 2 != 0).ToArray();
Array.Sort(evenNumbers, new Comparison<int>(sortFunc));
Array.Sort(oddNumbers, new Comparison<int>(sortFunc));
printNumbers(evenNumbers, oddNumbers);
}
}
}
| 30.7 | 124 | 0.559175 | [
"MIT"
] | deedeedextor/Software-University | C#Advanced/C#Advanced/FunctionalProgrammingLE/8.CustomComparatorE/Program.cs | 923 | C# |
namespace PnP_Processor
{
partial class BOMList
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.BOM = new System.Windows.Forms.ListBox();
this.pnplist = new System.Windows.Forms.ListBox();
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.SuspendLayout();
//
// splitContainer1
//
this.splitContainer1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.Location = new System.Drawing.Point(0, 0);
this.splitContainer1.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.splitContainer1.Name = "splitContainer1";
this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.BOM);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.pnplist);
this.splitContainer1.Size = new System.Drawing.Size(533, 292);
this.splitContainer1.SplitterDistance = 172;
this.splitContainer1.SplitterWidth = 3;
this.splitContainer1.TabIndex = 0;
//
// BOM
//
this.BOM.Dock = System.Windows.Forms.DockStyle.Fill;
this.BOM.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.BOM.FormattingEnabled = true;
this.BOM.ItemHeight = 20;
this.BOM.Location = new System.Drawing.Point(0, 0);
this.BOM.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.BOM.Name = "BOM";
this.BOM.Size = new System.Drawing.Size(529, 168);
this.BOM.TabIndex = 0;
this.BOM.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.BOM_DrawItem);
this.BOM.SelectedIndexChanged += new System.EventHandler(this.BOM_SelectedIndexChanged);
//
// pnplist
//
this.pnplist.Dock = System.Windows.Forms.DockStyle.Fill;
this.pnplist.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.pnplist.FormattingEnabled = true;
this.pnplist.ItemHeight = 20;
this.pnplist.Location = new System.Drawing.Point(0, 0);
this.pnplist.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.pnplist.MultiColumn = true;
this.pnplist.Name = "pnplist";
this.pnplist.SelectionMode = System.Windows.Forms.SelectionMode.MultiSimple;
this.pnplist.Size = new System.Drawing.Size(529, 113);
this.pnplist.TabIndex = 1;
this.pnplist.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.pnplist_DrawItem);
this.pnplist.SelectedIndexChanged += new System.EventHandler(this.pnplist_SelectedIndexChanged);
//
// BOMList
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(533, 292);
this.Controls.Add(this.splitContainer1);
this.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.Name = "BOMList";
this.Text = "BOMList";
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();
this.splitContainer1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.ListBox BOM;
private System.Windows.Forms.ListBox pnplist;
}
} | 45.061404 | 108 | 0.60366 | [
"MIT"
] | FabianoGK/GerberTools | PnP_Processor/BOMList.Designer.cs | 5,139 | C# |
// Copyright (c) 2015 - 2019 Doozy Entertainment. All Rights Reserved.
// This code can only be used under the standard Unity Asset Store End User License Agreement
// A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms
using Doozy.Engine.Settings;
using Doozy.Engine.Utils;
using UnityEngine;
using UnityEngine.Audio;
#if UNITY_EDITOR
using UnityEditor;
#endif
// ReSharper disable UnusedMethodReturnValue.Global
// ReSharper disable UnusedMember.Global
// ReSharper disable MemberCanBePrivate.Global
namespace Doozy.Engine.Soundy
{
/// <inheritdoc />
/// <summary>
/// Central component of the Soundy system that binds all the sound sub-systems together.
/// It gets the SoundGroupData references from the SoundyDatabase and passes them to the SoundyPooler, that in turn manages and uses SoundyControllers to play the sounds.
/// </summary>
[AddComponentMenu(MenuUtils.SoundyManager_AddComponentMenu_MenuName, MenuUtils.SoundyManager_AddComponentMenu_Order)]
[DisallowMultipleComponent]
[DefaultExecutionOrder(DoozyExecutionOrder.SOUNDY_MANAGER)]
public class SoundyManager : MonoBehaviour
{
#region UNITY_EDITOR
#if UNITY_EDITOR
[MenuItem(MenuUtils.SoundyManager_MenuItem_ItemName, false, MenuUtils.SoundyManager_MenuItem_Priority)]
private static void CreateComponent(MenuCommand menuCommand) { AddToScene(true); }
#endif
#endregion
#region Singleton
protected SoundyManager() { }
private static SoundyManager s_instance;
/// <summary> Returns a reference to the SoundyManager in the Scene. If one does not exist, it gets created. </summary>
public static SoundyManager Instance
{
get
{
if (s_instance != null) return s_instance;
if (ApplicationIsQuitting) return null;
s_instance = FindObjectOfType<SoundyManager>();
// ReSharper disable once RedundantArgumentDefaultValue
if (s_instance == null) DontDestroyOnLoad(AddToScene(false).gameObject);
return s_instance;
}
}
#endregion
#region Constants
public const string DATABASE = "Database";
public const string GENERAL = "General";
public const string NEW_SOUND_GROUP = "New Sound Group";
public const string NO_SOUND = "No Sound";
public const string SOUNDS = "Sounds";
public const string SOUNDY = "Soundy";
#endregion
#region Static Properties
/// <summary> Internal variable used as a flag when the application is quitting </summary>
private static bool ApplicationIsQuitting = false;
/// <summary> Internal variable that keeps track if this class has been initialized </summary>
private static bool s_initialized;
/// <summary> Internal variable that keeps a reference to the SoundyPooler component attached to this GameObject </summary>
private static SoundyPooler s_pooler;
/// <summary> Returns a reference to the SoundyPooler component on this GameObject. If one does not exist, it gets added. </summary>
public static SoundyPooler Pooler
{
get
{
if (s_pooler != null) return s_pooler;
s_pooler = Instance.gameObject.GetComponent<SoundyPooler>();
if (s_pooler == null) s_pooler = Instance.gameObject.AddComponent<SoundyPooler>();
return s_pooler;
}
}
/// <summary> Direct reference to the SoundyDatabase asset </summary>
public static SoundyDatabase Database { get { return SoundySettings.Database; } }
#endregion
#region Properties
private bool DebugComponent { get { return DoozySettings.Instance.DebugSoundyManager; } }
#endregion
#region Unity Methods
#if UNITY_2019_3_OR_NEWER
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
private static void RunOnStart()
{
ApplicationIsQuitting = false;
s_initialized = false;
s_pooler = null;
}
#endif
private void Awake() { s_initialized = true; }
#endregion
#region Static Methods
/// <summary> Add SoundyManager to scene and returns a reference to it </summary>
public static SoundyManager AddToScene(bool selectGameObjectAfterCreation = false) { return DoozyUtils.AddToScene<SoundyManager>(MenuUtils.SoundyManager_GameObject_Name, true, selectGameObjectAfterCreation); }
/// <summary> Create a new SoundyController in the current scene and get a reference to it </summary>
public static SoundyController GetController() { return SoundyController.GetController(); }
/// <summary> Returns a proper formatted filename for a given database name </summary>
/// <param name="databaseName"> Database name </param>
public static string GetSoundDatabaseFilename(string databaseName) { return "SoundDatabase_" + databaseName.Trim(); }
/// <summary> Initializes the SoundyManager Instance </summary>
public static void Init()
{
if (s_initialized || s_instance != null) return;
s_instance = Instance;
for (int i = 0; i < SoundyPooler.MinimumNumberOfControllers + 1; i++)
SoundyPooler.GetControllerFromPool().Stop();
}
/// <summary> Stop all SoundyControllers from playing and destroys the GameObjects they are attached to </summary>
public static void KillAllControllers()
{
if (Instance.DebugComponent) DDebug.Log("Kill All Controllers", Instance);
SoundyController.KillAll();
}
/// <summary> Mute all the SoundyControllers </summary>
public static void MuteAllControllers()
{
if (Instance.DebugComponent) DDebug.Log("Mute All Controllers", Instance);
SoundyController.MuteAll();
}
/// <summary> Mute all sound sources (including MasterAudio) </summary>
public static void MuteAllSounds()
{
if (Instance.DebugComponent) DDebug.Log("Mute All Sounds", Instance);
MuteAllControllers();
#if dUI_MasterAudio
DarkTonic.MasterAudio.MasterAudio.MuteEverything();
#endif
}
/// <summary> Pause all the SoundyControllers that are currently playing </summary>
public static void PauseAllControllers()
{
if (Instance.DebugComponent) DDebug.Log("Pause All Controllers", Instance);
SoundyController.PauseAll();
}
/// <summary> Pause all sound sources (including MasterAudio) </summary>
public static void PauseAllSounds()
{
if (Instance.DebugComponent) DDebug.Log("Pause All Sounds", Instance);
PauseAllControllers();
#if dUI_MasterAudio
DarkTonic.MasterAudio.MasterAudio.PauseEverything();
#endif
}
/// <summary>
/// Play the specified sound at the given position.
/// Returns a reference to the SoundyController that is playing the sound.
/// Returns null if no sound is found.
/// </summary>
/// <param name="databaseName"> The sound category </param>
/// <param name="soundName"> Sound Name of the sound </param>
/// <param name="position"> The position from where this sound will play from </param>
public static SoundyController Play(string databaseName, string soundName, Vector3 position)
{
if (!s_initialized) s_instance = Instance;
if (Database == null) return null;
if (soundName.Equals(NO_SOUND)) return null;
SoundGroupData soundGroupData = Database.GetAudioData(databaseName, soundName);
if (soundGroupData == null) return null;
if (Instance.DebugComponent) DDebug.Log("Play '" + databaseName + "' / '" + soundName + "' SoundGroupData at " + position + " position", Instance);
return soundGroupData.Play(position, Database.GetSoundDatabase(databaseName).OutputAudioMixerGroup);
}
/// <summary>
/// Play the specified sound, at the given position.
/// Returns a reference to the SoundyController that is playing the sound.
/// Returns null if the AudioClip is null.
/// </summary>
/// <param name="audioClip"> The AudioClip to play </param>
/// <param name="position"> The position from where this sound will play from </param>
public static SoundyController Play(AudioClip audioClip, Vector3 position)
{
if (!s_initialized) s_instance = Instance;
return Play(audioClip, null, position);
}
/// <summary>
/// Play the specified sound and follow a given target Transform while playing.
/// Returns a reference to the SoundyController that is playing the sound.
/// Returns null if no sound is found.
/// </summary>
/// <param name="databaseName"> The sound category </param>
/// <param name="soundName"> Sound Name of the sound </param>
/// <param name="followTarget"> The target transform that the sound will follow while playing </param>
public static SoundyController Play(string databaseName, string soundName, Transform followTarget)
{
if (!s_initialized) s_instance = Instance;
if (Database == null) return null;
if (soundName.Equals(NO_SOUND)) return null;
SoundGroupData soundGroupData = Database.GetAudioData(databaseName, soundName);
if (soundGroupData == null) return null;
if (Instance.DebugComponent) DDebug.Log("Play '" + databaseName + "' / '" + soundName + "' SoundGroupData and follow the '" + followTarget.name + "' GameObject", Instance);
return soundGroupData.Play(followTarget, Database.GetSoundDatabase(databaseName).OutputAudioMixerGroup);
}
/// <summary>
/// Play the specified sound, at the set position.
/// Returns a reference to the SoundyController that is playing the sound.
/// Returns null if the AudioClip is null.
/// </summary>
/// <param name="audioClip"> The AudioClip to play </param>
/// <param name="followTarget"> The target transform that the sound will follow while playing </param>
public static SoundyController Play(AudioClip audioClip, Transform followTarget)
{
if (!s_initialized) s_instance = Instance;
return Play(audioClip, null, followTarget);
}
/// <summary>
/// Play the specified sound with the given category, name and type.
/// Returns a reference to the SoundyController that is playing the sound.
/// Returns null if no sound is found.
/// </summary>
/// <param name="databaseName"> The sound category </param>
/// <param name="soundName"> Sound Name of the sound </param>
public static SoundyController Play(string databaseName, string soundName)
{
if (!s_initialized) s_instance = Instance;
if (Database == null) return null;
if (soundName.Equals(NO_SOUND)) return null;
if (string.IsNullOrEmpty(databaseName) || string.IsNullOrEmpty(databaseName.Trim())) return null;
if (string.IsNullOrEmpty(soundName) || string.IsNullOrEmpty(soundName.Trim())) return null;
SoundDatabase soundDatabase = Database.GetSoundDatabase(databaseName);
if (soundDatabase == null) return null;
SoundGroupData soundGroupData = soundDatabase.GetData(soundName);
if (soundGroupData == null) return null;
return soundGroupData.Play(Pooler.transform, soundDatabase.OutputAudioMixerGroup);
}
/// <summary>
/// Play the passed AudioClip.
/// Returns a reference to the SoundyController that is playing the sound.
/// Returns null if the AudioClip is null.
/// </summary>
/// <param name="audioClip"> The AudioClip to play </param>
public static SoundyController Play(AudioClip audioClip)
{
if (!s_initialized) s_instance = Instance;
return Play(audioClip, null, Pooler.transform);
}
/// <summary>
/// Play the specified audio clip with the given parameters, at the set position.
/// Returns a reference to the SoundyController that is playing the sound.
/// Returns null if the AudioClip is null.
/// </summary>
/// <param name="audioClip"> The AudioClip to play </param>
/// <param name="outputAudioMixerGroup"> The output audio mixer group that this sound will get routed through </param>
/// <param name="position"> The position from where this sound will play from </param>
/// <param name="volume"> The volume of the audio source (0.0 to 1.0) </param>
/// <param name="pitch"> The pitch of the audio source </param>
/// <param name="loop"> Is the audio clip looping? </param>
/// <param name="spatialBlend">
/// Sets how much this AudioSource is affected by 3D space calculations (attenuation,
/// doppler etc). 0.0 makes the sound full 2D, 1.0 makes it full 3D
/// </param>
public static SoundyController Play(AudioClip audioClip, AudioMixerGroup outputAudioMixerGroup, Vector3 position,
float volume = 1, float pitch = 1, bool loop = false, float spatialBlend = 1)
{
if (!s_initialized) s_instance = Instance;
if (audioClip == null) return null;
SoundyController controller = SoundyPooler.GetControllerFromPool();
controller.SetSourceProperties(audioClip, volume, pitch, loop, spatialBlend);
controller.SetOutputAudioMixerGroup(outputAudioMixerGroup);
controller.SetPosition(position);
controller.gameObject.name = "[AudioClip]-(" + audioClip.name + ")";
controller.Play();
if (Instance.DebugComponent) DDebug.Log("Play '" + audioClip.name + "' AudioClip", Instance);
return controller;
}
/// <summary>
/// Play the specified audio clip with the given parameters (and follow a given Transform while playing).
/// Returns a reference to the SoundyController that is playing the sound.
/// Returns null if the AudioClip is null.
/// </summary>
/// <param name="audioClip"> The AudioClip to play </param>
/// <param name="outputAudioMixerGroup"> The output audio mixer group that this sound will get routed through </param>
/// <param name="followTarget"> The target transform that the sound will follow while playing </param>
/// <param name="volume"> The volume of the audio source (0.0 to 1.0) </param>
/// <param name="pitch"> The pitch of the audio source </param>
/// <param name="loop"> Is the audio clip looping? </param>
/// <param name="spatialBlend">
/// Sets how much this AudioSource is affected by 3D space calculations (attenuation,
/// doppler etc). 0.0 makes the sound full 2D, 1.0 makes it full 3D
/// </param>
public static SoundyController Play(AudioClip audioClip, AudioMixerGroup outputAudioMixerGroup,
Transform followTarget = null, float volume = 1, float pitch = 1, bool loop = false,
float spatialBlend = 1)
{
if (!s_initialized) s_instance = Instance;
if (audioClip == null) return null;
SoundyController controller = SoundyPooler.GetControllerFromPool();
controller.SetSourceProperties(audioClip, volume, pitch, loop, spatialBlend);
controller.SetOutputAudioMixerGroup(outputAudioMixerGroup);
if (followTarget == null)
{
spatialBlend = 0;
controller.SetFollowTarget(Pooler.transform);
}
else
{
controller.SetFollowTarget(followTarget);
}
controller.gameObject.name = "[AudioClip]-(" + audioClip.name + ")";
controller.Play();
if (Instance.DebugComponent) DDebug.Log("Play '" + audioClip.name + "' AudioClip", Instance);
return controller;
}
/// <summary>
/// Play a sound according to the settings in the SoundyData reference.
/// Returns a reference to the SoundyController that is playing the sound if data.SoundSource is set to either Soundy or AudioClip.
/// If data is null or data.SoundSource is set to MasterAudio, it will always return null because MasterAudio is the one playing the sound and not a SoundyController </summary>
/// <param name="data"> Sound settings </param>
public static SoundyController Play(SoundyData data)
{
if (data == null) return null;
if (!s_initialized) s_instance = Instance;
switch (data.SoundSource)
{
case SoundSource.Soundy:
return Play(data.DatabaseName, data.SoundName);
case SoundSource.AudioClip:
return Play(data.AudioClip, data.OutputAudioMixerGroup);
case SoundSource.MasterAudio:
if (Instance.DebugComponent) DDebug.Log("Play '" + data.SoundName + "' with MasterAudio", Instance);
#if dUI_MasterAudio
DarkTonic.MasterAudio.MasterAudio.PlaySound(data.SoundName);
//DDebug.Log("MasterAudio - Play Sound: " + data.SoundName);
#endif
break;
}
return null;
}
/// <summary> Stop all the SoundyControllers that are currently playing </summary>
public static void StopAllControllers()
{
if (Instance.DebugComponent) DDebug.Log("Stop All Controllers", Instance);
SoundyController.StopAll();
}
/// <summary> Stop all sound sources (including MasterAudio) </summary>
public static void StopAllSounds()
{
if (Instance.DebugComponent) DDebug.Log("Stop All Sounds", Instance);
StopAllControllers();
#if dUI_MasterAudio
DarkTonic.MasterAudio.MasterAudio.StopEverything();
#endif
}
/// <summary> Unmute all the SoundyControllers that were previously muted </summary>
public static void UnmuteAllControllers()
{
if (Instance.DebugComponent) DDebug.Log("Unmute All Controllers", Instance);
SoundyController.UnmuteAll();
}
/// <summary> Unmute all sound sources (including MasterAudio) </summary>
public static void UnmuteAllSounds()
{
if (Instance.DebugComponent) DDebug.Log("Unmute All Sounds", Instance);
UnmuteAllControllers();
#if dUI_MasterAudio
DarkTonic.MasterAudio.MasterAudio.UnmuteEverything();
#endif
}
/// <summary> Unpause all the SoundyControllers that were previously paused </summary>
public static void UnpauseAllControllers()
{
if (Instance.DebugComponent) DDebug.Log("Unpause All Controllers", Instance);
SoundyController.UnpauseAll();
}
/// <summary> Unpause all sound sources (including MasterAudio) </summary>
public static void UnpauseAllSounds()
{
if (Instance.DebugComponent) DDebug.Log("Unpause All Sounds", Instance);
UnpauseAllControllers();
#if dUI_MasterAudio
DarkTonic.MasterAudio.MasterAudio.UnpauseEverything();
#endif
}
#endregion
}
} | 46.168203 | 217 | 0.636622 | [
"MIT"
] | danielfroes/Binocolar | Assets/Doozy/Engine/Soundy/SoundyManager.cs | 20,039 | C# |
namespace Whyvra.Tunnel.Common.Models
{
public class CreateUpdateServerDto
{
public string Name { get; set; }
public string Description { get; set; }
public string AssignedRange { get; set; }
public string Dns { get; set; }
public string Endpoint { get; set; }
public int ListenPort { get; set; }
public string PublicKey { get; set; }
}
} | 21.684211 | 49 | 0.597087 | [
"MIT"
] | whyvra/tunnel | Whyvra.Tunnel.Common/Models/CreateUpdateServerDto.cs | 412 | C# |
using System.Collections.Generic;
using Microsoft.Xna.Framework.Input;
namespace Nez
{
/// <summary>
/// A virtual input represented as a float between -1 and 1
/// </summary>
public class VirtualAxis : VirtualInput
{
public List<Node> Nodes = new List<Node>();
float _simulatedValue;
int _simulationStep;
public float Value
{
get
{
for (var i = 0; i < Nodes.Count; i++)
{
var val = Nodes[i].Value;
if (val != 0)
return val;
}
return _simulatedValue;
}
}
public VirtualAxis()
{
}
public VirtualAxis(params Node[] nodes)
{
Nodes.AddRange(nodes);
}
public void Simulate(float value)
{
_simulatedValue = value;
_simulationStep = 1;
}
public override void Update()
{
for (var i = 0; i < Nodes.Count; i++)
Nodes[i].Update();
switch (_simulationStep)
{
case 1:
_simulationStep++;
break;
case 2:
_simulatedValue = 0;
_simulationStep = 0;
break;
}
}
public static implicit operator float(VirtualAxis axis)
{
return axis.Value;
}
#region Node types
public abstract class Node : VirtualInputNode
{
public abstract float Value { get; }
}
public class GamePadLeftStickX : Node
{
public int GamepadIndex;
public float Deadzone;
public GamePadLeftStickX(int gamepadIndex = 0, float deadzone = Input.DEFAULT_DEADZONE)
{
GamepadIndex = gamepadIndex;
Deadzone = deadzone;
}
public override float Value => Mathf.SignThreshold(Input.GamePads[GamepadIndex].GetLeftStick(Deadzone).X, Deadzone);
}
public class GamePadLeftStickY : Node
{
/// <summary>
/// if true, pressing up will return -1 and down will return 1 matching GamePadDpadUpDown
/// </summary>
public bool InvertResult = true;
public int GamepadIndex;
public float Deadzone;
public GamePadLeftStickY(int gamepadIndex = 0, float deadzone = Input.DEFAULT_DEADZONE)
{
GamepadIndex = gamepadIndex;
Deadzone = deadzone;
}
public override float Value
{
get
{
var multiplier = InvertResult ? -1 : 1;
return multiplier *
Mathf.SignThreshold(Input.GamePads[GamepadIndex].GetLeftStick(Deadzone).Y, Deadzone);
}
}
}
public class GamePadRightStickX : Node
{
public int GamepadIndex;
public float Deadzone;
public GamePadRightStickX(int gamepadIndex = 0, float deadzone = Input.DEFAULT_DEADZONE)
{
GamepadIndex = gamepadIndex;
Deadzone = deadzone;
}
public override float Value => Mathf.SignThreshold(Input.GamePads[GamepadIndex].GetRightStick(Deadzone).X, Deadzone);
}
public class GamePadRightStickY : Node
{
public int GamepadIndex;
public float Deadzone;
public GamePadRightStickY(int gamepadIndex = 0, float deadzone = Input.DEFAULT_DEADZONE)
{
GamepadIndex = gamepadIndex;
Deadzone = deadzone;
}
public override float Value => Mathf.SignThreshold(Input.GamePads[GamepadIndex].GetRightStick(Deadzone).Y, Deadzone);
}
public class GamePadDpadLeftRight : Node
{
public int GamepadIndex;
public GamePadDpadLeftRight(int gamepadIndex = 0)
{
GamepadIndex = gamepadIndex;
}
public override float Value
{
get
{
if (Input.GamePads[GamepadIndex].DpadRightDown)
return 1f;
else if (Input.GamePads[GamepadIndex].DpadLeftDown)
return -1f;
else
return 0f;
}
}
}
public class GamePadDpadUpDown : Node
{
public int GamepadIndex;
public GamePadDpadUpDown(int gamepadIndex = 0)
{
GamepadIndex = gamepadIndex;
}
public override float Value
{
get
{
if (Input.GamePads[GamepadIndex].DpadDownDown)
return 1f;
else if (Input.GamePads[GamepadIndex].DpadUpDown)
return -1f;
else
return 0f;
}
}
}
public class KeyboardKeys : Node
{
public OverlapBehavior OverlapBehavior;
public Keys Positive;
public Keys Negative;
float _value;
bool _turned;
public KeyboardKeys(OverlapBehavior overlapBehavior, Keys negative, Keys positive)
{
OverlapBehavior = overlapBehavior;
Negative = negative;
Positive = positive;
}
public override void Update()
{
if (Input.IsKeyDown(Positive))
{
if (Input.IsKeyDown(Negative))
{
switch (OverlapBehavior)
{
default:
case OverlapBehavior.CancelOut:
_value = 0;
break;
case OverlapBehavior.TakeNewer:
if (!_turned)
{
_value *= -1;
_turned = true;
}
break;
case OverlapBehavior.TakeOlder:
//value stays the same
break;
}
}
else
{
_turned = false;
_value = 1;
}
}
else if (Input.IsKeyDown(Negative))
{
_turned = false;
_value = -1;
}
else
{
_turned = false;
_value = 0;
}
}
public override float Value => _value;
}
#endregion
}
}
| 17.807829 | 120 | 0.634892 | [
"Apache-2.0",
"MIT"
] | fuzzypixelz/Nez | Nez.Portable/Input/Virtual/VirtualAxis.cs | 5,006 | C# |
using UnityEngine;
namespace AnilTools
{
public static class Vibration
{
#if UNITY_ANDROID && !UNITY_EDITOR
public static readonly AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
public static readonly AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
public static readonly AndroidJavaObject vibrator = currentActivity.Call<AndroidJavaObject>("getSystemService", "vibrator");
#else
public static AndroidJavaClass unityPlayer;
public static AndroidJavaObject currentActivity;
public static AndroidJavaObject vibrator;
#endif
private const string vibrate = "vibrate";
public static void Vibrate()
{
if (isAndroid())
vibrator.Call(vibrate);
else
Handheld.Vibrate();
}
public static void Vibrate(long milliseconds)
{
milliseconds = milliseconds < 50 ? 50 : milliseconds;
if (isAndroid())
vibrator.Call(vibrate, milliseconds);
else
Handheld.Vibrate();
}
public static bool HasVibrator()
{
return isAndroid();
}
public static void Cancel()
{
if (isAndroid())
vibrator.Call(vibrate);
}
private static bool isAndroid()
{
#if UNITY_ANDROID && !UNITY_EDITOR
return true;
#else
return false;
#endif
}
}
} | 28.105263 | 129 | 0.586142 | [
"Unlicense"
] | benanil/AnilTools-Utility | Utils/heleper/Android and ios/Vibration.cs | 1,604 | C# |
using UnityEngine;
namespace Common
{
public class AndroidBackBtnManager : Singleton<AndroidBackBtnManager>
{
private void Awake()
{
DontDestroyOnLoad(gameObject);
}
private void FixedUpdate ()
{
if (Application.platform != RuntimePlatform.Android)
return;
if (!Input.GetKey(KeyCode.Escape))
return;
Application.Quit();
System.Diagnostics.Process.GetCurrentProcess().Kill();
var activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity");
activity.Call<bool>("moveTaskToBack", true);
}
}
} | 21.464286 | 121 | 0.717138 | [
"BSD-2-Clause"
] | kugorang/Unity_2dRunTemplate | Assets/Scripts/Common/AndroidBackBtnManager.cs | 603 | C# |
using System.Threading.Tasks;
using book_management_models;
using book_management_persistence.Contexts;
using book_management_persistence.Repositories;
namespace book_management_persistence.Implements
{
public class OrderItemRepositoryImpl : BaseRepositoryImpl<OrderItem>, IOrderItemRepository
{
public OrderItemRepositoryImpl(AppDbContext context) : base(context)
{
}
public async Task<bool> CreateOrderItem(OrderItem orderItem)
{
var result = await this.InsertAsync(orderItem);
return result;
}
}
} | 26.772727 | 94 | 0.719864 | [
"MIT"
] | trungtruongpham/DE_assignment | book-management-be/book-management-persistence/Implements/OrderItemRepositoryImpl.cs | 591 | C# |
namespace BFF.Model.ImportExport
{
public interface ILoadConfiguration : IConfiguration
{
}
} | 17.666667 | 56 | 0.716981 | [
"MIT"
] | Yeah69/BFF | Model/ImportExport/ILoadConfiguration.cs | 108 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ram-2018-01-04.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.RAM.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.RAM.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for ResourceShareAssociation Object
/// </summary>
public class ResourceShareAssociationUnmarshaller : IUnmarshaller<ResourceShareAssociation, XmlUnmarshallerContext>, IUnmarshaller<ResourceShareAssociation, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
ResourceShareAssociation IUnmarshaller<ResourceShareAssociation, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public ResourceShareAssociation Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
ResourceShareAssociation unmarshalledObject = new ResourceShareAssociation();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("associatedEntity", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.AssociatedEntity = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("associationType", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.AssociationType = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("creationTime", targetDepth))
{
var unmarshaller = DateTimeUnmarshaller.Instance;
unmarshalledObject.CreationTime = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("external", targetDepth))
{
var unmarshaller = BoolUnmarshaller.Instance;
unmarshalledObject.External = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("lastUpdatedTime", targetDepth))
{
var unmarshaller = DateTimeUnmarshaller.Instance;
unmarshalledObject.LastUpdatedTime = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("resourceShareArn", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.ResourceShareArn = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("resourceShareName", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.ResourceShareName = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("status", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Status = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("statusMessage", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.StatusMessage = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static ResourceShareAssociationUnmarshaller _instance = new ResourceShareAssociationUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static ResourceShareAssociationUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 39.835714 | 185 | 0.598888 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/RAM/Generated/Model/Internal/MarshallTransformations/ResourceShareAssociationUnmarshaller.cs | 5,577 | C# |
#region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// 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.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using Grpc.Core.Internal;
using Grpc.Core.Utils;
namespace Grpc.Core
{
/// <summary>
/// A property of an <see cref="AuthContext"/>.
/// Note: experimental API that can change or be removed without any prior notice.
/// </summary>
public class AuthProperty
{
string name;
byte[] valueBytes;
Lazy<string> value;
private AuthProperty(string name, byte[] valueBytes)
{
this.name = GrpcPreconditions.CheckNotNull(name);
this.valueBytes = GrpcPreconditions.CheckNotNull(valueBytes);
this.value = new Lazy<string>(() => MarshalUtils.GetStringUTF8(this.valueBytes));
}
/// <summary>
/// Gets the name of the property.
/// </summary>
public string Name
{
get
{
return name;
}
}
/// <summary>
/// Gets the string value of the property.
/// </summary>
public string Value
{
get
{
return value.Value;
}
}
/// <summary>
/// Gets the binary value of the property.
/// </summary>
public byte[] ValueBytes
{
get
{
var valueCopy = new byte[valueBytes.Length];
Buffer.BlockCopy(valueBytes, 0, valueCopy, 0, valueBytes.Length);
return valueCopy;
}
}
/// <summary>
/// Creates an instance of <c>AuthProperty</c>.
/// </summary>
/// <param name="name">the name</param>
/// <param name="valueBytes">the binary value of the property</param>
public static AuthProperty Create(string name, byte[] valueBytes)
{
GrpcPreconditions.CheckNotNull(valueBytes);
var valueCopy = new byte[valueBytes.Length];
Buffer.BlockCopy(valueBytes, 0, valueCopy, 0, valueBytes.Length);
return new AuthProperty(name, valueCopy);
}
/// <summary>
/// Gets the binary value of the property (without making a defensive copy).
/// </summary>
internal byte[] ValueBytesUnsafe
{
get
{
return valueBytes;
}
}
/// <summary>
/// Creates and instance of <c>AuthProperty</c> without making a defensive copy of <c>valueBytes</c>.
/// </summary>
internal static AuthProperty CreateUnsafe(string name, byte[] valueBytes)
{
return new AuthProperty(name, valueBytes);
}
}
}
| 29.857143 | 109 | 0.574163 | [
"Apache-2.0"
] | 0lento/grpc | src/csharp/Grpc.Core/AuthProperty.cs | 3,344 | C# |
using System;
using System.Globalization;
using Avalonia;
using Avalonia.Data.Converters;
using NodeEditor.Model;
namespace NodeEditor.Converters;
public class PinToPointConverter : IValueConverter
{
public static PinToPointConverter Instance = new();
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
if (value is IPin pin)
{
var x = pin.X;
var y = pin.Y;
if (pin.Parent is { })
{
x += pin.Parent.X;
y += pin.Parent.Y;
}
return new Point(x, y);
}
return new Point();
}
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
| 22.594595 | 101 | 0.594498 | [
"MIT"
] | janbiehl/NodeEditor | src/NodeEditorAvalonia/Converters/PinToPointConverter.cs | 836 | C# |
using System;
using System.Collections.Generic;
// this code from unity technologies tree view sample
// http://files.unity3d.com/mads/TreeViewExamples.zip
namespace UnityExtensions.Memo {
// TreeElementUtility and TreeElement are useful helper classes for backend tree data structures.
// See tests at the bottom for examples of how to use.
public static class MemoTreeElementUtility {
public static void TreeToList<T>( T root, IList<T> result ) where T : MemoTreeElement {
if( result == null )
throw new NullReferenceException( "The input 'IList<T> result' list is null" );
result.Clear();
Stack<T> stack = new Stack<T>();
stack.Push( root );
while( stack.Count > 0 ) {
T current = stack.Pop();
result.Add( current );
if( current.children != null && current.children.Count > 0 ) {
for( int i = current.children.Count - 1; i >= 0; i-- ) {
stack.Push( ( T )current.children[ i ] );
}
}
}
}
// Returns the root of the tree parsed from the list (always the first element).
// Important: the first item and is required to have a depth value of -1.
// The rest of the items should have depth >= 0.
public static T ListToTree<T>( IList<T> list ) where T : MemoTreeElement {
// Validate input
ValidateDepthValues( list );
// Clear old states
foreach( var element in list ) {
element.parent = null;
element.children = null;
}
// Set child and parent references using depth info
for( int parentIndex = 0; parentIndex < list.Count; parentIndex++ ) {
var parent = list[ parentIndex ];
bool alreadyHasValidChildren = parent.children != null;
if( alreadyHasValidChildren )
continue;
int parentDepth = parent.depth;
int childCount = 0;
// Count children based depth value, we are looking at children until it's the same depth as this object
for( int i = parentIndex + 1; i < list.Count; i++ ) {
if( list[ i ].depth == parentDepth + 1 )
childCount++;
if( list[ i ].depth <= parentDepth )
break;
}
// Fill child array
List<MemoTreeElement> childList = null;
if( childCount != 0 ) {
childList = new List<MemoTreeElement>( childCount ); // Allocate once
childCount = 0;
for( int i = parentIndex + 1; i < list.Count; i++ ) {
if( list[ i ].depth == parentDepth + 1 ) {
list[ i ].parent = parent;
childList.Add( list[ i ] );
childCount++;
}
if( list[ i ].depth <= parentDepth )
break;
}
}
parent.children = childList;
}
return list[ 0 ];
}
// Check state of input list
public static void ValidateDepthValues<T>( IList<T> list ) where T : MemoTreeElement {
if( list.Count == 0 )
throw new ArgumentException( "list should have items, count is 0, check before calling ValidateDepthValues", "list" );
if( list[ 0 ].depth != -1 )
throw new ArgumentException( "list item at index 0 should have a depth of -1 (since this should be the hidden root of the tree). Depth is: " + list[ 0 ].depth, "list" );
for( int i = 0; i < list.Count - 1; i++ ) {
int depth = list[ i ].depth;
int nextDepth = list[ i + 1 ].depth;
if( nextDepth > depth && nextDepth - depth > 1 )
throw new ArgumentException( string.Format( "Invalid depth info in input list. Depth cannot increase more than 1 per row. Index {0} has depth {1} while index {2} has depth {3}", i, depth, i + 1, nextDepth ) );
}
for( int i = 1; i < list.Count; ++i )
if( list[ i ].depth < 0 )
throw new ArgumentException( "Invalid depth value for item at index " + i + ". Only the first item (the root) should have depth below 0." );
if( list.Count > 1 && list[ 1 ].depth != 0 )
throw new ArgumentException( "Input list item at index 1 is assumed to have a depth of 0", "list" );
}
// For updating depth values below any given element e.g after reparenting elements
public static void UpdateDepthValues<T>( T root ) where T : MemoTreeElement {
if( root == null )
throw new ArgumentNullException( "root", "The root is null" );
if( !root.hasChildren )
return;
Stack<MemoTreeElement> stack = new Stack<MemoTreeElement>();
stack.Push( root );
while( stack.Count > 0 ) {
MemoTreeElement current = stack.Pop();
if( current.children != null ) {
foreach( var child in current.children ) {
child.depth = current.depth + 1;
stack.Push( child );
}
}
}
}
// Returns true if there is an ancestor of child in the elements list
static bool IsChildOf<T>( T child, IList<T> elements ) where T : MemoTreeElement {
while( child != null ) {
child = ( T )child.parent;
if( elements.Contains( child ) )
return true;
}
return false;
}
public static IList<T> FindCommonAncestorsWithinList<T>( IList<T> elements ) where T : MemoTreeElement {
if( elements.Count == 1 )
return new List<T>( elements );
List<T> result = new List<T>( elements );
result.RemoveAll( g => IsChildOf( g, elements ) );
return result;
}
}
} | 43.013245 | 230 | 0.496998 | [
"MIT"
] | 654306663/UnityExtensions | Extensions/Memo/Editor/Scripts/TreeView/MemoTreeElementUtility.cs | 6,495 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using StardewValley;
namespace FarmHouseRedone.Pathing
{
public class Node
{
public Vector2 position;
public bool traversible;
public Node parent;
public float weightCost;
public int gCost;
public int hCost;
public int fCost
{
get
{
return gCost + hCost;
}
}
public int x
{
get
{
return (int)position.X;
}
}
public int y
{
get
{
return (int)position.Y;
}
}
public Node(Vector2 position, bool traversible)
{
this.position = position;
this.traversible = traversible;
}
}
}
| 18.634615 | 55 | 0.488132 | [
"MIT"
] | mjSurber/FarmHouse | FarmHouseRedone/Pathing/Node.cs | 971 | C# |
using ThornParser.Controllers;
using ThornParser.Parser;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
namespace ThornParser.Models.ParseModels
{
public class EnemyCastStartMechanic : Mechanic
{
public EnemyCastStartMechanic(long skillId, string inGameName, MechanicPlotlySetting plotlySetting, string shortName, int internalCoolDown, List<MechanicChecker> conditions, TriggerRule rule) : this(skillId, inGameName, plotlySetting, shortName, shortName, shortName, internalCoolDown, conditions, rule)
{
}
public EnemyCastStartMechanic(long skillId, string inGameName, MechanicPlotlySetting plotlySetting, string shortName, string description, string fullName, int internalCoolDown, List<MechanicChecker> conditions, TriggerRule rule) : base(skillId, inGameName, plotlySetting, shortName, description, fullName, internalCoolDown, conditions, rule)
{
IsEnemyMechanic = true;
}
public EnemyCastStartMechanic(long skillId, string inGameName, MechanicPlotlySetting plotlySetting, string shortName, int internalCoolDown) : this(skillId, inGameName, plotlySetting, shortName, shortName, shortName, internalCoolDown)
{
}
public EnemyCastStartMechanic(long skillId, string inGameName, MechanicPlotlySetting plotlySetting, string shortName, string description, string fullName, int internalCoolDown) : base(skillId, inGameName, plotlySetting, shortName, description, fullName, internalCoolDown)
{
IsEnemyMechanic = true;
}
public override void CheckMechanic(ParsedLog log, Dictionary<ushort, DummyActor> regroupedMobs)
{
MechanicData mechData = log.MechanicData;
CombatData combatData = log.CombatData;
HashSet<ushort> playersIds = log.PlayerIDs;
foreach (CombatItem c in log.CombatData.GetCastDataById(SkillId))
{
DummyActor amp = null;
if (c.IsActivation.StartCasting() && Keep(c, log))
{
Target target = log.FightData.Logic.Targets.Find(x => x.InstID == c.SrcInstid && x.FirstAware <= c.Time && x.LastAware >= c.Time);
if (target != null)
{
amp = target;
}
else
{
AgentItem a = log.AgentData.GetAgent(c.SrcAgent, c.Time);
if (playersIds.Contains(a.InstID))
{
continue;
}
else if (a.MasterAgent != 0)
{
AgentItem m = log.AgentData.GetAgent(a.MasterAgent, c.Time);
if (playersIds.Contains(m.InstID))
{
continue;
}
}
if (!regroupedMobs.TryGetValue(a.ID, out amp))
{
amp = new DummyActor(a);
regroupedMobs.Add(a.ID, amp);
}
}
}
if (amp != null)
{
mechData[this].Add(new MechanicLog(log.FightData.ToFightSpace(c.Time), this, amp));
}
}
}
}
} | 45.671053 | 349 | 0.562662 | [
"MIT"
] | Lego6245/GW2-Elite-Insights-Parser | ThornParser/Models/ParseModels/Mechanics/EnemyCastStartMechanic.cs | 3,473 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("QiNiuTest")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("QiNiuTest")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("aa3b9439-3f86-40e6-827e-69bba3945a4d")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 25.378378 | 56 | 0.71246 | [
"Apache-2.0"
] | lyfing22/StoreMini | QiNiuTest/Properties/AssemblyInfo.cs | 1,290 | 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 resource-groups-2017-11-27.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ResourceGroups.Model
{
/// <summary>
/// The unique identifiers for a resource group.
/// </summary>
public partial class GroupIdentifier
{
private string _groupArn;
private string _groupName;
/// <summary>
/// Gets and sets the property GroupArn.
/// <para>
/// The ARN of the resource group.
/// </para>
/// </summary>
[AWSProperty(Min=12, Max=1600)]
public string GroupArn
{
get { return this._groupArn; }
set { this._groupArn = value; }
}
// Check to see if GroupArn property is set
internal bool IsSetGroupArn()
{
return this._groupArn != null;
}
/// <summary>
/// Gets and sets the property GroupName.
/// <para>
/// The name of the resource group.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=128)]
public string GroupName
{
get { return this._groupName; }
set { this._groupName = value; }
}
// Check to see if GroupName property is set
internal bool IsSetGroupName()
{
return this._groupName != null;
}
}
} | 28.794872 | 114 | 0.586821 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/ResourceGroups/Generated/Model/GroupIdentifier.cs | 2,246 | C# |
using Microsoft.Extensions.Logging;
using Serilog.Configuration;
using Serilog.Formatting;
using Serilog.Formatting.Compact;
using Serilog.Formatting.Display;
using Serilog.Microsoft.Logging.Core;
using System;
using System.Collections.Generic;
namespace Serilog.Microsoft.Logging.File
{
internal static class Utility
{
public static Serilog.Core.Logger CreateFileLogger(FileConfiguration config)
{
if (config?.PathFormat == null) throw new ArgumentNullException(nameof(config.PathFormat));
var formatter = config.RenderJson ?
(ITextFormatter)new RenderedCompactJsonFormatter()
: new MessageTemplateTextFormatter(config.Template, null);
var bufferSize = config.AsyncBufferSize.HasValue ? config.AsyncBufferSize.Value : 10000;
var configuration = new LoggerConfiguration()
.MinimumLevel.Is(CoreUtility.GetMinimumLogLevel(config.LogLevel))
.Enrich.FromLogContext();
Action<LoggerSinkConfiguration> configureFile = w => w.File(
formatter,
Environment.ExpandEnvironmentVariables(config.PathFormat),
fileSizeLimitBytes: config.FileSizeLimit,
retainedFileCountLimit: config.FileCountLimit,
shared: config.Shared,
flushToDiskInterval: TimeSpan.FromSeconds(config.FlushInterval),
rollingInterval: config.RollingInterval,
rollOnFileSizeLimit: true,
buffered: config.GroupLogging);
if (config.AsyncBufferSize.HasValue)
{
configuration = configuration
.WriteTo.Async(configureFile,
bufferSize: bufferSize,
blockWhenFull: !config.DropLogsOnBufferLimit);
}
else
{
configureFile(configuration.WriteTo);
}
if (!config.RenderJson)
configuration.Enrich.With<EventNumEnricher>();
if (!config.RenderJson && config.IncludeScopes)
configuration.Enrich.With<ScopeEnricher>();
foreach (var levelOverride in config.LogLevel ?? new Dictionary<string, LogLevel>())
{
configuration.MinimumLevel.Override(levelOverride.Key, CoreUtility.ConvertLogLevel(levelOverride.Value));
}
return configuration.CreateLogger();
}
}
}
| 39.538462 | 121 | 0.610506 | [
"Apache-2.0"
] | igloo15/Serilog.Microsoft.Logger | src/Serilog.Microsoft.Logger.File/Utility.cs | 2,572 | C# |
using Gybs.Extensions;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text.RegularExpressions;
namespace Gybs.Results
{
/// <summary>
/// Represents a dictionary-like structure for the errors which can be converted to result's errors.
/// </summary>
public sealed class ResultErrorsDictionary : IReadOnlyDictionary<string, IReadOnlyCollection<string>>
{
private static readonly Regex ExpressionRegex = new Regex("([a-zA-Z0-9_]+)(?=\\.|$)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private readonly Dictionary<string, List<string>> _errors = new Dictionary<string, List<string>>();
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <param name="key">The key of the value to get.</param>
public IReadOnlyCollection<string> this[string key] => _errors[key];
/// <summary>
/// Gets a collection containing the keys in the dictionary.
/// </summary>
public IEnumerable<string> Keys => _errors.Keys;
/// <summary>
/// Gets a collection containing the values in the dictionary.
/// </summary>
public IEnumerable<IReadOnlyCollection<string>> Values => _errors.Values;
/// <summary>
/// Gets the number of key/value pairs contained in the dictionary.
/// </summary>
public int Count => _errors.Count;
/// <summary>
/// Adds a new error.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="messages">The messages.</param>
/// <returns>The dictionary itself.</returns>
public ResultErrorsDictionary Add(string key, params string[] messages)
{
if (!_errors.TryGetValue(key, out var currentMessages))
{
currentMessages = new List<string>();
_errors.Add(key, currentMessages);
}
currentMessages.AddRange(messages);
return this;
}
/// <summary>
/// Adds a new error with the key generated from the expression (with pattern Type.PropertyA.PropertyB).
/// </summary>
/// <typeparam name="TType">Type used to build the key.</typeparam>
/// <param name="propertyExpression">Expression used to generate the key.</param>
/// <param name="messages">The messages.</param>
/// <returns>The dictionary itself.</returns>
public ResultErrorsDictionary Add<TType>(Expression<Func<TType, object>> propertyExpression, params string[] messages)
{
var memberExpression = propertyExpression.Body as MemberExpression
?? (propertyExpression.Body as UnaryExpression)?.Operand as MemberExpression;
if (memberExpression is null) throw new ArgumentNullException(nameof(propertyExpression));
var keyParts = new[] { typeof(TType).Name }
.Concat(ExpressionRegex
.Matches(memberExpression.ToString())
.OfType<Match>()
.Select(m => m.Value)
.Skip(1)
);
var key = string.Join(".", keyParts);
return Add(key, messages);
}
/// <summary>
/// Converts stored data to a readonly dictionary.
/// </summary>
/// <returns>The dictionary with the errors.</returns>
[Obsolete("Use ResultErrorsDictionary directly.")]
public IReadOnlyDictionary<string, IReadOnlyCollection<string>> ToDictionary()
{
return _errors.ToDictionary(e => e.Key, e => e.Value.CastToReadOnly());
}
/// <summary>
/// Returns whether this dictionary contains a particular key.
/// </summary>
/// <param name="key">The key to locate.</param>
/// <returns>True if dictionary contains the key; otherwise, false.</returns>
public bool ContainsKey(string key) => _errors.ContainsKey(key);
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <param name="key">The key whose value to get.</param>
/// <param name="value">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized.</param>
/// <returns>True if the object contains an element with the specified key; otherwise, false.</returns>
public bool TryGetValue(string key, out IReadOnlyCollection<string> value)
{
if (!_errors.TryGetValue(key, out var innerValue))
{
value = new string[0];
return false;
}
value = innerValue.CastToReadOnly();
return true;
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>An enumerator that can be used to iterate through the collection.</returns>
public IEnumerator<KeyValuePair<string, IReadOnlyCollection<string>>> GetEnumerator() => new Enumerator(_errors);
IEnumerator IEnumerable.GetEnumerator() => new Enumerator(_errors);
private struct Enumerator : IEnumerator<KeyValuePair<string, IReadOnlyCollection<string>>>
{
private readonly IEnumerator<KeyValuePair<string, List<string>>> _enumerator;
private KeyValuePair<string, IReadOnlyCollection<string>> _current;
public KeyValuePair<string, IReadOnlyCollection<string>> Current => _current;
object IEnumerator.Current => _current;
public Enumerator(Dictionary<string, List<string>> dictionary)
{
_enumerator = dictionary.GetEnumerator();
}
public void Dispose() => _enumerator.Dispose();
public bool MoveNext()
{
if (!_enumerator.MoveNext())
{
return false;
}
var current = _enumerator.Current;
_current = new KeyValuePair<string, IReadOnlyCollection<string>>(current.Key, current.Value);
return true;
}
public void Reset()
{
_current = default;
_enumerator.Reset();
}
}
}
}
| 40.714286 | 237 | 0.598017 | [
"MIT"
] | wk0w/gybs | src/Gybs/Results/ResultErrorsDictionary.cs | 6,555 | C# |
namespace Orchard.Tasks.Scheduling {
public interface IScheduledTaskHandler : IDependency {
void Process(ScheduledTaskContext context);
}
} | 31.8 | 59 | 0.72956 | [
"MIT"
] | AccentureRapid/OrchardCollaboration | src/Orchard/Tasks/Scheduling/IScheduledTaskHandler.cs | 159 | C# |
namespace Nzy3d.Plot3D.Primitives.Axes.Layout.Renderers
{
public interface ITickRenderer
{
string Format(double value);
}
}
| 16.125 | 55 | 0.775194 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | BobLd/Nzy3d | Nzy3d/Plot3D/Primitives/Axes/Layout/Renderers/ITickRenderer.cs | 129 | C# |
namespace PlatformSpecifics;
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.ConfigureFonts(fonts =>
{
fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
});
return builder.Build();
}
}
| 17.444444 | 61 | 0.694268 | [
"MIT"
] | davidbritch/dotnet-maui-samples | PlatformIntegration/PlatformSpecifics/PlatformSpecifics/MauiProgram.cs | 316 | C# |
using NUnit.Framework;
using System.Diagnostics.CodeAnalysis;
[assembly: SuppressMessage("Microsoft.Design", "CA1034", Justification = "We don't care about Java-style classes in tests")]
[assembly: SuppressMessage("Microsoft.Design", "CA1031", Justification = "We don't care about Java-style classes in tests")]
[assembly: SuppressMessage("Microsoft.Design", "CA1822", Justification = "We don't care about Java-style classes in tests")]
| 62.714286 | 124 | 0.769932 | [
"Apache-2.0"
] | NightOwl888/J2N | tests/TestAssemblyInfo.cs | 441 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
public class TouchController : MonoBehaviour
{
RaycastHit hit;
//[Header("Organel Manager")]
public OrganelManager organelManager;
//[Header("Bilgi Texti")]
public Text InfoText;
public GameObject YaziPanel;
//[Header("Outline Shader")]
public Shader outline;
public AudioSource blobSoundEffect;
public int OrganelBilgiIndex = 0;
public int OrganelListLength = 0;
public string SelectedOrganelTag = "Çekirdek";
public bool isActive = false;
Organel FindedOrganel;
public GameObject İleriButton;
public GameObject GeriButton;
//Swipe Model Turn Variables
public GameObject HucreModel;
private Touch touch;
private Vector2 touchPosition;
private Quaternion rotationY;
[Range(0f,100f)] public float rotateSpeedModifier = 0.1f;
void FixedUpdate()
{
if (Input.GetMouseButtonDown(0))
{
Touch();
}
SwipeModel();
}
public void SwipeModel()
{
if(Input.touchCount > 0)
{
touch = Input.GetTouch(0);
if(touch.phase == TouchPhase.Moved)
{
rotationY = Quaternion.Euler(0f,-touch.deltaPosition.x*rotateSpeedModifier,0f);
HucreModel.transform.rotation = rotationY * HucreModel.transform.rotation;
}
}
}
//Dokunmayı kontrol eden fonksiyon
void Touch()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//Debug.Log("Okçu Aktiflik: " + isArcherActive);
if (Physics.Raycast(ray, out hit) && !isActive)
{
Debug.LogError("Touch : " + hit.collider.tag);
GetOrganelInfo(InfoText, hit.collider.tag);
}
}
//Organel bilgisini Text'e yazdırır.
void GetOrganelInfo(Text InfoText, string OrganelTag)
{
SelectedOrganelTag = OrganelTag;
InfoText.text = SearchOrganelForInfo(OrganelTag,0);
}
//Organelde ara
public string SearchOrganelForInfo(string organelTag, int infoIndex)
{
string wasFoundInfo = "";
foreach (var item in organelManager.Organeller)
{
if(item.Etiket == organelTag)
{
FindedOrganel = item;
//YaziPanel.SetActive(true);
Animator animator = YaziPanel.GetComponent<Animator>();
if (animator != null)
{
animator.SetBool("isOpen",true);
blobSoundEffect.Play();
if(item.OrganelBilgi.Count > 1)
{
İleriButton.SetActive(true);
GeriButton.SetActive(false);
}
if(item.OrganelBilgi.Count == 1)
{
İleriButton.SetActive(false);
GeriButton.SetActive(false);
}
isActive = true;
}
wasFoundInfo = item.OrganelBilgi[infoIndex];
//Burada İndeksler Arasında Gezerek Bütün Bilgileri Göstereceğim.
//if(OrganelBilgiIndex >=0 && OrganelBilgiIndex < OrganelListLength - 1)
//{
// wasFoundInfo = item.OrganelBilgi[infoIndex];
//}
OrganelListLength = item.OrganelBilgi.Count;
item.SetOutline(outline); //Aranan organel bulunduğunda outline shader uygular.
break;
}
else
{
if (item.isOutline)
{
item.RemoveOutline();
}
}
}
return wasFoundInfo;
}
//Bulunan Organeli Dondurur
public Organel GetFindedOrganel()
{
if(FindedOrganel != null)
{
return FindedOrganel;
}
return null;
}
}
| 25.836478 | 95 | 0.539922 | [
"MIT"
] | 00mjk/HucreAR | Assets/Scripts/TouchController.cs | 4,125 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101
{
using static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Extensions;
/// <summary>Azure capacity definition.</summary>
public partial class AzureCapacity :
Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.IAzureCapacity,
Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.IAzureCapacityInternal
{
/// <summary>Backing field for <see cref="Default" /> property.</summary>
private int _default;
/// <summary>The default capacity that would be used.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Kusto.Origin(Microsoft.Azure.PowerShell.Cmdlets.Kusto.PropertyOrigin.Owned)]
public int Default { get => this._default; set => this._default = value; }
/// <summary>Backing field for <see cref="Maximum" /> property.</summary>
private int _maximum;
/// <summary>Maximum allowed capacity.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Kusto.Origin(Microsoft.Azure.PowerShell.Cmdlets.Kusto.PropertyOrigin.Owned)]
public int Maximum { get => this._maximum; set => this._maximum = value; }
/// <summary>Backing field for <see cref="Minimum" /> property.</summary>
private int _minimum;
/// <summary>Minimum allowed capacity.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Kusto.Origin(Microsoft.Azure.PowerShell.Cmdlets.Kusto.PropertyOrigin.Owned)]
public int Minimum { get => this._minimum; set => this._minimum = value; }
/// <summary>Backing field for <see cref="ScaleType" /> property.</summary>
private Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.AzureScaleType _scaleType;
/// <summary>Scale type.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Kusto.Origin(Microsoft.Azure.PowerShell.Cmdlets.Kusto.PropertyOrigin.Owned)]
public Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.AzureScaleType ScaleType { get => this._scaleType; set => this._scaleType = value; }
/// <summary>Creates an new <see cref="AzureCapacity" /> instance.</summary>
public AzureCapacity()
{
}
}
/// Azure capacity definition.
public partial interface IAzureCapacity :
Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IJsonSerializable
{
/// <summary>The default capacity that would be used.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Info(
Required = true,
ReadOnly = false,
Description = @"The default capacity that would be used.",
SerializedName = @"default",
PossibleTypes = new [] { typeof(int) })]
int Default { get; set; }
/// <summary>Maximum allowed capacity.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Info(
Required = true,
ReadOnly = false,
Description = @"Maximum allowed capacity.",
SerializedName = @"maximum",
PossibleTypes = new [] { typeof(int) })]
int Maximum { get; set; }
/// <summary>Minimum allowed capacity.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Info(
Required = true,
ReadOnly = false,
Description = @"Minimum allowed capacity.",
SerializedName = @"minimum",
PossibleTypes = new [] { typeof(int) })]
int Minimum { get; set; }
/// <summary>Scale type.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Info(
Required = true,
ReadOnly = false,
Description = @"Scale type.",
SerializedName = @"scaleType",
PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.AzureScaleType) })]
Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.AzureScaleType ScaleType { get; set; }
}
/// Azure capacity definition.
internal partial interface IAzureCapacityInternal
{
/// <summary>The default capacity that would be used.</summary>
int Default { get; set; }
/// <summary>Maximum allowed capacity.</summary>
int Maximum { get; set; }
/// <summary>Minimum allowed capacity.</summary>
int Minimum { get; set; }
/// <summary>Scale type.</summary>
Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.AzureScaleType ScaleType { get; set; }
}
} | 46.329897 | 149 | 0.645527 | [
"MIT"
] | Agazoth/azure-powershell | src/Kusto/generated/api/Models/Api202101/AzureCapacity.cs | 4,398 | 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.Diagnostics;
using System.Text.RegularExpressions;
using System.Threading;
using Microsoft.AspNetCore.NodeServices.Util;
using Microsoft.Extensions.Logging;
// This is under the NodeServices namespace because post 2.1 it will be moved to that package
namespace Microsoft.AspNetCore.NodeServices.Npm
{
/// <summary>
/// Executes the <c>script</c> entries defined in a <c>package.json</c> file,
/// capturing any output written to stdio.
/// </summary>
internal class NodeScriptRunner : IDisposable
{
private Process? _npmProcess;
public EventedStreamReader StdOut { get; }
public EventedStreamReader StdErr { get; }
private static readonly Regex AnsiColorRegex = new Regex("\x001b\\[[0-9;]*m", RegexOptions.None, TimeSpan.FromSeconds(1));
public NodeScriptRunner(string workingDirectory, string scriptName, string? arguments, IDictionary<string, string>? envVars, string pkgManagerCommand, DiagnosticSource diagnosticSource, CancellationToken applicationStoppingToken)
{
if (string.IsNullOrEmpty(workingDirectory))
{
throw new ArgumentException("Cannot be null or empty.", nameof(workingDirectory));
}
if (string.IsNullOrEmpty(scriptName))
{
throw new ArgumentException("Cannot be null or empty.", nameof(scriptName));
}
if (string.IsNullOrEmpty(pkgManagerCommand))
{
throw new ArgumentException("Cannot be null or empty.", nameof(pkgManagerCommand));
}
var exeToRun = pkgManagerCommand;
var completeArguments = $"run {scriptName} -- {arguments ?? string.Empty}";
if (OperatingSystem.IsWindows())
{
// On Windows, the node executable is a .cmd file, so it can't be executed
// directly (except with UseShellExecute=true, but that's no good, because
// it prevents capturing stdio). So we need to invoke it via "cmd /c".
exeToRun = "cmd";
completeArguments = $"/c {pkgManagerCommand} {completeArguments}";
}
var processStartInfo = new ProcessStartInfo(exeToRun)
{
Arguments = completeArguments,
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
WorkingDirectory = workingDirectory
};
if (envVars != null)
{
foreach (var keyValuePair in envVars)
{
processStartInfo.Environment[keyValuePair.Key] = keyValuePair.Value;
}
}
_npmProcess = LaunchNodeProcess(processStartInfo, pkgManagerCommand);
StdOut = new EventedStreamReader(_npmProcess.StandardOutput);
StdErr = new EventedStreamReader(_npmProcess.StandardError);
applicationStoppingToken.Register(((IDisposable)this).Dispose);
if (diagnosticSource.IsEnabled("Microsoft.AspNetCore.NodeServices.Npm.NpmStarted"))
{
diagnosticSource.Write(
"Microsoft.AspNetCore.NodeServices.Npm.NpmStarted",
new
{
processStartInfo = processStartInfo,
process = _npmProcess
});
}
}
public void AttachToLogger(ILogger logger)
{
// When the node task emits complete lines, pass them through to the real logger
StdOut.OnReceivedLine += line =>
{
if (!string.IsNullOrWhiteSpace(line))
{
// Node tasks commonly emit ANSI colors, but it wouldn't make sense to forward
// those to loggers (because a logger isn't necessarily any kind of terminal)
logger.LogInformation(StripAnsiColors(line));
}
};
StdErr.OnReceivedLine += line =>
{
if (!string.IsNullOrWhiteSpace(line))
{
logger.LogError(StripAnsiColors(line));
}
};
// But when it emits incomplete lines, assume this is progress information and
// hence just pass it through to StdOut regardless of logger config.
StdErr.OnReceivedChunk += chunk =>
{
Debug.Assert(chunk.Array != null);
var containsNewline = Array.IndexOf(
chunk.Array, '\n', chunk.Offset, chunk.Count) >= 0;
if (!containsNewline)
{
Console.Write(chunk.Array, chunk.Offset, chunk.Count);
}
};
}
private static string StripAnsiColors(string line)
=> AnsiColorRegex.Replace(line, string.Empty);
private static Process LaunchNodeProcess(ProcessStartInfo startInfo, string commandName)
{
try
{
var process = Process.Start(startInfo)!;
// See equivalent comment in OutOfProcessNodeInstance.cs for why
process.EnableRaisingEvents = true;
return process;
}
catch (Exception ex)
{
var message = $"Failed to start '{commandName}'. To resolve this:.\n\n"
+ $"[1] Ensure that '{commandName}' is installed and can be found in one of the PATH directories.\n"
+ $" Current PATH enviroment variable is: { Environment.GetEnvironmentVariable("PATH") }\n"
+ " Make sure the executable is in one of those directories, or update your PATH.\n\n"
+ "[2] See the InnerException for further details of the cause.";
throw new InvalidOperationException(message, ex);
}
}
void IDisposable.Dispose()
{
if (_npmProcess != null && !_npmProcess.HasExited)
{
_npmProcess.Kill(entireProcessTree: true);
_npmProcess = null;
}
}
}
}
| 40.62963 | 237 | 0.569736 | [
"Apache-2.0"
] | Asifshikder/aspnetcore | src/Middleware/Spa/SpaServices.Extensions/src/Npm/NodeScriptRunner.cs | 6,582 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using sfShareLib;
using System.ComponentModel.DataAnnotations;
using System.Web.Helpers;
using CDSShareLib.Helper;
namespace sfAPIService.Models
{
public class AccumulateUsagLog
{
public class Detail
{
public int CompanyId { get; set; }
public string CompanyName { get; set; }
public int? FactoryQty { get; set; }
public int? EquipmentQty { get; set; }
public long DeviceMessage { get; set; }
public DateTime UpdatedAt { get; set; }
}
public List<Detail> getAll(int days, string order)
{
DBHelper._AccumulateUsageLog dbhelp = new DBHelper._AccumulateUsageLog();
var usageLogList = dbhelp.GetAll(days, order);
if (usageLogList == null)
throw new CDSException(12101);
return dbhelp.GetAll(days, order).Select(s => new Detail()
{
CompanyId = s.CompanyId,
CompanyName = s.Company == null ? "" : s.Company.Name,
FactoryQty = s.FactoryQty,
EquipmentQty = s.EquipmentQty,
UpdatedAt = s.UpdatedAt
}).ToList<Detail>();
}
public List<Detail> getAllByCompanyId(int companyId, int days, string order)
{
DBHelper._AccumulateUsageLog dbhelp = new DBHelper._AccumulateUsageLog();
var usageLogList = dbhelp.GetAllByCompanyId(companyId, days, order);
if (usageLogList == null)
throw new CDSException(12101);
return usageLogList.Select(s => new Detail()
{
CompanyId = s.CompanyId,
CompanyName = s.Company == null ? "" : s.Company.Name,
FactoryQty = s.FactoryQty,
EquipmentQty = s.EquipmentQty,
UpdatedAt = s.UpdatedAt
}).ToList<Detail>();
}
public Detail getLastByCompanyId(int companyId)
{
DBHelper._AccumulateUsageLog dbhelp = new DBHelper._AccumulateUsageLog();
AccumulateUsageLog usageLog = dbhelp.GetLastByCommpanyId(companyId);
if (usageLog == null)
throw new CDSException(12102);
return new Detail()
{
CompanyId = usageLog.CompanyId,
CompanyName = usageLog.Company == null ? "" : usageLog.Company.Name,
FactoryQty = usageLog.FactoryQty,
EquipmentQty = usageLog.EquipmentQty,
UpdatedAt = usageLog.UpdatedAt
};
}
}
} | 35.434211 | 85 | 0.567397 | [
"MIT"
] | KevinKao809/CDS20 | APIService/Models/AccumulateUsagLog.cs | 2,695 | C# |
using System.Collections.Generic;
using System.Management;
namespace WindowsMonitor.Performance.Raw.Network
{
/// <summary>
/// </summary>
public sealed class Icmp
{
public string Caption { get; private set; }
public string Description { get; private set; }
public ulong FrequencyObject { get; private set; }
public ulong FrequencyPerfTime { get; private set; }
public ulong FrequencySys100Ns { get; private set; }
public uint MessagesOutboundErrors { get; private set; }
public uint MessagesPersec { get; private set; }
public uint MessagesReceivedErrors { get; private set; }
public uint MessagesReceivedPersec { get; private set; }
public uint MessagesSentPersec { get; private set; }
public string Name { get; private set; }
public uint ReceivedAddressMask { get; private set; }
public uint ReceivedAddressMaskReply { get; private set; }
public uint ReceivedDestUnreachable { get; private set; }
public uint ReceivedEchoPersec { get; private set; }
public uint ReceivedEchoReplyPersec { get; private set; }
public uint ReceivedParameterProblem { get; private set; }
public uint ReceivedRedirectPersec { get; private set; }
public uint ReceivedSourceQuench { get; private set; }
public uint ReceivedTimeExceeded { get; private set; }
public uint ReceivedTimestampPersec { get; private set; }
public uint ReceivedTimestampReplyPersec { get; private set; }
public uint SentAddressMask { get; private set; }
public uint SentAddressMaskReply { get; private set; }
public uint SentDestinationUnreachable { get; private set; }
public uint SentEchoPersec { get; private set; }
public uint SentEchoReplyPersec { get; private set; }
public uint SentParameterProblem { get; private set; }
public uint SentRedirectPersec { get; private set; }
public uint SentSourceQuench { get; private set; }
public uint SentTimeExceeded { get; private set; }
public uint SentTimestampPersec { get; private set; }
public uint SentTimestampReplyPersec { get; private set; }
public ulong TimestampObject { get; private set; }
public ulong TimestampPerfTime { get; private set; }
public ulong TimestampSys100Ns { get; private set; }
public static IEnumerable<Icmp> Retrieve(string remote, string username, string password)
{
var options = new ConnectionOptions
{
Impersonation = ImpersonationLevel.Impersonate,
Username = username,
Password = password
};
var managementScope = new ManagementScope(new ManagementPath($"\\\\{remote}\\root\\cimv2"), options);
managementScope.Connect();
return Retrieve(managementScope);
}
public static IEnumerable<Icmp> Retrieve()
{
var managementScope = new ManagementScope(new ManagementPath("root\\cimv2"));
return Retrieve(managementScope);
}
public static IEnumerable<Icmp> Retrieve(ManagementScope managementScope)
{
var objectQuery = new ObjectQuery("SELECT * FROM Win32_PerfRawData_Tcpip_ICMP");
var objectSearcher = new ManagementObjectSearcher(managementScope, objectQuery);
var objectCollection = objectSearcher.Get();
foreach (ManagementObject managementObject in objectCollection)
yield return new Icmp
{
Caption = (string) (managementObject.Properties["Caption"]?.Value),
Description = (string) (managementObject.Properties["Description"]?.Value),
FrequencyObject = (ulong) (managementObject.Properties["Frequency_Object"]?.Value ?? default(ulong)),
FrequencyPerfTime = (ulong) (managementObject.Properties["Frequency_PerfTime"]?.Value ?? default(ulong)),
FrequencySys100Ns = (ulong) (managementObject.Properties["Frequency_Sys100NS"]?.Value ?? default(ulong)),
MessagesOutboundErrors = (uint) (managementObject.Properties["MessagesOutboundErrors"]?.Value ?? default(uint)),
MessagesPersec = (uint) (managementObject.Properties["MessagesPersec"]?.Value ?? default(uint)),
MessagesReceivedErrors = (uint) (managementObject.Properties["MessagesReceivedErrors"]?.Value ?? default(uint)),
MessagesReceivedPersec = (uint) (managementObject.Properties["MessagesReceivedPersec"]?.Value ?? default(uint)),
MessagesSentPersec = (uint) (managementObject.Properties["MessagesSentPersec"]?.Value ?? default(uint)),
Name = (string) (managementObject.Properties["Name"]?.Value),
ReceivedAddressMask = (uint) (managementObject.Properties["ReceivedAddressMask"]?.Value ?? default(uint)),
ReceivedAddressMaskReply = (uint) (managementObject.Properties["ReceivedAddressMaskReply"]?.Value ?? default(uint)),
ReceivedDestUnreachable = (uint) (managementObject.Properties["ReceivedDestUnreachable"]?.Value ?? default(uint)),
ReceivedEchoPersec = (uint) (managementObject.Properties["ReceivedEchoPersec"]?.Value ?? default(uint)),
ReceivedEchoReplyPersec = (uint) (managementObject.Properties["ReceivedEchoReplyPersec"]?.Value ?? default(uint)),
ReceivedParameterProblem = (uint) (managementObject.Properties["ReceivedParameterProblem"]?.Value ?? default(uint)),
ReceivedRedirectPersec = (uint) (managementObject.Properties["ReceivedRedirectPersec"]?.Value ?? default(uint)),
ReceivedSourceQuench = (uint) (managementObject.Properties["ReceivedSourceQuench"]?.Value ?? default(uint)),
ReceivedTimeExceeded = (uint) (managementObject.Properties["ReceivedTimeExceeded"]?.Value ?? default(uint)),
ReceivedTimestampPersec = (uint) (managementObject.Properties["ReceivedTimestampPersec"]?.Value ?? default(uint)),
ReceivedTimestampReplyPersec = (uint) (managementObject.Properties["ReceivedTimestampReplyPersec"]?.Value ?? default(uint)),
SentAddressMask = (uint) (managementObject.Properties["SentAddressMask"]?.Value ?? default(uint)),
SentAddressMaskReply = (uint) (managementObject.Properties["SentAddressMaskReply"]?.Value ?? default(uint)),
SentDestinationUnreachable = (uint) (managementObject.Properties["SentDestinationUnreachable"]?.Value ?? default(uint)),
SentEchoPersec = (uint) (managementObject.Properties["SentEchoPersec"]?.Value ?? default(uint)),
SentEchoReplyPersec = (uint) (managementObject.Properties["SentEchoReplyPersec"]?.Value ?? default(uint)),
SentParameterProblem = (uint) (managementObject.Properties["SentParameterProblem"]?.Value ?? default(uint)),
SentRedirectPersec = (uint) (managementObject.Properties["SentRedirectPersec"]?.Value ?? default(uint)),
SentSourceQuench = (uint) (managementObject.Properties["SentSourceQuench"]?.Value ?? default(uint)),
SentTimeExceeded = (uint) (managementObject.Properties["SentTimeExceeded"]?.Value ?? default(uint)),
SentTimestampPersec = (uint) (managementObject.Properties["SentTimestampPersec"]?.Value ?? default(uint)),
SentTimestampReplyPersec = (uint) (managementObject.Properties["SentTimestampReplyPersec"]?.Value ?? default(uint)),
TimestampObject = (ulong) (managementObject.Properties["Timestamp_Object"]?.Value ?? default(ulong)),
TimestampPerfTime = (ulong) (managementObject.Properties["Timestamp_PerfTime"]?.Value ?? default(ulong)),
TimestampSys100Ns = (ulong) (managementObject.Properties["Timestamp_Sys100NS"]?.Value ?? default(ulong))
};
}
}
} | 63.474138 | 127 | 0.728779 | [
"MIT"
] | Biztactix/WindowsMonitor | WindowsMonitor.Standard/Performance/Raw/Network/Icmp.cs | 7,363 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RHSCommonSense : RHStatement
{
public override string StatementName { get { return "Common Reasoning"; } }
public override float Time { get { return 4.0f; } }
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
| 20.619048 | 79 | 0.642032 | [
"MIT"
] | sdasd30/TSSG | Assets/Scripts/Rhetoric/Statements/RHSCommonSense.cs | 435 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/urlmon.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop
{
public unsafe partial struct PROTOCOLDATA
{
[NativeTypeName("DWORD")]
public uint grfFlags;
[NativeTypeName("DWORD")]
public uint dwState;
[NativeTypeName("LPVOID")]
public void* pData;
[NativeTypeName("ULONG")]
public uint cbData;
}
}
| 27.304348 | 145 | 0.671975 | [
"MIT"
] | Ethereal77/terrafx.interop.windows | sources/Interop/Windows/um/urlmon/PROTOCOLDATA.cs | 630 | C# |
using Cysharp.Threading.Tasks;
using Cysharp.Threading.Tasks.Linq;
using Cysharp.Threading.Tasks.Triggers;
using Millennium.InGame.Effect;
using Millennium.Sound;
using System;
using System.Threading;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.Serialization;
namespace Millennium.InGame.Entity.Enemy
{
public abstract class EnemyBase : EntityLiving
{
[SerializeField]
private int m_InitialHealth = 1000;
public bool CanMove => Health > 0;
private void Start()
{
Health = HealthMax = m_InitialHealth;
DamageWhenEnter(this.GetCancellationTokenOnDestroy());
}
public override void DealDamage(DamageSource damage)
{
Health -= damage.Damage;
var player = damage.Attacker as Player.Player;
if (player != null)
{
player.AddScore(damage.Damage);
}
if (Health / Math.Max(HealthMax, 0.0) <= 0.1)
{
SoundManager.I.PlaySe(SeType.PlayerBulletHitCritical).Forget();
}
else
{
SoundManager.I.PlaySe(SeType.PlayerBulletHit).Forget();
}
if (Health <= 0)
{
if (player != null)
player.AddScore(HealthMax);
EffectManager.I.Play(EffectType.Explosion, transform.position);
SoundManager.I.PlaySe(SeType.Explosion).Forget();
Destroy(gameObject);
}
}
protected UniTask DamageWhenEnter(CancellationToken token)
{
return this.GetAsyncTriggerEnter2DTrigger()
.ForEachAsync(collision =>
{
if (collision.gameObject.GetComponent<Entity>() is EntityLiving entity)
{
entity.DealDamage(new DamageSource(this, 100));
}
}, token);
}
}
}
| 27.657534 | 91 | 0.556711 | [
"MIT"
] | andanteyk/Millennium | Assets/Millennium/Scripts/InGame/Entity/Enemy/EnemyBase.cs | 2,019 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("HomeworkDOTNET1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HomeworkDOTNET1")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("339c65f3-1322-4867-895d-47c1f346eb64")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 26.513514 | 57 | 0.692151 | [
"MIT"
] | ZYChimne/HomeworkDOTNET | HomeworkDOTNET1/HomeworkDOTNET1/Properties/AssemblyInfo.cs | 1,322 | C# |
namespace CodeHollow.FeedReader.Feeds
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
/// <summary>
/// Rss Feed according to Rss 0.91 specification:
/// http://www.rssboard.org/rss-0-9-1-netscape
/// </summary>
public class Rss091Feed : BaseFeed
{
/// <summary>
/// The required field "description"
/// </summary>
public string Description { get; set; }
/// <summary>
/// The required field "language"
/// /// </summary>
public string Language { get; set; }
/// <summary>
/// The "copyright" field
/// </summary>
public string Copyright { get; set; }
/// <summary>
/// The "docs" field
/// </summary>
public string Docs { get; set; }
/// <summary>
/// The "image" element
/// </summary>
public FeedImage Image { get; set; }
/// <summary>
/// The "lastBuildDate" element
/// </summary>
public string LastBuildDateString { get; set; }
/// <summary>
/// The "lastBuildDate" as DateTime. Null if parsing failed or lastBuildDate is empty.
/// </summary>
public DateTime? LastBuildDate { get; set; }
/// <summary>
/// The "managingEditor" field
/// </summary>
public string ManagingEditor { get; set; }
/// <summary>
/// The "pubDate" field
/// </summary>
public string PublishingDateString { get; set; }
/// <summary>
/// The "pubDate" field as DateTime. Null if parsing failed or pubDate is empty.
/// </summary>
public DateTime? PublishingDate { get; set; }
/// <summary>
/// The "rating" field
/// </summary>
public string Rating { get; set; }
/// <summary>
/// All "day" elements in "skipDays"
/// </summary>
public ICollection<string> SkipDays { get; set; }
/// <summary>
/// All "hour" elements in "skipHours"
/// </summary>
public ICollection<string> SkipHours { get; set; }
/// <summary>
/// The "textInput" element
/// </summary>
public FeedTextInput TextInput { get; set; }
/// <summary>
/// The "webMaster" element
/// </summary>
public string WebMaster { get; set; }
/// <summary>
/// All elements that start with "sy:"
/// </summary>
public Syndication Sy { get; set; }
/// <summary>
/// default constructor (for serialization)
/// </summary>
public Rss091Feed()
: base()
{
this.SkipDays = new List<string>();
this.SkipHours = new List<string>();
}
/// <summary>
/// Reads a rss 0.91 feed based on the xml given in channel
/// </summary>
/// <param name="feedXml">the whole feed as xml</param>
/// <param name="channel">the channel xml element</param>
public Rss091Feed(string feedXml, XElement channel)
: base(feedXml, channel)
{
this.Description = channel.GetValue("description");
this.Language = channel.GetValue("language");
this.Image = new Rss091FeedImage(channel.GetElement("image"));
this.Copyright = channel.GetValue("copyright");
this.ManagingEditor = channel.GetValue("managingEditor");
this.WebMaster = channel.GetValue("webMaster");
this.Rating = channel.GetValue("rating");
this.PublishingDateString = channel.GetValue("pubDate");
this.PublishingDate = Helpers.TryParseDateTime(this.PublishingDateString);
this.LastBuildDateString = channel.GetValue("lastBuildDate");
this.LastBuildDate = Helpers.TryParseDateTime(this.LastBuildDateString);
this.Docs = channel.GetValue("docs");
this.TextInput = new FeedTextInput(channel.GetElement("textinput"));
this.Sy = new Syndication(channel);
var skipHours = channel.GetElement("skipHours");
if (skipHours != null)
this.SkipHours = skipHours.GetElements("hour")?.Select(x => x.GetValue()).ToList();
var skipDays = channel.GetElement("skipDays");
if (skipDays != null)
this.SkipDays = skipDays.GetElements("day")?.Select(x => x.GetValue()).ToList();
var items = channel.GetElements("item");
AddItems(items);
}
/// <summary>
/// Creates the base <see cref="Feed"/> element out of this feed.
/// </summary>
/// <returns>feed</returns>
public override Feed ToFeed()
{
Feed f = new Feed(this);
f.Copyright = this.Copyright;
f.Description = this.Description;
f.ImageUrl = this.Image?.Url;
f.Language = this.Language;
f.LastUpdatedDate = this.LastBuildDate;
f.LastUpdatedDateString = this.LastBuildDateString;
f.Type = FeedType.Rss_0_91;
return f;
}
internal virtual void AddItems(IEnumerable<XElement> items)
{
foreach (var item in items)
{
this.Items.Add(new Rss091FeedItem(item));
}
}
}
}
| 31.520231 | 99 | 0.54117 | [
"MIT"
] | nieltg/CodeHollow.FeedReader.Core | CodeHollow.FeedReader.Core/Feeds/0.91/Rss091Feed.cs | 5,455 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
namespace Azure.ResourceManager.Compute.Models
{
/// <summary> The TerminateNotificationProfile. </summary>
public partial class TerminateNotificationProfile
{
/// <summary> Initializes a new instance of TerminateNotificationProfile. </summary>
public TerminateNotificationProfile()
{
}
/// <summary> Initializes a new instance of TerminateNotificationProfile. </summary>
/// <param name="notBeforeTimeout"> Configurable length of time a Virtual Machine being deleted will have to potentially approve the Terminate Scheduled Event before the event is auto approved (timed out). The configuration must be specified in ISO 8601 format, the default value is 5 minutes (PT5M). </param>
/// <param name="enable"> Specifies whether the Terminate Scheduled event is enabled or disabled. </param>
internal TerminateNotificationProfile(string notBeforeTimeout, bool? enable)
{
NotBeforeTimeout = notBeforeTimeout;
Enable = enable;
}
/// <summary> Configurable length of time a Virtual Machine being deleted will have to potentially approve the Terminate Scheduled Event before the event is auto approved (timed out). The configuration must be specified in ISO 8601 format, the default value is 5 minutes (PT5M). </summary>
public string NotBeforeTimeout { get; set; }
/// <summary> Specifies whether the Terminate Scheduled event is enabled or disabled. </summary>
public bool? Enable { get; set; }
}
}
| 51.090909 | 317 | 0.71293 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/compute/Azure.ResourceManager.Compute/src/Generated/Models/TerminateNotificationProfile.cs | 1,686 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.UI.Xaml.Media.Imaging
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
#endif
public partial class SvgImageSource : global::Windows.UI.Xaml.Media.ImageSource
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::System.Uri UriSource
{
get
{
return (global::System.Uri)this.GetValue(UriSourceProperty);
}
set
{
this.SetValue(UriSourceProperty, value);
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public double RasterizePixelWidth
{
get
{
return (double)this.GetValue(RasterizePixelWidthProperty);
}
set
{
this.SetValue(RasterizePixelWidthProperty, value);
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public double RasterizePixelHeight
{
get
{
return (double)this.GetValue(RasterizePixelHeightProperty);
}
set
{
this.SetValue(RasterizePixelHeightProperty, value);
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public static global::Windows.UI.Xaml.DependencyProperty RasterizePixelHeightProperty { get; } =
Windows.UI.Xaml.DependencyProperty.Register(
nameof(RasterizePixelHeight), typeof(double),
typeof(global::Windows.UI.Xaml.Media.Imaging.SvgImageSource),
new FrameworkPropertyMetadata(default(double)));
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public static global::Windows.UI.Xaml.DependencyProperty RasterizePixelWidthProperty { get; } =
Windows.UI.Xaml.DependencyProperty.Register(
nameof(RasterizePixelWidth), typeof(double),
typeof(global::Windows.UI.Xaml.Media.Imaging.SvgImageSource),
new FrameworkPropertyMetadata(default(double)));
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public static global::Windows.UI.Xaml.DependencyProperty UriSourceProperty { get; } =
Windows.UI.Xaml.DependencyProperty.Register(
nameof(UriSource), typeof(global::System.Uri),
typeof(global::Windows.UI.Xaml.Media.Imaging.SvgImageSource),
new FrameworkPropertyMetadata(default(global::System.Uri)));
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public SvgImageSource()
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Xaml.Media.Imaging.SvgImageSource", "SvgImageSource.SvgImageSource()");
}
#endif
// Forced skipping of method Windows.UI.Xaml.Media.Imaging.SvgImageSource.SvgImageSource()
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public SvgImageSource( global::System.Uri uriSource)
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Xaml.Media.Imaging.SvgImageSource", "SvgImageSource.SvgImageSource(Uri uriSource)");
}
#endif
// Forced skipping of method Windows.UI.Xaml.Media.Imaging.SvgImageSource.SvgImageSource(System.Uri)
// Forced skipping of method Windows.UI.Xaml.Media.Imaging.SvgImageSource.UriSource.get
// Forced skipping of method Windows.UI.Xaml.Media.Imaging.SvgImageSource.UriSource.set
// Forced skipping of method Windows.UI.Xaml.Media.Imaging.SvgImageSource.RasterizePixelWidth.get
// Forced skipping of method Windows.UI.Xaml.Media.Imaging.SvgImageSource.RasterizePixelWidth.set
// Forced skipping of method Windows.UI.Xaml.Media.Imaging.SvgImageSource.RasterizePixelHeight.get
// Forced skipping of method Windows.UI.Xaml.Media.Imaging.SvgImageSource.RasterizePixelHeight.set
// Forced skipping of method Windows.UI.Xaml.Media.Imaging.SvgImageSource.Opened.add
// Forced skipping of method Windows.UI.Xaml.Media.Imaging.SvgImageSource.Opened.remove
// Forced skipping of method Windows.UI.Xaml.Media.Imaging.SvgImageSource.OpenFailed.add
// Forced skipping of method Windows.UI.Xaml.Media.Imaging.SvgImageSource.OpenFailed.remove
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::Windows.Foundation.IAsyncOperation<global::Windows.UI.Xaml.Media.Imaging.SvgImageSourceLoadStatus> SetSourceAsync( global::Windows.Storage.Streams.IRandomAccessStream streamSource)
{
throw new global::System.NotImplementedException("The member IAsyncOperation<SvgImageSourceLoadStatus> SvgImageSource.SetSourceAsync(IRandomAccessStream streamSource) is not implemented in Uno.");
}
#endif
// Forced skipping of method Windows.UI.Xaml.Media.Imaging.SvgImageSource.UriSourceProperty.get
// Forced skipping of method Windows.UI.Xaml.Media.Imaging.SvgImageSource.RasterizePixelWidthProperty.get
// Forced skipping of method Windows.UI.Xaml.Media.Imaging.SvgImageSource.RasterizePixelHeightProperty.get
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public event global::Windows.Foundation.TypedEventHandler<global::Windows.UI.Xaml.Media.Imaging.SvgImageSource, global::Windows.UI.Xaml.Media.Imaging.SvgImageSourceFailedEventArgs> OpenFailed
{
[global::Uno.NotImplemented]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Xaml.Media.Imaging.SvgImageSource", "event TypedEventHandler<SvgImageSource, SvgImageSourceFailedEventArgs> SvgImageSource.OpenFailed");
}
[global::Uno.NotImplemented]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Xaml.Media.Imaging.SvgImageSource", "event TypedEventHandler<SvgImageSource, SvgImageSourceFailedEventArgs> SvgImageSource.OpenFailed");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public event global::Windows.Foundation.TypedEventHandler<global::Windows.UI.Xaml.Media.Imaging.SvgImageSource, global::Windows.UI.Xaml.Media.Imaging.SvgImageSourceOpenedEventArgs> Opened
{
[global::Uno.NotImplemented]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Xaml.Media.Imaging.SvgImageSource", "event TypedEventHandler<SvgImageSource, SvgImageSourceOpenedEventArgs> SvgImageSource.Opened");
}
[global::Uno.NotImplemented]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Xaml.Media.Imaging.SvgImageSource", "event TypedEventHandler<SvgImageSource, SvgImageSourceOpenedEventArgs> SvgImageSource.Opened");
}
}
#endif
}
}
| 46.643836 | 226 | 0.771219 | [
"Apache-2.0"
] | JTOne123/uno | src/Uno.UI/Generated/3.0.0.0/Windows.UI.Xaml.Media.Imaging/SvgImageSource.cs | 6,810 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using InjecaoDependenciaDiretaEF.Data;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http;
using InjecaoDependenciaDiretaEF.Services;
namespace InjecaoDependenciaDiretaEF
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext<AplicacaoContext>(options =>
options.UseInMemoryDatabase("DBMemory"));
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddScoped<IEnvioEmail, EnvioEmail>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.Seed();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
public static class DataBaseExtend
{
public static void Seed(this IApplicationBuilder builder)
{
var db = builder.ApplicationServices.CreateScope().ServiceProvider.GetService<AplicacaoContext>();
db.SeedData();
}
}
}
| 28.586667 | 110 | 0.665112 | [
"MIT"
] | carloscds/CSharpSamples | InjecaoDependenciaDiretaEF/InjecaoDependenciaDiretaEF/Startup.cs | 2,144 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.