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 |
|---|---|---|---|---|---|---|---|---|
// Copyright (c) 2021 Maxim Kuzmin. All rights reserved. Licensed under the MIT License.
using Makc2021.Layer3.Sample.Entities.UserRole;
using Makc2021.Layer3.Sample.Mappers.EF.Entities.Role;
using Makc2021.Layer3.Sample.Mappers.EF.Entities.User;
namespace Makc2021.Layer3.Sample.Mappers.EF.Entities.UserRole
{
/// <summary>
/// Объект сущности "UserRole" сопоставителя.
/// </summary>
public class MapperUserRoleEntityObject : UserRoleEntityObject
{
#region Properties
/// <summary>
/// Объект сущности "Role".
/// </summary>
public MapperRoleEntityObject ObjectOfRoleEntity { get; set; }
/// <summary>
/// Объект сущности "User".
/// </summary>
public MapperUserEntityObject ObjectOfUserEntity { get; set; }
#endregion Properties
}
}
| 29.172414 | 89 | 0.666667 | [
"MIT"
] | maxim-kuzmin/Makc2021 | server/src/Makc2021.Layer3.Sample.Mappers.EF/Entities/UserRole/MapperUserRoleEntityObject.cs | 903 | C# |
namespace OzgeErsu.Models
{
public class Video
{
public string id { get; set; }
public string priority { get; set; }
public string video { get; set; }
public string splash { get; set; }
public string link { get; set; }
public string active { get; set; }
}
}
| 18.052632 | 45 | 0.51895 | [
"MIT"
] | onurcelikeng/OzgeErsu | OzgeErsu/Models/Video.cs | 345 | 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 apigateway-2015-07-09.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.APIGateway.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.APIGateway.Model.Internal.MarshallTransformations
{
/// <summary>
/// GetRequestValidators Request Marshaller
/// </summary>
public class GetRequestValidatorsRequestMarshaller : IMarshaller<IRequest, GetRequestValidatorsRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((GetRequestValidatorsRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(GetRequestValidatorsRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.APIGateway");
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2015-07-09";
request.HttpMethod = "GET";
if (!publicRequest.IsSetRestApiId())
throw new AmazonAPIGatewayException("Request object does not have required field RestApiId set");
request.AddPathResource("{restapi_id}", StringUtils.FromString(publicRequest.RestApiId));
if (publicRequest.IsSetLimit())
request.Parameters.Add("limit", StringUtils.FromInt(publicRequest.Limit));
if (publicRequest.IsSetPosition())
request.Parameters.Add("position", StringUtils.FromString(publicRequest.Position));
request.ResourcePath = "/restapis/{restapi_id}/requestvalidators";
request.MarshallerVersion = 2;
request.UseQueryString = true;
return request;
}
private static GetRequestValidatorsRequestMarshaller _instance = new GetRequestValidatorsRequestMarshaller();
internal static GetRequestValidatorsRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static GetRequestValidatorsRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 36.726316 | 155 | 0.657782 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/APIGateway/Generated/Model/Internal/MarshallTransformations/GetRequestValidatorsRequestMarshaller.cs | 3,489 | C# |
// RetrieveMetadataChangesRequest.cs
//
using System;
using System.Collections.Generic;
using Xrm.Sdk.Metadata.Query;
namespace Xrm.Sdk.Messages
{
public class RetrieveMetadataChangesRequest : OrganizationRequest
{
// Summary:
// Gets or sets a timestamp value representing when the last request was made.
//
// Returns:
// Type: Returns_String A timestamp value representing when the last request
// was made.
public string ClientVersionStamp;
//
// Summary:
// Gets or sets a value to filter what deleted metadata items will be returned.
//
// Returns:
// Type: Microsoft.Xrm.Sdk.Metadata.Query.DeletedMetadataFiltersA value to filter
// what deleted metadata items will be returned.
public DeletedMetadataFilters DeletedMetadataFilters;
//
// Summary:
// Gets or sets the query representing the metadata to return.
//
// Returns:
// Type:Microsoft.Xrm.Sdk.Metadata.Query.EntityQueryExpressionThe query representing
// the metadata to return.
public EntityQueryExpression Query;
public string Serialise()
{
return @"<request i:type='a:RetrieveMetadataChangesRequest' xmlns:a='http://schemas.microsoft.com/xrm/2011/Contracts'>
<a:Parameters xmlns:b='http://schemas.datacontract.org/2004/07/System.Collections.Generic'>
<a:KeyValuePairOfstringanyType>
<b:key>ClientVersionStamp</b:key>" + Attribute.SerialiseValue(ClientVersionStamp,null) + @"
</a:KeyValuePairOfstringanyType>
<a:KeyValuePairOfstringanyType>
<b:key>Query</b:key>
" + MetadataSerialiser.SerialiseEntityQueryExpression(Query) + @"
</a:KeyValuePairOfstringanyType>
</a:Parameters>
<a:RequestId i:nil='true' />
<a:RequestName>RetrieveMetadataChanges</a:RequestName>
</request>";
}
}
}
| 35.42623 | 130 | 0.598797 | [
"MIT"
] | jatinrai06/sparkle | SparkleXrmSource/SparkleXrm/Sdk/Messages/RetrieveMetadataChangesRequest.cs | 2,161 | C# |
namespace Emarketing.Authorization.Accounts.Dto
{
public enum TenantAvailabilityState
{
Available = 1,
InActive,
NotFound
}
}
| 16.3 | 48 | 0.625767 | [
"MIT"
] | farazahmed879/Emarketing | aspnet-core/src/Emarketing.Application/Authorization/Accounts/Dto/TenantAvailabilityState.cs | 165 | C# |
namespace StudentSystem.Services.Models.Web.Students
{
using System;
using System.Runtime.Serialization;
[DataContract]
public class StudentRequestModel
{
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }
[DataMember]
public string Email { get; set; }
[DataMember]
public DateTime DateOfBirth { get; set; }
}
} | 21.619048 | 53 | 0.612335 | [
"MIT"
] | itplamen/StudentSystem | StudentSystem/Services/StudentSystem.Services.Models.Web/Students/StudentRequestModel.cs | 456 | C# |
//
// KinoFog - Deferred fog effect
//
// Copyright (C) 2015 Keijiro Takahashi
//
// 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 UnityEngine;
namespace Kino
{
[ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
[AddComponentMenu("Kino Image Effects/Fog")]
public class Fog : MonoBehaviour
{
#region Public Properties
// Start distance
[SerializeField]
float _startDistance = 1;
public float startDistance {
get { return _startDistance; }
set { _startDistance = value; }
}
// Use radial distance
[SerializeField]
bool _useRadialDistance;
public bool useRadialDistance {
get { return _useRadialDistance; }
set { _useRadialDistance = value; }
}
// Fade-to-skybox flag
[SerializeField]
bool _fadeToSkybox;
public bool fadeToSkybox {
get { return _fadeToSkybox; }
set { _fadeToSkybox = value; }
}
#endregion
#region Private Properties
[SerializeField] Shader _shader;
Material _material;
#endregion
#region MonoBehaviour Functions
void OnEnable()
{
GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth;
}
[ImageEffectOpaque]
void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (_material == null)
{
_material = new Material(_shader);
_material.hideFlags = HideFlags.DontSave;
}
_startDistance = Mathf.Max(_startDistance, 0.0f);
_material.SetFloat("_DistanceOffset", _startDistance);
var mode = RenderSettings.fogMode;
if (mode == FogMode.Linear)
{
var start = RenderSettings.fogStartDistance;
var end = RenderSettings.fogEndDistance;
var invDiff = 1.0f / Mathf.Max(end - start, 1.0e-6f);
_material.SetFloat("_LinearGrad", -invDiff);
_material.SetFloat("_LinearOffs", end * invDiff);
_material.DisableKeyword("FOG_EXP");
_material.DisableKeyword("FOG_EXP2");
}
else if (mode == FogMode.Exponential)
{
const float coeff = 1.4426950408f; // 1/ln(2)
var density = RenderSettings.fogDensity;
_material.SetFloat("_Density", coeff * density);
_material.EnableKeyword("FOG_EXP");
_material.DisableKeyword("FOG_EXP2");
}
else // FogMode.ExponentialSquared
{
const float coeff = 1.2011224087f; // 1/sqrt(ln(2))
var density = RenderSettings.fogDensity;
_material.SetFloat("_Density", coeff * density);
_material.DisableKeyword("FOG_EXP");
_material.EnableKeyword("FOG_EXP2");
}
if (_useRadialDistance)
_material.EnableKeyword("RADIAL_DIST");
else
_material.DisableKeyword("RADIAL_DIST");
if (_fadeToSkybox)
{
_material.EnableKeyword("USE_SKYBOX");
// Transfer the skybox parameters.
var skybox = RenderSettings.skybox;
_material.SetTexture("_SkyCubemap", skybox.GetTexture("_Tex"));
_material.SetColor("_SkyTint", skybox.GetColor("_Tint"));
_material.SetFloat("_SkyExposure", skybox.GetFloat("_Exposure"));
_material.SetFloat("_SkyRotation", skybox.GetFloat("_Rotation"));
}
else
{
_material.DisableKeyword("USE_SKYBOX");
_material.SetColor("_FogColor", RenderSettings.fogColor);
}
// Calculate vectors towards frustum corners.
var cam = GetComponent<Camera>();
var camtr = cam.transform;
var camNear = cam.nearClipPlane;
var camFar = cam.farClipPlane;
var tanHalfFov = Mathf.Tan(cam.fieldOfView * Mathf.Deg2Rad / 2);
var toRight = camtr.right * camNear * tanHalfFov * cam.aspect;
var toTop = camtr.up * camNear * tanHalfFov;
var v_tl = camtr.forward * camNear - toRight + toTop;
var v_tr = camtr.forward * camNear + toRight + toTop;
var v_br = camtr.forward * camNear + toRight - toTop;
var v_bl = camtr.forward * camNear - toRight - toTop;
var v_s = v_tl.magnitude * camFar / camNear;
// Draw screen quad.
RenderTexture.active = destination;
_material.SetTexture("_MainTex", source);
_material.SetPass(0);
GL.PushMatrix();
GL.LoadOrtho();
GL.Begin(GL.QUADS);
GL.MultiTexCoord2(0, 0, 0);
GL.MultiTexCoord(1, v_bl.normalized * v_s);
GL.Vertex3(0, 0, 0.1f);
GL.MultiTexCoord2(0, 1, 0);
GL.MultiTexCoord(1, v_br.normalized * v_s);
GL.Vertex3(1, 0, 0.1f);
GL.MultiTexCoord2(0, 1, 1);
GL.MultiTexCoord(1, v_tr.normalized * v_s);
GL.Vertex3(1, 1, 0.1f);
GL.MultiTexCoord2(0, 0, 1);
GL.MultiTexCoord(1, v_tl.normalized * v_s);
GL.Vertex3(0, 1, 0.1f);
GL.End();
GL.PopMatrix();
}
#endregion
}
}
| 34.84127 | 83 | 0.581321 | [
"Unlicense"
] | Marwan0/KvantGrass | Assets/Kino/Fog/Fog.cs | 6,587 | C# |
/*
CloudGenix Controller SDK
(c) 2018 CloudGenix, Inc.
All Rights Reserved
https://www.cloudgenix.com
This SDK is released under the MIT license.
For support, please contact us on:
NetworkToCode Slack channel #cloudgenix: http://slack.networktocode.com
Email: developers@cloudgenix.com
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using RestWrapper;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace CloudGenix.Classes
{
public class FlowResponse
{
#region Public-Members
[JsonProperty("flows")]
public FlowCollection Flows { get; set; }
#endregion
#region Private-Members
#endregion
#region Constructors-and-Factories
public FlowResponse()
{
}
#endregion
#region Public-Methods
public override string ToString()
{
return string.Format("[FlowResponse: Flows={0}]", Flows);
}
#endregion
#region Private-Methods
#endregion
#region Public-Embedded-Classes
public class FlowCollection
{
[JsonProperty("debug_level")]
public string DebugLevel { get; set; }
[JsonProperty("start_time")]
public DateTime? StartTime { get; set; }
[JsonProperty("end_time")]
public DateTime? EndTime { get; set; }
[JsonProperty("items")]
public List<Flow> Items { get; set; }
public FlowCollection()
{
Items = new List<Flow>();
}
public override string ToString()
{
return string.Format("[FlowCollection: DebugLevel={0}, StartTime={1}, EndTime={2}, Items={3}]", DebugLevel, StartTime, EndTime, Items);
}
public class Flow
{
[JsonProperty("app_id")]
public string AppId { get; set; }
[JsonProperty("average_ntt")]
public object AverageNetworkTransferTime { get; set; }
[JsonProperty("average_pg")]
public object AveragePathGoodput { get; set; }
[JsonProperty("average_rtt")]
public object AverageResponseTime { get; set; }
[JsonProperty("average_srt")]
public object AverageServerResponseTime { get; set; }
[JsonProperty("average_udp_trt")]
public object AverageUdpTransactionResponseTime { get; set; }
[JsonProperty("avg_jitter_c2s")]
public object AverageJitterClientToServer { get; set; }
[JsonProperty("avg_jitter_s2c")]
public object AverageJitterServerToClient { get; set; }
[JsonProperty("avg_mos_c2s")]
public object AverageMosClientToServer { get; set; }
[JsonProperty("avg_mos_s2c")]
public object AverageMosServerToClient { get; set; }
[JsonProperty("avg_packet_loss_c2s")]
public object AveragePacketLossClientToServer { get; set; }
[JsonProperty("avg_packet_loss_s2c")]
public object AveragePacketLossServerToClient { get; set; }
[JsonProperty("bytes_c2s")]
public long BytesClientToServer { get; set; }
[JsonProperty("bytes_s2c")]
public long BytesServerToClient { get; set; }
[JsonProperty("codec_c2s")]
public List<object> CodecClientToServer { get; set; }
[JsonProperty("codec_s2c")]
public List<object> CodecServerToClient { get; set; }
[JsonProperty("destination_ip")]
public string DestinationIp { get; set; }
[JsonProperty("destination_port")]
public int DestinationPort { get; set; }
[JsonProperty("fc_app_id")]
public string FlowControllerAppId { get; set; }
[JsonProperty("fin_c2s")]
public int TcpFinClientToServer { get; set; }
[JsonProperty("fin_s2c")]
public int TcpFinServerToClient { get; set; }
[JsonProperty("flow_decision_metadata_list")]
public List<object> FlowDecisionMetadataList { get; set; }
[JsonProperty("flow_end_time_ms")]
public long FlowEndTimeMs { get; set; }
[JsonProperty("flow_start_time_ms")]
public long FlowStartTimeMs { get; set; }
[JsonProperty("incomplete_transactions")]
public object IncompleteTransactions { get; set; }
[JsonProperty("init_success")]
public object InitSuccess { get; set; }
[JsonProperty("is_local_traffic")]
public bool? IsLocalTraffic { get; set; }
[JsonProperty("is_security_policy_present")]
public bool? SecurityPolicyPresent { get; set; }
[JsonProperty("lan_to_wan")]
public bool? LanToWan { get; set; }
[JsonProperty("max_jitter_c2s")]
public object MaxJitterClientToServer { get; set; }
[JsonProperty("max_jitter_s2c")]
public object MaxJitterServerToClient { get; set; }
[JsonProperty("max_mos_c2s")]
public object MaxMosClientToServer { get; set; }
[JsonProperty("max_mos_s2c")]
public object MaxMosServerToClient { get; set; }
[JsonProperty("max_ntt")]
public object MaxNetworkTransferTime { get; set; }
[JsonProperty("max_packet_loss_c2s")]
public object MaxPacketLossClientToServer { get; set; }
[JsonProperty("max_packet_loss_s2c")]
public object MaxPacketLossServerToClient { get; set; }
[JsonProperty("max_pg")]
public object MaxPacketGap { get; set; }
[JsonProperty("max_rtt")]
public object MaxRoundTripTime { get; set; }
[JsonProperty("max_srt")]
public object MaxServerResponseTime { get; set; }
[JsonProperty("max_udp_trt")]
public object MaxUdpTransactionResponseTime { get; set; }
[JsonProperty("media_type")]
public object MediaType { get; set; }
[JsonProperty("min_mos_c2s")]
public object MinMosClientToServer { get; set; }
[JsonProperty("min_mos_s2c")]
public object MinMosServerToClient { get; set; }
[JsonProperty("min_ntt")]
public object MinNetworkTransferTime { get; set; }
[JsonProperty("min_pg")]
public object MinPacketGap { get; set; }
[JsonProperty("min_rtt")]
public object MinRoundTripTime { get; set; }
[JsonProperty("min_srt")]
public object MinServerResponseTime { get; set; }
[JsonProperty("min_udp_trt")]
public object MinUdpTransactionResponseTime { get; set; }
[JsonProperty("new_flow")]
public bool? NewFlow { get; set; }
[JsonProperty("ooo_pkts_c2s")]
public long OutOfOrderPacketsClientToServer { get; set; }
[JsonProperty("ooo_pkts_s2c")]
public long OutOfOrderPacketsServerToClient { get; set; }
[JsonProperty("packets_c2s")]
public long PacketsClientToServer { get; set; }
[JsonProperty("packets_s2c")]
public long PacketsServerToClient { get; set; }
[JsonProperty("path_id")]
public string PathId { get; set; }
[JsonProperty("path_type")]
public string PathType { get; set; }
[JsonProperty("policy_id")]
public string PolicyId { get; set; }
[JsonProperty("priority_class")]
public int PriorityClass { get; set; }
[JsonProperty("protocol")]
public int Protocol { get; set; }
[JsonProperty("reset_c2s")]
public long ResetClientToServer { get; set; }
[JsonProperty("reset_s2c")]
public long ResetServerToClient { get; set; }
[JsonProperty("retransmit_bytes_c2s")]
public long RetransmitBytesClientToServer { get; set; }
[JsonProperty("retransmit_bytes_s2c")]
public long RetransmitBytesServerToClient { get; set; }
[JsonProperty("retransmit_pkts_c2s")]
public long RetransmitPacketsClientToServer { get; set; }
[JsonProperty("retransmit_pkts_s2c")]
public long RetransmitPacketsServerToClient { get; set; }
[JsonProperty("sack_pkts_c2s")]
public long SelectiveAckPacketsClientToServer { get; set; }
[JsonProperty("sack_pkts_s2c")]
public long SelectiveAckPacketsServerToClient { get; set; }
[JsonProperty("source_ip")]
public string SourceIp { get; set; }
[JsonProperty("source_port")]
public int SourcePort { get; set; }
[JsonProperty("success_transactions")]
public object SuccessTransactions { get; set; }
[JsonProperty("syn_c2s")]
public long SynClientToServer { get; set; }
[JsonProperty("syn_s2c")]
public long SynServerToClient { get; set; }
[JsonProperty("traffic_type")]
public string TrafficType { get; set; }
[JsonProperty("unknown_domain")]
public object UnknownDomain { get; set; }
[JsonProperty("wan_path_change_reason")]
public object WanPathChangeReason { get; set; }
public Flow()
{
}
public override string ToString()
{
return string.Format("[Flow: AppId={0}, AverageNetworkTransferTime={1}, AveragePathGoodput={2}, AverageResponseTime={3}, AverageServerResponseTime={4}, AverageUdpTransactionResponseTime={5}, AverageJitterClientToServer={6}, AverageJitterServerToClient={7}, AverageMosClientToServer={8}, AverageMosServerToClient={9}, AveragePacketLossClientToServer={10}, AveragePacketLossServerToClient={11}, BytesClientToServer={12}, BytesServerToClient={13}, CodecClientToServer={14}, CodecServerToClient={15}, DestinationIp={16}, DestinationPort={17}, FlowControllerAppId={18}, TcpFinClientToServer={19}, TcpFinServerToClient={20}, FlowDecisionMetadataList={21}, FlowEndTimeMs={22}, FlowStartTimeMs={23}, IncompleteTransactions={24}, InitSuccess={25}, IsLocalTraffic={26}, SecurityPolicyPresent={27}, LanToWan={28}, MaxJitterClientToServer={29}, MaxJitterServerToClient={30}, MaxMosClientToServer={31}, MaxMosServerToClient={32}, MaxNetworkTransferTime={33}, MaxPacketLossClientToServer={34}, MaxPacketLossServerToClient={35}, MaxPacketGap={36}, MaxRoundTripTime={37}, MaxServerResponseTime={38}, MaxUdpTransactionResponseTime={39}, MediaType={40}, MinMosClientToServer={41}, MinMosServerToClient={42}, MinNetworkTransferTime={43}, MinPacketGap={44}, MinRoundTripTime={45}, MinServerResponseTime={46}, MinUdpTransactionResponseTime={47}, NewFlow={48}, OutOfOrderPacketsClientToServer={49}, OutOfOrderPacketsServerToClient={50}, PacketsClientToServer={51}, PacketsServerToClient={52}, PathId={53}, PathType={54}, PolicyId={55}, PriorityClass={56}, Protocol={57}, ResetClientToServer={58}, ResetServerToClient={59}, RetransmitBytesClientToServer={60}, RetransmitBytesServerToClient={61}, RetransmitPacketsClientToServer={62}, RetransmitPacketsServerToClient={63}, SelectiveAckPacketsClientToServer={64}, SelectiveAckPacketsServerToClient={65}, SourceIp={66}, SourcePort={67}, SuccessTransactions={68}, SynClientToServer={69}, SynServerToClient={70}, TrafficType={71}, UnknownDomain={72}, WanPathChangeReason={73}]", AppId, AverageNetworkTransferTime, AveragePathGoodput, AverageResponseTime, AverageServerResponseTime, AverageUdpTransactionResponseTime, AverageJitterClientToServer, AverageJitterServerToClient, AverageMosClientToServer, AverageMosServerToClient, AveragePacketLossClientToServer, AveragePacketLossServerToClient, BytesClientToServer, BytesServerToClient, CodecClientToServer, CodecServerToClient, DestinationIp, DestinationPort, FlowControllerAppId, TcpFinClientToServer, TcpFinServerToClient, FlowDecisionMetadataList, FlowEndTimeMs, FlowStartTimeMs, IncompleteTransactions, InitSuccess, IsLocalTraffic, SecurityPolicyPresent, LanToWan, MaxJitterClientToServer, MaxJitterServerToClient, MaxMosClientToServer, MaxMosServerToClient, MaxNetworkTransferTime, MaxPacketLossClientToServer, MaxPacketLossServerToClient, MaxPacketGap, MaxRoundTripTime, MaxServerResponseTime, MaxUdpTransactionResponseTime, MediaType, MinMosClientToServer, MinMosServerToClient, MinNetworkTransferTime, MinPacketGap, MinRoundTripTime, MinServerResponseTime, MinUdpTransactionResponseTime, NewFlow, OutOfOrderPacketsClientToServer, OutOfOrderPacketsServerToClient, PacketsClientToServer, PacketsServerToClient, PathId, PathType, PolicyId, PriorityClass, Protocol, ResetClientToServer, ResetServerToClient, RetransmitBytesClientToServer, RetransmitBytesServerToClient, RetransmitPacketsClientToServer, RetransmitPacketsServerToClient, SelectiveAckPacketsClientToServer, SelectiveAckPacketsServerToClient, SourceIp, SourcePort, SuccessTransactions, SynClientToServer, SynServerToClient, TrafficType, UnknownDomain, WanPathChangeReason);
}
}
}
#endregion
}
}
| 43.296636 | 3,631 | 0.623111 | [
"MIT"
] | CloudGenix/sdk-csharp | CloudGenixSdk/Classes/FlowResponse.cs | 14,160 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//------------------------------------------------------------------------------
using System;
using System.Data.Common;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
namespace Microsoft.SqlServer.Server
{
internal class SmiSettersStream : Stream
{
private SmiEventSink_Default _sink;
private ITypedSettersV3 _setters;
private int _ordinal;
private long _lengthWritten;
private SmiMetaData _metaData;
internal SmiSettersStream(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData)
{
Debug.Assert(null != sink);
Debug.Assert(null != setters);
Debug.Assert(0 <= ordinal);
Debug.Assert(null != metaData);
_sink = sink;
_setters = setters;
_ordinal = ordinal;
_lengthWritten = 0;
_metaData = metaData;
}
public override bool CanRead
{
get
{
return false;
}
}
// If CanSeek is false, Position, Seek, Length, and SetLength should throw.
public override bool CanSeek
{
get
{
return false;
}
}
public override bool CanWrite
{
get
{
return true;
}
}
public override long Length
{
get
{
return _lengthWritten;
}
}
public override long Position
{
get
{
return _lengthWritten;
}
set
{
throw SQL.StreamSeekNotSupported();
}
}
public override void Flush()
{
_lengthWritten = ValueUtilsSmi.SetBytesLength(_sink, _setters, _ordinal, _metaData, _lengthWritten);
}
public override long Seek(long offset, SeekOrigin origin)
{
throw SQL.StreamSeekNotSupported();
}
public override void SetLength(long value)
{
if (value < 0)
{
throw ADP.ArgumentOutOfRange(nameof(value));
}
ValueUtilsSmi.SetBytesLength(_sink, _setters, _ordinal, _metaData, value);
}
public override int Read(byte[] buffer, int offset, int count)
{
throw SQL.StreamReadNotSupported();
}
public override void Write(byte[] buffer, int offset, int count)
{
_lengthWritten += ValueUtilsSmi.SetBytes(_sink, _setters, _ordinal, _metaData, _lengthWritten, buffer, offset, count);
}
}
}
| 25.973684 | 130 | 0.525498 | [
"MIT"
] | 2E0PGS/corefx | src/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiSettersStream.cs | 2,961 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Primjer 01")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Primjer 01")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9e377e8e-c2b9-40ed-be6e-ab0f7afe2edc")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.648649 | 84 | 0.743001 | [
"MIT"
] | jasarsoft/examples | cs/jlp4/Poglavlje 21/Primjer 01/Properties/AssemblyInfo.cs | 1,396 | C# |
// <copyright file="TranscriptionToHtml.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
// </copyright>
namespace Connector
{
using System;
using System.Linq;
using System.Text;
public static class TranscriptionToHtml
{
public static string ToHtml(SpeechTranscript transcription, string filename)
{
if (transcription == null)
{
throw new ArgumentNullException(nameof(transcription));
}
var isMultiChannel = transcription?.RecognizedPhrases != null && transcription.RecognizedPhrases.Any(s => s != null && s.Channel != 0);
var html = $@"<html lang='en'> <head> <meta http-equiv='content-type' content='text/html; charset=utf-8'> <title>{filename}</title>";
html += @"<link rel='stylesheet' href='https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css' integrity='sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh' crossorigin='anonymous'>";
html += @"<style>a.inline-decoration { color:#000000 !important; text-decoration:none; } .utterance-playing { background-color: lightgray; opacity: 0.9; }</style>";
html += @"<link href='https://amp.azure.net/libs/amp/2.3.3/skins/amp-default/azuremediaplayer.min.css' rel='stylesheet'>";
html += @"<script src='https://amp.azure.net/libs/amp/2.3.3/azuremediaplayer.min.js'></script>";
html += @"</head>";
html += $@"<body> <h3>{filename}</h3> <div class='text-center'><audio id='azuremediaplayer2' class='azuremediaplayer amp-default-skin amp-big-play-centered' tabindex='0'></audio></div><br><br><div class='text-center'><img </div><br><table class='table'><thead><tr><td>Speaker</td>{(isMultiChannel ? "<td>Channel</td><td>Text</td><td>Text</td>" : "<td>Text</td>")}</tr></thead><tbody>";
var htmlBuilder = new StringBuilder(html);
if (transcription.RecognizedPhrases != null)
{
foreach (var recognizedPhrase in transcription.RecognizedPhrases.OrderBy(s => s.Offset))
{
var sentence = recognizedPhrase.NBest.FirstOrDefault();
if (sentence == null)
{
continue;
}
htmlBuilder.Append("<tr>");
htmlBuilder.Append("<td>" + recognizedPhrase.Speaker + @"</td>");
var confidenceIndication = "<span";
if (sentence.Confidence <= .5)
{
confidenceIndication = "<span class='table-danger'";
}
else if (sentence.Confidence <= .7)
{
confidenceIndication = "<span class='table-warning'";
}
if (isMultiChannel)
{
htmlBuilder.Append($"<td>{recognizedPhrase.Channel}</td>");
if (recognizedPhrase.Channel % 2 == 1)
{
htmlBuilder.Append($"<td><a href='javascript:jumpTime({recognizedPhrase.Offset});' class='inline-decoration'></a></td>");
htmlBuilder.Append($"<td><a href='javascript:jumpTime({recognizedPhrase.Offset});' class='inline-decoration'{confidenceIndication}>{sentence.Display}</span></a></td>");
}
else
{
htmlBuilder.Append($"<td><a href='javascript:jumpTime({recognizedPhrase.Offset});' class='inline-decoration'{confidenceIndication}>{sentence.Display}</span></a></td>");
htmlBuilder.Append($"<td><a href='javascript:jumpTime({recognizedPhrase.Offset});' class='inline-decoration'></a></td>");
}
}
else
{
htmlBuilder.Append($"<td><a href='javascript:jumpTime({recognizedPhrase.Offset});' class='inline-decoration'{confidenceIndication}>{sentence.Display}</span></a></td>");
}
htmlBuilder.Append("</tr>");
htmlBuilder.AppendLine(string.Empty);
}
}
htmlBuilder.Append(@"</tbody></table>");
htmlBuilder.Append(@"<script> var myOptions = { controls: true, width: '450', height: '250', poster: 'http://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RE2qVsJ?ver=3f74' }; </script>");
htmlBuilder.Append(@"</body></html>");
return htmlBuilder.ToString();
}
}
} | 54.573034 | 397 | 0.554457 | [
"MIT"
] | ArcherAZ/cognitive-services-speech-sdk | samples/ingestion/ingestion-client/Connector/TranscriptionToHtml.cs | 4,857 | C# |
#region License
// Distributed under the BSD License
// =================================
//
// Copyright (c) 2010, Hadi Hariri
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Hadi Hariri nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> 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.
// =============================================================
//
//
// Parts of this Software use JsonFX Serialization Library which is distributed under the MIT License:
//
// Distributed under the terms of an MIT-style license:
//
// The MIT License
//
// Copyright (c) 2006-2009 Stephen M. McKamey
//
// 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.IO;
using System.Net;
using System.Text;
using EasyHttp.Codecs;
using EasyHttp.Configuration;
using EasyHttp.Http.Abstractions;
namespace EasyHttp.Http
{
public class HttpResponse
{
readonly IDecoder _decoder;
IHttpWebResponse _response;
public virtual string CharacterSet { get; private set; }
public virtual string ContentType { get; private set; }
public virtual HttpStatusCode StatusCode { get; private set; }
public virtual string StatusDescription { get; private set; }
public virtual CookieCollection Cookies { get; private set; }
public virtual int Age { get; private set; }
public virtual HttpMethod[] Allow { get; private set; }
public virtual CacheControl CacheControl { get; private set; }
public virtual string ContentEncoding { get; private set; }
public virtual string ContentLanguage { get; private set; }
public virtual long ContentLength { get; private set; }
public virtual string ContentLocation { get; private set; }
// TODO :This should be files
public virtual string ContentDisposition { get; private set; }
public virtual DateTime Date { get; private set; }
public virtual string ETag { get; private set; }
public virtual DateTime Expires { get; private set; }
public virtual DateTime LastModified { get; private set; }
public virtual string Location { get; private set; }
public virtual CacheControl Pragma { get; private set; }
public virtual string Server { get; private set; }
public virtual WebHeaderCollection RawHeaders { get; private set; }
public virtual Stream ResponseStream { get { return _response.GetResponseStream(); }
}
public virtual dynamic DynamicBody
{
get { return _decoder.DecodeToDynamic(RawText, ContentType); }
}
public virtual string RawText { get; private set; }
public virtual T StaticBody<T>(string overrideContentType = null)
{
if (overrideContentType != null)
{
return _decoder.DecodeToStatic<T>(RawText, overrideContentType);
}
return _decoder.DecodeToStatic<T>(RawText, ContentType);
}
public HttpResponse() : this(null)
{
}
public HttpResponse(IDecoder decoder)
{
_decoder = decoder ?? new DefaultEncoderDecoderConfiguration().GetDecoder();
}
public virtual void GetResponse(IHttpWebRequest request, string filename, bool streamResponse)
{
try
{
_response = request.GetResponse();
}
catch (WebException webException)
{
if (webException.Response == null)
{
throw;
}
_response = new HttpWebResponseWrapper((HttpWebResponse) webException.Response);
}
GetHeaders();
if (streamResponse) return;
using (var stream = _response.GetResponseStream())
{
if (stream == null) return;
if (!string.IsNullOrEmpty(filename))
{
using (var filestream = new FileStream(filename, FileMode.CreateNew))
{
int count;
var buffer = new byte[8192];
while ((count = stream.Read(buffer, 0, buffer.Length)) > 0)
{
filestream.Write(buffer, 0, count);
}
}
}
else
{
var encoding = string.IsNullOrEmpty(CharacterSet) ? Encoding.UTF8 : Encoding.GetEncoding(CharacterSet);
using (var reader = new StreamReader(stream, encoding))
{
RawText = reader.ReadToEnd();
}
}
}
}
void GetHeaders()
{
CharacterSet = _response.CharacterSet;
ContentType = _response.ContentType;
StatusCode = _response.StatusCode;
StatusDescription = _response.StatusDescription;
Cookies = _response.Cookies;
ContentEncoding = _response.ContentEncoding;
ContentLength = _response.ContentLength;
Date = DateTime.Now;
LastModified = _response.LastModified;
Server = _response.Server;
if (!String.IsNullOrEmpty(GetHeader("Age")))
{
Age = Convert.ToInt32(GetHeader("Age"));
}
ContentLanguage = GetHeader("Content-Language");
ContentLocation = GetHeader("Content-Location");
ContentDisposition = GetHeader("Content-Disposition");
ETag = GetHeader("ETag");
Location = GetHeader("Location");
if (!String.IsNullOrEmpty(GetHeader("Expires")))
{
DateTime expires;
if (DateTime.TryParse(GetHeader("Expires"), out expires))
{
Expires = expires;
}
}
// TODO: Finish this.
// public HttpMethod Allow { get; private set; }
// public CacheControl CacheControl { get; private set; }
// public CacheControl Pragma { get; private set; }
RawHeaders = _response.Headers;
}
string GetHeader(string header)
{
var headerValue = _response.GetResponseHeader(header);
return headerValue.Replace("\"", "");
}
}
} | 38.207048 | 123 | 0.629886 | [
"BSD-3-Clause"
] | ChrisMcKee/EasyHttp | src/EasyHttp/Http/HttpResponse.cs | 8,675 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace StronglyTypedIds
{
internal static class SourceGenerationHelper
{
public static string CreateId(
string idNamespace,
string idName,
ParentClass? parentClass,
StronglyTypedIdConverter converters,
StronglyTypedIdBackingType backingType,
StronglyTypedIdImplementations implementations)
=> CreateId(idNamespace, idName, parentClass, converters, backingType, implementations, null);
public static string CreateId(
string idNamespace,
string idName,
ParentClass? parentClass,
StronglyTypedIdConverter converters,
StronglyTypedIdBackingType backingType,
StronglyTypedIdImplementations implementations,
StringBuilder? sb)
{
var resources = backingType switch
{
StronglyTypedIdBackingType.Guid => EmbeddedSources.GuidResources,
StronglyTypedIdBackingType.Int => EmbeddedSources.IntResources,
StronglyTypedIdBackingType.Long => EmbeddedSources.LongResources,
StronglyTypedIdBackingType.String => EmbeddedSources.StringResources,
StronglyTypedIdBackingType.NullableString => EmbeddedSources.NullableStringResources,
StronglyTypedIdBackingType.NewId => EmbeddedSources.NewIdResources,
_ => throw new ArgumentException("Unknown backing type: " + backingType, nameof(backingType)),
};
return CreateId(idNamespace, idName, parentClass, converters, implementations, resources, sb);
}
static string CreateId(
string idNamespace,
string idName,
ParentClass? parentClass,
StronglyTypedIdConverter converters,
StronglyTypedIdImplementations implementations,
EmbeddedSources.ResourceCollection resources,
StringBuilder? sb)
{
if (string.IsNullOrEmpty(idName))
{
throw new ArgumentException("Value cannot be null or empty.", nameof(idName));
}
if (converters == StronglyTypedIdConverter.Default)
{
throw new ArgumentException("Cannot use default converter - must provide concrete values or None", nameof(converters));
}
if (implementations == StronglyTypedIdImplementations.Default)
{
throw new ArgumentException("Cannot use default implementations - must provide concrete values or None", nameof(implementations));
}
var hasNamespace = !string.IsNullOrEmpty(idNamespace);
var useTypeConverter = converters.IsSet(StronglyTypedIdConverter.TypeConverter);
var useNewtonsoftJson = converters.IsSet(StronglyTypedIdConverter.NewtonsoftJson);
var useSystemTextJson = converters.IsSet(StronglyTypedIdConverter.SystemTextJson);
var useEfCoreValueConverter = converters.IsSet(StronglyTypedIdConverter.EfCoreValueConverter);
var useDapperTypeHandler = converters.IsSet(StronglyTypedIdConverter.DapperTypeHandler);
var useIEquatable = implementations.IsSet(StronglyTypedIdImplementations.IEquatable);
var useIComparable = implementations.IsSet(StronglyTypedIdImplementations.IComparable);
var parentsCount = 0;
sb ??= new StringBuilder();
sb.Append(resources.Header);
if (resources.NullableEnable)
{
sb.AppendLine("#nullable enable");
}
if (hasNamespace)
{
sb
.Append("namespace ")
.Append(idNamespace)
.AppendLine(@"
{");
}
while (parentClass is not null)
{
sb
.Append(" partial ")
.Append(parentClass.Keyword)
.Append(' ')
.Append(parentClass.Name)
.Append(' ')
.Append(parentClass.Constraints)
.AppendLine(@"
{");
parentsCount++;
parentClass = parentClass.Child;
}
if (useNewtonsoftJson)
{
sb.AppendLine(EmbeddedSources.NewtonsoftJsonAttributeSource);
}
if (useSystemTextJson)
{
sb.AppendLine(EmbeddedSources.SystemTextJsonAttributeSource);
}
if (useTypeConverter)
{
sb.AppendLine(EmbeddedSources.TypeConverterAttributeSource);
}
sb.Append(resources.BaseId);
ReplaceInterfaces(sb, useIEquatable, useIComparable);
// IEquatable is already implemented whether or not the interface is implemented
if (useIComparable)
{
sb.AppendLine(resources.Comparable);
}
if (useEfCoreValueConverter)
{
sb.AppendLine(resources.EfCoreValueConverter);
}
if (useDapperTypeHandler)
{
sb.AppendLine(resources.DapperTypeHandler);
}
if (useTypeConverter)
{
sb.AppendLine(resources.TypeConverter);
}
if (useNewtonsoftJson)
{
sb.AppendLine(resources.Newtonsoft);
}
if (useSystemTextJson)
{
sb.AppendLine(resources.SystemTextJson);
}
sb.Replace("TESTID", idName);
sb.AppendLine(@" }");
for (int i = 0; i < parentsCount; i++)
{
sb.AppendLine(@" }");
}
if (hasNamespace)
{
sb.Append('}').AppendLine();
}
return sb.ToString();
}
private static void ReplaceInterfaces(StringBuilder sb, bool useIEquatable, bool useIComparable)
{
var interfaces = new List<string>();
if (useIComparable)
{
interfaces.Add("System.IComparable<TESTID>");
}
if (useIEquatable)
{
interfaces.Add("System.IEquatable<TESTID>");
}
if (interfaces.Count > 0)
{
sb.Replace("INTERFACES", string.Join(", ", interfaces));
}
else
{
sb.Replace(": INTERFACES", string.Empty);
}
}
}
} | 33.765 | 146 | 0.558567 | [
"MIT"
] | Khitiara/StronglyTypedId | src/StronglyTypedIds/SourceGenerationHelper.cs | 6,753 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Time_Sheet_Buddy.Data;
namespace Time_Sheet_Buddy.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20210812204006_List instead of IEnumerable of the Issues in the Backlog")]
partial class ListinsteadofIEnumerableoftheIssuesintheBacklog
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasDefaultSchema("Identity")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.8")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex")
.HasFilter("[NormalizedName] IS NOT NULL");
b.ToTable("Role");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("RoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("UserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(450)");
b.Property<string>("ProviderKey")
.HasColumnType("nvarchar(450)");
b.Property<string>("ProviderDisplayName")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("UserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("RoleId")
.HasColumnType("nvarchar(450)");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("UserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(450)");
b.Property<string>("Name")
.HasColumnType("nvarchar(450)");
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("UserTokens");
});
modelBuilder.Entity("Time_Sheet_Buddy.Entities.Backlog", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.HasKey("Id");
b.ToTable("Backlogs");
});
modelBuilder.Entity("Time_Sheet_Buddy.Entities.Issue", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("AssignedTo")
.HasColumnType("nvarchar(max)");
b.Property<string>("Assignee")
.HasColumnType("nvarchar(max)");
b.Property<int?>("BacklogId")
.HasColumnType("int");
b.Property<DateTime>("Date")
.HasColumnType("datetime2");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<double>("Duration")
.HasColumnType("float");
b.Property<string>("Project")
.HasColumnType("nvarchar(max)");
b.Property<string>("State")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Title")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("BacklogId");
b.ToTable("Issue");
});
modelBuilder.Entity("Time_Sheet_Buddy.Entities.Projectcs", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.HasKey("Id");
b.ToTable("Projectcs");
});
modelBuilder.Entity("Time_Sheet_Buddy.Entities.Stete", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.HasKey("Id");
b.ToTable("Stetes");
});
modelBuilder.Entity("Time_Sheet_Buddy.Models.ApplicationUser", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("bit");
b.Property<string>("FirstName")
.HasColumnType("nvarchar(max)");
b.Property<string>("LastName")
.HasColumnType("nvarchar(max)");
b.Property<bool>("LockoutEnabled")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("datetimeoffset");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<string>("PasswordHash")
.HasColumnType("nvarchar(max)");
b.Property<string>("PhoneNumber")
.HasColumnType("nvarchar(max)");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("bit");
b.Property<byte[]>("ProfilePicture")
.HasColumnType("varbinary(max)");
b.Property<string>("SecurityStamp")
.HasColumnType("nvarchar(max)");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("bit");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<int>("UsernameChangeLimit")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex")
.HasFilter("[NormalizedUserName] IS NOT NULL");
b.ToTable("User");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Time_Sheet_Buddy.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Time_Sheet_Buddy.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Time_Sheet_Buddy.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Time_Sheet_Buddy.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Time_Sheet_Buddy.Entities.Issue", b =>
{
b.HasOne("Time_Sheet_Buddy.Entities.Backlog", null)
.WithMany("Issues")
.HasForeignKey("BacklogId");
});
modelBuilder.Entity("Time_Sheet_Buddy.Entities.Backlog", b =>
{
b.Navigation("Issues");
});
#pragma warning restore 612, 618
}
}
}
| 37.415816 | 125 | 0.463489 | [
"MIT"
] | kostadinmarkov99/Time_Sheet_Buddy | Time_Sheet_Buddy/Migrations/20210812204006_List instead of IEnumerable of the Issues in the Backlog.Designer.cs | 14,669 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static unsafe partial class Kernel32
{
internal const uint LOCALE_ALLOW_NEUTRAL_NAMES = 0x08000000; // Flag to allow returning neutral names/lcids for name conversion
internal const uint LOCALE_ILANGUAGE = 0x00000001;
internal const uint LOCALE_SUPPLEMENTAL = 0x00000002;
internal const uint LOCALE_REPLACEMENT = 0x00000008;
internal const uint LOCALE_NEUTRALDATA = 0x00000010;
internal const uint LOCALE_SPECIFICDATA = 0x00000020;
internal const uint LOCALE_SISO3166CTRYNAME = 0x0000005A;
internal const uint LOCALE_SNAME = 0x0000005C;
internal const uint LOCALE_INEUTRAL = 0x00000071;
internal const uint LOCALE_SSHORTTIME = 0x00000079;
internal const uint LOCALE_STIMEFORMAT = 0x00001003;
internal const uint LOCALE_IFIRSTDAYOFWEEK = 0x0000100C;
internal const uint LOCALE_RETURN_NUMBER = 0x20000000;
internal const uint LOCALE_NOUSEROVERRIDE = 0x80000000;
internal const int COMPARE_STRING = 0x0001;
internal const uint TIME_NOSECONDS = 0x00000002;
internal const string LOCALE_NAME_USER_DEFAULT = null;
internal const string LOCALE_NAME_SYSTEM_DEFAULT = "!x-sys-default-locale";
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal static extern unsafe int LCIDToLocaleName(int locale, char *pLocaleName, int cchName, uint dwFlags);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal static extern int LocaleNameToLCID(string lpName, uint dwFlags);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal static extern unsafe int LCMapStringEx(
string? lpLocaleName,
uint dwMapFlags,
char* lpSrcStr,
int cchSrc,
void* lpDestStr,
int cchDest,
void* lpVersionInformation,
void* lpReserved,
IntPtr sortHandle);
[DllImport("kernel32.dll", EntryPoint = "FindNLSStringEx")]
internal static extern unsafe int FindNLSStringEx(
char* lpLocaleName,
uint dwFindNLSStringFlags,
char* lpStringSource,
int cchSource,
char* lpStringValue,
int cchValue,
int* pcchFound,
void* lpVersionInformation,
void* lpReserved,
IntPtr sortHandle);
[DllImport("kernel32.dll", EntryPoint = "CompareStringEx")]
internal static extern unsafe int CompareStringEx(
char* lpLocaleName,
uint dwCmpFlags,
char* lpString1,
int cchCount1,
char* lpString2,
int cchCount2,
void* lpVersionInformation,
void* lpReserved,
IntPtr lParam);
[DllImport("kernel32.dll", EntryPoint = "CompareStringOrdinal")]
internal static extern unsafe int CompareStringOrdinal(
char* lpString1,
int cchCount1,
char* lpString2,
int cchCount2,
bool bIgnoreCase);
[DllImport("kernel32.dll", EntryPoint = "FindStringOrdinal")]
internal static extern unsafe int FindStringOrdinal(
uint dwFindStringOrdinalFlags,
char* lpStringSource,
int cchSource,
char* lpStringValue,
int cchValue,
int bIgnoreCase);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal static extern unsafe bool IsNLSDefinedString(
int Function,
uint dwFlags,
IntPtr lpVersionInformation,
char* lpString,
int cchStr);
#if !ENABLE_WINRT
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
internal static extern Interop.BOOL GetUserPreferredUILanguages(uint dwFlags, uint* pulNumLanguages, char* pwszLanguagesBuffer, uint* pcchLanguagesBuffer);
#endif //!ENABLE_WINRT
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal static extern int GetLocaleInfoEx(string lpLocaleName, uint LCType, void* lpLCData, int cchData);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal static extern bool EnumSystemLocalesEx(EnumLocalesProcEx lpLocaleEnumProcEx, uint dwFlags, void* lParam, IntPtr reserved);
internal delegate BOOL EnumLocalesProcEx(char* lpLocaleString, uint dwFlags, void* lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal static extern bool EnumTimeFormatsEx(EnumTimeFormatsProcEx lpTimeFmtEnumProcEx, string lpLocaleName, uint dwFlags, void* lParam);
internal delegate BOOL EnumTimeFormatsProcEx(char* lpTimeFormatString, void* lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal static extern int GetCalendarInfoEx(string? lpLocaleName, uint Calendar, IntPtr lpReserved, uint CalType, IntPtr lpCalData, int cchData, out int lpValue);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal static extern int GetCalendarInfoEx(string? lpLocaleName, uint Calendar, IntPtr lpReserved, uint CalType, IntPtr lpCalData, int cchData, IntPtr lpValue);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal static extern bool EnumCalendarInfoExEx(EnumCalendarInfoProcExEx pCalInfoEnumProcExEx, string lpLocaleName, uint Calendar, string? lpReserved, uint CalType, void* lParam);
internal delegate BOOL EnumCalendarInfoProcExEx(char* lpCalendarInfoString, uint Calendar, IntPtr lpReserved, void* lParam);
[StructLayout(LayoutKind.Sequential)]
internal struct NlsVersionInfoEx
{
internal int dwNLSVersionInfoSize;
internal int dwNLSVersion;
internal int dwDefinedVersion;
internal int dwEffectiveId;
internal Guid guidCustomVersion;
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal static extern unsafe bool GetNLSVersionEx(int function, string localeName, NlsVersionInfoEx* lpVersionInformation);
}
}
| 47.486301 | 188 | 0.632338 | [
"MIT"
] | 85331479/coreclr | src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Globalization.cs | 6,933 | C# |
using System;
using System.IO;
using System.Text;
using Itage.MimeHtml2Html;
using McMaster.Extensions.CommandLineUtils;
using Microsoft.Extensions.Logging;
namespace Mime2Html
{
internal class Program
{
[Argument(0)] private string Source { get; } = null!;
private static void Main(string[] args) => CommandLineApplication.Execute<Program>(args);
// ReSharper disable once UnusedMember.Local
private void OnExecute()
{
Console.OutputEncoding = Encoding.Unicode;
ILoggerFactory loggerFactory = LoggerFactory.Create(o => { o.AddConsole().SetMinimumLevel(LogLevel.Debug); });
var conversionOptions = new MimeConversionOptions
{
CompressCss = true,
CompressHtml = true,
CompressImages = true,
JpegCompressorQuality = 100,
MaxPngColors = 256
};
var converter = new MimeConverter(conversionOptions, loggerFactory.CreateLogger<MimeConverter>());
string outputFilename = Path.ChangeExtension(Source, "html");
using FileStream sourceStream = File.OpenRead(Source);
using FileStream destinationStream = File.Open(outputFilename, FileMode.Create);
bool result = converter.Convert(sourceStream, destinationStream).Result;
if (!result)
{
Environment.Exit(-1);
}
}
}
} | 36.825 | 122 | 0.622539 | [
"MIT"
] | itage-biz/MimeHtml2Html | src/Mime2Html/Program.cs | 1,475 | C# |
// Copyright (c) 2018 Siegfried Pammer
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace ICSharpCode.Decompiler.Metadata
{
public enum TargetFrameworkIdentifier
{
NETFramework,
NETCoreApp,
NETStandard,
Silverlight
}
enum DecompilerRuntime
{
NETFramework,
NETCoreApp,
Mono
}
/// <summary>
/// Used to resolve assemblies referenced by an assembly.
/// </summary>
public class UniversalAssemblyResolver : AssemblyReferenceClassifier, IAssemblyResolver
{
static UniversalAssemblyResolver()
{
// TODO : test whether this works with Mono on *Windows*, not sure if we'll
// ever need this...
if (Type.GetType("Mono.Runtime") != null)
decompilerRuntime = DecompilerRuntime.Mono;
else if (typeof(object).Assembly.GetName().Name == "System.Private.CoreLib")
decompilerRuntime = DecompilerRuntime.NETCoreApp;
else if (Environment.OSVersion.Platform == PlatformID.Unix)
decompilerRuntime = DecompilerRuntime.Mono;
}
DotNetCorePathFinder dotNetCorePathFinder;
readonly bool throwOnError;
readonly PEStreamOptions streamOptions;
readonly MetadataReaderOptions metadataOptions;
readonly string mainAssemblyFileName;
readonly string baseDirectory;
readonly List<string> directories = new List<string>();
static readonly List<string> gac_paths = GetGacPaths();
static readonly DecompilerRuntime decompilerRuntime;
public void AddSearchDirectory(string directory)
{
directories.Add(directory);
dotNetCorePathFinder?.AddSearchDirectory(directory);
}
public void RemoveSearchDirectory(string directory)
{
directories.Remove(directory);
dotNetCorePathFinder?.RemoveSearchDirectory(directory);
}
public string[] GetSearchDirectories()
{
return directories.ToArray();
}
readonly string targetFramework;
readonly string runtimePack;
readonly TargetFrameworkIdentifier targetFrameworkIdentifier;
readonly Version targetFrameworkVersion;
/// <summary>
/// Creates a new instance of the <see cref="UniversalAssemblyResolver"/>.
/// </summary>
/// <param name="mainAssemblyFileName">
/// The full path to the "main assembly" (i.e., the assembly being decompiled). This is used to
/// resolve assemblies that are located next the main assembly. If no full path is used, the resolver
/// falls back to using <see cref="Environment.CurrentDirectory"/>.
/// </param>
/// <param name="throwOnError">
/// If <see langword="true"/> an <see cref="AssemblyResolutionException"/> is thrown, in case the
/// assembly reference cannot be resolved.
/// </param>
/// <param name="targetFramework">
/// The target framework name as used by <see cref="System.Runtime.Versioning.TargetFrameworkAttribute"/>.
/// That is, "{framework},Version={version}": currently it supports ".NETCoreApp", ".NETStandard" and
/// "Silverlight", if the string doesn't match any of these, the resolver falls back to ".NET Framework",
/// which is "classic" .NET <= 4.8.
/// </param>
/// <param name="runtimePack">
/// Identifier of the runtime pack this assembly was compiled for.
/// If omitted, falling back to "Microsoft.NETCore.App" and this is ignored in case of classic .NET</param>
/// <param name="streamOptions">Options used for the <see cref="PEReader"/>.</param>
/// <param name="metadataOptions">Options used for the <see cref="MetadataReader"/>.</param>
public UniversalAssemblyResolver(string mainAssemblyFileName, bool throwOnError, string targetFramework,
string runtimePack = null, PEStreamOptions streamOptions = PEStreamOptions.Default, MetadataReaderOptions metadataOptions = MetadataReaderOptions.Default)
{
this.mainAssemblyFileName = mainAssemblyFileName;
this.throwOnError = throwOnError;
this.streamOptions = streamOptions;
this.metadataOptions = metadataOptions;
this.targetFramework = targetFramework ?? string.Empty;
this.runtimePack = runtimePack ?? "Microsoft.NETCore.App";
(targetFrameworkIdentifier, targetFrameworkVersion) = ParseTargetFramework(this.targetFramework);
if (mainAssemblyFileName != null)
{
string baseDirectory = Path.GetDirectoryName(mainAssemblyFileName);
if (string.IsNullOrWhiteSpace(this.baseDirectory))
this.baseDirectory = Environment.CurrentDirectory;
AddSearchDirectory(baseDirectory);
}
}
internal static (TargetFrameworkIdentifier, Version) ParseTargetFramework(string targetFramework)
{
string[] tokens = targetFramework.Split(',');
TargetFrameworkIdentifier identifier;
switch (tokens[0].Trim().ToUpperInvariant())
{
case ".NETCOREAPP":
identifier = TargetFrameworkIdentifier.NETCoreApp;
break;
case ".NETSTANDARD":
identifier = TargetFrameworkIdentifier.NETStandard;
break;
case "SILVERLIGHT":
identifier = TargetFrameworkIdentifier.Silverlight;
break;
default:
identifier = TargetFrameworkIdentifier.NETFramework;
break;
}
Version version = null;
for (int i = 1; i < tokens.Length; i++)
{
var pair = tokens[i].Trim().Split('=');
if (pair.Length != 2)
continue;
switch (pair[0].Trim().ToUpperInvariant())
{
case "VERSION":
var versionString = pair[1].TrimStart('v', ' ', '\t');
if (identifier == TargetFrameworkIdentifier.NETCoreApp ||
identifier == TargetFrameworkIdentifier.NETStandard)
{
if (versionString.Length == 3)
versionString += ".0";
}
if (!Version.TryParse(versionString, out version))
version = null;
break;
}
}
return (identifier, version ?? ZeroVersion);
}
#if !VSADDIN
public PEFile Resolve(IAssemblyReference name)
{
var file = FindAssemblyFile(name);
if (file == null)
{
if (throwOnError)
throw new AssemblyResolutionException(name);
return null;
}
return new PEFile(file, new FileStream(file, FileMode.Open, FileAccess.Read), streamOptions, metadataOptions);
}
public PEFile ResolveModule(PEFile mainModule, string moduleName)
{
string baseDirectory = Path.GetDirectoryName(mainModule.FileName);
string moduleFileName = Path.Combine(baseDirectory, moduleName);
if (!File.Exists(moduleFileName))
{
if (throwOnError)
throw new Exception($"Module {moduleName} could not be found!");
return null;
}
return new PEFile(moduleFileName, new FileStream(moduleFileName, FileMode.Open, FileAccess.Read), streamOptions, metadataOptions);
}
public Task<PEFile> ResolveAsync(IAssemblyReference name)
{
return Task.Run(() => Resolve(name));
}
public Task<PEFile> ResolveModuleAsync(PEFile mainModule, string moduleName)
{
return Task.Run(() => ResolveModule(mainModule, moduleName));
}
#endif
public override bool IsSharedAssembly(IAssemblyReference reference, out string runtimePack)
{
return dotNetCorePathFinder.TryResolveDotNetCoreShared(reference, out runtimePack) != null;
}
public string FindAssemblyFile(IAssemblyReference name)
{
if (name.IsWindowsRuntime)
{
return FindWindowsMetadataFile(name);
}
string file;
switch (targetFrameworkIdentifier)
{
case TargetFrameworkIdentifier.NETCoreApp:
case TargetFrameworkIdentifier.NETStandard:
if (IsZeroOrAllOnes(targetFrameworkVersion))
goto default;
if (dotNetCorePathFinder == null)
{
if (mainAssemblyFileName == null)
dotNetCorePathFinder = new DotNetCorePathFinder(targetFrameworkIdentifier, targetFrameworkVersion, runtimePack);
else
dotNetCorePathFinder = new DotNetCorePathFinder(mainAssemblyFileName, targetFramework, runtimePack, targetFrameworkIdentifier, targetFrameworkVersion);
foreach (var directory in directories)
{
dotNetCorePathFinder.AddSearchDirectory(directory);
}
}
file = dotNetCorePathFinder.TryResolveDotNetCore(name);
if (file != null)
return file;
goto default;
case TargetFrameworkIdentifier.Silverlight:
if (IsZeroOrAllOnes(targetFrameworkVersion))
goto default;
file = ResolveSilverlight(name, targetFrameworkVersion);
if (file != null)
return file;
goto default;
default:
return ResolveInternal(name);
}
}
string FindWindowsMetadataFile(IAssemblyReference name)
{
// Finding Windows Metadata (winmd) is currently only supported on Windows.
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
return null;
// TODO : Find a way to detect the base directory for the required Windows SDK.
string basePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Windows Kits", "10", "References");
if (!Directory.Exists(basePath))
return FindWindowsMetadataInSystemDirectory(name);
// TODO : Find a way to detect the required Windows SDK version.
var di = new DirectoryInfo(basePath);
basePath = null;
foreach (var versionFolder in di.EnumerateDirectories())
{
basePath = versionFolder.FullName;
}
if (basePath == null)
return FindWindowsMetadataInSystemDirectory(name);
basePath = Path.Combine(basePath, name.Name);
if (!Directory.Exists(basePath))
return FindWindowsMetadataInSystemDirectory(name);
basePath = Path.Combine(basePath, FindClosestVersionDirectory(basePath, name.Version));
if (!Directory.Exists(basePath))
return FindWindowsMetadataInSystemDirectory(name);
string file = Path.Combine(basePath, name.Name + ".winmd");
if (!File.Exists(file))
return FindWindowsMetadataInSystemDirectory(name);
return file;
}
string FindWindowsMetadataInSystemDirectory(IAssemblyReference name)
{
string file = Path.Combine(Environment.SystemDirectory, "WinMetadata", name.Name + ".winmd");
if (File.Exists(file))
return file;
return null;
}
/// <summary>
/// This only works on Windows
/// </summary>
string ResolveSilverlight(IAssemblyReference name, Version version)
{
string[] targetFrameworkSearchPaths = {
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Microsoft Silverlight"),
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Microsoft Silverlight")
};
foreach (var baseDirectory in targetFrameworkSearchPaths)
{
if (!Directory.Exists(baseDirectory))
continue;
var versionDirectory = Path.Combine(baseDirectory, FindClosestVersionDirectory(baseDirectory, version));
var file = SearchDirectory(name, versionDirectory);
if (file != null)
return file;
}
return null;
}
string FindClosestVersionDirectory(string basePath, Version version)
{
string path = null;
foreach (var folder in new DirectoryInfo(basePath).GetDirectories().Select(d => DotNetCorePathFinder.ConvertToVersion(d.Name))
.Where(v => v.Item1 != null).OrderByDescending(v => v.Item1))
{
if (path == null || folder.Item1 >= version)
path = folder.Item2;
}
return path ?? version.ToString();
}
string ResolveInternal(IAssemblyReference name)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
var assembly = SearchDirectory(name, directories);
if (assembly != null)
return assembly;
var framework_dir = Path.GetDirectoryName(typeof(object).Module.FullyQualifiedName);
var framework_dirs = decompilerRuntime == DecompilerRuntime.Mono
? new[] { framework_dir, Path.Combine(framework_dir, "Facades") }
: new[] { framework_dir };
if (IsSpecialVersionOrRetargetable(name))
{
assembly = SearchDirectory(name, framework_dirs);
if (assembly != null)
return assembly;
}
if (name.Name == "mscorlib")
{
assembly = GetCorlib(name);
if (assembly != null)
return assembly;
}
assembly = GetAssemblyInGac(name);
if (assembly != null)
return assembly;
// when decompiling assemblies that target frameworks prior to 4.0, we can fall back to the 4.0 assemblies in case the target framework is not installed.
// but when looking for Microsoft.Build.Framework, Version=15.0.0.0 we should not use the version 4.0 assembly here so that the LoadedAssembly logic can instead fall back to version 15.1.0.0
if (name.Version <= new Version(4, 0, 0, 0))
{
assembly = SearchDirectory(name, framework_dirs);
if (assembly != null)
return assembly;
}
if (throwOnError)
throw new AssemblyResolutionException(name);
return null;
}
#region .NET / mono GAC handling
string SearchDirectory(IAssemblyReference name, IEnumerable<string> directories)
{
foreach (var directory in directories)
{
string file = SearchDirectory(name, directory);
if (file != null)
return file;
}
return null;
}
static bool IsSpecialVersionOrRetargetable(IAssemblyReference reference)
{
return IsZeroOrAllOnes(reference.Version) || reference.IsRetargetable;
}
string SearchDirectory(IAssemblyReference name, string directory)
{
var extensions = name.IsWindowsRuntime ? new[] { ".winmd", ".dll" } : new[] { ".dll", ".exe" };
foreach (var extension in extensions)
{
string file = Path.Combine(directory, name.Name + extension);
if (!File.Exists(file))
continue;
try
{
return file;
}
catch (BadImageFormatException)
{
continue;
}
}
return null;
}
static bool IsZeroOrAllOnes(Version version)
{
return version == null
|| (version.Major == 0 && version.Minor == 0 && version.Build == 0 && version.Revision == 0)
|| (version.Major == 65535 && version.Minor == 65535 && version.Build == 65535 && version.Revision == 65535);
}
internal static Version ZeroVersion = new Version(0, 0, 0, 0);
string GetCorlib(IAssemblyReference reference)
{
var version = reference.Version;
var corlib = typeof(object).Assembly.GetName();
if (decompilerRuntime != DecompilerRuntime.NETCoreApp)
{
if (corlib.Version == version || IsSpecialVersionOrRetargetable(reference))
return typeof(object).Module.FullyQualifiedName;
}
if (reference.PublicKeyToken == null)
return null;
string path;
if (decompilerRuntime == DecompilerRuntime.Mono)
{
path = GetMonoMscorlibBasePath(version);
}
else
{
path = GetMscorlibBasePath(version, reference.PublicKeyToken.ToHexString(8));
}
if (path == null)
return null;
var file = Path.Combine(path, "mscorlib.dll");
if (File.Exists(file))
return file;
return null;
}
string GetMscorlibBasePath(Version version, string publicKeyToken)
{
string GetSubFolderForVersion()
{
switch (version.Major)
{
case 1:
if (version.MajorRevision == 3300)
return "v1.0.3705";
return "v1.1.4322";
case 2:
return "v2.0.50727";
case 4:
return "v4.0.30319";
default:
if (throwOnError)
throw new NotSupportedException("Version not supported: " + version);
return null;
}
}
if (publicKeyToken == "969db8053d3322ac")
{
string programFiles = Environment.Is64BitOperatingSystem ?
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) :
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
string cfPath = $@"Microsoft.NET\SDK\CompactFramework\v{version.Major}.{version.Minor}\WindowsCE\";
string cfBasePath = Path.Combine(programFiles, cfPath);
if (Directory.Exists(cfBasePath))
return cfBasePath;
}
else
{
string rootPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET");
string[] frameworkPaths = new[] {
Path.Combine(rootPath, "Framework"),
Path.Combine(rootPath, "Framework64")
};
string folder = GetSubFolderForVersion();
if (folder != null)
{
foreach (var path in frameworkPaths)
{
var basePath = Path.Combine(path, folder);
if (Directory.Exists(basePath))
return basePath;
}
}
}
if (throwOnError)
throw new NotSupportedException("Version not supported: " + version);
return null;
}
string GetMonoMscorlibBasePath(Version version)
{
var path = Directory.GetParent(typeof(object).Module.FullyQualifiedName).Parent.FullName;
if (version.Major == 1)
path = Path.Combine(path, "1.0");
else if (version.Major == 2)
{
if (version.MajorRevision == 5)
path = Path.Combine(path, "2.1");
else
path = Path.Combine(path, "2.0");
}
else if (version.Major == 4)
path = Path.Combine(path, "4.0");
else
{
if (throwOnError)
throw new NotSupportedException("Version not supported: " + version);
return null;
}
return path;
}
public static List<string> GetGacPaths()
{
if (decompilerRuntime == DecompilerRuntime.Mono)
return GetDefaultMonoGacPaths();
var paths = new List<string>(2);
var windir = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
if (windir == null)
return paths;
paths.Add(Path.Combine(windir, "assembly"));
paths.Add(Path.Combine(windir, "Microsoft.NET", "assembly"));
return paths;
}
static List<string> GetDefaultMonoGacPaths()
{
var paths = new List<string>(1);
var gac = GetCurrentMonoGac();
if (gac != null)
paths.Add(gac);
var gac_paths_env = Environment.GetEnvironmentVariable("MONO_GAC_PREFIX");
if (string.IsNullOrEmpty(gac_paths_env))
return paths;
var prefixes = gac_paths_env.Split(Path.PathSeparator);
foreach (var prefix in prefixes)
{
if (string.IsNullOrEmpty(prefix))
continue;
var gac_path = Path.Combine(Path.Combine(Path.Combine(prefix, "lib"), "mono"), "gac");
if (Directory.Exists(gac_path) && !paths.Contains(gac))
paths.Add(gac_path);
}
return paths;
}
static string GetCurrentMonoGac()
{
return Path.Combine(
Directory.GetParent(
Path.GetDirectoryName(typeof(object).Module.FullyQualifiedName)).FullName,
"gac");
}
public static string GetAssemblyInGac(IAssemblyReference reference)
{
if (reference.PublicKeyToken == null || reference.PublicKeyToken.Length == 0)
return null;
if (decompilerRuntime == DecompilerRuntime.Mono)
return GetAssemblyInMonoGac(reference);
return GetAssemblyInNetGac(reference);
}
static string GetAssemblyInMonoGac(IAssemblyReference reference)
{
for (int i = 0; i < gac_paths.Count; i++)
{
var gac_path = gac_paths[i];
var file = GetAssemblyFile(reference, string.Empty, gac_path);
if (File.Exists(file))
return file;
}
return null;
}
static string GetAssemblyInNetGac(IAssemblyReference reference)
{
var gacs = new[] { "GAC_MSIL", "GAC_32", "GAC_64", "GAC" };
var prefixes = new[] { string.Empty, "v4.0_" };
for (int i = 0; i < gac_paths.Count; i++)
{
for (int j = 0; j < gacs.Length; j++)
{
var gac = Path.Combine(gac_paths[i], gacs[j]);
var file = GetAssemblyFile(reference, prefixes[i], gac);
if (Directory.Exists(gac) && File.Exists(file))
return file;
}
}
return null;
}
static string GetAssemblyFile(IAssemblyReference reference, string prefix, string gac)
{
var gac_folder = new StringBuilder()
.Append(prefix)
.Append(reference.Version)
.Append("__");
for (int i = 0; i < reference.PublicKeyToken.Length; i++)
gac_folder.Append(reference.PublicKeyToken[i].ToString("x2"));
return Path.Combine(
Path.Combine(
Path.Combine(gac, reference.Name), gac_folder.ToString()),
reference.Name + ".dll");
}
/// <summary>
/// Gets the names of all assemblies in the GAC.
/// </summary>
public static IEnumerable<AssemblyNameReference> EnumerateGac()
{
var gacs = new[] { "GAC_MSIL", "GAC_32", "GAC_64", "GAC" };
foreach (var path in GetGacPaths())
{
foreach (var gac in gacs)
{
string rootPath = Path.Combine(path, gac);
if (!Directory.Exists(rootPath))
continue;
foreach (var item in new DirectoryInfo(rootPath).EnumerateFiles("*.dll", SearchOption.AllDirectories))
{
string[] name = Path.GetDirectoryName(item.FullName).Substring(rootPath.Length + 1).Split(new[] { "\\" }, StringSplitOptions.RemoveEmptyEntries);
if (name.Length != 2)
continue;
var match = Regex.Match(name[1], $"(v4.0_)?(?<version>[^_]+)_(?<culture>[^_]+)?_(?<publicKey>[^_]+)");
if (!match.Success)
continue;
string culture = match.Groups["culture"].Value;
if (string.IsNullOrEmpty(culture))
culture = "neutral";
yield return AssemblyNameReference.Parse(name[0] + ", Version=" + match.Groups["version"].Value + ", Culture=" + culture + ", PublicKeyToken=" + match.Groups["publicKey"].Value);
}
}
}
}
#endregion
}
}
| 31.478571 | 193 | 0.700749 | [
"MIT"
] | CreateAndInject/ILSpy | ICSharpCode.Decompiler/Metadata/UniversalAssemblyResolver.cs | 22,037 | C# |
// ************************************************************************
//
// * Copyright 2017 OSIsoft, LLC
// * Licensed under the Apache License, Version 2.0 (the "License");
// * you may not use this file except in compliance with the License.
// * You may obtain a copy of the License at
// *
// * <http://www.apache.org/licenses/LICENSE-2.0>
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// ************************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PIWebAPIWrapper.Client
{
public class ExtensionMethods
{
public static List<string> ConvertToList(string text)
{
return text.Split(',').ToList();
}
}
}
| 32.333333 | 77 | 0.592315 | [
"Apache-2.0"
] | jdryden-osi/PI-Web-API-Client-VBA | src/PIWebApiWrapper/PIWebApiWrapper/Client/ExtensionMethods.cs | 1,069 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("06.RemoveNumbersOddCount")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("06.RemoveNumbersOddCount")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ed113d21-3417-440a-99c9-86b2a8cf3657")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.405405 | 84 | 0.748065 | [
"MIT"
] | vassildinev/Data-Structures-and-Algorithms | 02.LinearDataStructuresHomework/06.RemoveNumbersOddCount/Properties/AssemblyInfo.cs | 1,424 | C# |
//#define SHOW_TDP_SETTINGS
using System;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using Logger = NHM.Common.Logger;
using NHMCore;
using NHMCore.Configs;
using NHMCore.Interfaces.DataVisualizer;
using NHMCore.Mining;
using NHMCore.Mining.Plugins;
using NHMCore.Mining.IdleChecking;
using NHMCore.Stats;
using NHMCore.Switching;
using NHMCore.Utils;
using static NHMCore.Translations;
using NiceHashMiner.Forms;
using NiceHashMiner.Forms.Components;
namespace NiceHashMiner
{
public partial class Form_Main : Form, FormHelpers.ICustomTranslate, IVersionDisplayer, IBalanceBTCDisplayer, IBalanceFiatDisplayer, IGlobalMiningRateDisplayer, IMiningProfitabilityDisplayer, INoInternetConnectionDisplayer
{
private bool _showWarningNiceHashData;
private bool _exitCalled = false;
//private bool _isDeviceDetectionInitialized = false;
// this is TEMP remove it as soon as possible
private DevicesListViewSpeedControl devicesListViewEnableControl1;
private bool _isManuallyStarted = false;
public Form_Main()
{
InitializeComponent();
CenterToScreen();
Icon = NHMCore.Properties.Resources.logo;
errorWarningProvider2.Icon = new IconEx(IconEx.SystemIcons.Warning, new Size(16, 16)).Icon; // SystemIcons.Warning;
labelWarningNotProfitableOrNoIntenret.Visible = false;
InitElevationWarning();
this.TopMost = ConfigManager.GeneralConfig.GUIWindowsAlwaysOnTop;
devicesListViewEnableControl1 = devicesMainBoard1.SpeedsControl;
FormHelpers.SubscribeAllControls(this);
Width = ConfigManager.GeneralConfig.MainFormSize.X;
Height = ConfigManager.GeneralConfig.MainFormSize.Y;
Text = ApplicationStateManager.Title;
notifyIcon1.Icon = NHMCore.Properties.Resources.logo;
notifyIcon1.Text = Application.ProductName + " v" + Application.ProductVersion +
"\n" + Tr("Double-click to restore...");
linkLabelNewVersion.Text = "";
InitMainConfigGuiData();
devicesMainBoard1.SecondPanelVisible = false;
labelDemoMode.DataBindings.AddSafeBinding("Visible", MiningState.Instance, nameof(MiningState.Instance.IsDemoMining), true, DataSourceUpdateMode.OnPropertyChanged);
labelDemoMode.BringToFront();
labelDemoMode.VisibleChanged += LabelDemoMode_VisibleChanged;
InitControlValidators();
FormHelpers.TranslateFormControls(this);
}
private void LabelDemoMode_VisibleChanged(object sender, EventArgs e)
{
if (labelDemoMode.Visible)
{
errorProvider1.SetError(textBoxBTCAddress, "");
errorProvider1.SetError(textBoxWorkerName, "");
}
else
{
textBoxBTCAddress_Validate();
textBoxWorkerName_Validate();
}
}
private void InitDataBindings()
{
comboBoxLocation.DataBindings.Add("SelectedIndex", ConfigManager.GeneralConfig, nameof(ConfigManager.GeneralConfig.ServiceLocation), false, DataSourceUpdateMode.OnPropertyChanged);
textBoxBTCAddress.DataBindings.AddSafeBinding("Text", ConfigManager.CredentialsSettings, nameof(ConfigManager.CredentialsSettings.BitcoinAddress), false, DataSourceUpdateMode.OnPropertyChanged);
textBoxWorkerName.DataBindings.AddSafeBinding("Text", ConfigManager.CredentialsSettings, nameof(ConfigManager.CredentialsSettings.WorkerName), false, DataSourceUpdateMode.OnPropertyChanged);
linkLabelCheckStats.DataBindings.AddSafeBinding("Enabled", ConfigManager.CredentialsSettings, nameof(ConfigManager.CredentialsSettings.IsCredentialsValid), false, DataSourceUpdateMode.OnPropertyChanged);
// mining /benchmarking
buttonPlugins.DataBindings.AddSafeBinding("Enabled", MiningState.Instance, nameof(MiningState.Instance.IsNotBenchmarkingOrMining), false, DataSourceUpdateMode.OnPropertyChanged);
textBoxBTCAddress.DataBindings.AddSafeBinding("Enabled", MiningState.Instance, nameof(MiningState.Instance.IsNotBenchmarkingOrMining), false, DataSourceUpdateMode.OnPropertyChanged);
textBoxWorkerName.DataBindings.AddSafeBinding("Enabled", MiningState.Instance, nameof(MiningState.Instance.IsNotBenchmarkingOrMining), false, DataSourceUpdateMode.OnPropertyChanged);
comboBoxLocation.DataBindings.AddSafeBinding("Enabled", MiningState.Instance, nameof(MiningState.Instance.IsNotBenchmarkingOrMining), false, DataSourceUpdateMode.OnPropertyChanged);
buttonBenchmark.DataBindings.AddSafeBinding("Enabled", MiningState.Instance, nameof(MiningState.Instance.IsNotBenchmarkingOrMining), false, DataSourceUpdateMode.OnPropertyChanged);
buttonSettings.DataBindings.AddSafeBinding("Enabled", MiningState.Instance, nameof(MiningState.Instance.IsNotBenchmarkingOrMining), false, DataSourceUpdateMode.OnPropertyChanged);
linkLabelAdminPrivs.DataBindings.AddSafeBinding("Enabled", MiningState.Instance, nameof(MiningState.Instance.IsNotBenchmarkingOrMining), false, DataSourceUpdateMode.OnPropertyChanged);
// start stop all
buttonStartMining.DataBindings.AddSafeBinding("Enabled", MiningState.Instance, nameof(MiningState.Instance.AnyDeviceStopped), false, DataSourceUpdateMode.OnPropertyChanged);
buttonStopMining.DataBindings.AddSafeBinding("Enabled", MiningState.Instance, nameof(MiningState.Instance.AnyDeviceRunning), false, DataSourceUpdateMode.OnPropertyChanged);
////labelDemoMode.DataBindings.Add("Enabled", MiningState.Instance, nameof(MiningState.Instance.IsDemoMining), false, DataSourceUpdateMode.OnPropertyChanged);
//labelDemoMode.DataBindings.Add("Visible", MiningState.Instance, nameof(MiningState.Instance.IsDemoMining), true, DataSourceUpdateMode.OnPropertyChanged);
devicesMainBoard1.DataBindings.AddSafeBinding(nameof(devicesMainBoard1.SecondPanelVisible), MiningState.Instance, nameof(MiningState.Instance.AnyDeviceRunning), false, DataSourceUpdateMode.OnPropertyChanged);
}
private void textBoxBTCAddress_Validate()
{
var trimmedBtcText = textBoxBTCAddress.Text.Trim();
var result = ApplicationStateManager.SetBTCIfValidOrDifferent(trimmedBtcText);
if (ApplicationStateManager.SetResult.INVALID == result)
{
errorProvider1.SetError(textBoxBTCAddress, Tr("Invalid Bitcoin address! {0} will start mining in DEMO mode. In the DEMO mode, you can test run the miner and be able see how much you can earn using your computer. Would you like to continue in DEMO mode?\n\nDISCLAIMER: YOU WILL NOT EARN ANYTHING DURING DEMO MODE!", NHMProductInfo.Name));
}
else
{
errorProvider1.SetError(textBoxBTCAddress, "");
}
}
private void textBoxWorkerName_Validate()
{
var trimmedWorkerNameText = textBoxWorkerName.Text.Trim();
var result = ApplicationStateManager.SetWorkerIfValidOrDifferent(trimmedWorkerNameText);
if (ApplicationStateManager.SetResult.INVALID == result)
{
errorProvider1.SetError(textBoxWorkerName, Tr("Invalid workername!\n\nPlease enter a valid workername (Aa-Zz, 0-9, up to 15 character long)."));
}
else
{
errorProvider1.SetError(textBoxWorkerName, "");
}
}
private void InitControlValidators()
{
textBoxBTCAddress.TextChanged += (s, e) => textBoxBTCAddress_Validate();
//textBoxBTCAddress.Validating += textBoxBTCAddress_TextChanged;
//textBoxBTCAddress.Validated += textBoxBTCAddress_TextChanged;
textBoxWorkerName.TextChanged += (s, e) => textBoxWorkerName_Validate();
//textBoxWorkerName.Validating += textBoxWorkerName_ValidateCorrect;
//textBoxWorkerName.Validated += textBoxWorkerName_ValidateCorrect;
}
void FormHelpers.ICustomTranslate.CustomTranslate()
{
MessageBoxManager.Unregister();
MessageBoxManager.Yes = Tr("&Yes");
MessageBoxManager.No = Tr("&No");
MessageBoxManager.OK = Tr("&OK");
MessageBoxManager.Cancel = Tr("&Cancel");
MessageBoxManager.Retry = Tr("&Retry");
MessageBoxManager.Register();
//??? doesn't get translated if we don't translate it directly????
toolStripStatusLabelGlobalRateText.Text = Tr("Global rate:");
toolStripStatusLabelBTCDayText.Text =
"BTC/" + Tr(ConfigManager.GeneralConfig.TimeUnit.ToString());
toolStripStatusLabelBalanceText.Text = RatesAndStatsStates.Instance.LabelBalanceText;
devicesListViewEnableControl1.InitLocale();
// this one here is probably redundant
labelDemoMode.Text = Tr("{0} is running in DEMO mode!", NHMProductInfo.Name);
toolTip1.SetToolTip(labelDemoMode, Tr("You have not entered a bitcoin address. {0} will start mining in DEMO mode. In the DEMO mode, you can test run the miner and be able see how much you can earn using your computer. Would you like to continue in DEMO mode?\n\nDISCLAIMER: YOU WILL NOT EARN ANYTHING DURING DEMO MODE!", NHMProductInfo.Name));
SetToolTip(Tr("User's bitcoin address for mining."),
textBoxBTCAddress, labelBitcoinAddress);
SetToolTip(Tr("To identify the user's computer."),
textBoxWorkerName, labelWorkerName);
SetToolTip(Tr("Sets the mining location. Choosing Hong Kong or Tokyo will add extra latency."),
comboBoxLocation, labelServiceLocation);
}
private void SetToolTip(string text, params Control[] controls)
{
foreach (var control in controls)
{
toolTip1.SetToolTip(control, text);
}
}
private void InitElevationWarning()
{
if (!Helpers.IsElevated && !ConfigManager.GeneralConfig.DisableDevicePowerModeSettings)
{
errorWarningProvider2.SetError(linkLabelAdminPrivs, Tr("Disabled NVIDIA power mode settings due to insufficient permissions. If you want to use this feature you need to run as Administrator."));
linkLabelAdminPrivs.Click += (s, e) =>
{
var dialogResult = MessageBox.Show(Tr("Click yes if you wish to run {0} as Administrator.", NHMProductInfo.Name),
Tr("Run as Administrator"),
MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (dialogResult == DialogResult.Yes)
RunAsAdmin.SelfElevate();
};
}
else
{
linkLabelAdminPrivs.Visible = false;
}
}
// InitMainConfigGuiData gets called after settings are changed and whatnot but this is a crude and tightly coupled way of doing things
private void InitMainConfigGuiData()
{
textBoxBTCAddress.Text = ConfigManager.CredentialsSettings.BitcoinAddress;
textBoxWorkerName.Text = ConfigManager.CredentialsSettings.WorkerName;
_showWarningNiceHashData = true;
// init active display currency after config load
ExchangeRateApi.ActiveDisplayCurrency = ConfigManager.GeneralConfig.DisplayCurrency;
toolStripStatusLabelBalanceDollarValue.Text = "(" + ExchangeRateApi.ActiveDisplayCurrency + ")";
toolStripStatusLabelBalanceText.Text = RatesAndStatsStates.Instance.LabelBalanceText;
devicesListViewEnableControl1.SetPayingColumns();
}
// TODO this has nothing to do with Mian_Form
private void IdleCheck(object sender, IdleChangedEventArgs e)
{
if (!ConfigManager.GeneralConfig.StartMiningWhenIdle || _isManuallyStarted) return;
// TODO set is mining here
if (MiningState.Instance.IsCurrentlyMining)
{
if (!e.IsIdle)
{
ApplicationStateManager.StopAllDevice();
Logger.Info("NICEHASH", "Resumed from idling");
}
}
else if (ApplicationStateManager.CurrentForm == ApplicationStateManager.CurrentFormState.Main && e.IsIdle)
{
Logger.Info("NICEHASH", "Entering idling state");
if (StartMining(false) != StartMiningReturnType.StartMining)
{
ApplicationStateManager.StopAllDevice();
}
}
}
private void SetChildFormCenter(Form form)
{
form.StartPosition = FormStartPosition.Manual;
form.Location = new Point(Location.X + (Width - form.Width) / 2, Location.Y + (Height - form.Height) / 2);
}
private async void Form_Main_Shown(object sender, EventArgs e)
{
//// TODO temporary hooks
ApplicationStateManager._ratesComunication = devicesListViewEnableControl1;
// handle these callbacks differently
NiceHashStats.OnConnectionLost += ConnectionLostCallback;
NiceHashStats.OnExchangeUpdate += UpdateExchange;
foreach (Control c in Controls)
{
c.Enabled = false;
}
using (var loadingControl = new StartupLoadingControl(Tr("Loading, please wait...")))
{
Controls.Add(loadingControl);
var location = new Point((Width - loadingControl.Width) / 2, (int)((Height - loadingControl.Height) * 0.3));
loadingControl.Location = location;
loadingControl.BringToFront();
var progress = new Progress<(string loadMessageText, int perc)>(p =>
{
loadingControl.Progress = (int) p.perc;
loadingControl.LoadMessageText = p.loadMessageText;
});
var progressDownload = new Progress<(string loadMessageText, int perc)>(p =>
{
loadingControl.ProgressSecond = (int) p.perc;
loadingControl.LoadMessageTextSecond = p.loadMessageText;
});
await ApplicationStateManager.InitializeManagersAndMiners(loadingControl);
}
devicesListViewEnableControl1.SetComputeDevices(AvailableDevices.Devices.ToList());
foreach (Control c in Controls)
{
c.Enabled = true;
}
// Data bindings
InitDataBindings();
textBoxBTCAddress_Validate();
textBoxWorkerName_Validate();
if (ConfigManager.GeneralConfig.AutoStartMining)
{
// well this is started manually as we want it to start at runtime
_isManuallyStarted = true;
if (StartMining(false) != StartMiningReturnType.StartMining)
{
_isManuallyStarted = false;
ApplicationStateManager.StopAllDevice();
}
}
#if SHOW_TDP_SETTINGS
var form_TDP = new Form_TDPSettings();
form_TDP.Show();
#endif
}
private void UpdateGlobalRate(double totalRate)
{
var factorTimeUnit = TimeFactor.TimeUnit;
var scaleBTC = ConfigManager.GeneralConfig.AutoScaleBTCValues && totalRate < 0.1;
var totalDisplayRate = totalRate * factorTimeUnit * (scaleBTC ? 1000 : 1);
var displayTimeUnit = Tr(ConfigManager.GeneralConfig.TimeUnit.ToString());
toolStripStatusLabelBTCDayText.Text = scaleBTC ? $"mBTC/{displayTimeUnit}" : $"BTC/{displayTimeUnit}";
toolStripStatusLabelGlobalRateValue.Text = totalDisplayRate.ToString(scaleBTC ? "F5" : "F8", CultureInfo.InvariantCulture);
var timeFactorRate = ExchangeRateApi
.ConvertToActiveCurrency((totalRate * factorTimeUnit * ExchangeRateApi.GetUsdExchangeRate()));
toolStripStatusLabelBTCDayValue.Text = timeFactorRate.ToString("F2", CultureInfo.InvariantCulture);
toolStripStatusLabelBalanceText.Text = RatesAndStatsStates.Instance.LabelBalanceText;
}
private void UpdateExchange(object sender, EventArgs e)
{
FormHelpers.SafeInvoke(this, () =>
{
var br = ExchangeRateApi.GetUsdExchangeRate();
var currencyRate = Tr("N/A");
if (br > 0)
{
currencyRate = ExchangeRateApi.ConvertToActiveCurrency(br).ToString("F2");
}
toolTip1.SetToolTip(statusStrip1, $"1 BTC = {currencyRate} {ExchangeRateApi.ActiveDisplayCurrency}");
Logger.Info("NICEHASH", $"Current Bitcoin rate: {br.ToString("F2", CultureInfo.InvariantCulture)}");
});
}
private void ConnectionLostCallback(object sender, EventArgs e)
{
if (!NHSmaData.HasData && ConfigManager.GeneralConfig.ShowInternetConnectionWarning &&
_showWarningNiceHashData)
{
_showWarningNiceHashData = false;
var dialogResult = MessageBox.Show(Tr("{0} requires internet connection to run. Please ensure that you are connected to the internet before running {0}. Would you like to continue?", NHMProductInfo.Name),
Tr("Check internet connection"),
MessageBoxButtons.YesNo, MessageBoxIcon.Error);
if (dialogResult == DialogResult.Yes)
return;
if (dialogResult == DialogResult.No)
Application.Exit();
}
}
private void LinkLabelCheckStats_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
if (ConfigManager.CredentialsSettings.IsCredentialsValid == false) return;
ApplicationStateManager.VisitMiningStatsPage();
}
private void LinkLabelNewVersion_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
var isInstalled = UpdateHelpers.IsNHMInstalled();
if (!isInstalled)
{
ApplicationStateManager.VisitNewVersionUrl();
return;
}
using (var updaterForm = new Form_ChooseUpdate())
{
SetChildFormCenter(updaterForm);
ApplicationStateManager.CurrentForm = ApplicationStateManager.CurrentFormState.Update;
updaterForm.ShowDialog();
ApplicationStateManager.CurrentForm = ApplicationStateManager.CurrentFormState.Main;
}
}
private void ButtonBenchmark_Click(object sender, EventArgs e)
{
bool startMining = false;
using (var benchmarkForm = new Form_Benchmark())
{
SetChildFormCenter(benchmarkForm);
ApplicationStateManager.CurrentForm = ApplicationStateManager.CurrentFormState.Benchmark;
benchmarkForm.ShowDialog();
ApplicationStateManager.CurrentForm = ApplicationStateManager.CurrentFormState.Main;
startMining = benchmarkForm.StartMiningOnFinish;
}
InitMainConfigGuiData();
if (startMining)
{
ButtonStartMining_Click(null, null);
}
}
private void ButtonSettings_Click(object sender, EventArgs e)
{
using (var settings = new Form_Settings())
{
SetChildFormCenter(settings);
ApplicationStateManager.CurrentForm = ApplicationStateManager.CurrentFormState.Settings;
settings.ShowDialog();
ApplicationStateManager.CurrentForm = ApplicationStateManager.CurrentFormState.Main;
if (settings.IsRestartNeeded)
{
if (!settings.SetDefaults)
{
MessageBox.Show(
Tr("Settings change requires {0} to restart.", NHMProductInfo.Name),
Tr("Restart Notice"),
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
ApplicationStateManager.RestartProgram();
return;
}
}
InitMainConfigGuiData();
// TODO check this later
IdleCheckManager.StartIdleCheck(ConfigManager.GeneralConfig.IdleCheckType, IdleCheck);
}
private void ButtonStartMining_Click(object sender, EventArgs e)
{
_isManuallyStarted = true;
if (StartMining(true) == StartMiningReturnType.ShowNoMining)
{
_isManuallyStarted = false;
ApplicationStateManager.StopAllDevice();
MessageBox.Show(Tr("{0} cannot start mining. Make sure you have at least one enabled device that has at least one enabled and benchmarked algorithm.", NHMProductInfo.Name),
Tr("Warning!"),
MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void ButtonStopMining_Click(object sender, EventArgs e)
{
_isManuallyStarted = false;
ApplicationStateManager.StopAllDevice();
}
private void ButtonLogo_Click(object sender, EventArgs e)
{
Process.Start(Links.VisitUrl);
}
private void ButtonHelp_Click(object sender, EventArgs e)
{
Process.Start(Links.NhmHelp);
}
private void ToolStripStatusLabel10_Click(object sender, EventArgs e)
{
Process.Start(Links.NhmPayingFaq);
}
private void ToolStripStatusLabel10_MouseHover(object sender, EventArgs e)
{
statusStrip1.Cursor = Cursors.Hand;
}
private void ToolStripStatusLabel10_MouseLeave(object sender, EventArgs e)
{
statusStrip1.Cursor = Cursors.Default;
}
///////////////////////////////////////
// Miner control functions
private enum StartMiningReturnType
{
StartMining,
ShowNoMining,
IgnoreMsg
}
// TODO this thing needs to be completely removed
// TODO this will be moved outside of GUI code, replace textBoxBTCAddress.Text with ConfigManager.GeneralConfig.BitcoinAddress
private StartMiningReturnType StartMining(bool showWarnings)
{
//if (ConfigManager.GeneralConfig.BitcoinAddress.Equals(""))
//{
// if (showWarnings)
// {
// var result = MessageBox.Show(Tr("You have not entered a bitcoin address. {0} will start mining in DEMO mode. In the DEMO mode, you can test run the miner and be able see how much you can earn using your computer. Would you like to continue in DEMO mode?\n\nDISCLAIMER: YOU WILL NOT EARN ANYTHING DURING DEMO MODE!"),
// Tr("Start mining in DEMO mode?"),
// MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
// if (result == DialogResult.Yes)
// {
// _demoMode = true;
// //labelDemoMode.Visible = true;
// }
// else
// {
// return StartMiningReturnType.IgnoreMsg;
// }
// }
// else
// {
// return StartMiningReturnType.IgnoreMsg;
// }
//}
////else if (!VerifyMiningAddress(true)) return StartMiningReturnType.IgnoreMsg; // TODO this whole shitty thing
var hasData = NHSmaData.HasData;
if (!showWarnings)
{
for (var i = 0; i < 10; i++)
{
if (hasData) break;
Thread.Sleep(1000);
hasData = NHSmaData.HasData;
Logger.Info("NICEHASH", $"After {i}s has data: {hasData}");
}
}
if (!hasData)
{
Logger.Debug("NICEHASH", "No data received within timeout");
if (showWarnings)
{
MessageBox.Show(Tr("Unable to get NiceHash profitability data. If you are connected to internet, try again later."),
Tr("Error!"),
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return StartMiningReturnType.IgnoreMsg;
}
var isMining = true;
ApplicationStateManager.StartAllAvailableDevices();
return isMining ? StartMiningReturnType.StartMining : StartMiningReturnType.ShowNoMining;
}
private void Form_Main_ResizeEnd(object sender, EventArgs e)
{
ConfigManager.GeneralConfig.MainFormSize.X = Width;
ConfigManager.GeneralConfig.MainFormSize.Y = Height;
}
// StateDisplay interfaces
void IVersionDisplayer.DisplayVersion(object sender, string version)
{
FormHelpers.SafeInvoke(this, () =>
{
linkLabelNewVersion.Text = version;
errorWarningProvider2.SetError(linkLabelNewVersion, version);
});
}
// TODO this might need some formatters?
void IBalanceBTCDisplayer.DisplayBTCBalance(object sender, double btcBalance)
{
FormHelpers.SafeInvoke(this, () =>
{
if (ConfigManager.GeneralConfig.AutoScaleBTCValues && btcBalance < 0.1)
{
toolStripStatusLabelBalanceBTCCode.Text = "mBTC";
toolStripStatusLabelBalanceBTCValue.Text =
(btcBalance * 1000).ToString("F5", CultureInfo.InvariantCulture);
}
else
{
toolStripStatusLabelBalanceBTCCode.Text = "BTC";
toolStripStatusLabelBalanceBTCValue.Text = btcBalance.ToString("F6", CultureInfo.InvariantCulture);
}
});
}
void IBalanceFiatDisplayer.DisplayFiatBalance(object sender, (double fiatBalance, string fiatCurrencySymbol) args)
{
FormHelpers.SafeInvoke(this, () =>
{
toolStripStatusLabelBalanceDollarText.Text = args.fiatBalance.ToString("F2", CultureInfo.InvariantCulture);
toolStripStatusLabelBalanceDollarValue.Text = $"({args.fiatCurrencySymbol})";
});
}
void IGlobalMiningRateDisplayer.DisplayGlobalMiningRate(object sender, double totalMiningRate)
{
FormHelpers.SafeInvoke(this, () =>
{
UpdateGlobalRate(totalMiningRate);
});
}
//void IStartMiningDisplayer.DisplayMiningStarted(object sender, EventArgs _)
//{
// FormHelpers.SafeInvoke(this, () =>
// {
// //// Disable profitable notification on start
// //_isNotProfitable = false;
// HideWarning();
// });
//}
//void IStopMiningDisplayer.DisplayMiningStopped(object sender, EventArgs _)
//{
// FormHelpers.SafeInvoke(this, () =>
// {
// //// Disable IFTTT notification before label call
// //_isNotProfitable = false;
// labelDemoMode.Visible = false;
// _demoMode = false; // TODO this is logic
// UpdateGlobalRate(0);
// });
//}
private void ButtonPlugins_Click(object sender, EventArgs e)
{
using (var minerPluginsForm = new Form_MinerPlugins())
{
SetChildFormCenter(minerPluginsForm);
minerPluginsForm.ShowDialog();
}
}
private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
if (MouseButtons.Right == e.Button)
{
contextMenuStrip1.Show();
}
}
private void ExitToolStripMenuItem_Click(object sender, EventArgs e)
{
_exitCalled = true;
Application.Exit();
}
private void ToolStripMenuItemShow_Click(object sender, EventArgs e)
{
Show();
WindowState = FormWindowState.Normal;
notifyIcon1.Visible = false;
}
// Minimize to system tray if MinimizeToTray is set to true
private void Form1_Resize(object sender, EventArgs e)
{
if (ConfigManager.GeneralConfig.MinimizeToTray && FormWindowState.Minimized == WindowState)
{
notifyIcon1.Visible = true;
Hide();
}
}
// Restore NiceHashMiner from the system tray
private void NotifyIcon1_DoubleClick(object sender, EventArgs e)
{
Show();
WindowState = FormWindowState.Normal;
notifyIcon1.Visible = false;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing &&
ConfigManager.GeneralConfig.MinimizeToTray &&
!_exitCalled)
{
notifyIcon1.Visible = true;
Hide();
e.Cancel = true;
return;
}
FormHelpers.UnsubscribeAllControls(this);
ApplicationStateManager.BeforeExit();
MessageBoxManager.Unregister();
}
private bool _isProfitable = true;
private bool _noInternet = false;
void IMiningProfitabilityDisplayer.DisplayMiningProfitable(object sender, bool isProfitable)
{
if (ConfigManager.GeneralConfig.UseIFTTT)
{
if (isProfitable)
{
Ifttt.PostToIfttt("nicehash", "Mining is once again profitable and has resumed.");
}
else
{
Ifttt.PostToIfttt("nicehash", "Mining NOT profitable and has stopped.");
}
}
_isProfitable = isProfitable;
ShowOrHideWarningLabel(_isProfitable, _noInternet);
}
void INoInternetConnectionDisplayer.DisplayNoInternetConnection(object sender, bool noInternet)
{
_noInternet = noInternet;
ShowOrHideWarningLabel(_isProfitable, _noInternet);
}
private void ShowOrHideWarningLabel(bool isProfitable, bool noInternet)
{
FormHelpers.SafeInvoke(this, () => {
if (!isProfitable || noInternet)
{
var text = "";
if (!isProfitable)
{
text += Environment.NewLine + Tr("CURRENTLY MINING NOT PROFITABLE.");
}
if (noInternet)
{
text += Environment.NewLine + Tr("CURRENTLY NOT MINING. NO INTERNET CONNECTION.");
}
labelWarningNotProfitableOrNoIntenret.Text = text;
labelWarningNotProfitableOrNoIntenret.Visible = true;
}
else
{
labelWarningNotProfitableOrNoIntenret.Visible = false;
}
});
}
}
}
| 43.286479 | 356 | 0.606216 | [
"MIT"
] | hichamnimz80/NiceHashMiner | src/NiceHashMiner/Forms/Form_Main.cs | 32,335 | C# |
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using XrmToolBox.Extensibility;
using XrmToolBox.Extensibility.Interfaces;
namespace DLaB.XrmToolBoxCommon
{
public partial class DialogBase : Form, IWorkerHost
{
protected PluginControlBase CallingControl { get; set; }
protected IOrganizationService Service => CallingControl.Service;
public DialogBase()
{
InitializeComponent();
}
public DialogBase(PluginControlBase callingControl)
: this()
{
if (callingControl == null)
{
throw new ArgumentNullException(nameof(callingControl));
}
CallingControl = callingControl;
}
#region Helper Methods
protected void RetrieveEntityMetadatasOnLoad(Action<IEnumerable<EntityMetadata>> loadEntities)
{
var entities = ((PropertyInterface.IEntityMetadatas)CallingControl).EntityMetadatas;
if (entities == null)
{
_callBackForRetrieveEntityMetadatas = loadEntities;
ExecuteMethod(RetrieveEntities);
}
else
{
loadEntities(entities);
}
}
private Action<IEnumerable<EntityMetadata>> _callBackForRetrieveEntityMetadatas;
private void RetrieveEntities()
{
WorkAsync(new WorkAsyncInfo("Retrieving Entities...", e =>
{
e.Result = Service.Execute(new RetrieveAllEntitiesRequest {EntityFilters = EntityFilters.Entity, RetrieveAsIfPublished = true});
})
{
PostWorkCallBack = e =>
{
var entityContainer = ((PropertyInterface.IEntityMetadatas) CallingControl);
entityContainer.EntityMetadatas = ((RetrieveAllEntitiesResponse) e.Result).EntityMetadata;
_callBackForRetrieveEntityMetadatas(entityContainer.EntityMetadatas);
}
});
}
#endregion // Helper Methods
#region IWorkerHost Members
private readonly Worker _worker = new Worker();
public void SetWorkingMessage(string message, int width = 340, int height = 100)
{
_worker.SetWorkingMessage(this, message, width, height);
}
public void WorkAsync(WorkAsyncInfo info)
{
info.Host = this;
_worker.WorkAsync(info);
}
public void RaiseRequestConnectionEvent(RequestConnectionEventArgs args)
{
CallingControl.RaiseRequestConnectionEvent(args);
}
#endregion // IWorkerHost Members
/// <summary>
/// Checks to make sure that the Plugin has an IOrganizationService Connection, before calling the action.
/// </summary>
/// <param name="action"></param>
protected void ExecuteMethod(Action action)
{
AssertCallingControlExists();
CallingControl.ExecuteMethod(null, new ExternalMethodCallerInfo(action));
}
private void AssertCallingControlExists()
{
if (CallingControl == null) { throw new NullReferenceException("Use the \"DialogBase(PluginUserControlBase)\" Constructor"); }
}
}
}
| 32.224299 | 144 | 0.612529 | [
"MIT"
] | Bhawk90/DLaB.Xrm.XrmToolBoxTools | DLaB.XrmToolBoxCommon/DialogBase.cs | 3,450 | C# |
using DiExtension.SimpleInject;
using JohnLambe.Tests.JLUtilsTest;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test.DiExtensionTest
{
[TestClass]
public class ChainableContextTest
{
public ChainableContextTest()
{
_baseContext.RegisterInstance(typeof(TestClass), new TestClass() { X = "A" });
_context = new ChainableContext(_baseContext);
}
/// <summary>
/// Resolve an item in the parent context using the child context.
/// </summary>
[TestMethod]
public void ResolveFromParent()
{
// Act:
var resolved = _context.GetInstance<TestClass>();
// Assert:
Assert.AreEqual("A", resolved.X);
}
/// <summary>
/// Register an additional, independent instance in the base context, after creating the child context.
/// </summary>
[TestMethod]
public void AddToBaseAndResolve()
{
// Arrange:
_baseContext.RegisterInstance(typeof(TestClass2), new TestClass2() { X = "C" });
// Act:
var resolved = _context.GetInstance<TestClass>();
var resolved2 = _context.GetInstance<TestClass2>();
// Assert:
Assert.AreEqual("A", resolved.X);
Assert.AreEqual("C", resolved2.X);
}
/// <summary>
/// Register an additional, independent instance in the child context.
/// </summary>
[TestMethod]
public void AddAndResolve()
{
// Arrange:
_context.RegisterInstance(typeof(TestClass2), new TestClass2() { X = "C" });
// Act:
var resolved = _context.GetInstance<TestClass>();
var resolved2 = _context.GetInstance<TestClass2>();
// Assert:
Assert.AreEqual("A", resolved.X);
Assert.AreEqual("C", resolved2.X);
}
/// <summary>
/// Register an overriding registration in the child context.
/// Resolving returns this instead of the parent one.
/// </summary>
[TestMethod]
public void OverrideAndResolve()
{
// Arrange:
_context.RegisterInstance(typeof(TestClass), new TestClass() { X = "B" });
// Act:
var resolved = _context.GetInstance<TestClass>();
// Assert:
Assert.AreEqual("B", resolved.X);
}
#region Child of ChainableContext
/// <summary>
/// Create a child context of a <see cref="ChainableContext"/>, nested two levels below the root context, and test that items are successfully registered in its setup event.
/// </summary>
// Note: ChainableContext can also be a root context.
[TestMethod]
public void SetupChildContext()
{
// Act:
_context.OnSetupChildContext += _context_OnSetupChildContext;
var context2 = _context.CreateChildContext(); // create a child of the child context
// Assert:
Assert.AreEqual(_testInstance.ToString(), context2.GetInstance<StringBuilder>().ToString()); // registered in the OnSetupChildContext event
TestUtil.AssertThrows<Exception>(() => _context.GetInstance<StringBuilder>()); // not registered in parent
// Check that normal child behaviour are not broken:
var resolved = _baseContext.GetInstance<TestClass>(); // resolve item in root context
Assert.AreEqual("A", resolved.X);
ResolveFromParent(); // resolve item inherited from root to one level below root
resolved = context2.GetInstance<TestClass>(); // resolve same item inherited from root to two levels down
Assert.AreEqual("A", resolved.X);
}
private void _context_OnSetupChildContext(object sender, ChainableContext.SetupContextEventArgs args)
{
args.Context.RegisterInstance(typeof(StringBuilder), _testInstance);
}
protected StringBuilder _testInstance = new StringBuilder("test");
#endregion
#region classes for test
public class TestClass
{
public string X { get; set; }
}
public class TestClass2 : TestClass
{ }
#endregion
protected ChainableContext _context;
protected SiExtendedDiContext _baseContext = new SiExtendedDiContext();
}
}
| 33.164286 | 181 | 0.597243 | [
"MIT"
] | JohnLambe/JLCSUtils | JLCSUtils/DiExtensionTest/ChainableContextTest.cs | 4,645 | C# |
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
using System;
using System.ComponentModel.Design;
using System.Runtime.InteropServices;
namespace Microsoft.VisualStudio.FSharp.ProjectSystem
{
internal sealed class VSProjectConstants
{
public static readonly Guid guidCSharpBrowseLibrary = new Guid("58f1bad0-2288-45b9-ac3a-d56398f7781d"); // For IVsObjBrowser.NavigateTo to browse a referenced C# project
public static readonly Guid guidVBBrowseLibrary = new Guid("414AC972-9829-4B6A-A8D7-A08152FEB8AA"); // For IVsObjBrowser.NavigateTo to browse a referenced VB project
public static readonly Guid guidObjectBrowser = new Guid("{CFF630F8-2DB3-44BA-9FC9-6489665DE5B8}"); // For IVsUIShellOpenDocument3.GetProvisionalViewingStatusForEditor to check if object browser can preview
/// CommandIDs matching the commands defined symbols in MenusAndCommands.vsct (stored with FSharp.ProjectSystem.FSharp)
public static readonly Guid guidFSharpProjectCmdSet = new Guid("75AC5611-A912-4195-8A65-457AE17416FB");
public static readonly CommandID MoveUpCmd = new CommandID(guidFSharpProjectCmdSet, 0x3002);
public static readonly CommandID AddNewItemBelow = new CommandID(guidFSharpProjectCmdSet, 0x3003);
public static readonly CommandID AddExistingItemBelow = new CommandID(guidFSharpProjectCmdSet, 0x3004);
public static readonly CommandID AddNewItemAbove = new CommandID(guidFSharpProjectCmdSet, 0x3005);
public static readonly CommandID AddExistingItemAbove = new CommandID(guidFSharpProjectCmdSet, 0x3006);
public static readonly CommandID MoveDownCmd = new CommandID(guidFSharpProjectCmdSet, 0x3007);
public static readonly CommandID NewFolderAbove = new CommandID(guidFSharpProjectCmdSet, 0x3008);
public static readonly CommandID NewFolderBelow = new CommandID(guidFSharpProjectCmdSet, 0x3009);
public static readonly CommandID FSharpSendThisReferenceToInteractiveCmd = new CommandID(guidFSharpProjectCmdSet, 0x5004);
public static readonly CommandID FSharpSendReferencesToInteractiveCmd = new CommandID(guidFSharpProjectCmdSet, 0x5005);
public static readonly CommandID FSharpSendProjectOutputToInteractiveCmd = new CommandID(guidFSharpProjectCmdSet, 0x5006);
}
}
| 76.903226 | 214 | 0.794883 | [
"MIT"
] | 0x6a62/fsharp | vsintegration/src/FSharp.ProjectSystem.Base/Project/VSProjectConstants.cs | 2,384 | C# |
using System.Drawing;
namespace MathematicalSetViewer
{
public class ImageLocation
{
public Bitmap image { get; set; }
public XY BotLeft { get; set; }
public XY TopRight { get; set; }
public ImageLocation(/*XY bl, XY tr, */Bitmap img)
{
//this.BotLeft = bl;
//this.TopRight = tr;
image = img;
}
}
} | 20.947368 | 58 | 0.525126 | [
"MIT"
] | Noah-Jaffe/MathematicalSetViewer | ImageLocation.cs | 400 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.AutoScaling
{
/// <summary>
/// Provides an AutoScaling Schedule resource.
///
/// ## Example Usage
///
/// ```csharp
/// using Pulumi;
/// using Aws = Pulumi.Aws;
///
/// class MyStack : Stack
/// {
/// public MyStack()
/// {
/// var foobarGroup = new Aws.AutoScaling.Group("foobarGroup", new Aws.AutoScaling.GroupArgs
/// {
/// AvailabilityZones =
/// {
/// "us-west-2a",
/// },
/// ForceDelete = true,
/// HealthCheckGracePeriod = 300,
/// HealthCheckType = "ELB",
/// MaxSize = 1,
/// MinSize = 1,
/// TerminationPolicies =
/// {
/// "OldestInstance",
/// },
/// });
/// var foobarSchedule = new Aws.AutoScaling.Schedule("foobarSchedule", new Aws.AutoScaling.ScheduleArgs
/// {
/// AutoscalingGroupName = foobarGroup.Name,
/// DesiredCapacity = 0,
/// EndTime = "2016-12-12T06:00:00Z",
/// MaxSize = 1,
/// MinSize = 0,
/// ScheduledActionName = "foobar",
/// StartTime = "2016-12-11T18:00:00Z",
/// });
/// }
///
/// }
/// ```
/// </summary>
public partial class Schedule : Pulumi.CustomResource
{
/// <summary>
/// The ARN assigned by AWS to the autoscaling schedule.
/// </summary>
[Output("arn")]
public Output<string> Arn { get; private set; } = null!;
/// <summary>
/// The name or Amazon Resource Name (ARN) of the Auto Scaling group.
/// </summary>
[Output("autoscalingGroupName")]
public Output<string> AutoscalingGroupName { get; private set; } = null!;
/// <summary>
/// The number of EC2 instances that should be running in the group. Default 0. Set to -1 if you don't want to change the desired capacity at the scheduled time.
/// </summary>
[Output("desiredCapacity")]
public Output<int> DesiredCapacity { get; private set; } = null!;
/// <summary>
/// The time for this action to end, in "YYYY-MM-DDThh:mm:ssZ" format in UTC/GMT only (for example, 2014-06-01T00:00:00Z ).
/// If you try to schedule your action in the past, Auto Scaling returns an error message.
/// </summary>
[Output("endTime")]
public Output<string> EndTime { get; private set; } = null!;
/// <summary>
/// The maximum size for the Auto Scaling group. Default 0.
/// Set to -1 if you don't want to change the maximum size at the scheduled time.
/// </summary>
[Output("maxSize")]
public Output<int> MaxSize { get; private set; } = null!;
/// <summary>
/// The minimum size for the Auto Scaling group. Default 0.
/// Set to -1 if you don't want to change the minimum size at the scheduled time.
/// </summary>
[Output("minSize")]
public Output<int> MinSize { get; private set; } = null!;
/// <summary>
/// The time when recurring future actions will start. Start time is specified by the user following the Unix cron syntax format.
/// </summary>
[Output("recurrence")]
public Output<string> Recurrence { get; private set; } = null!;
/// <summary>
/// The name of this scaling action.
/// </summary>
[Output("scheduledActionName")]
public Output<string> ScheduledActionName { get; private set; } = null!;
/// <summary>
/// The time for this action to start, in "YYYY-MM-DDThh:mm:ssZ" format in UTC/GMT only (for example, 2014-06-01T00:00:00Z ).
/// If you try to schedule your action in the past, Auto Scaling returns an error message.
/// </summary>
[Output("startTime")]
public Output<string> StartTime { get; private set; } = null!;
/// <summary>
/// Create a Schedule resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public Schedule(string name, ScheduleArgs args, CustomResourceOptions? options = null)
: base("aws:autoscaling/schedule:Schedule", name, args ?? new ScheduleArgs(), MakeResourceOptions(options, ""))
{
}
private Schedule(string name, Input<string> id, ScheduleState? state = null, CustomResourceOptions? options = null)
: base("aws:autoscaling/schedule:Schedule", name, state, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing Schedule resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="state">Any extra arguments used during the lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static Schedule Get(string name, Input<string> id, ScheduleState? state = null, CustomResourceOptions? options = null)
{
return new Schedule(name, id, state, options);
}
}
public sealed class ScheduleArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The name or Amazon Resource Name (ARN) of the Auto Scaling group.
/// </summary>
[Input("autoscalingGroupName", required: true)]
public Input<string> AutoscalingGroupName { get; set; } = null!;
/// <summary>
/// The number of EC2 instances that should be running in the group. Default 0. Set to -1 if you don't want to change the desired capacity at the scheduled time.
/// </summary>
[Input("desiredCapacity")]
public Input<int>? DesiredCapacity { get; set; }
/// <summary>
/// The time for this action to end, in "YYYY-MM-DDThh:mm:ssZ" format in UTC/GMT only (for example, 2014-06-01T00:00:00Z ).
/// If you try to schedule your action in the past, Auto Scaling returns an error message.
/// </summary>
[Input("endTime")]
public Input<string>? EndTime { get; set; }
/// <summary>
/// The maximum size for the Auto Scaling group. Default 0.
/// Set to -1 if you don't want to change the maximum size at the scheduled time.
/// </summary>
[Input("maxSize")]
public Input<int>? MaxSize { get; set; }
/// <summary>
/// The minimum size for the Auto Scaling group. Default 0.
/// Set to -1 if you don't want to change the minimum size at the scheduled time.
/// </summary>
[Input("minSize")]
public Input<int>? MinSize { get; set; }
/// <summary>
/// The time when recurring future actions will start. Start time is specified by the user following the Unix cron syntax format.
/// </summary>
[Input("recurrence")]
public Input<string>? Recurrence { get; set; }
/// <summary>
/// The name of this scaling action.
/// </summary>
[Input("scheduledActionName", required: true)]
public Input<string> ScheduledActionName { get; set; } = null!;
/// <summary>
/// The time for this action to start, in "YYYY-MM-DDThh:mm:ssZ" format in UTC/GMT only (for example, 2014-06-01T00:00:00Z ).
/// If you try to schedule your action in the past, Auto Scaling returns an error message.
/// </summary>
[Input("startTime")]
public Input<string>? StartTime { get; set; }
public ScheduleArgs()
{
}
}
public sealed class ScheduleState : Pulumi.ResourceArgs
{
/// <summary>
/// The ARN assigned by AWS to the autoscaling schedule.
/// </summary>
[Input("arn")]
public Input<string>? Arn { get; set; }
/// <summary>
/// The name or Amazon Resource Name (ARN) of the Auto Scaling group.
/// </summary>
[Input("autoscalingGroupName")]
public Input<string>? AutoscalingGroupName { get; set; }
/// <summary>
/// The number of EC2 instances that should be running in the group. Default 0. Set to -1 if you don't want to change the desired capacity at the scheduled time.
/// </summary>
[Input("desiredCapacity")]
public Input<int>? DesiredCapacity { get; set; }
/// <summary>
/// The time for this action to end, in "YYYY-MM-DDThh:mm:ssZ" format in UTC/GMT only (for example, 2014-06-01T00:00:00Z ).
/// If you try to schedule your action in the past, Auto Scaling returns an error message.
/// </summary>
[Input("endTime")]
public Input<string>? EndTime { get; set; }
/// <summary>
/// The maximum size for the Auto Scaling group. Default 0.
/// Set to -1 if you don't want to change the maximum size at the scheduled time.
/// </summary>
[Input("maxSize")]
public Input<int>? MaxSize { get; set; }
/// <summary>
/// The minimum size for the Auto Scaling group. Default 0.
/// Set to -1 if you don't want to change the minimum size at the scheduled time.
/// </summary>
[Input("minSize")]
public Input<int>? MinSize { get; set; }
/// <summary>
/// The time when recurring future actions will start. Start time is specified by the user following the Unix cron syntax format.
/// </summary>
[Input("recurrence")]
public Input<string>? Recurrence { get; set; }
/// <summary>
/// The name of this scaling action.
/// </summary>
[Input("scheduledActionName")]
public Input<string>? ScheduledActionName { get; set; }
/// <summary>
/// The time for this action to start, in "YYYY-MM-DDThh:mm:ssZ" format in UTC/GMT only (for example, 2014-06-01T00:00:00Z ).
/// If you try to schedule your action in the past, Auto Scaling returns an error message.
/// </summary>
[Input("startTime")]
public Input<string>? StartTime { get; set; }
public ScheduleState()
{
}
}
}
| 41.137324 | 170 | 0.574168 | [
"ECL-2.0",
"Apache-2.0"
] | michael-golden/pulumi-aws | sdk/dotnet/AutoScaling/Schedule.cs | 11,683 | C# |
using System;
using System.Collections.Generic;
namespace TorshiaWebApp.Models
{
public class Task
{
public Task()
{
this.TaskSectors = new HashSet<TaskSector>();
this.DueDate = DateTime.UtcNow;
}
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public DateTime DueDate { get; set; }
public string Participants { get; set; }
public bool IsReported { get; set; } = false;
public virtual ICollection<TaskSector> TaskSectors { get; set; }
}
}
| 22.035714 | 72 | 0.585089 | [
"MIT"
] | svetlimladenov/C-Sharp-Web-Development-Basics | 10.Exam Preparation 2/SIS/src/TorshiaWebApp/Models/Task.cs | 619 | C# |
private enum GateController.GateEnemyState // TypeDefIndex: 8059
{
// Fields
public int value__; // 0x0
public const GateController.GateEnemyState None = 0;
public const GateController.GateEnemyState NotExist = 1;
public const GateController.GateEnemyState Alive = 2;
public const GateController.GateEnemyState Dead = 3;
public const GateController.GateEnemyState MAX = 4;
}
| 31.916667 | 64 | 0.793734 | [
"MIT"
] | SinsofSloth/RF5-global-metadata | _no_namespace/GateController.GateEnemyState.cs | 383 | C# |
namespace DatingApp.API.Dtos
{
public class UserForUpdateDto
{
public string Introduction { get; set; }
public string LookingFor { get; set; }
public string Interests { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
} | 20.6 | 48 | 0.595469 | [
"MIT"
] | pavanbadempet/Dating-App | DatingApp.API/Dtos/UserForUpdateDto.cs | 309 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Collections;
using System.Threading.Tasks;
using System.Windows.Forms;
using AH.ModuleController.OPRMSSR;
using AH.DUtility;
namespace AH.ModuleController.UI.OPR.Forms
{
public partial class frmOTCalender : AH.Shared.UI.frmSmartFormStandard
{
public int intOT { set; get; }
StringFormat strFormat; //Used to format the grid rows.
ArrayList arrColumnLefts = new ArrayList();//Used to save left coordinates of columns
ArrayList arrColumnWidths = new ArrayList();//Used to save column widths
int iCellHeight = 0; //Used to get/set the datagridview cell height
int iTotalWidth = 0; //
int iRow = 0;//Used as counter
bool bFirstPage = false; //Used to check whether we are printing first page
bool bNewPage = false;// Used to check whether we are printing a new page
int iHeaderHeight = 0; //Used
OPRMSSR.OPRWSClient accmSc = new OPRMSSR.OPRWSClient();
public DateTime dteOtDate { set; get; }
List<string> ottheater = new List<string>();
List<string> myCollection = new List<string>();
List<string> otIncharge = new List<string>();
public string a;
#region "Grid"
public frmOTCalender(string strRegId, string dtDate, string strCollRow = "", int intCol = 0)
{
a = strRegId;
InitializeComponent();
}
public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
{
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
return newImage;
}
private void frmOTCalender_Load(object sender, EventArgs e)
{
this.Top = 70;
try
{
DateTime dtedate = Convert.ToDateTime(dteOTSchedulingDate.Text.ToString());
txtotDate.Text = dtedate.ToString("dd/MM/yyyy") + " " + dtedate.ToString("dddd");
pictureBox1.Image = ScaleImage(pictureBox1.Image, 180, 200);
grid_column();
int i = 1;
//DG.Rows[0].Cells[i].Selected = true; 'Cahnge 05_02_15'
DG.Rows[0].Cells[intOT].Selected = true; //Cahnge 05_02_15'
// DataGridViewCellStyle style = new DataGridViewCellStyle();
for (int k = 0; k < DG.Rows.Count; k++)
{
//DG.Rows[k].Cells[intOT].Style.BackColor = Color.Yellow;
if (DG[intOT, k].Style.BackColor != Color.Pink)
{
DG[intOT, k].Style.BackColor = Color.Yellow;
}
}
tabControl2.TabPages[i - 1].Controls.Add(pictureBox1);
tabControl2.TabPages[i - 1].Controls.Add(lvwDetails);
tabControl2.TabPages[i - 1].Controls.Add(lvwPackage);
lvwPackage.Items.Clear();
lvwDetails.Items.Clear();
}
catch (System.ServiceModel.CommunicationException commp)
{
MessageBox.Show(Utility.CommunicationErrorMsg, Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private DataGridViewTextBoxColumn Create_Grid_Column(string pname, string htext, int cwidth, Boolean true_false, DataGridViewContentAlignment Align,
Boolean read_only)
{
DataGridViewTextBoxColumn col0 = new DataGridViewTextBoxColumn();
col0.DataPropertyName = pname;
col0.HeaderText = htext;
col0.DefaultCellStyle.ForeColor = Color.Black;
col0.DefaultCellStyle.BackColor = Color.White;
col0.Visible = true_false;
col0.DefaultCellStyle.Alignment = Align;
col0.Width = cwidth;
col0.ReadOnly = read_only;
return col0;
}
private void grid_column()
{
//int r = DG.RowCount;
try
{
ottheater.Clear();
DG.Columns.Clear();
DG.Rows.Clear();
DG.Columns.Add(Create_Grid_Column("Theater Name>>", "Theater Name>>", 400, true, DataGridViewContentAlignment.MiddleCenter, true));
mFillTheaterist();
tabControl2.TabPages.Clear();
foreach (string strtheater in ottheater)
{
DG.Columns.Add(Create_Grid_Column(strtheater, strtheater, 400, true, DataGridViewContentAlignment.TopCenter, true));
string title = strtheater + (tabControl2.TabCount + 1).ToString();
//TabPage myTabPage = new TabPage(title);
TabPage myTabPage = new TabPage(strtheater);
tabControl2.TabPages.Add(myTabPage);
}
int j = 48;
DG.Rows.Add(j);
var fromTimeString = "";
TimeSpan result = TimeSpan.FromMinutes(30);
DataGridViewCellStyle style = new DataGridViewCellStyle();
for (int i = 0; i < j; i++)
{
fromTimeString = result.ToString().Substring(0, 5);
DG[0, i].Style.BackColor = Color.Wheat;
DG[0, i].Style.ForeColor = Color.DimGray;
DG[0, i].Style.Font = new Font("Courier New", 12.4f, FontStyle.Bold);
DG[0, i].Value = fromTimeString;
DG.Columns[0].Width = 80;
DG.Rows[i].Height = 40;
if (i == 46)
{
result = result + TimeSpan.Parse("00:29");
}
else
{
result = result + TimeSpan.Parse("00:30");
}
}
int k = 0;
string strSchedulueID = "";
List<CalenderOT> objcal = new List<CalenderOT>();
objcal = accmSc.DisplayOTScheduling("Displayschedule", dteOTSchedulingDate.Text.ToString()).ToList();
foreach (CalenderOT strpos in objcal)
{
if (strSchedulueID != strpos.ScheduleID)
{
if (strpos.intCol != k)
{
//DG[strpos.intCol, strpos.intRow].Value = "Occupied for " + strpos.RegNo + " to " + strpos.Fromtime + "-" + strpos.Totime;
//DG[strpos.intCol, strpos.intRow].Value = "Occupied - " + strpos.ScheduleID;
DG[strpos.intCol, strpos.intRow].Value = "Occupied " + strpos.RegNo + " " + strpos.PatientName + "-" + strpos.ScheduleID;
DG[strpos.intCol, strpos.intRow].Style.ForeColor = Color.Blue;
strSchedulueID = strpos.ScheduleID;
k = strpos.intCol;
}
}
DG[strpos.intCol, strpos.intRow].Style.BackColor = Color.Pink; //doesn't work
k = 0;
}
objcal.Clear();
for (int b = 0; b < DG.Rows.Count; b++)
{
if (DG.Rows[b].Cells[intOT].Style.BackColor != Color.Pink)
{
DG.Rows[b].Cells[intOT].Style.BackColor = Color.Yellow;
}
}
}
catch (System.ServiceModel.CommunicationException commp)
{
MessageBox.Show(Utility.CommunicationErrorMsg, Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
public double[] ExtractGridData(DataGridView grid)
{
int numCells = grid.SelectedCells.Count;
int intcells = 1;
int lngpos;
string strrowpos = "";
string strcolpos = "";
string strTheaterName = "";
string hh = "";
double[] cellsData = new double[numCells];
foreach (DataGridViewCell cell in grid.SelectedCells)
{
hh = DG.Rows[cell.RowIndex].Cells[0].Value.ToString();
strrowpos = strrowpos + (hh + "|" + cell.RowIndex) + ",";
strcolpos = cell.ColumnIndex.ToString();
if (intcells == 1)
{
//DG.Rows[cell.RowIndex].Cells[cell.ColumnIndex].Value = "Occupied";
strTheaterName = DG.Columns[cell.ColumnIndex].HeaderText;
txtEndtime.Text = hh;
intcells = intcells + 1;
}
//MessageBox.Show(hh.ToString());
}
txtStarttime.Text = hh;
lngpos = (strrowpos.ToString().Length - 1);
txtstartRowpos.Text = strrowpos.Substring(0, lngpos);
txtColpos.Text = strcolpos;
txtTheaterName.Text = strTheaterName.ToString();
myCollection.Clear();
myCollection.Add(txtstartRowpos.Text);
intcells = 1;
foreach (DataGridViewCell cell in grid.SelectedCells)
{
if (intcells == 1)
{
if (a != "")
{
//DG.Rows[cell.RowIndex].Cells[cell.ColumnIndex].Value = "Occupied for "
// + txtStarttime.Text + " to " + txtEndtime.Text;
DG.Rows[cell.RowIndex].Cells[cell.ColumnIndex].Value = "Occupied for ";
}
intcells = intcells + 1;
}
}
return cellsData;
}
private void mFillTheaterist()
{
try
{
List<Theater> theater = accmSc.GetTheater().ToList();
foreach (Theater bo in theater)
{
ottheater.Add(bo.Theatertitle.ToString());
}
}
catch (System.ServiceModel.CommunicationException commp)
{
MessageBox.Show(Utility.CommunicationErrorMsg, Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void MergeCellsInRow(int row, int col1, int col2)
{
Graphics g = DG.CreateGraphics();
Pen p = new Pen(DG.GridColor);
Rectangle r1 = DG.GetCellDisplayRectangle(col1, row, true);
Rectangle r2 = DG.GetCellDisplayRectangle(col2, row, true);
int recWidth = 0;
string recValue = string.Empty;
for (int i = col1; i <= col2; i++)
{
recWidth += DG.GetCellDisplayRectangle(i, row, true).Width;
if (DG[i, row].Value != null)
recValue += DG[i, row].Value.ToString() + " ";
}
Rectangle newCell = new Rectangle(r1.X, r1.Y, recWidth, r1.Height);
g.FillRectangle(new SolidBrush(DG.DefaultCellStyle.BackColor), newCell);
g.DrawRectangle(p, newCell);
g.DrawString(recValue, DG.DefaultCellStyle.Font, new SolidBrush(DG.DefaultCellStyle.ForeColor), newCell.X + 3, newCell.Y + 3);
}
private void MergeCellsInColumn(int col, int row1, int row2)
{
Graphics g = DG.CreateGraphics();
Pen p = new Pen(DG.GridColor);
Rectangle r1 = DG.GetCellDisplayRectangle(col, row1, true);
Rectangle r2 = DG.GetCellDisplayRectangle(col, row2, true);
int recHeight = 0;
string recValue = string.Empty;
for (int i = row1; i <= row2; i++)
{
recHeight += DG.GetCellDisplayRectangle(col, i, true).Height;
if (DG[col, i].Value != null)
recValue += DG[col, i].Value.ToString() + " ";
}
Rectangle newCell = new Rectangle(r1.X, r1.Y, r1.Width, recHeight);
g.FillRectangle(new SolidBrush(DG.DefaultCellStyle.BackColor), newCell);
g.DrawRectangle(p, newCell);
g.DrawString(recValue, DG.DefaultCellStyle.Font, new SolidBrush(DG.DefaultCellStyle.ForeColor), newCell.X + 3, newCell.Y + 3);
}
private void MergeCells(int RowId1, int RowId2, int Column, bool isSelected)
{
Graphics g = DG.CreateGraphics();
Pen gridPen = new Pen(DG.GridColor);
Rectangle CellRectangle1 = DG.GetCellDisplayRectangle(Column, RowId1, true);
Rectangle CellRectangle2 = DG.GetCellDisplayRectangle(Column, RowId2, true);
int rectHeight = 0;
string MergedRows = String.Empty;
for (int i = RowId1; i <= RowId2; i++)
{
rectHeight += DG.GetCellDisplayRectangle(Column, i, false).Height;
}
Rectangle newCell = new Rectangle(CellRectangle1.X, CellRectangle1.Y, CellRectangle1.Width, rectHeight);
g.FillRectangle(new SolidBrush(isSelected ? DG.DefaultCellStyle.SelectionBackColor : DG.DefaultCellStyle.BackColor), newCell);
g.DrawRectangle(gridPen, newCell);
g.DrawString(DG.Rows[RowId1].Cells[Column].Value.ToString(), DG.DefaultCellStyle.Font, new SolidBrush(isSelected ? DG.DefaultCellStyle.SelectionForeColor : DG.DefaultCellStyle.ForeColor), newCell.X + newCell.Width / 3, newCell.Y + newCell.Height / 3);
}
private void patientAssignToolStripMenuItem_Click(object sender, EventArgs e)
{
//double chargeCount;
ExtractGridData(DG);
foreach (DataGridViewCell cell in DG.SelectedCells)
{
DataGridViewCellStyle CellStyle = new DataGridViewCellStyle();
CellStyle.BackColor = Color.Pink;
DG.Rows[cell.RowIndex].Cells[cell.ColumnIndex].Style = CellStyle;
}
frmOTPatient frm = new frmOTPatient(myCollection);
frm.starttime = txtStarttime.Text;
frm.Endtime = txtEndtime.Text;
frm.strDate = dteOTSchedulingDate.Text.ToString();
frm.TheaterName = txtTheaterName.Text;
frm.Colpos = txtColpos.Text;
frm.intStatus = 0;
if (lvwDetails.Items.Count > 0)
{
frm.strScheduleID = lvwDetails.Items[0].Text.ToString();
}
frm.ShowDialog();
btnrefresh_Click(sender, e);
}
private void DG_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
{
if (DG.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected == true)
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All & ~DataGridViewPaintParts.Border);
using (Pen p = new Pen(Color.Red, 1))
{
Rectangle rect = e.CellBounds;
rect.Width -= 2;
rect.Height -= 2;
e.Graphics.DrawRectangle(p, rect);
}
e.Handled = true;
}
}
}
private void DG_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
{
DataGridViewCellStyle style = new DataGridViewCellStyle();
foreach (DataGridViewCell cell in this.DG.SelectedCells)
{
if (cell.Value != null && (cell.ColumnIndex != 0 && cell.RowIndex != 0))
{
cell.Style = style;
style.Font = new Font("Courier New", 10f, FontStyle.Bold);
style.ForeColor = Color.Blue;
style.BackColor = Color.Pink;
}
}
}
private void DG_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
try
{
if (e.RowIndex != -1 && e.ColumnIndex != -1)
{
tabControl2.SelectedIndex = e.ColumnIndex - 1;
if (e.ColumnIndex > 0)
{
tabControl2.TabPages[e.ColumnIndex - 1].Controls.Add(pictureBox1);
tabControl2.TabPages[e.ColumnIndex - 1].Controls.Add(lvwDetails);
tabControl2.TabPages[e.ColumnIndex - 1].Controls.Add(lvwPackage);
}
else
{
tabControl2.TabPages[e.ColumnIndex].Controls.Add(pictureBox1);
tabControl2.TabPages[e.ColumnIndex].Controls.Add(lvwDetails);
tabControl2.TabPages[e.ColumnIndex].Controls.Add(lvwPackage);
}
lvwDetails.Items.Clear();
lvwPackage.Items.Clear();
//if (DG.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
//{
// string name = DG.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
// lvwDetails.Items.Add(name.ToString());
//}
// pictureBox1.Image = new Bitmap("C:" + @"\pic\CAN6WFNL.jpg");
if (DG.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
{
string name = DG.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
string strSchedulingID = name.Substring(name.LastIndexOf("-") + 1).Trim();
string strRegNo = "";
List<CalenderOT> objdoctors = new List<CalenderOT>();
//objdoctors = Doctorsdetails(name.ToString());
objdoctors = accmSc.DisplayOTPackage("Displaypackage1", strSchedulingID.ToString()).ToList();
foreach (CalenderOT Doctotrs in objdoctors)
{
ListViewItem lvi1 = new ListViewItem();
lvi1.Text = Doctotrs.PackageId.ToString();
lvi1.SubItems.Add(Doctotrs.PackageName.ToString());
lvwPackage.Items.Add(lvi1);
}
objdoctors = accmSc.DisplayOTSschedulingDoctors("Displayscheduingpatient", strSchedulingID.ToString()).ToList();
foreach (CalenderOT Doctotrs in objdoctors)
{
ListViewItem lvi = new ListViewItem();
lvi.Text = Doctotrs.ScheduleID;
lvi.SubItems.Add(Doctotrs.RegNo.ToString());
strRegNo = Doctotrs.RegNo.ToString();
lvi.SubItems.Add(Doctotrs.DoctorsCode.ToString());
lvi.SubItems.Add(Doctotrs.doctorsName.ToString());
//lvi.SubItems[1].UseItemStyleForSubItems = false;
//listView1.Items[0].SubItems[1].BackColor = Color.Yellow;
lvwDetails.Items.Add(lvi);
}
if (strRegNo.ToString() != "")
{
//loadImage(strRegNo.ToString() + ".Jpg");
}
foreach (ListViewItem item in lvwDetails.Items)
{
if ((item.Index % 2) == 0)
item.BackColor = Color.Yellow;
else
item.BackColor = Color.LightBlue;
}
}
if (e.Button == MouseButtons.Right)
{
if (e.ColumnIndex == intOT)
{
DataGridViewCell clickedCell = (sender as DataGridView).Rows[e.RowIndex].Cells[e.ColumnIndex];
this.DG.CurrentCell = clickedCell; // Select the clicked cell, for instance
var relativeMousePosition = DG.PointToClient(Cursor.Position);
this.menuStrip.Show(DG, relativeMousePosition);
}
}
}
}
catch (System.ServiceModel.CommunicationException commp)
{
MessageBox.Show(Utility.CommunicationErrorMsg, Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void dteOTSchedulingDate_ValueChanged(object sender, EventArgs e)
{
//DateTime dtedate = Convert.ToDateTime(dteOtDate.ToString());
//DateTime dtedate = Convert.ToDateTime(dteOTSchedulingDate.Text.ToString());
//txtotDate.Text = dtedate.ToString("dd/MM/yyyy") + " " + dtedate.ToString("dddd");
tabControl2.TabPages.Clear();
DG.Rows.Clear();
grid_column();
DateTime dtedate = Convert.ToDateTime(dteOTSchedulingDate.Text.ToString());
txtotDate.Text = dtedate.ToString("dd/MM/yyyy") + " " + dtedate.ToString("dddd");
//getData();
DataGridViewCellStyle style = new DataGridViewCellStyle();
foreach (DataGridViewCell cell in this.DG.SelectedCells)
{
if (cell.Value != null && (cell.ColumnIndex != 0 && cell.RowIndex != 0))
{
cell.Style = style;
style.Font = new Font("Courier New", 15f, FontStyle.Bold);
style.ForeColor = Color.Blue;
style.BackColor = Color.Pink;
}
}
tabControl1.SelectedTab = tabPage1;
//grid_column1(dtedate.ToString());
}
private void tabControl2_Click(object sender, EventArgs e)
{
for (int j = 0; j < DG.Columns.Count; j++)
{
DG.Rows[0].Cells[j].Selected = false;
}
int i = tabControl2.SelectedIndex + 1;
DG.Rows[0].Cells[i].Selected = true;
tabControl2.TabPages[i - 1].Controls.Add(pictureBox1);
tabControl2.TabPages[i - 1].Controls.Add(lvwDetails);
tabControl2.TabPages[i - 1].Controls.Add(lvwPackage);
//pictureBox1.Image = new Bitmap("C:" + @"\pic\CAN6WFNL.jpg");
lvwDetails.Items.Clear();
lvwPackage.Items.Clear();
}
private void tabControl2_DrawItem(object sender, DrawItemEventArgs e)
{
TabPage CurrentTab = tabControl2.TabPages[e.Index];
Rectangle ItemRect = tabControl2.GetTabRect(e.Index);
SolidBrush FillBrush = new SolidBrush(Color.Red);
SolidBrush TextBrush = new SolidBrush(Color.White);
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
//If we are currently painting the Selected TabItem we'll
//change the brush colors and inflate the rectangle.
if (System.Convert.ToBoolean(e.State & DrawItemState.Selected))
{
FillBrush.Color = Color.White;
TextBrush.Color = Color.Red;
ItemRect.Inflate(2, 2);
}
//Set up rotation for left and right aligned tabs
if (tabControl2.Alignment == TabAlignment.Left || tabControl2.Alignment == TabAlignment.Right)
{
float RotateAngle = 90;
if (tabControl2.Alignment == TabAlignment.Left)
RotateAngle = 270;
PointF cp = new PointF(ItemRect.Left + (ItemRect.Width / 2), ItemRect.Top + (ItemRect.Height / 2));
e.Graphics.TranslateTransform(cp.X, cp.Y);
e.Graphics.RotateTransform(RotateAngle);
ItemRect = new Rectangle(-(ItemRect.Height / 2), -(ItemRect.Width / 2), ItemRect.Height, ItemRect.Width);
}
//Next we'll paint the TabItem with our Fill Brush
e.Graphics.FillRectangle(FillBrush, ItemRect);
//Now draw the text.
e.Graphics.DrawString(CurrentTab.Text, e.Font, TextBrush, (RectangleF)ItemRect, sf);
//Reset any Graphics rotation
e.Graphics.ResetTransform();
//Finally, we should Dispose of our brushes.
FillBrush.Dispose();
TextBrush.Dispose();
//*************************
tabControl2.TabPages[e.Index].BackColor = Color.Beige;
TabPage tabPages = tabControl2.TabPages[e.Index];
Graphics graphics = e.Graphics;
Brush textBrush = new SolidBrush(Color.Green); //fore color brush
Rectangle tabBounds = tabControl2.GetTabRect(e.Index);
if (e.State == DrawItemState.Selected)
{
graphics.FillRectangle(Brushes.SkyBlue, e.Bounds); //fill background color
}
else
{
textBrush = new System.Drawing.SolidBrush(e.ForeColor);
e.DrawBackground();
}
Font tabFont = new Font("Book Antiqua", 12, FontStyle.Italic | FontStyle.Bold, GraphicsUnit.Pixel);
StringFormat strFormat = new StringFormat();
strFormat.Alignment = StringAlignment.Near;
strFormat.LineAlignment = StringAlignment.Near;
// draw text
graphics.DrawString(tabPages.Text, tabFont, textBrush, tabBounds, new StringFormat(strFormat));
graphics.Dispose();
textBrush.Dispose();
}
private void btnrefresh_Click(object sender, EventArgs e)
{
tabControl2.TabPages.Clear();
DG.Rows.Clear();
grid_column();
DateTime dtedate = Convert.ToDateTime(dteOTSchedulingDate.Text.ToString());
txtotDate.Text = dtedate.ToString("dd/MM/yyyy") + " " + dtedate.ToString("dddd");
//getData();
DataGridViewCellStyle style = new DataGridViewCellStyle();
foreach (DataGridViewCell cell in this.DG.SelectedCells)
{
if (cell.Value != null && (cell.ColumnIndex != 0 && cell.RowIndex != 0))
{
cell.Style = style;
style.Font = new Font("Courier New", 15f, FontStyle.Bold);
style.ForeColor = Color.Blue;
style.BackColor = Color.Pink;
}
}
}
private void grid_column1(string strDate)
{
int j = 49;
int introw = 0;
try
{
DGbarChart.Rows.Clear();
var fromTimeString = "";
TimeSpan result = TimeSpan.FromMinutes(30);
DataGridViewCellStyle style = new DataGridViewCellStyle();
for (int i = 0; i < j; i++)
{
fromTimeString = result.ToString().Substring(0, 5);
if (i == 0)
{
DGbarChart.Columns.Add(Create_Grid_Column("Incharge", "Incharge", 200, true, DataGridViewContentAlignment.TopLeft, true));
DGbarChart.Rows[i].Height = 80;
}
else
{
//TimeSpan result = TimeSpan.FromHours(i - 1);
//string fromTimeString = result.ToString("hh':'mm");
//DG.Columns.Add(_clsGrid.Create_Grid_Column((i-1).ToString(),(i-1).ToString(), 50, true, DataGridViewContentAlignment.TopLeft, true));
DGbarChart.Columns.Add(Create_Grid_Column(fromTimeString, fromTimeString, 50, true, DataGridViewContentAlignment.TopLeft, true));
//DGbarChart.Rows[i].Height = 40;
DGbarChart[i, 0].Style.Font = new Font("Courier New", 10f, FontStyle.Regular);
if (i == 47)
{
result = result + TimeSpan.Parse("00:29");
}
else
{
result = result + TimeSpan.Parse("00:30");
}
}
}
List<CalenderOT> Cal = new List<CalenderOT>();
//Cal = accmSc.GetInchargeIDBar("Getincharge", "").ToList();
List<OperationMaster> oprMaster = new List<OperationMaster>();
oprMaster = accmSc.GetInchargeIDBarchart().ToList();
int intRow = oprMaster.Count;
int K = 0;
DGbarChart.Rows.Add(intRow);
foreach (OperationMaster strIncharName in oprMaster)
{
if (strIncharName.RegName.ToString() != "")
{
DGbarChart[0, introw].Value = strIncharName.RegName.ToString() + "|" + strIncharName.RegId.ToString();
string strName = DGbarChart[0, introw].Value.ToString();
string strInchargeIdID = strName.Substring(strName.LastIndexOf("|") + 1).Trim();
//DGbarChart[1, introw].Value = strIncharName.RegName.ToString();
//Cal = accmSc.GetInchargeIDBar("Getincharge", DGbarChart[0, 0].Value.ToString()).ToList();
Cal = accmSc.GetRowposofBarchat("Getrowpos", strInchargeIdID.ToString(), strDate.ToString()).ToList();
foreach (CalenderOT rowpos in Cal)
{
int i = rowpos.intRow;
//DGbarChart[i + 1, introw].Value = i;
DGbarChart[i + 1, introw].Value = "A";
//DG.Rows[strpos].DefaultCellStyle.BackColor = Color.Yellow;
DGbarChart[i + 1, introw].Style.BackColor = Color.DarkSeaGreen; //doesn't work
}
introw = introw + 1;
}
}
}
catch (System.ServiceModel.CommunicationException commp)
{
MessageBox.Show(Utility.CommunicationErrorMsg, Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void tabControl1_Click(object sender, EventArgs e)
{
if (tabControl1.SelectedIndex==1 )
{
DateTime dtedate = Convert.ToDateTime(dteOTSchedulingDate.Text.ToString());
grid_column1(dtedate.ToString("dd/MM/yyyy"));
}
}
#endregion
#region "Print"
private void btnPrintBar_Click(object sender, EventArgs e)
{
PrintDialog printDialog = new PrintDialog();
printDialog.Document = printDoc;
printDialog.UseEXDialog = true;
//Get the document
if (DialogResult.OK == printDialog.ShowDialog())
{
printDoc.DocumentName = "Bar Chart Print";
printDoc.Print();
}
}
private void printDoc_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
try
{
strFormat = new StringFormat();
strFormat.Alignment = StringAlignment.Near;
strFormat.LineAlignment = StringAlignment.Center;
strFormat.Trimming = StringTrimming.EllipsisCharacter;
arrColumnLefts.Clear();
arrColumnWidths.Clear();
iCellHeight = 0;
iRow = 0;
bFirstPage = true;
bNewPage = true;
// Calculating Total Widths
iTotalWidth = 0;
foreach (DataGridViewColumn dgvGridCol in DG.Columns)
{
iTotalWidth += dgvGridCol.Width;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void printDoc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
try
{
//Set the left margin
int iLeftMargin = e.MarginBounds.Left;
//Set the top margin
int iTopMargin = e.MarginBounds.Top;
//Whether more pages have to print or not
bool bMorePagesToPrint = false;
int iTmpWidth = 0;
//For the first page to print set the cell width and header height
if (bFirstPage)
{
foreach (DataGridViewColumn GridCol in DGbarChart.Columns)
{
//iTmpWidth = 14;
iTmpWidth = (int)(Math.Floor((double)((double)GridCol.Width /
(double)iTotalWidth * (double)iTotalWidth *
((double)e.MarginBounds.Width / (double)iTotalWidth)))) + 1;
iHeaderHeight = (int)(e.Graphics.MeasureString(GridCol.HeaderText,
GridCol.InheritedStyle.Font, iTmpWidth).Height) + 11;
// Save width and height of headres
arrColumnLefts.Add(iLeftMargin);
arrColumnWidths.Add(iTmpWidth);
iLeftMargin += iTmpWidth;
}
}
//Loop till all the grid rows not get printed
while (iRow <= DGbarChart.Rows.Count - 1)
{
DataGridViewRow GridRow = DGbarChart.Rows[iRow];
//Set the cell height
iCellHeight = GridRow.Height + 5;
int iCount = 0;
//Check whether the current page settings allo more rows to print
if (iTopMargin + iCellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
{
bNewPage = true;
bFirstPage = false;
bMorePagesToPrint = true;
break;
}
else
{
if (bNewPage)
{
//Draw Header
e.Graphics.DrawString("Customer Summary", new Font(DGbarChart.Font, FontStyle.Bold),
Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top + 2 -
e.Graphics.MeasureString("Customer Summary", new Font(DGbarChart.Font,
FontStyle.Bold), e.MarginBounds.Width).Height - 13);
e.Graphics.DrawString("Address1", new Font(DGbarChart.Font, FontStyle.Bold),
Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top + 15 -
e.Graphics.MeasureString("Address1", new Font(DGbarChart.Font,
FontStyle.Bold), e.MarginBounds.Width).Height - 13);
e.Graphics.DrawString("Address2", new Font(DGbarChart.Font, FontStyle.Bold),
Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top + 30 -
e.Graphics.MeasureString("Address2", new Font(DGbarChart.Font,
FontStyle.Bold), e.MarginBounds.Width).Height - 13);
e.Graphics.DrawString("Email", new Font(DGbarChart.Font, FontStyle.Bold),
Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top + 40 -
e.Graphics.MeasureString("Email", new Font(DGbarChart.Font,
FontStyle.Bold), e.MarginBounds.Width).Height - 13);
String strDate = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString();
//Draw Date
e.Graphics.DrawString(strDate, new Font(DGbarChart.Font, FontStyle.Bold),
Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width -
e.Graphics.MeasureString(strDate, new Font(DGbarChart.Font,
FontStyle.Bold), e.MarginBounds.Width).Width), e.MarginBounds.Top -
e.Graphics.MeasureString("Customer Summary", new Font(new Font(DGbarChart.Font,
FontStyle.Bold), FontStyle.Bold), e.MarginBounds.Width).Height - 13);
//Draw Columns
iTopMargin = e.MarginBounds.Top + 30;
foreach (DataGridViewColumn GridCol in DGbarChart.Columns)
{
e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),
new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
(int)arrColumnWidths[iCount], iHeaderHeight));
e.Graphics.DrawRectangle(Pens.Black,
new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
(int)arrColumnWidths[iCount], iHeaderHeight));
e.Graphics.DrawString(GridCol.HeaderText, GridCol.InheritedStyle.Font,
new SolidBrush(GridCol.InheritedStyle.ForeColor),
new RectangleF((int)arrColumnLefts[iCount], iTopMargin,
(int)arrColumnWidths[iCount], iHeaderHeight), strFormat);
iCount++;
}
bNewPage = false;
iTopMargin += iHeaderHeight;
}
iCount = 0;
//Draw Columns Contents
foreach (DataGridViewCell Cel in GridRow.Cells)
{
if (Cel.Value != null)
{
if (Cel.InheritedStyle.BackColor != Color.DarkSeaGreen)
{
e.Graphics.DrawString(Cel.Value.ToString(), Cel.InheritedStyle.Font,
new SolidBrush(Cel.InheritedStyle.ForeColor),
new RectangleF((int)arrColumnLefts[iCount], (float)iTopMargin,
(int)arrColumnWidths[iCount], (float)iCellHeight), strFormat);
}
else
{
e.Graphics.DrawString(Cel.Value.ToString(), Cel.InheritedStyle.Font,
new SolidBrush(Cel.InheritedStyle.ForeColor),
new RectangleF((int)arrColumnLefts[iCount], (float)iTopMargin,
(int)arrColumnWidths[iCount], (float)iCellHeight), strFormat);
}
//Drawing Cells Borders
//e.Graphics.DrawRectangle(Pens.Black, new Rectangle((int)arrColumnLefts[iCount],
// iTopMargin, (int)arrColumnWidths[iCount], iCellHeight));
}
if (Cel.InheritedStyle.BackColor != Color.DarkSeaGreen)
{
e.Graphics.DrawRectangle(Pens.Black, new Rectangle((int)arrColumnLefts[iCount],
iTopMargin, (int)arrColumnWidths[iCount], iCellHeight));
}
iCount++;
}
}
iRow++;
iTopMargin += iCellHeight;
}
//If more lines exist, print another page.
if (bMorePagesToPrint)
e.HasMorePages = true;
else
e.HasMorePages = false;
}
catch (Exception exc)
{
MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
private void printCal_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
try
{
strFormat = new StringFormat();
strFormat.Alignment = StringAlignment.Near;
strFormat.LineAlignment = StringAlignment.Center;
strFormat.Trimming = StringTrimming.EllipsisCharacter;
arrColumnLefts.Clear();
arrColumnWidths.Clear();
iCellHeight = 0;
iRow = 0;
bFirstPage = true;
bNewPage = true;
// Calculating Total Widths
iTotalWidth = 0;
foreach (DataGridViewColumn dgvGridCol in DG.Columns)
{
iTotalWidth += dgvGridCol.Width;
}
}
catch (System.ServiceModel.CommunicationException commp)
{
MessageBox.Show(Utility.CommunicationErrorMsg, Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void printCal_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
try
{
//Set the left margin
int iLeftMargin = e.MarginBounds.Left;
//Set the top margin
int iTopMargin = e.MarginBounds.Top;
//Whether more pages have to print or not
bool bMorePagesToPrint = false;
int iTmpWidth = 0;
//For the first page to print set the cell width and header height
if (bFirstPage)
{
foreach (DataGridViewColumn GridCol in DG.Columns)
{
//iTmpWidth = 14;
iTmpWidth = (int)(Math.Floor((double)((double)GridCol.Width /
(double)iTotalWidth * (double)iTotalWidth *
((double)e.MarginBounds.Width / (double)iTotalWidth)))) + 1;
iHeaderHeight = (int)(e.Graphics.MeasureString(GridCol.HeaderText,
GridCol.InheritedStyle.Font, iTmpWidth).Height) + 11;
// Save width and height of headres
arrColumnLefts.Add(iLeftMargin);
arrColumnWidths.Add(iTmpWidth);
iLeftMargin += iTmpWidth;
}
}
//Loop till all the grid rows not get printed
while (iRow <= DG.Rows.Count - 1)
{
DataGridViewRow GridRow = DG.Rows[iRow];
//Set the cell height
iCellHeight = GridRow.Height + 5;
int iCount = 0;
//Check whether the current page settings allo more rows to print
if (iTopMargin + iCellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
{
bNewPage = true;
bFirstPage = false;
bMorePagesToPrint = true;
break;
}
else
{
if (bNewPage)
{
//Draw Header
e.Graphics.DrawString("Operation Schedule", new Font(DG.Font, FontStyle.Bold),
Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top + 2 -
e.Graphics.MeasureString("Operation Schedule", new Font(DG.Font,
FontStyle.Bold), e.MarginBounds.Width).Height - 13);
e.Graphics.DrawString(Utility.GetCompanyName, new Font(DG.Font, FontStyle.Bold),
Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top + 20 -
e.Graphics.MeasureString(Utility.GetCompanyName, new Font(DG.Font,
FontStyle.Bold), e.MarginBounds.Width).Height - 13);
e.Graphics.DrawString("115/7/A Distillary Road, Gandaria", new Font(DG.Font, FontStyle.Bold),
Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top + 40 -
e.Graphics.MeasureString("115/7/A Distillary Road, Gandaria", new Font(DGbarChart.Font,
FontStyle.Bold), e.MarginBounds.Width).Height - 13);
e.Graphics.DrawString("Dhaka-1207, Bangladesh", new Font(DG.Font, FontStyle.Bold),
Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top + 60 -
e.Graphics.MeasureString("Dhaka-1207, Bangladesh", new Font(DG.Font,
FontStyle.Bold), e.MarginBounds.Width).Height - 13);
e.Graphics.DrawString("[T]:88-02-7440527,7440907 [F]:88-02-7441006", new Font(DG.Font, FontStyle.Bold),
Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top + 80 -
e.Graphics.MeasureString("[T]:88-02-7440527,7440907 [F]:88-02-7441006", new Font(DG.Font,
FontStyle.Bold), e.MarginBounds.Width).Height - 13);
//e.Graphics.DrawString("Schedule Date: " + dteOTSchedulingDate.Text, new Font(DG.Font, FontStyle.Bold),
// Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top + 80 -
// e.Graphics.MeasureString("Schedule Date: " + dteOTSchedulingDate.Text, new Font(DG.Font,
// FontStyle.Bold), e.MarginBounds.Width).Height - 13);
String strDate = "Print Date: " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString();
//Draw Date
e.Graphics.DrawString(strDate, new Font(DG.Font, FontStyle.Regular),
Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width -
e.Graphics.MeasureString(strDate, new Font(DG.Font,
FontStyle.Regular), e.MarginBounds.Width).Width), e.MarginBounds.Top -
e.Graphics.MeasureString("Operation Schedule", new Font(new Font(DG.Font,
FontStyle.Regular), FontStyle.Regular), e.MarginBounds.Width).Height - 13);
e.Graphics.DrawString("Schedule Date: " + dteOTSchedulingDate.Text, new Font(DG.Font, FontStyle.Regular),
Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width -
e.Graphics.MeasureString(strDate, new Font(DG.Font,
FontStyle.Regular), e.MarginBounds.Width).Width), e.MarginBounds.Top +15-
e.Graphics.MeasureString("Schedule Date: " + dteOTSchedulingDate.Text, new Font(new Font(DG.Font,
FontStyle.Regular), FontStyle.Regular), e.MarginBounds.Width).Height - 13);
//Draw Columns
iTopMargin = e.MarginBounds.Top + 75;
foreach (DataGridViewColumn GridCol in DG.Columns)
{
e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),
new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
(int)arrColumnWidths[iCount], iHeaderHeight));
e.Graphics.DrawRectangle(Pens.Black,
new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
(int)arrColumnWidths[iCount], iHeaderHeight));
e.Graphics.DrawString(GridCol.HeaderText, GridCol.InheritedStyle.Font,
new SolidBrush(GridCol.InheritedStyle.ForeColor),
new RectangleF((int)arrColumnLefts[iCount], iTopMargin,
(int)arrColumnWidths[iCount], iHeaderHeight), strFormat);
iCount++;
}
bNewPage = false;
iTopMargin += iHeaderHeight;
}
iCount = 0;
//Draw Columns Contents
foreach (DataGridViewCell Cel in GridRow.Cells)
{
if (Cel.Value != null)
{
if (Cel.InheritedStyle.BackColor == Color.Pink)
{
//MessageBox.Show("");
//e.Graphics.DrawString(Cel.Value.ToString(), Cel.InheritedStyle.Font,
// new SolidBrush(Cel.InheritedStyle.BackColor),
// new RectangleF((int)arrColumnLefts[iCount], (float)iTopMargin,
// (int)arrColumnWidths[iCount], (float)iCellHeight), strFormat);
e.Graphics.DrawString(Cel.Value.ToString(), Cel.InheritedStyle.Font,
new SolidBrush(Cel.InheritedStyle.ForeColor),
new RectangleF((int)arrColumnLefts[iCount], (float)iTopMargin,
(int)arrColumnWidths[iCount], (float)iCellHeight), strFormat);
}
else
{
e.Graphics.DrawString(Cel.Value.ToString(), Cel.InheritedStyle.Font,
new SolidBrush(Cel.InheritedStyle.ForeColor),
new RectangleF((int)arrColumnLefts[iCount], (float)iTopMargin,
(int)arrColumnWidths[iCount], (float)iCellHeight), strFormat);
e.Graphics.DrawRectangle(Pens.Black, new Rectangle((int)arrColumnLefts[iCount],
iTopMargin, (int)arrColumnWidths[iCount], iCellHeight));
}
}
else
{
if (Cel.InheritedStyle.BackColor != Color.Pink)
{
e.Graphics.DrawRectangle(Pens.Black, new Rectangle((int)arrColumnLefts[iCount],
iTopMargin, (int)arrColumnWidths[iCount], iCellHeight));
}
}
//Drawing Cells Borders
//e.Graphics.DrawRectangle(Pens.Black, new Rectangle((int)arrColumnLefts[iCount],
// iTopMargin, (int)arrColumnWidths[iCount], iCellHeight));
iCount++;
}
}
iRow++;
iTopMargin += iCellHeight;
}
//If more lines exist, print another page.
if (bMorePagesToPrint)
e.HasMorePages = true;
else
e.HasMorePages = false;
}
catch (Exception exc)
{
MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnPrintCal_Click(object sender, EventArgs e)
{
PrintDialog printDialog = new PrintDialog();
printDialog.Document = printCal;
printDialog.UseEXDialog = true;
//Get the document
if (DialogResult.OK == printDialog.ShowDialog())
{
printCal.DocumentName = "OT Calender Print";
//printPreviewDialog1.Document = printDocument2;
Printpreview.Document = printCal;
Printpreview.PrintPreviewControl.Zoom = 1;
//printCal.Print();
Printpreview.ShowDialog();
}
}
private void btnPrint_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
PrintDialog printDialog = new PrintDialog();
printDialog.Document = printDoc;
printDialog.UseEXDialog = true;
//Get the document
if (DialogResult.OK == printDialog.ShowDialog())
{
printDoc.DocumentName = "OT Calender Print";
//printPreviewDialog1.Document = printDocument2;
Printpreview.Document = printDoc;
Printpreview.PrintPreviewControl.Zoom = 1;
//printCal.Print();
Printpreview.ShowDialog();
}
}
private void btnSave_Click(object sender, EventArgs e)
{
}
}
}
| 48.457976 | 263 | 0.49377 | [
"Apache-2.0"
] | atiq-shumon/DotNetProjects | Hospital_ERP_VS13-WCF_WF/AH.ModuleController/UI/OPR/Forms/frmOTCalender.cs | 56,504 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Kata.CustomTypes.Gamependium
{
public abstract class GameBase
{
protected List<PieceSetBase> Sets { get; }
protected IResetter Board { get; set; }
public GameBase(IPlayerService playerService)
{
Sets = new List<PieceSetBase>();
CreatePieceSets();
CreateBoard();
}
protected abstract void CreatePieceSets();
protected abstract void CreateBoard();
public virtual void Display(bool reset = false)
{
if (reset)
{
Board.Reset();
}
Console.WriteLine(Board);
}
}
}
| 23.580645 | 55 | 0.563611 | [
"MIT"
] | contino/dotnet-training-course | Kata/CustomTypes/AdHoc/Gamependium/GameBase.cs | 733 | C# |
using AConfig;
using NeoCortexApi.Entities;
using NeoCortexApi;
using NeoCortexApi.Network;
using NeoCortexApi.Utility;
using Daenet.ImageBinarizerLib;
using Daenet.ImageBinarizerLib.Entities;
namespace ConsoleApp
{
internal class Experiment
{
HtmConfig htmConfig;
ArgsConfig expConfig;
public Experiment(ArgsConfig config)
{
expConfig = config;
htmConfig = config.htmConfig;
}
public void run()
{
int height = htmConfig.InputDimensions[0];
int width = htmConfig.InputDimensions[1];
Dictionary<string, int[]> sdrs;
// By default it only returns subdirectories one level deep.
var directories = Directory.GetDirectories(expConfig.inputFolder).ToList();
(Dictionary<string, int[]> binaries, // List of Binarized images
Dictionary<string, List<string>> inputsPath // Path of the list of images found in the given folder
) = imageBinarization(directories, width, height);
// The key of the dictionary helps to keep track of which class the SDR belongs to
(sdrs, var cortexLayer) = SPTrain(htmConfig, binaries);
HelpersTemp helperFunc = new HelpersTemp();
Dictionary<string, double> listCorrelation = new();
Dictionary<string, double> ListInputcorelation = new();
foreach (KeyValuePair<string, List<string>> entry in inputsPath) // loop of the folder (classes) eg: cabbage, carrot, etc
{
var classLabel = entry.Key;
var filePathList = entry.Value;
var numberOfImages = filePathList.Count;
for (int i = 0; i < numberOfImages; i++) // loop of the images inside the folder
{
if (!sdrs.TryGetValue(filePathList[i], out int[] sdr1)) continue;
foreach (KeyValuePair<string, List<string>> secondEntry in inputsPath)
{ // loop of the folder (again)
var classLabel2 = secondEntry.Key;
var filePathList2 = secondEntry.Value;
var numberOfImages2 = filePathList2.Count;
// loop of the images inside the folder
for (int j = 0; j < numberOfImages2; j++)
{
if (!sdrs.TryGetValue(filePathList2[j], out int[] sdr2)) continue;
string fileNameofFirstImage = Path.GetFileNameWithoutExtension(filePathList[i]);
string fileNameOfSecondImage = Path.GetFileNameWithoutExtension(filePathList2[j]);
string temp = $"{classLabel + fileNameofFirstImage}__{classLabel2 + fileNameOfSecondImage}";
listCorrelation.Add(temp, MathHelpers.CalcArraySimilarity(sdr1, sdr2));
//find the similarity between the pictures from same folder
ListInputcorelation.Add(temp, MathHelpers.CalcArraySimilarity(binaries[filePathList[i]].IndexWhere((el) => el == 1), binaries[filePathList2[j]].IndexWhere((el) => el == 1)));
}
}
}
}
var classes = inputsPath.Keys.ToList();
helperFunc.printSimilarityMatrix(listCorrelation, "micro", classes);
helperFunc.printSimilarityMatrix(listCorrelation, "macro", classes);
helperFunc.printSimilarityMatrix(listCorrelation, "both", classes);
///Console.WriteLine(ListInputcorelation["Cabbagepic1__CabbagePic2"]);
///input file encoding
/// passing the SDR values and given image SDR value after image binarization to the function PredictLabel
///int[] encodedInputImage = ReadImageData("C:/Software Engineering/Project/neocortexapi-classification/ImageClassification/ImageClassification/bin/Debug/net6.0/InputFolder/Cabbage/CA_6.jpg", width, height);
///Changing hard coded image path to get the folder details from command prompt and then predict the folder.
Console.WriteLine("Please enter the folder path to predict the label of the image");
string encodedInputImage = Console.ReadLine();
int[] encodedInputImages = ReadImageData(encodedInputImage, height, width);
var temp1 = cortexLayer.Compute(encodedInputImages, true);
var activeColumns = cortexLayer.GetResult("sp") as int[];
var sdrOfInputImage = activeColumns.OrderBy(c => c).ToArray();
string predictedLabel = PredictLabel(sdrOfInputImage, sdrs);
Console.WriteLine($"The label predicted is { predictedLabel}");
Console.ReadLine();
/// <summary>
/// To find out the label prediction of the given image
/// Created by Codechasers
/// </summary>
/// <param name="sdrOfInputImage"></param>
/// <param name="sdrs"></param>
/// <returns></returns>
string PredictLabel(int[] sdrOfInputImage, Dictionary<string, int[]> sdrs)
{
//Dictionary<string, List<string>> inputsPath = new Dictionary<string, List<string>>();
string label = "Could not able to predict the label";
double similarityWithEachSDR = 0;
double similarityWithPreviousSDR = 0;
double temp1 = 0;
foreach (KeyValuePair<string, List<string>> secondEntry in inputsPath)
{
double sumOfSimilarities = 0; //sum of similarities with images in Same Class(Label)
// loop of each folder in input folder
var classLabel2 = secondEntry.Key;
var filePathList2 = secondEntry.Value;
var numberOfImages2 = filePathList2.Count;
for (int j = 0; j < numberOfImages2; j++) // loop of each image in each category of inputs
{
if (!sdrs.TryGetValue(filePathList2[j], out int[] sdr2)) continue;
//calculating the similarity between SDR of Input Images with the SDR of the current iterated image (Learning Dataset)
similarityWithEachSDR = MathHelpers.CalcArraySimilarity(sdrOfInputImage, sdr2);
sumOfSimilarities += similarityWithEachSDR;
}
//calculating the Average similarity of the Input Image with Learning Images in each Category (Label)
sumOfSimilarities /= numberOfImages2;
if (sumOfSimilarities > temp1)
{
temp1 = sumOfSimilarities;
label = $"{"The image is predicted as " + secondEntry.Key}";
if (temp1 < 50.0) //This depends and selected based on the HTM parameters given in htmconfig.json file
{
label = "The similarity of Input Image is too low, hence the given image might not belong to the Learning Dataset";
}
}
Console.WriteLine("\n> The Input Image is similar to Digit" + secondEntry.Key + " by " + sumOfSimilarities + " %");
}
//Display the highest similarity of the Input Image with the training category
Console.WriteLine("\n Highest Similarity is: " + temp1 + " % ");
return label;
}
}
/// <summary>
/// Get the Image path and width and height for Image Binarization
/// </summary>
/// <param name="directories"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <returns></returns>
private Tuple<Dictionary<string, int[]>, Dictionary<string, List<string>>> imageBinarization(List<string> directories, int width, int height)
{
Dictionary<string, List<string>> inputsPath = new Dictionary<string, List<string>>();
Dictionary<string, int[]> binaries = new Dictionary<string, int[]>();
foreach (var fullPath in directories)
{
string folderName = Path.GetFileName(fullPath);
if (!inputsPath.ContainsKey(folderName))
{
inputsPath[folderName] = new List<string>();
}
var filePathList = Directory.GetFiles(fullPath).Where(name => !name.EndsWith(".txt")).ToList();
foreach (var filePath in filePathList)
{
inputsPath[folderName].Add(filePath);
// Image binarization
int[] inputVector = ReadImageData(filePath, height, width);
binaries.Add(filePath, inputVector);
// Write binarized data to a file
var baseDir = Path.GetDirectoryName(filePath);
var fileNameWithoutExt = Path.GetFileNameWithoutExtension(filePath);
var ext = "txt";
var fullFileName = $"{fileNameWithoutExt}.{ext}";
System.IO.File.WriteAllLines(Path.Combine(baseDir, fullFileName), inputVector.Select(tb => tb.ToString()));
}
}
return Tuple.Create(binaries, inputsPath);
}
/// <summary>
/// Returns Binarized Image in integer array
/// </summary>
/// <param name="imagePath">Name of Image to be binarized</param>
/// <param name="height">Height of Binarized Image</param>
/// <param name="width">Width of Binarized Image</param>
/// Parameter modified by Veena to check the result accuracy
/// <returns></returns>
public int[] ReadImageData(string imagePath, int height, int width)
{
var parameters = new BinarizerParams
{
InputImagePath = imagePath,
ImageHeight = height,
ImageWidth = width,
BlueThreshold = 201,
RedThreshold = 205,
GreenThreshold = 210
};
ImageBinarizer bizer = new ImageBinarizer(parameters);
var doubleArray = bizer.GetArrayBinary();
var hg = doubleArray.GetLength(1);
var wd = doubleArray.GetLength(0);
var intArray = new int[hg * wd];
for (int j = 0; j < hg; j++)
{
for (int i = 0; i < wd; i++)
{
intArray[j * wd + i] = (int)doubleArray[i, j, 0];
}
}
return intArray;
}
/// <summary> Modified by Long Nguyen
/// Pulling out SDRs after HPC fires a STABLE event when training the SP with list of patterns
/// </summary>
/// <param name="cfg"></param> Spatial Pooler configuration by HtmConfig style
/// <param name="inputValues"></param> Binary input vector (pattern) list
private static (Dictionary<string, int[]>, CortexLayer<object, object> cortexLayer) SPTrain(HtmConfig cfg, Dictionary<string, int[]> inputValues)
{
// Creates the htm memory.
var mem = new Connections(cfg);
bool isInStableState = false;
// HPC extends the default Spatial Pooler algorithm.
// The purpose of HPC is to set the SP in the new-born stage at the begining of the learning process.
// In this stage the boosting is very active, but the SP behaves instable. After this stage is over
// (defined by the second argument) the HPC is controlling the learning process of the SP.
// Once the SDR generated for every input gets stable, the HPC will fire event that notifies your code
// that SP is stable now.
HomeostaticPlasticityController hpa = new HomeostaticPlasticityController(mem, inputValues.Count * 40,
(isStable, numPatterns, actColAvg, seenInputs) =>
{
// Event should only be fired when entering the stable state.
// Ideal SP should never enter unstable state after stable state.
if (isStable == false)
{
Console.WriteLine($"INSTABLE STATE");
// This should usually not happen.
isInStableState = false;
}
else
{
Console.WriteLine($"STABLE STATE");
// Here you can perform any action if required.
isInStableState = true;
}
});
// It creates the instance of Spatial Pooler Multithreaded version.
SpatialPooler sp = new SpatialPoolerMT(hpa);
// Initializes the Spatial Pooler
sp.Init(mem, new DistributedMemory() { ColumnDictionary = new InMemoryDistributedDictionary<int, NeoCortexApi.Entities.Column>(1) });
// mem.TraceProximalDendritePotential(true);
// It creates the instance of the neo-cortex layer.
// Algorithm will be performed inside of that layer.
CortexLayer<object, object> cortexLayer = new CortexLayer<object, object>("L1");
// Add encoder as the very first module. This model is connected to the sensory input cells
// that receive the input. Encoder will receive the input and forward the encoded signal
// to the next module.
//cortexLayer.HtmModules.Add("encoder", encoder);
// The next module in the layer is Spatial Pooler. This module will receive the output of the
// encoder.
cortexLayer.HtmModules.Add("sp", sp);
// Learning process will take 1000 iterations (cycles)
int maxSPLearningCycles = 1;
// Save the result SDR into a list of array
Dictionary<string, int[]> outputValues = new Dictionary<string, int[]>();
for (int cycle = 0; cycle < maxSPLearningCycles; cycle++)
{
Console.WriteLine($"Cycle ** {cycle} ** Stability: {isInStableState}");
int iteration = 0;
outputValues.Clear(); // Remove all elements in output SDR list
// This trains the layer on input pattern.
foreach (var input in inputValues)
{
iteration++;
// Learn the input pattern.
// Output lyrOut is the output of the last module in the layer.
var lyrOut = cortexLayer.Compute(input.Value, true);
// This is a general way to get the SpatialPooler result from the layer.
var activeColumns = cortexLayer.GetResult("sp") as int[];
var actCols = activeColumns.OrderBy(c => c).ToArray();
outputValues[input.Key] = actCols;
}
if (isInStableState)
break;
}
return (outputValues, cortexLayer);
}
}
}
| 48.725552 | 230 | 0.564353 | [
"Apache-2.0"
] | VeenaAlphonsa/neocortexapi-classification | ImageClassification/ImageClassification/Experiment.cs | 15,448 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using NBitcoin;
using Stratis.Bitcoin.Connection;
using Stratis.Bitcoin.P2P.Peer;
using Stratis.Bitcoin.Utilities;
using Stratis.FederatedPeg.Features.FederationGateway.Interfaces;
using Stratis.FederatedPeg.Features.FederationGateway.NetworkHelpers;
namespace Stratis.FederatedPeg.Features.FederationGateway.TargetChain
{
/// <inheritdoc />
public class PartialTransactionRequester : IPartialTransactionRequester
{
private readonly ILoggerFactory loggerFactory;
private readonly ILogger logger;
private readonly ICrossChainTransferStore crossChainTransferStore;
private readonly IAsyncLoopFactory asyncLoopFactory;
private readonly INodeLifetime nodeLifetime;
private readonly IConnectionManager connectionManager;
private readonly IFederationGatewaySettings federationGatewaySettings;
private IAsyncLoop asyncLoop;
public PartialTransactionRequester(
ILoggerFactory loggerFactory,
ICrossChainTransferStore crossChainTransferStore,
IAsyncLoopFactory asyncLoopFactory,
INodeLifetime nodeLifetime,
IConnectionManager connectionManager,
IFederationGatewaySettings federationGatewaySettings)
{
Guard.NotNull(loggerFactory, nameof(loggerFactory));
Guard.NotNull(crossChainTransferStore, nameof(crossChainTransferStore));
Guard.NotNull(asyncLoopFactory, nameof(asyncLoopFactory));
Guard.NotNull(nodeLifetime, nameof(nodeLifetime));
Guard.NotNull(federationGatewaySettings, nameof(federationGatewaySettings));
this.loggerFactory = loggerFactory;
this.logger = loggerFactory.CreateLogger(this.GetType().FullName);
this.crossChainTransferStore = crossChainTransferStore;
this.asyncLoopFactory = asyncLoopFactory;
this.nodeLifetime = nodeLifetime;
this.connectionManager = connectionManager;
this.federationGatewaySettings = federationGatewaySettings;
}
/// <inheritdoc />
public async Task BroadcastAsync(RequestPartialTransactionPayload payload)
{
List<INetworkPeer> peers = this.connectionManager.ConnectedPeers.ToList();
var ipAddressComparer = new IPAddressComparer();
foreach (INetworkPeer peer in peers)
{
// Broadcast to peers.
if (!peer.IsConnected)
continue;
if (this.federationGatewaySettings.FederationNodeIpEndPoints.Any(e => ipAddressComparer.Equals(e.Address, peer.PeerEndPoint.Address)))
{
try
{
await peer.SendMessageAsync(payload).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
}
}
}
/// <inheritdoc />
public void Start()
{
this.asyncLoop = this.asyncLoopFactory.Run(nameof(PartialTransactionRequester), token =>
{
// Broadcast the partial transaction with the earliest inputs.
KeyValuePair<uint256, Transaction> kv = this.crossChainTransferStore.GetTransactionsByStatusAsync(
CrossChainTransferStatus.Partial, true).GetAwaiter().GetResult().FirstOrDefault();
if (kv.Key != null)
{
BroadcastAsync(new RequestPartialTransactionPayload(kv.Key).AddPartial(kv.Value)).GetAwaiter().GetResult();
this.logger.LogInformation("Partial template requested");
}
this.logger.LogTrace("(-)[PARTIAL_TEMPLATES_JOB]");
return Task.CompletedTask;
},
this.nodeLifetime.ApplicationStopping,
TimeSpans.TenSeconds);
}
/// <inheritdoc />
public void Stop()
{
if (this.asyncLoop != null)
{
this.asyncLoop.Dispose();
this.asyncLoop = null;
}
}
}
}
| 39.236364 | 150 | 0.634847 | [
"MIT"
] | quantumagi/FederatedSidechains | src/Stratis.FederatedPeg.Features.FederationGateway/TargetChain/PartialTransactionRequester.cs | 4,318 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Azure.Core.Testing;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Azure.AI.TextAnalytics.Samples
{
[LiveOnly]
public partial class TextAnalyticsSamples
{
[Test]
public void DetectLanguageBatch()
{
string endpoint = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_ENDPOINT");
string apiKey = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_API_KEY");
// Instantiate a client that will be used to call the service.
var client = new TextAnalyticsClient(new Uri(endpoint), new TextAnalyticsApiKeyCredential(apiKey));
#region Snippet:TextAnalyticsSample1DetectLanguageBatch
var inputs = new List<DetectLanguageInput>
{
new DetectLanguageInput("1", "Hello world")
{
CountryHint = "us",
},
new DetectLanguageInput("2", "Bonjour tout le monde")
{
CountryHint = "fr",
},
new DetectLanguageInput("3", "Hola mundo")
{
CountryHint = "es",
},
new DetectLanguageInput("4", ":) :( :D")
{
CountryHint = DetectLanguageInput.None,
}
};
DetectLanguageResultCollection results = client.DetectLanguageBatch(inputs, new TextAnalyticsRequestOptions { IncludeStatistics = true });
#endregion
int i = 0;
Debug.WriteLine($"Results of Azure Text Analytics \"Detect Language\" Model, version: \"{results.ModelVersion}\"");
Debug.WriteLine("");
foreach (DetectLanguageResult result in results)
{
DetectLanguageInput document = inputs[i++];
Debug.WriteLine($"On document (Id={document.Id}, CountryHint=\"{document.CountryHint}\", Text=\"{document.Text}\"):");
if (result.HasError)
{
Debug.WriteLine($" Document error code: {result.Error.Code}.");
Debug.WriteLine($" Message: {result.Error.Message}.");
}
else
{
Debug.WriteLine($" Detected language {result.PrimaryLanguage.Name} with confidence {result.PrimaryLanguage.Score}.");
Debug.WriteLine($" Document statistics:");
Debug.WriteLine($" Character count (in Unicode graphemes): {result.Statistics.GraphemeCount}");
Debug.WriteLine($" Transaction count: {result.Statistics.TransactionCount}");
Debug.WriteLine("");
}
}
Debug.WriteLine($"Batch operation statistics:");
Debug.WriteLine($" Document count: {results.Statistics.DocumentCount}");
Debug.WriteLine($" Valid document count: {results.Statistics.ValidDocumentCount}");
Debug.WriteLine($" Invalid document count: {results.Statistics.InvalidDocumentCount}");
Debug.WriteLine($" Transaction count: {results.Statistics.TransactionCount}");
Debug.WriteLine("");
}
}
}
| 41.156627 | 150 | 0.565574 | [
"MIT"
] | Kishp01/azure-sdk-for-net | sdk/textanalytics/Azure.AI.TextAnalytics/tests/samples/Sample1_DetectLanguageBatch.cs | 3,418 | C# |
/*
* Copyright (c) 2019-2021 Angouri.
* AngouriMath is licensed under MIT.
* Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
* Website: https://am.angouri.org.
*/
using AngouriMath.Core;
namespace AngouriMath
{
partial record Entity
{
partial record Number
{
#pragma warning disable SealedOrAbstract // The only exception: those three records are neither abstract nor sealed
partial record Complex
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Complex;
}
partial record Rational
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Rational;
}
partial record Real
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Real;
}
#pragma warning restore SealedOrAbstract
partial record Integer
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Integer;
}
}
partial record Variable
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Any;
}
partial record Tensor
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Any;
}
partial record Sumf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Complex;
}
partial record Minusf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Complex;
}
partial record Mulf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Complex;
}
partial record Divf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Complex;
}
partial record Sinf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Complex;
}
partial record Cosf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Complex;
}
partial record Tanf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Complex;
}
partial record Cotanf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Complex;
}
partial record Logf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Complex;
}
partial record Powf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Complex;
}
partial record Secantf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Complex;
}
partial record Cosecantf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Complex;
}
partial record Arcsecantf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Complex;
}
partial record Arccosecantf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Complex;
}
partial record Arcsinf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Complex;
}
partial record Arccosf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Complex;
}
partial record Arctanf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Complex;
}
partial record Arccotanf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Complex;
}
partial record Factorialf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Complex;
}
partial record Derivativef
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Complex;
}
partial record Integralf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Complex;
}
partial record Limitf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Complex;
}
partial record Signumf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Complex;
}
partial record Absf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Real;
}
partial record Boolean
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Boolean;
}
partial record Notf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Boolean;
}
partial record Andf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Boolean;
}
partial record Orf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Boolean;
}
partial record Xorf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Boolean;
}
partial record Impliesf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Boolean;
}
partial record Equalsf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Boolean;
}
partial record Greaterf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Boolean;
}
partial record GreaterOrEqualf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Boolean;
}
partial record Lessf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Boolean;
}
partial record LessOrEqualf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Boolean;
}
partial record Set
{
partial record FiniteSet
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Any;
}
partial record Interval
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Real;
}
partial record ConditionalSet
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Any;
}
partial record SpecialSet
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Any;
}
partial record Unionf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Any;
}
partial record Intersectionf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Any;
}
partial record SetMinusf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Any;
}
partial record Inf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Boolean;
}
}
partial record Phif
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Integer;
}
partial record Providedf
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Any;
}
partial record Piecewise
{
/// <inheritdoc/>
public override Domain Codomain { get; protected init; } = Domain.Any;
}
}
}
| 28.52994 | 115 | 0.508868 | [
"MIT"
] | Suchiman/AngouriMath | Sources/AngouriMath/Core/Domains.Classes.cs | 9,531 | C# |
#region License
// Copyright (c) 2007 James Newton-King
//
// 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.Collections.Generic;
using System.Globalization;
using System.Text;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Linq.JsonPath
{
internal class JPath
{
private readonly string _expression;
public List<PathFilter> Filters { get; private set; }
private int _currentIndex;
public JPath(string expression)
{
ValidationUtils.ArgumentNotNull(expression, "expression");
_expression = expression;
Filters = new List<PathFilter>();
ParseMain();
}
private void ParseMain()
{
int currentPartStartIndex = _currentIndex;
EatWhitespace();
if (_expression.Length == _currentIndex)
{
return;
}
if (_expression[_currentIndex] == '$')
{
if (_expression.Length == 1)
{
return;
}
// only increment position for "$." or "$["
// otherwise assume property that starts with $
char c = _expression[_currentIndex + 1];
if (c == '.' || c == '[')
{
_currentIndex++;
currentPartStartIndex = _currentIndex;
}
}
if (!ParsePath(Filters, currentPartStartIndex, false))
{
int lastCharacterIndex = _currentIndex;
EatWhitespace();
if (_currentIndex < _expression.Length)
{
throw new JsonException("Unexpected character while parsing path: " + _expression[lastCharacterIndex]);
}
}
}
private bool ParsePath(List<PathFilter> filters, int currentPartStartIndex, bool query)
{
bool scan = false;
bool followingIndexer = false;
bool followingDot = false;
bool ended = false;
while (_currentIndex < _expression.Length && !ended)
{
char currentChar = _expression[_currentIndex];
switch (currentChar)
{
case '[':
case '(':
if (_currentIndex > currentPartStartIndex)
{
string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex);
PathFilter filter = (scan) ? (PathFilter)new ScanFilter() { Name = member } : new FieldFilter() { Name = member };
filters.Add(filter);
scan = false;
}
filters.Add(ParseIndexer(currentChar));
_currentIndex++;
currentPartStartIndex = _currentIndex;
followingIndexer = true;
followingDot = false;
break;
case ']':
case ')':
ended = true;
break;
case ' ':
//EatWhitespace();
if (_currentIndex < _expression.Length)
{
ended = true;
}
break;
case '.':
if (_currentIndex > currentPartStartIndex)
{
string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex);
if (member == "*")
{
member = null;
}
PathFilter filter = (scan) ? (PathFilter)new ScanFilter() { Name = member } : new FieldFilter() { Name = member };
filters.Add(filter);
scan = false;
}
if (_currentIndex + 1 < _expression.Length && _expression[_currentIndex + 1] == '.')
{
scan = true;
_currentIndex++;
}
_currentIndex++;
currentPartStartIndex = _currentIndex;
followingIndexer = false;
followingDot = true;
break;
default:
if (query && (currentChar == '=' || currentChar == '<' || currentChar == '!' || currentChar == '>' || currentChar == '|' || currentChar == '&'))
{
ended = true;
}
else
{
if (followingIndexer)
{
throw new JsonException("Unexpected character following indexer: " + currentChar);
}
_currentIndex++;
}
break;
}
}
bool atPathEnd = (_currentIndex == _expression.Length);
if (_currentIndex > currentPartStartIndex)
{
string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex).TrimEnd();
if (member == "*")
{
member = null;
}
PathFilter filter = (scan) ? (PathFilter)new ScanFilter() { Name = member } : new FieldFilter() { Name = member };
filters.Add(filter);
}
else
{
// no field name following dot in path and at end of base path/query
if (followingDot && (atPathEnd || query))
{
throw new JsonException("Unexpected end while parsing path.");
}
}
return atPathEnd;
}
private PathFilter ParseIndexer(char indexerOpenChar)
{
_currentIndex++;
char indexerCloseChar = (indexerOpenChar == '[') ? ']' : ')';
EnsureLength("Path ended with open indexer.");
EatWhitespace();
if (_expression[_currentIndex] == '\'')
{
return ParseQuotedField(indexerCloseChar);
}
else if (_expression[_currentIndex] == '?')
{
return ParseQuery(indexerCloseChar);
}
else
{
return ParseArrayIndexer(indexerCloseChar);
}
}
private PathFilter ParseArrayIndexer(char indexerCloseChar)
{
int start = _currentIndex;
int? end = null;
List<int> indexes = null;
int colonCount = 0;
int? startIndex = null;
int? endIndex = null;
int? step = null;
while (_currentIndex < _expression.Length)
{
char currentCharacter = _expression[_currentIndex];
if (currentCharacter == ' ')
{
end = _currentIndex;
EatWhitespace();
continue;
}
if (currentCharacter == indexerCloseChar)
{
int length = (end ?? _currentIndex) - start;
if (indexes != null)
{
if (length == 0)
{
throw new JsonException("Array index expected.");
}
string indexer = _expression.Substring(start, length);
int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture);
indexes.Add(index);
return new ArrayMultipleIndexFilter { Indexes = indexes };
}
else if (colonCount > 0)
{
if (length > 0)
{
string indexer = _expression.Substring(start, length);
int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture);
if (colonCount == 1)
{
endIndex = index;
}
else
{
step = index;
}
}
return new ArraySliceFilter { Start = startIndex, End = endIndex, Step = step };
}
else
{
if (length == 0)
{
throw new JsonException("Array index expected.");
}
string indexer = _expression.Substring(start, length);
int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture);
return new ArrayIndexFilter { Index = index };
}
}
else if (currentCharacter == ',')
{
int length = (end ?? _currentIndex) - start;
if (length == 0)
{
throw new JsonException("Array index expected.");
}
if (indexes == null)
{
indexes = new List<int>();
}
string indexer = _expression.Substring(start, length);
indexes.Add(Convert.ToInt32(indexer, CultureInfo.InvariantCulture));
_currentIndex++;
EatWhitespace();
start = _currentIndex;
end = null;
}
else if (currentCharacter == '*')
{
_currentIndex++;
EnsureLength("Path ended with open indexer.");
EatWhitespace();
if (_expression[_currentIndex] != indexerCloseChar)
{
throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter);
}
return new ArrayIndexFilter();
}
else if (currentCharacter == ':')
{
int length = (end ?? _currentIndex) - start;
if (length > 0)
{
string indexer = _expression.Substring(start, length);
int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture);
if (colonCount == 0)
{
startIndex = index;
}
else if (colonCount == 1)
{
endIndex = index;
}
else
{
step = index;
}
}
colonCount++;
_currentIndex++;
EatWhitespace();
start = _currentIndex;
end = null;
}
else if (!char.IsDigit(currentCharacter) && currentCharacter != '-')
{
throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter);
}
else
{
if (end != null)
{
throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter);
}
_currentIndex++;
}
}
throw new JsonException("Path ended with open indexer.");
}
private void EatWhitespace()
{
while (_currentIndex < _expression.Length)
{
if (_expression[_currentIndex] != ' ')
{
break;
}
_currentIndex++;
}
}
private PathFilter ParseQuery(char indexerCloseChar)
{
_currentIndex++;
EnsureLength("Path ended with open indexer.");
if (_expression[_currentIndex] != '(')
{
throw new JsonException("Unexpected character while parsing path indexer: " + _expression[_currentIndex]);
}
_currentIndex++;
QueryExpression expression = ParseExpression();
_currentIndex++;
EnsureLength("Path ended with open indexer.");
EatWhitespace();
if (_expression[_currentIndex] != indexerCloseChar)
{
throw new JsonException("Unexpected character while parsing path indexer: " + _expression[_currentIndex]);
}
return new QueryFilter
{
Expression = expression
};
}
private QueryExpression ParseExpression()
{
QueryExpression rootExpression = null;
CompositeExpression parentExpression = null;
while (_currentIndex < _expression.Length)
{
EatWhitespace();
if (_expression[_currentIndex] != '@')
{
throw new JsonException("Unexpected character while parsing path query: " + _expression[_currentIndex]);
}
_currentIndex++;
List<PathFilter> expressionPath = new List<PathFilter>();
if (ParsePath(expressionPath, _currentIndex, true))
{
throw new JsonException("Path ended with open query.");
}
EatWhitespace();
EnsureLength("Path ended with open query.");
QueryOperator op;
object value = null;
if (_expression[_currentIndex] == ')'
|| _expression[_currentIndex] == '|'
|| _expression[_currentIndex] == '&')
{
op = QueryOperator.Exists;
}
else
{
op = ParseOperator();
EatWhitespace();
EnsureLength("Path ended with open query.");
value = ParseValue();
EatWhitespace();
EnsureLength("Path ended with open query.");
}
BooleanQueryExpression booleanExpression = new BooleanQueryExpression
{
Path = expressionPath,
Operator = op,
Value = (op != QueryOperator.Exists) ? new JValue(value) : null
};
if (_expression[_currentIndex] == ')')
{
if (parentExpression != null)
{
parentExpression.Expressions.Add(booleanExpression);
return rootExpression;
}
return booleanExpression;
}
if (_expression[_currentIndex] == '&' && Match("&&"))
{
if (parentExpression == null || parentExpression.Operator != QueryOperator.And)
{
CompositeExpression andExpression = new CompositeExpression { Operator = QueryOperator.And };
if (parentExpression != null)
{
parentExpression.Expressions.Add(andExpression);
}
parentExpression = andExpression;
if (rootExpression == null)
{
rootExpression = parentExpression;
}
}
parentExpression.Expressions.Add(booleanExpression);
}
if (_expression[_currentIndex] == '|' && Match("||"))
{
if (parentExpression == null || parentExpression.Operator != QueryOperator.Or)
{
CompositeExpression orExpression = new CompositeExpression { Operator = QueryOperator.Or };
if (parentExpression != null)
{
parentExpression.Expressions.Add(orExpression);
}
parentExpression = orExpression;
if (rootExpression == null)
{
rootExpression = parentExpression;
}
}
parentExpression.Expressions.Add(booleanExpression);
}
}
throw new JsonException("Path ended with open query.");
}
private object ParseValue()
{
char currentChar = _expression[_currentIndex];
if (currentChar == '\'')
{
return ReadQuotedString();
}
else if (char.IsDigit(currentChar) || currentChar == '-')
{
StringBuilder sb = new StringBuilder();
sb.Append(currentChar);
_currentIndex++;
while (_currentIndex < _expression.Length)
{
currentChar = _expression[_currentIndex];
if (currentChar == ' ' || currentChar == ')')
{
string numberText = sb.ToString();
if (numberText.IndexOfAny(new char[] { '.', 'E', 'e' }) != -1)
{
double d;
if (double.TryParse(numberText, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out d))
{
return d;
}
else
{
throw new JsonException("Could not read query value.");
}
}
else
{
long l;
if (long.TryParse(numberText, NumberStyles.Integer, CultureInfo.InvariantCulture, out l))
{
return l;
}
else
{
throw new JsonException("Could not read query value.");
}
}
}
else
{
sb.Append(currentChar);
_currentIndex++;
}
}
}
else if (currentChar == 't')
{
if (Match("true"))
{
return true;
}
}
else if (currentChar == 'f')
{
if (Match("false"))
{
return false;
}
}
else if (currentChar == 'n')
{
if (Match("null"))
{
return null;
}
}
throw new JsonException("Could not read query value.");
}
private string ReadQuotedString()
{
StringBuilder sb = new StringBuilder();
_currentIndex++;
while (_currentIndex < _expression.Length)
{
char currentChar = _expression[_currentIndex];
if (currentChar == '\\' && _currentIndex + 1 < _expression.Length)
{
_currentIndex++;
if (_expression[_currentIndex] == '\'')
{
sb.Append('\'');
}
else if (_expression[_currentIndex] == '\\')
{
sb.Append('\\');
}
else
{
throw new JsonException(@"Unknown escape chracter: \" + _expression[_currentIndex]);
}
_currentIndex++;
}
else if (currentChar == '\'')
{
_currentIndex++;
{
return sb.ToString();
}
}
else
{
_currentIndex++;
sb.Append(currentChar);
}
}
throw new JsonException("Path ended with an open string.");
}
private bool Match(string s)
{
int currentPosition = _currentIndex;
foreach (char c in s)
{
if (currentPosition < _expression.Length && _expression[currentPosition] == c)
{
currentPosition++;
}
else
{
return false;
}
}
_currentIndex = currentPosition;
return true;
}
private QueryOperator ParseOperator()
{
if (_currentIndex + 1 >= _expression.Length)
{
throw new JsonException("Path ended with open query.");
}
if (Match("=="))
{
return QueryOperator.Equals;
}
if (Match("!=") || Match("<>"))
{
return QueryOperator.NotEquals;
}
if (Match("<="))
{
return QueryOperator.LessThanOrEquals;
}
if (Match("<"))
{
return QueryOperator.LessThan;
}
if (Match(">="))
{
return QueryOperator.GreaterThanOrEquals;
}
if (Match(">"))
{
return QueryOperator.GreaterThan;
}
throw new JsonException("Could not read query operator.");
}
private PathFilter ParseQuotedField(char indexerCloseChar)
{
List<string> fields = null;
while (_currentIndex < _expression.Length)
{
string field = ReadQuotedString();
EatWhitespace();
EnsureLength("Path ended with open indexer.");
if (_expression[_currentIndex] == indexerCloseChar)
{
if (fields != null)
{
fields.Add(field);
return new FieldMultipleFilter { Names = fields };
}
else
{
return new FieldFilter { Name = field };
}
}
else if (_expression[_currentIndex] == ',')
{
_currentIndex++;
EatWhitespace();
if (fields == null)
{
fields = new List<string>();
}
fields.Add(field);
}
else
{
throw new JsonException("Unexpected character while parsing path indexer: " + _expression[_currentIndex]);
}
}
throw new JsonException("Path ended with open indexer.");
}
private void EnsureLength(string message)
{
if (_currentIndex >= _expression.Length)
{
throw new JsonException(message);
}
}
internal IEnumerable<JToken> Evaluate(JToken t, bool errorWhenNoMatch)
{
return Evaluate(Filters, t, errorWhenNoMatch);
}
internal static IEnumerable<JToken> Evaluate(List<PathFilter> filters, JToken t, bool errorWhenNoMatch)
{
IEnumerable<JToken> current = new[] { t };
foreach (PathFilter filter in filters)
{
current = filter.ExecuteFilter(current, errorWhenNoMatch);
}
return current;
}
}
} | 34.142487 | 168 | 0.421732 | [
"MIT"
] | 2947721120/json | Src/Newtonsoft.Json/Linq/JsonPath/JPath.cs | 26,358 | C# |
using System.Threading.Tasks;
using Cosmos.Serialization.Toml.Nett;
// ReSharper disable once CheckNamespace
namespace Cosmos.Serialization.Toml
{
/// <summary>
/// TomlDotNet extensions
/// </summary>
public static partial class Extensions
{
/// <summary>
/// To Toml
/// </summary>
/// <param name="o"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static string ToToml<T>(this T o)
{
return NettHelper.Serialize(o);
}
/// <summary>
/// To Toml async
/// </summary>
/// <param name="o"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static Task<string> ToTomlAsync<T>(this T o)
{
return NettHelper.SerializeAsync(o);
}
}
} | 25.823529 | 59 | 0.53303 | [
"Apache-2.0"
] | alexinea/dotnet-static-pages | src/Cosmos.Serialization.Nett/Cosmos/Serialization/Toml/Extensions/Extensions.Nett.Object.cs | 878 | 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 waf-regional-2016-11-28.normal.json service model.
*/
using System;
using Amazon.Runtime;
using Amazon.Util.Internal;
namespace Amazon.WAFRegional
{
/// <summary>
/// Configuration for accessing Amazon WAFRegional service
/// </summary>
public partial class AmazonWAFRegionalConfig : ClientConfig
{
private static readonly string UserAgentString =
InternalSDKUtils.BuildUserAgentString("3.7.0.103");
private string _userAgent = UserAgentString;
/// <summary>
/// Default constructor
/// </summary>
public AmazonWAFRegionalConfig()
{
this.AuthenticationServiceName = "waf-regional";
}
/// <summary>
/// The constant used to lookup in the region hash the endpoint.
/// </summary>
public override string RegionEndpointServiceName
{
get
{
return "waf-regional";
}
}
/// <summary>
/// Gets the ServiceVersion property.
/// </summary>
public override string ServiceVersion
{
get
{
return "2016-11-28";
}
}
/// <summary>
/// Gets the value of UserAgent property.
/// </summary>
public override string UserAgent
{
get
{
return _userAgent;
}
}
}
} | 26.2875 | 110 | 0.589158 | [
"Apache-2.0"
] | EbstaLimited/aws-sdk-net | sdk/src/Services/WAFRegional/Generated/AmazonWAFRegionalConfig.cs | 2,103 | C# |
using System.Reflection;
using Unity.Entities;
namespace EntitiesBT.Entities
{
[UpdateBefore(typeof(VirtualMachineSystem))]
public class BehaviorTreeLifeCycleSystem : SystemBase
{
struct LastTargetComponent : ISystemStateComponentData
{
public Entity Target;
public NodeBlobRef Blob;
}
// TODO: sync-points optimization?
protected override void OnUpdate()
{
// create
Entities
.WithoutBurst()
.WithStructuralChanges()
.WithNone<LastTargetComponent>()
.ForEach((Entity entity, in BlackboardDataQuery query, in BehaviorTreeComponent bt, in BehaviorTreeTargetComponent target, in BehaviorTreeOrderComponent order) =>
{
var blob = new NodeBlobRef(bt.Blob.BlobRef.Clone());
EntityManager.AddComponentData(entity, new LastTargetComponent {Target = target.Value, Blob = blob});
BindBehaviorTree(entity, bt, query, target.Value, order.Value, blob);
}).Run();
// update
Entities
.WithoutBurst()
.WithStructuralChanges()
.WithChangeFilter<BehaviorTreeTargetComponent>()
.ForEach((Entity entity, ref LastTargetComponent lastTarget, in BlackboardDataQuery query, in BehaviorTreeComponent bt, in BehaviorTreeTargetComponent target, in BehaviorTreeOrderComponent order) =>
{
if (lastTarget.Target != target.Value)
{
UnbindBehaviorTree(entity, lastTarget.Target);
BindBehaviorTree(entity, bt, query, target.Value, order.Value, lastTarget.Blob);
lastTarget.Target = target.Value;
}
}).Run();
// delete
Entities
.WithoutBurst()
.WithStructuralChanges()
.WithNone<BehaviorTreeTargetComponent>()
.ForEach((Entity entity, in LastTargetComponent lastTarget) =>
{
UnbindBehaviorTree(entity, lastTarget.Target);
lastTarget.Blob.BlobRef.Dispose();
EntityManager.RemoveComponent<LastTargetComponent>(entity);
}).Run();
}
void BindBehaviorTree(Entity behaviorTreeEntity, in BehaviorTreeComponent bt, in BlackboardDataQuery query, Entity target, int order, NodeBlobRef blob)
{
if (bt.AutoCreation != AutoCreateType.None)
{
foreach (var componentType in query.Set)
{
if (EntityManager.HasComponent(target, componentType)) continue;
var shouldCreate =
bt.AutoCreation.HasFlagFast(AutoCreateType.ReadOnly) && componentType.AccessModeType == ComponentType.AccessMode.ReadOnly
|| bt.AutoCreation.HasFlagFast(AutoCreateType.ReadWrite) && componentType.AccessModeType == ComponentType.AccessMode.ReadWrite
|| bt.AutoCreation.HasFlagFast(AutoCreateType.BehaviorTreeComponent) && TypeManager.GetType(componentType.TypeIndex)?.GetCustomAttribute<BehaviorTreeComponentAttribute>() != null
;
if (shouldCreate)
{
var typeInfo = TypeManager.GetTypeInfo(componentType.TypeIndex);
switch (typeInfo.Category)
{
case TypeManager.TypeCategory.ComponentData:
EntityManager.AddComponent(target, componentType);
break;
case TypeManager.TypeCategory.BufferData:
EntityManager.AddComponent(target, ComponentType.ReadWrite(componentType.TypeIndex));
break;
}
}
}
}
var buffer = EntityManager.GetBuffer<BehaviorTreeBufferElement>(target);
var orderedIndex = 0;
// TODO: binary search?
while (orderedIndex < buffer.Length && buffer[orderedIndex].Order < order) orderedIndex++;
var element = new BehaviorTreeBufferElement
(
order
, bt.Thread.ToRuntimeThread()
, blob
, EntityManager.GetEntityQueryMask(query.Query)
, behaviorTreeEntity
, query.Query.GetDependency()
);
buffer.Insert(orderedIndex, element);
}
void UnbindBehaviorTree(Entity behaviorTreeEntity, Entity targetEntity)
{
if (!EntityManager.HasComponent<BehaviorTreeBufferElement>(targetEntity))
{
// TODO: log error message?
return;
}
var buffer = EntityManager.GetBuffer<BehaviorTreeBufferElement>(targetEntity);
for (var i = buffer.Length - 1; i >= 0; i--)
{
if (buffer[i].BehaviorTree == behaviorTreeEntity)
{
buffer.RemoveAt(i);
break;
}
}
// TODO: log not found?
}
}
} | 43.837398 | 214 | 0.54822 | [
"MIT"
] | r2d2m/EntitiesBT | Packages/essential/Runtime/Entities/BehaviorTreeLifeCycleSystem.cs | 5,394 | C# |
namespace PrimeFuncPack;
partial class Dependency<T1, T2, T3, T4, T5>
{
public Dependency<T1, T2, T3, T4, T5, T6> With<T6>(
T6 sixth)
=>
new(
firstResolver,
secondResolver,
thirdResolver,
fourthResolver,
fifthResolver,
_ => sixth);
} | 22.266667 | 55 | 0.511976 | [
"MIT"
] | pfpack/early-dependency | src/dependency-core/Core/Dependency.05/With.06/With.06.cs | 334 | C# |
using FatturaElettronica.FatturaElettronicaHeader.CedentePrestatore;
using FatturaElettronica.Tabelle;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Tests
{
[TestClass]
public class IscrizioneREAValidator
: BaseClass<IscrizioneREA, FatturaElettronica.Validators.IscrizioneREAValidator>
{
[TestMethod]
public void UfficioIsRequired()
{
AssertRequired(x => x.Ufficio);
}
[TestMethod]
public void UfficioOnlyAcceptsTableValues()
{
AssertOnlyAcceptsTableValues<Provincia>(x => x.Ufficio);
}
[TestMethod]
public void NumeroREAIsRequired()
{
AssertRequired(x => x.NumeroREA);
}
[TestMethod]
public void NumeroREAMinMaxLength()
{
AssertMinMaxLength(x => x.NumeroREA, 1, 20);
}
[TestMethod]
public void NumeroREAMustBeBasicLatin()
{
AssertMustBeBasicLatin(x => x.NumeroREA);
}
[TestMethod]
public void SocioUnicoIsOptional()
{
AssertOptional(x => x.SocioUnico);
}
[TestMethod]
public void SocioUnicoOnlyAcceptsTableValues()
{
AssertOnlyAcceptsTableValues<SocioUnico>(x => x.SocioUnico);
}
[TestMethod]
public void StatoLiquidazioneIsRequired()
{
AssertRequired(x => x.StatoLiquidazione);
}
[TestMethod]
public void StatoLiquidazioneOnlyAcceptsTableValues()
{
AssertOnlyAcceptsTableValues<StatoLiquidazione>(x => x.StatoLiquidazione);
}
}
}
| 28.810345 | 88 | 0.60383 | [
"BSD-3-Clause"
] | MassimoLinossi/FatturaElettronica.NET | Test/IscrizioneREAValidator.cs | 1,673 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using YesSpa.Common.Configuration;
namespace YesSpa.AspNetCore
{
public static class ApplicationBuilderExtensions
{
/// <summary>
/// Use in Startup.Configure() to enable SPA routing. Use at the end of middleware chain.
/// </summary>
public static void UseYesSpa(this IApplicationBuilder applicationBuilder)
{
var spaConfiguration = applicationBuilder.ApplicationServices.GetRequiredService<IYesSpaConfiguration>();
spaConfiguration.UseYesSpa(applicationBuilder);
}
}
}
| 31.473684 | 111 | 0.765886 | [
"MIT"
] | mtebenev/YesSpa | YesSpa.AspNetCore/ApplicationBuilderExtensions.cs | 598 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MainMenu : MonoBehaviour
{
public GameObject mainMenu;
public GameObject optionsMenu;
public GameObject creditsMenu;
IEnumerator LoadingAsync(int index)
{
yield return new WaitForSeconds(2);
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(index);
while (!asyncLoad.isDone)
{
yield return null;
}
}
public void StartGame(int scene)
{
StartCoroutine(LoadingAsync(scene));
}
public void MenuMain()
{
mainMenu.SetActive(true);
optionsMenu.SetActive(false);
creditsMenu.SetActive(false);
}
public void Options()
{
mainMenu.SetActive(false);
optionsMenu.SetActive(true);
creditsMenu.SetActive(false);
}
public void Credits()
{
mainMenu.SetActive(false);
optionsMenu.SetActive(false);
creditsMenu.SetActive(true);
}
public void ExitGame()
{
Application.Quit();
}
private void Start()
{
if (optionsMenu != null)
optionsMenu.SetActive(false);
}
} | 20.966102 | 70 | 0.623282 | [
"MIT"
] | JoanStark/GlobalGameJam-2021 | GlobalGameJam2021/Assets/Scripts/Menu/MainMenu.cs | 1,239 | C# |
using System;
using System.Web.Hosting;
using CurrencyChart.Server;
using CurrencyChart.Server.Hubs;
using CurrencyChart.Server.Services;
using LiteDB;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Microsoft.Owin.FileSystems;
using Microsoft.Owin.Hosting;
using Microsoft.Owin.StaticFiles;
using Newtonsoft.Json;
using Owin;
using JsonSerializer = Newtonsoft.Json.JsonSerializer;
[assembly: OwinStartup(typeof(Startup))]
namespace CurrencyChart.Server
{
public class Startup
{
private readonly LiteRepository _documentStore;
public Startup(LiteRepository documentStore)
{
_documentStore = documentStore;
}
public void Configuration(IAppBuilder app)
{
GlobalHost.DependencyResolver = new DefaultDependencyResolver();
var serializer = new JsonSerializer()
{
DateTimeZoneHandling = DateTimeZoneHandling.Local,
DateFormatString = "dd.MM.yyyy hh:mm:ss"
};
GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer);
GlobalHost.DependencyResolver.Register(typeof(ChartHub), () => new ChartHub(_documentStore));
HostingEnvironment.RegisterObject(new DataUpdateService(_documentStore));
var sampleBootstrapper = new DefaultBootstrapper(_documentStore);
app
.UseFileServer(new FileServerOptions
{
RequestPath = new PathString("/scripts"),
FileSystem = new PhysicalFileSystem("scripts")
})
.UseFileServer(new FileServerOptions
{
RequestPath = new PathString("/codebehind"),
FileSystem = new PhysicalFileSystem("codebehind")
})
.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration();
map.RunSignalR(hubConfiguration);
})
.UseNancy(cfg => cfg.Bootstrapper = sampleBootstrapper);
}
public static IDisposable Start(string url)
{
var db = new LiteDatabase(@"storage.db");
var rep = new LiteRepository(db, true);
return WebApp.Start(url, app => new Startup(rep).Configuration(app));
}
}
} | 34.175676 | 105 | 0.599051 | [
"MIT"
] | alldevic/CurrencyChart | CurrencyChart.Server/Startup.cs | 2,529 | C# |
//MIT, 2015-2017, WinterDev
using System;
using System.Runtime.InteropServices;
namespace LayoutFarm.CefBridge
{
public enum CefBwCallMsg
{
//custom msg
CefBw_MyCef_EnableKeyIntercept = 11,
CefBw_SetSize = 25,
CefBw_PostData = 27,
CefBw_CloseBw = 28,
CefBw_GetMainFrame = 29,
CefBw_GetCefBrowser = 31,
}
static partial class Cef3Binder
{
[DllImport(Cef3Binder.CEF_CLIENT_DLL, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr NewInstance(int typeName, MyCefCallback callback, ref JsValue v1);
[DllImport(Cef3Binder.CEF_CLIENT_DLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void MyCefMet_CallN(IntPtr me, int metName, out JsValue ret, ref JsValue v1,
ref JsValue v2, ref JsValue v3, ref JsValue v4, ref JsValue v5, ref JsValue v6, ref JsValue v7);
[DllImport(Cef3Binder.CEF_CLIENT_DLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void MyCefMet_S_CallN(int metName, out JsValue ret, ref JsValue v1,
ref JsValue v2, ref JsValue v3, ref JsValue v4, ref JsValue v5, ref JsValue v6, ref JsValue v7);
public static IntPtr NewInstance(int typeName, MyCefCallback callback)
{
JsValue not_used = new JsValue();
return NewInstance(typeName, callback, ref not_used);
}
public static void MyCefMet_Call0(IntPtr me, int metName, out JsValue ret)
{
JsValue v_notUsed = new JsValue();
MyCefMet_CallN(
me, metName, out ret
, ref v_notUsed, ref v_notUsed, ref v_notUsed, ref v_notUsed, ref v_notUsed, ref v_notUsed, ref v_notUsed
);
}
public static void MyCefMet_Call1(IntPtr me, int metName, out JsValue ret
, ref JsValue v1
)
{
JsValue v_notUsed = new JsValue();
MyCefMet_CallN(
me, metName, out ret
, ref v1, ref v_notUsed, ref v_notUsed, ref v_notUsed, ref v_notUsed, ref v_notUsed, ref v_notUsed
);
}
public static void MyCefMet_Call2(IntPtr me, int metName, out JsValue ret
, ref JsValue v1, ref JsValue v2
)
{
JsValue v_notUsed = new JsValue();
MyCefMet_CallN(
me, metName, out ret
, ref v1, ref v2,
ref v_notUsed, ref v_notUsed, ref v_notUsed, ref v_notUsed, ref v_notUsed
);
}
public static void MyCefMet_Call3(IntPtr me, int metName, out JsValue ret
, ref JsValue v1, ref JsValue v2, ref JsValue v3
)
{
JsValue v_notUsed = new JsValue();
MyCefMet_CallN(
me, metName, out ret
, ref v1, ref v2, ref v3,
ref v_notUsed, ref v_notUsed, ref v_notUsed, ref v_notUsed
);
}
public static void MyCefMet_Call4(IntPtr me, int metName, out JsValue ret
, ref JsValue v1, ref JsValue v2, ref JsValue v3, ref JsValue v4/*5117*/
)
{
JsValue v_notUsed = new JsValue();
MyCefMet_CallN(
me, metName, out ret
, ref v1, ref v2, ref v3, ref v4,
ref v_notUsed, ref v_notUsed, ref v_notUsed
);
}
public static void MyCefMet_Call5(IntPtr me, int metName, out JsValue ret
, ref JsValue v1, ref JsValue v2, ref JsValue v3, ref JsValue v4, ref JsValue v5
)
{
JsValue v_notUsed = new JsValue();
MyCefMet_CallN(
me, metName, out ret
, ref v1, ref v2, ref v3, ref v4, ref v5,
ref v_notUsed, ref v_notUsed
);
}
public static void MyCefMet_Call6(IntPtr me, int metName, out JsValue ret
, ref JsValue v1, ref JsValue v2, ref JsValue v3, ref JsValue v4, ref JsValue v5, ref JsValue v6
)
{
JsValue v_notUsed = new JsValue();
MyCefMet_CallN(
me, metName, out ret
, ref v1, ref v2, ref v3, ref v4, ref v5, ref v6,
ref v_notUsed
);
}
public static void MyCefMet_Call7(IntPtr me, int metName, out JsValue ret
, ref JsValue v1, ref JsValue v2, ref JsValue v3, ref JsValue v4, ref JsValue v5, ref JsValue v6, ref JsValue v7
)
{
MyCefMet_CallN(
me, metName, out ret
, ref v1, ref v2, ref v3, ref v4, ref v5, ref v6, ref v7
);
}
//----------
public static void MyCefMet_S_Call0( int metName, out JsValue ret)
{
JsValue v_notUsed = new JsValue();
MyCefMet_S_CallN(
metName, out ret
, ref v_notUsed, ref v_notUsed, ref v_notUsed, ref v_notUsed, ref v_notUsed, ref v_notUsed, ref v_notUsed
);
}
public static void MyCefMet_S_Call1(int metName, out JsValue ret
, ref JsValue v1
)
{
JsValue v_notUsed = new JsValue();
MyCefMet_S_CallN(
metName, out ret
, ref v1, ref v_notUsed, ref v_notUsed, ref v_notUsed, ref v_notUsed, ref v_notUsed, ref v_notUsed
);
}
public static void MyCefMet_S_Call2(int metName, out JsValue ret
, ref JsValue v1, ref JsValue v2
)
{
JsValue v_notUsed = new JsValue();
MyCefMet_S_CallN(
metName, out ret
, ref v1, ref v2,
ref v_notUsed, ref v_notUsed, ref v_notUsed, ref v_notUsed, ref v_notUsed
);
}
public static void MyCefMet_S_Call3(int metName, out JsValue ret
, ref JsValue v1, ref JsValue v2, ref JsValue v3
)
{
JsValue v_notUsed = new JsValue();
MyCefMet_S_CallN(
metName, out ret
, ref v1, ref v2, ref v3,
ref v_notUsed, ref v_notUsed, ref v_notUsed, ref v_notUsed
);
}
public static void MyCefMet_S_Call4(int metName, out JsValue ret
, ref JsValue v1, ref JsValue v2, ref JsValue v3, ref JsValue v4/*5117*/
)
{
JsValue v_notUsed = new JsValue();
MyCefMet_S_CallN(
metName, out ret
, ref v1, ref v2, ref v3, ref v4,
ref v_notUsed, ref v_notUsed, ref v_notUsed
);
}
public static void MyCefMet_S_Call5(int metName, out JsValue ret
, ref JsValue v1, ref JsValue v2, ref JsValue v3, ref JsValue v4, ref JsValue v5
)
{
JsValue v_notUsed = new JsValue();
MyCefMet_S_CallN(
metName, out ret
, ref v1, ref v2, ref v3, ref v4, ref v5,
ref v_notUsed, ref v_notUsed
);
}
public static void MyCefMet_S_Call6(int metName, out JsValue ret
, ref JsValue v1, ref JsValue v2, ref JsValue v3, ref JsValue v4, ref JsValue v5, ref JsValue v6
)
{
JsValue v_notUsed = new JsValue();
MyCefMet_S_CallN(
metName, out ret
, ref v1, ref v2, ref v3, ref v4, ref v5, ref v6,
ref v_notUsed
);
}
public static void MyCefMet_S_Call7(int metName, out JsValue ret
, ref JsValue v1, ref JsValue v2, ref JsValue v3, ref JsValue v4, ref JsValue v5, ref JsValue v6, ref JsValue v7
)
{
MyCefMet_S_CallN(
metName, out ret
, ref v1, ref v2, ref v3, ref v4, ref v5, ref v6, ref v7
);
}
}
} | 34.428571 | 118 | 0.567816 | [
"BSD-3-Clause"
] | prepare/CefBridge | CefBridge/Cef3Binder_Auto.cs | 7,714 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Travelling.OpenApiEntity.Ctrip.Hotel.Module;
namespace Travelling.OpenApiEntity.Ctrip.Hotel
{
[Serializable]
public class OTA_HotelCacheChangeReturnEntity:CtripBaseAPIReturnEntity
{
private List<HotelCacheChange> hotelCacheChangeList = new List<HotelCacheChange>();
/// <summary>
/// 存刷新信息列表
/// </summary>
public List<HotelCacheChange> HotelCacheChangeList
{
get
{
return this.hotelCacheChangeList;
}
set
{
this.hotelCacheChangeList = value;
}
}
}
}
| 24.066667 | 91 | 0.605263 | [
"MIT"
] | binlyzhuo/travel | src/Travelling.OpenApiEntity/Ctrip/Hotel/OTA_HotelCacheChangeReturnEntity.cs | 738 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.DataBoxEdge.V20210201Preview.Outputs
{
/// <summary>
/// Authentication mechanism for IoT devices.
/// </summary>
[OutputType]
public sealed class AuthenticationResponse
{
/// <summary>
/// Symmetric key for authentication.
/// </summary>
public readonly Outputs.SymmetricKeyResponse? SymmetricKey;
[OutputConstructor]
private AuthenticationResponse(Outputs.SymmetricKeyResponse? symmetricKey)
{
SymmetricKey = symmetricKey;
}
}
}
| 27.903226 | 82 | 0.680925 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/DataBoxEdge/V20210201Preview/Outputs/AuthenticationResponse.cs | 865 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Effekseer.Utl;
namespace Effekseer.Binary
{
class GenerationLocationValues
{
public static byte[] GetBytes(Data.GenerationLocationValues value, Data.ParentEffectType parentEffectType, SortedDictionary<string, int> model_and_index, Dictionary<Data.ProceduralModelParameter, int> pmodel_and_index, ExporterVersion version)
{
List<byte[]> data = new List<byte[]>();
if (value.EffectsRotation)
{
data.Add((1).GetBytes());
}
else
{
data.Add((0).GetBytes());
}
var type = value.Type.GetValue();
// Fallback
if (version < ExporterVersion.Ver16Alpha1)
{
if (type == Data.GenerationLocationValues.ParameterType.Model && value.Model.ModelReference.Value == Data.ModelReferenceType.ProceduralModel)
{
type = Data.GenerationLocationValues.ParameterType.Point;
}
}
data.Add(((int)type).GetBytes());
if (type == Data.GenerationLocationValues.ParameterType.Point)
{
data.Add(value.Point.Location.GetBytes(1.0f));
}
else if (type == Data.GenerationLocationValues.ParameterType.Sphere)
{
data.Add((value.Sphere.Radius.Max).GetBytes());
data.Add((value.Sphere.Radius.Min).GetBytes());
data.Add((value.Sphere.RotationX.Max / 180.0f * (float)Math.PI).GetBytes());
data.Add((value.Sphere.RotationX.Min / 180.0f * (float)Math.PI).GetBytes());
data.Add((value.Sphere.RotationY.Max / 180.0f * (float)Math.PI).GetBytes());
data.Add((value.Sphere.RotationY.Min / 180.0f * (float)Math.PI).GetBytes());
}
if (type == Data.GenerationLocationValues.ParameterType.Model)
{
if (version >= ExporterVersion.Ver16Alpha3)
{
var refType = (int)value.Model.ModelReference.Value;
data.Add((refType).GetBytes());
}
if (value.Model.ModelReference.Value == Data.ModelReferenceType.File)
{
var relative_path = value.Model.Model.RelativePath;
if (!string.IsNullOrEmpty(relative_path))
{
relative_path = Utils.GetModelPath(value.Model.Model);
if (model_and_index.ContainsKey(relative_path))
{
data.Add(model_and_index[relative_path].GetBytes());
}
else
{
data.Add(((int)-1).GetBytes());
}
}
else
{
data.Add(((int)-1).GetBytes());
}
}
else if (value.Model.ModelReference.Value == Data.ModelReferenceType.ProceduralModel)
{
if (value.Model.Reference.Value != null)
{
var ind = pmodel_and_index[value.Model.Reference.Value];
data.Add(ind.GetBytes());
}
else
{
data.Add(((int)-1).GetBytes());
}
}
else
{
throw new Exception();
}
data.Add(((int)value.Model.Type.Value).GetBytes());
}
else if (type == Data.GenerationLocationValues.ParameterType.Circle)
{
data.Add((value.Circle.Division.Value).GetBytes());
data.Add((value.Circle.Radius.Max).GetBytes());
data.Add((value.Circle.Radius.Min).GetBytes());
data.Add((value.Circle.AngleStart.Max / 180.0f * (float)Math.PI).GetBytes());
data.Add((value.Circle.AngleStart.Min / 180.0f * (float)Math.PI).GetBytes());
data.Add((value.Circle.AngleEnd.Max / 180.0f * (float)Math.PI).GetBytes());
data.Add((value.Circle.AngleEnd.Min / 180.0f * (float)Math.PI).GetBytes());
data.Add(((int)value.Circle.Type.Value).GetBytes());
// Version 1.30(10)
data.Add(((int)value.Circle.AxisDirection.Value).GetBytes());
data.Add((value.Circle.AngleNoize.Max / 180.0f * (float)Math.PI).GetBytes());
data.Add((value.Circle.AngleNoize.Min / 180.0f * (float)Math.PI).GetBytes());
}
else if (type == Data.GenerationLocationValues.ParameterType.Line)
{
data.Add((value.Line.Division.Value).GetBytes());
data.Add(value.Line.PositionStart.GetBytes(1.0f));
data.Add(value.Line.PositionEnd.GetBytes(1.0f));
data.Add((value.Line.PositionNoize.Max).GetBytes());
data.Add((value.Line.PositionNoize.Min).GetBytes());
data.Add(((int)value.Line.Type.Value).GetBytes());
}
return data.ToArray().ToArray();
}
}
} | 31.852713 | 245 | 0.663665 | [
"Apache-2.0",
"BSD-3-Clause"
] | Shockblast/Effekseer | Dev/Editor/EffekseerCore/Binary/GenerationLocationValues.cs | 4,111 | 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/ProcessSnapshot.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
using System;
using System.Runtime.Versioning;
namespace TerraFX.Interop.Windows;
/// <include file='PSS_HANDLE_FLAGS.xml' path='doc/member[@name="PSS_HANDLE_FLAGS"]/*' />
[Flags]
[SupportedOSPlatform("windows8.1")]
public enum PSS_HANDLE_FLAGS
{
/// <include file='PSS_HANDLE_FLAGS.xml' path='doc/member[@name="PSS_HANDLE_FLAGS.PSS_HANDLE_NONE"]/*' />
PSS_HANDLE_NONE = 0x00,
/// <include file='PSS_HANDLE_FLAGS.xml' path='doc/member[@name="PSS_HANDLE_FLAGS.PSS_HANDLE_HAVE_TYPE"]/*' />
PSS_HANDLE_HAVE_TYPE = 0x01,
/// <include file='PSS_HANDLE_FLAGS.xml' path='doc/member[@name="PSS_HANDLE_FLAGS.PSS_HANDLE_HAVE_NAME"]/*' />
PSS_HANDLE_HAVE_NAME = 0x02,
/// <include file='PSS_HANDLE_FLAGS.xml' path='doc/member[@name="PSS_HANDLE_FLAGS.PSS_HANDLE_HAVE_BASIC_INFORMATION"]/*' />
PSS_HANDLE_HAVE_BASIC_INFORMATION = 0x04,
/// <include file='PSS_HANDLE_FLAGS.xml' path='doc/member[@name="PSS_HANDLE_FLAGS.PSS_HANDLE_HAVE_TYPE_SPECIFIC_INFORMATION"]/*' />
PSS_HANDLE_HAVE_TYPE_SPECIFIC_INFORMATION = 0x08,
}
| 43.451613 | 145 | 0.751299 | [
"MIT"
] | reflectronic/terrafx.interop.windows | sources/Interop/Windows/Windows/um/ProcessSnapshot/PSS_HANDLE_FLAGS.cs | 1,349 | C# |
using System.Collections.Generic;
namespace Trowel.Common.Shell.Settings
{
/// <summary>
/// Represents a class that holds settings
/// </summary>
public interface ISettingsContainer
{
/// <summary>
/// The unique name of the settings container
/// </summary>
string Name { get; }
/// <summary>
/// Get a list of editable keys exposed by this container.
/// The container does not have to expose all keys via this method,
/// only ones that should appear in the settings form.
/// </summary>
/// <returns>The editable keys for this container</returns>
IEnumerable<SettingKey> GetKeys();
/// <summary>
/// Load values from the store into this instance
/// </summary>
/// <param name="store">The store to load values from</param>
void LoadValues(ISettingsStore store);
/// <summary>
/// Store values from this instance into the store
/// </summary>
/// <param name="store">The store to save into</param>
void StoreValues(ISettingsStore store);
}
} | 32.628571 | 75 | 0.595447 | [
"BSD-3-Clause"
] | mattiascibien/trowel | Trowel.Common/Shell/Settings/ISettingsContainer.cs | 1,144 | C# |
// Project: Daggerfall Tools For Unity
// Copyright: Copyright (C) 2009-2020 Daggerfall Workshop
// Web Site: http://www.dfworkshop.net
// License: MIT License (http://www.opensource.org/licenses/mit-license.php)
// Source Code: https://github.com/Interkarma/daggerfall-unity
// Original Author: Meteoric Dragon
// Contributors:
//
// Notes:
//
using DaggerfallWorkshop.Game.Serialization;
using UnityEngine;
using System;
namespace DaggerfallWorkshop.Game
{
/// <summary>
/// Tells HeightChanger.Update() which method to call to change controller height and camera position
/// </summary>
public enum HeightChangeAction
{
DoNothing,
DoStanding,
DoCrouching,
DoMounting,
DoDismounting,
DoSinking,
DoUnsinking
}
[RequireComponent(typeof(PlayerMotor))]
[RequireComponent(typeof(CharacterController))]
[RequireComponent(typeof(HeadBobber))]
[RequireComponent(typeof(LevitateMotor))]
public class PlayerHeightChanger : MonoBehaviour
{
private HeightChangeAction heightAction;
public HeightChangeAction HeightAction
{
get { return heightAction; }
set { heightAction = value; }
}
public bool IsInWaterTile { get; set; }
public bool ForcedSwimCrouch { get { return forcedSwimCrouch; } set { forcedSwimCrouch = value; } }
private bool forcedSwimCrouch = true;
private PlayerMotor playerMotor;
private CharacterController controller;
private HeadBobber headBobber;
private LevitateMotor levitateMotor;
private ClimbingMotor climbingMotor;
private Camera mainCamera;
public const float controllerStandingHeight = 1.8f;
public const float controllerCrouchHeight = 0.9f;
public const float controllerRideHeight = 2.6f; // Height of a horse plus seated rider. (1.6m + 1m)
public const float controllerSwimHeight = 0.30f;
public const float controllerSwimHorseDisplacement = 0.30f; // amount added to swim height if on horse
public const float eyeHeight = 0.09f; // Eye height is 9cm below top of capsule.
private float targetCamLevel;
private float prevCamLevel;
private float camCrouchLevel;
private float camStandLevel;
private float camRideLevel;
private float camSwimLevel;
//private float camSwimToCrouchDist;
private float camCrouchToStandDist;
//private float camStandToRideDist;
private float camTimer;
private const float timerFast = 0.10f;
private const float timerMedium = 0.25f;
private const float timerSlow = 0.4f;
private float timerMax = 0.1f;
private float camLerp_T; // for lerping to new camera position
private bool toggleRiding;
private bool toggleSink;
private bool controllerMounted;
private bool controllerSink;
// Intended height of controller while standing
public float FixedControllerStandingHeight
{
get { return controllerStandingHeight; }
}
// Intended height of controller while standing plus any adjustment amount
public float CurrentControllerStandingHeight
{
get { return controllerStandingHeight + StandingHeightAdjustment; }
}
// Allows for temporary dips in controller standing height to help player clear low doorways at bottom of stairs/ramp
// Should only be set when required and cleared when no longer required.
// Does nothing if player is crouched, and crouching/uncrouching will clear this adjustment
float standingHeightAdjustment;
public float StandingHeightAdjustment
{
get { return standingHeightAdjustment; }
set { ChangeStandingHeightAdjustment(value); }
}
private void Start()
{
playerMotor = GetComponent<PlayerMotor>();
controller = GetComponent<CharacterController>();
headBobber = GetComponent<HeadBobber>();
mainCamera = GameManager.Instance.MainCamera;
levitateMotor = GetComponent<LevitateMotor>();
climbingMotor = GetComponent<ClimbingMotor>();
camSwimLevel = controllerSwimHeight / 2f;
camCrouchLevel = controllerCrouchHeight / 2f;
camStandLevel = controllerStandingHeight / 2f;
camRideLevel = controllerRideHeight / 2f - eyeHeight;
//camSwimToCrouchDist = (controllerCrouchHeight - controllerSwimHeight) / 2f;
camCrouchToStandDist = (controllerStandingHeight - controllerCrouchHeight) / 2f;
//camStandToRideDist = (controllerRideHeight - controllerStandHeight) / 2f;
// Use event to set whether player is crouched on load
SaveLoadManager.OnStartLoad += SaveLoadManager_OnStartLoad;
}
/// <summary>
/// Determines what Height-changing action should be taken based on player's input and PlayerMotor.IsRiding
/// </summary>
public void DecideHeightAction()
{
bool onWater = (GameManager.Instance.PlayerMotor.OnExteriorWater == PlayerMotor.OnExteriorWaterMethod.Swimming);
bool swimming = levitateMotor.IsSwimming;
bool crouching = playerMotor.IsCrouching;
bool riding = playerMotor.IsRiding;
bool pressedCrouch = InputManager.Instance.ActionStarted(InputManager.Actions.Crouch);
bool climbing = climbingMotor.IsClimbing;
bool levitating = playerMotor.IsLevitating;
//timerMax = timerSlow;
// Handle uncrouch and levitating while swimming
if (levitating)
{
if (crouching)
{
heightAction = HeightChangeAction.DoStanding;
return;
}
onWater = false;
}
if (onWater && !toggleSink)
{
timerMax = timerSlow;
heightAction = HeightChangeAction.DoSinking;
toggleSink = true;
}
else if (!onWater && toggleSink)
{
timerMax = timerSlow;
heightAction = HeightChangeAction.DoUnsinking;
toggleSink = false;
}
else if (riding && !toggleRiding)
{
timerMax = timerMedium;
heightAction = HeightChangeAction.DoMounting;
toggleRiding = true;
}
else if (!riding && toggleRiding)
{
timerMax = timerFast;
heightAction = HeightChangeAction.DoDismounting;
toggleRiding = false;
}
else if (!riding && !onWater && !levitating)
{
// if we crouch out of water or while on solid ground
if ((!swimming || playerMotor.IsGrounded) && pressedCrouch)
{
timerMax = timerFast;
// Toggle crouching
if (crouching)
heightAction = HeightChangeAction.DoStanding;
else
heightAction = HeightChangeAction.DoCrouching;
forcedSwimCrouch = false;
}
// if climbing, force into standing
else if (climbing)
{
timerMax = timerMedium;
if (crouching)
heightAction = HeightChangeAction.DoStanding;
forcedSwimCrouch = false;
}
// if swimming but not crouching, crouch.
else if (swimming && !forcedSwimCrouch && !playerMotor.IsGrounded)
{
timerMax = timerMedium;
if (!crouching)
heightAction = HeightChangeAction.DoCrouching;
forcedSwimCrouch = true;
}
// if we're in a forced swim crouch, but not swimming, un-force the crouch
else if (!swimming && forcedSwimCrouch)
{
timerMax = timerMedium;
if (crouching)
heightAction = HeightChangeAction.DoStanding;
forcedSwimCrouch = false;
}
}
}
/// <summary>
/// Continue calling actions to increment camera towards destination.
/// </summary>
private void Update()
{
if (heightAction == HeightChangeAction.DoNothing || GameManager.IsGamePaused)
return;
if (heightAction == HeightChangeAction.DoSinking)
DoSinking();
else if (heightAction == HeightChangeAction.DoUnsinking)
DoUnsinking();
else if (heightAction == HeightChangeAction.DoCrouching)
DoCrouch();
else if (heightAction == HeightChangeAction.DoStanding && CanStand())
DoStand();
else if (heightAction == HeightChangeAction.DoMounting)
DoMount();
else
DoDismount();
}
#region HeightChangerActions
void ChangeStandingHeightAdjustment(float amount)
{
if (amount == standingHeightAdjustment)
return;
//Debug.LogFormat("Set new standing height adjustment {0}", amount);
standingHeightAdjustment = amount;
ControllerHeightChange(CurrentControllerStandingHeight - FixedControllerStandingHeight);
}
private void DoCrouch() // first lower camera, Controller height last
{
float prevHeight = controller.height;
timerTick();
UpdateCameraPosition(Mathf.Lerp(prevHeight / 2f, camCrouchLevel, camLerp_T));
if (camTimer >= timerMax)
{
standingHeightAdjustment = 0;
float targetHeight = controllerCrouchHeight;
ControllerHeightChange(targetHeight - prevHeight);
timerResetAction();
playerMotor.IsCrouching = true;
}
}
private void DoStand() // adjust height first, camera last
{
float prevHeight = controller.height;
if (playerMotor.IsCrouching)
{
standingHeightAdjustment = 0;
float targetHeight = CurrentControllerStandingHeight;
prevCamLevel = prevHeight / 2f;
targetCamLevel = ControllerHeightChange(targetHeight - prevHeight);
playerMotor.IsCrouching = false;
}
timerTick();
UpdateCameraPosition(Mathf.Lerp(prevCamLevel, targetCamLevel, camLerp_T));
if (camTimer >= timerMax)
{
timerResetAction();
}
}
private void DoMount() // adjust height first, camera last
{
if (!controllerMounted)
{
float prevHeight = controller.height;
float targetHeight;
prevCamLevel = prevHeight / 2f;
if (GameManager.Instance.PlayerMotor.OnExteriorWater == PlayerMotor.OnExteriorWaterMethod.Swimming)
{
targetHeight = controllerSwimHeight + controllerSwimHorseDisplacement;
prevCamLevel = camSwimLevel;
}
else // on ground
{
targetHeight = controllerRideHeight;
}
targetCamLevel = ControllerHeightChange(targetHeight - prevHeight);
controllerMounted = true;
playerMotor.IsCrouching = false;
}
timerTick();
UpdateCameraPosition(Mathf.Lerp(prevCamLevel, targetCamLevel, camLerp_T));
if (camTimer >= timerMax)
{
timerResetAction();
}
}
private void DoDismount() // adjust height first, camera last
{
if (controllerMounted)
{
float prevHeight = controller.height;
float targetHeight;
if (GameManager.Instance.PlayerMotor.OnExteriorWater == PlayerMotor.OnExteriorWaterMethod.Swimming)
{
prevCamLevel = prevHeight / 2f;
targetHeight = controllerSwimHeight;
}
else
{
prevCamLevel = camRideLevel;
targetHeight = CurrentControllerStandingHeight;
}
targetCamLevel = ControllerHeightChange(targetHeight - prevHeight);
controllerMounted = false;
playerMotor.IsCrouching = false;
}
timerTick();
UpdateCameraPosition(Mathf.Lerp(prevCamLevel, targetCamLevel, camLerp_T));
if (camTimer >= timerMax)
{
timerResetAction();
}
}
private void DoUnsinking()
{
if (controllerSink)
{
float baseHeight;
float displacement = 0;
prevCamLevel = camSwimLevel;
if (playerMotor.IsRiding)
{
baseHeight = controllerRideHeight;
displacement = controllerSwimHorseDisplacement;
prevCamLevel += displacement;
}
else
{
baseHeight = CurrentControllerStandingHeight;
}
float height = controllerSwimHeight + displacement;
float heightLoss = baseHeight - height;
targetCamLevel = ControllerHeightChange(heightLoss);
controllerSink = false;
IsInWaterTile = false;
playerMotor.IsCrouching = false;
GameManager.Instance.PlayerEnterExit.IsPlayerSwimming = false;
}
timerTick();
UpdateCameraPosition(Mathf.Lerp(prevCamLevel, targetCamLevel, camLerp_T));
if (camTimer >= timerMax)
{
timerResetAction();
}
}
private void DoSinking()
{
if (!controllerSink)
{
float baseHeight;
float displacement = 0;
if (!playerMotor.IsCrouching)
{
if (playerMotor.IsRiding)
{
baseHeight = controllerRideHeight;
displacement = controllerSwimHorseDisplacement;
prevCamLevel = camRideLevel;
}
else
{
baseHeight = CurrentControllerStandingHeight;
prevCamLevel = camStandLevel;
}
}
else
{
baseHeight = controllerCrouchHeight;
prevCamLevel = camCrouchLevel;
}
float height = controllerSwimHeight + displacement;
float heightLoss = baseHeight - height;
targetCamLevel = ControllerHeightChange(-1 * heightLoss);
controllerSink = true;
IsInWaterTile = true;
playerMotor.IsCrouching = false;
GameManager.Instance.PlayerEnterExit.IsPlayerSwimming = true;
}
timerTick();
UpdateCameraPosition(Mathf.Lerp(prevCamLevel, targetCamLevel, camLerp_T));
if (camTimer >= timerMax)
{
timerResetAction();
}
}
#endregion
#region Helpers
/// <summary>
/// Increment timer and camera LERP T value
/// </summary>
private void timerTick()
{
camTimer += Time.deltaTime;
camLerp_T = Mathf.Clamp((camTimer / timerMax), 0, 1);
}
/// <summary>
/// Reset the camera timer and action
/// </summary>
private void timerResetAction()
{
camTimer = 0f;
heightAction = HeightChangeAction.DoNothing;
}
/// <summary>
/// Set new camera position
/// </summary>
/// <param name="yPosMod">Y amount to change camera position</param>
private void UpdateCameraPosition(float yPosMod)
{
Vector3 camPos = mainCamera.transform.localPosition;
headBobber.RestPos = new Vector3(headBobber.RestPos.x, yPosMod);
mainCamera.transform.localPosition = new Vector3(camPos.x, yPosMod, camPos.z);
}
/// <summary>
/// Change controller height and position and return target height for camera to change to
/// </summary>
/// <param name="heightChange">Amount to modify controller height</param>
/// <returns>the target height the camera should change to</returns>
private float ControllerHeightChange(float heightChange)
{
bool dismounting = (heightAction == HeightChangeAction.DoDismounting);
bool mounting = (heightAction == HeightChangeAction.DoMounting);
controller.height = GetNearbyFloat(controller.height + heightChange);
float eyeChange = 0;
if (GameManager.Instance.PlayerMotor.OnExteriorWater != PlayerMotor.OnExteriorWaterMethod.Swimming)
{
if (dismounting)
eyeChange = -1 * eyeHeight;
else if (mounting)
eyeChange = eyeHeight;
}
controller.transform.position += new Vector3(0, heightChange / 2 + eyeChange);
return controller.height / 2 + eyeChange;
}
/// <summary>
/// Anti-floating point roundoff
/// </summary>
/// <param name="value">The value to evaluate</param>
/// <returns></returns>
private float GetNearbyFloat(float value)
{
if (CloseEnough(value, CurrentControllerStandingHeight))
return CurrentControllerStandingHeight;
else if (CloseEnough(value, controllerCrouchHeight))
return controllerCrouchHeight;
else if (CloseEnough(value, controllerRideHeight))
return controllerRideHeight;
else if (CloseEnough(value, controllerSwimHeight))
return controllerSwimHeight;
else if (CloseEnough(value, controllerSwimHeight + controllerSwimHorseDisplacement))
return controllerSwimHeight + controllerSwimHorseDisplacement;
// Couldn't get to an exact round-off within tolerance - return a fixed value based on current state rather than simply returning 0
// This fixes method from simply crunching player into a tiny ball during some edge cases
// Could probably replace the above round-off method completely with this, but just using as an improved failover for now
if (playerMotor.IsRiding && playerMotor.IsSwimming)
return controllerSwimHeight + controllerSwimHorseDisplacement;
else if (playerMotor.IsRiding && !playerMotor.IsSwimming)
return controllerRideHeight;
else if (playerMotor.IsSwimming)
return controllerSwimHeight;
else if (playerMotor.IsCrouching)
return controllerCrouchHeight;
else
return CurrentControllerStandingHeight;
}
private bool CloseEnough(float value1, float value2, float acceptableDifference = 0.01f)
{
return Math.Abs(value1 - value2) <= acceptableDifference;
}
/// <summary>
/// Does the player have enough room to stand from crouching position?
/// </summary>
/// <returns>returns true if enough room</returns>
private bool CanStand()
{
float distance = camCrouchToStandDist;
Ray ray = new Ray(controller.transform.position, Vector3.up);
return !Physics.SphereCast(ray, controller.radius, distance);
}
#endregion
#region Load Game Handling
private void SaveLoadManager_OnStartLoad(SaveData_v1 saveData)
{
PlayerPositionData_v1 savePos = saveData.playerData.playerPosition;
// save is crouched
if (!savePos.isCrouching && playerMotor.IsCrouching)
{
heightAction = HeightChangeAction.DoStanding;
}
else if (savePos.isCrouching && !playerMotor.IsCrouching)
{
heightAction = HeightChangeAction.DoCrouching;
}
toggleRiding = playerMotor.IsRiding;
toggleSink = GameManager.Instance.PlayerMotor.OnExteriorWater == PlayerMotor.OnExteriorWaterMethod.Swimming;
forcedSwimCrouch = levitateMotor.IsSwimming;
}
#endregion
}
}
| 37.945035 | 143 | 0.568431 | [
"MIT"
] | Aelthien/daggerfall-unity | Assets/Scripts/Game/Player/PlayerHeightChanger.cs | 21,401 | C# |
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.CodeDom.Compiler;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using ICSharpCode.Decompiler.Tests.Helpers;
using NUnit.Framework;
namespace ICSharpCode.Decompiler.Tests
{
[TestFixture, Parallelizable(ParallelScope.All)]
public class PrettyTestRunner
{
static readonly string TestCasePath = Tester.TestCasePath + "/Pretty";
[Test]
public void AllFilesHaveTests()
{
var testNames = typeof(PrettyTestRunner).GetMethods()
.Where(m => m.GetCustomAttributes(typeof(TestAttribute), false).Any())
.Select(m => m.Name)
.ToArray();
foreach (var file in new DirectoryInfo(TestCasePath).EnumerateFiles())
{
if (file.Extension.Equals(".il", StringComparison.OrdinalIgnoreCase)
|| file.Extension.Equals(".cs", StringComparison.OrdinalIgnoreCase))
{
var testName = file.Name.Split('.')[0];
Assert.Contains(testName, testNames);
}
}
}
static readonly CompilerOptions[] noRoslynOptions =
{
CompilerOptions.None,
CompilerOptions.Optimize
};
static readonly CompilerOptions[] roslynOnlyOptions =
{
CompilerOptions.UseRoslyn1_3_2,
CompilerOptions.Optimize | CompilerOptions.UseRoslyn1_3_2,
CompilerOptions.UseRoslyn2_10_0,
CompilerOptions.Optimize | CompilerOptions.UseRoslyn2_10_0,
CompilerOptions.UseRoslynLatest,
CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest,
};
static readonly CompilerOptions[] roslyn2OrNewerOptions =
{
CompilerOptions.UseRoslyn2_10_0,
CompilerOptions.Optimize | CompilerOptions.UseRoslyn2_10_0,
CompilerOptions.UseRoslynLatest,
CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest,
};
static readonly CompilerOptions[] roslynLatestOnlyOptions =
{
CompilerOptions.UseRoslynLatest,
CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest,
};
static readonly CompilerOptions[] dotnetCoreOnlyOptions =
{
CompilerOptions.UseRoslynLatest | CompilerOptions.ReferenceCore,
CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest | CompilerOptions.ReferenceCore,
};
static readonly CompilerOptions[] defaultOptions =
{
CompilerOptions.None,
CompilerOptions.Optimize,
CompilerOptions.UseRoslyn1_3_2,
CompilerOptions.Optimize | CompilerOptions.UseRoslyn1_3_2,
CompilerOptions.UseRoslyn2_10_0,
CompilerOptions.Optimize | CompilerOptions.UseRoslyn2_10_0,
CompilerOptions.UseRoslynLatest,
CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest,
};
static readonly CompilerOptions[] defaultOptionsWithMcs =
{
CompilerOptions.None,
CompilerOptions.Optimize,
CompilerOptions.UseRoslyn1_3_2,
CompilerOptions.Optimize | CompilerOptions.UseRoslyn1_3_2,
CompilerOptions.UseRoslyn2_10_0,
CompilerOptions.Optimize | CompilerOptions.UseRoslyn2_10_0,
CompilerOptions.UseRoslynLatest,
CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest,
CompilerOptions.UseMcs,
CompilerOptions.Optimize | CompilerOptions.UseMcs
};
[Test]
public void HelloWorld()
{
RunForLibrary();
RunForLibrary(asmOptions: AssemblerOptions.UseDebug);
}
[Test]
public void IndexRangeTest([ValueSource(nameof(dotnetCoreOnlyOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void InlineAssignmentTest([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void CompoundAssignmentTest([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void ShortCircuit([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void CustomShortCircuitOperators([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void ExceptionHandling([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions, decompilerSettings: new DecompilerSettings {
NullPropagation = false,
// legacy csc generates a dead store in debug builds
RemoveDeadStores = (cscOptions == CompilerOptions.None)
});
}
[Test]
public void Switch([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions, decompilerSettings: new DecompilerSettings {
// legacy csc generates a dead store in debug builds
RemoveDeadStores = (cscOptions == CompilerOptions.None),
SwitchExpressions = false,
});
}
[Test]
public void SwitchExpressions([ValueSource(nameof(roslynLatestOnlyOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void ReduceNesting([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void DelegateConstruction([ValueSource(nameof(defaultOptionsWithMcs))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions | CompilerOptions.Preview);
}
[Test]
public void AnonymousTypes([ValueSource(nameof(defaultOptionsWithMcs))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void Async([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void Lock([ValueSource(nameof(defaultOptionsWithMcs))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void Using([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(
cscOptions: cscOptions,
decompilerSettings: new DecompilerSettings { UseEnhancedUsing = false }
);
}
[Test]
public void UsingVariables([ValueSource(nameof(dotnetCoreOnlyOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void LiftedOperators([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void Generics([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void Loops([ValueSource(nameof(defaultOptionsWithMcs))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions, decompilerSettings: new DecompilerSettings {
// legacy csc generates a dead store in debug builds
RemoveDeadStores = (cscOptions == CompilerOptions.None),
UseExpressionBodyForCalculatedGetterOnlyProperties = false
});
}
[Test]
public void LocalFunctions([ValueSource(nameof(roslyn2OrNewerOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions | CompilerOptions.Preview);
}
[Test]
public void PropertiesAndEvents([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void AutoProperties([ValueSource(nameof(roslynOnlyOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void QueryExpressions([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void TypeAnalysisTests([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void CheckedUnchecked([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void UnsafeCode([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void ConstructorInitializers([ValueSource(nameof(defaultOptionsWithMcs))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void PInvoke([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
// This tests needs our own disassembler; ildasm has a bug with marshalinfo.
RunForLibrary(cscOptions: cscOptions, asmOptions: AssemblerOptions.UseOwnDisassembler);
}
[Test]
public void OutVariables([ValueSource(nameof(roslyn2OrNewerOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void InitializerTests([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void DynamicTests([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void ExpressionTrees([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void FixProxyCalls([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void ValueTypes([ValueSource(nameof(defaultOptionsWithMcs))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void VariableNaming([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions | CompilerOptions.GeneratePdb);
}
[Test]
public void VariableNamingWithoutSymbols([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
var settings = Tester.GetSettings(cscOptions);
settings.UseDebugSymbols = false;
RunForLibrary(cscOptions: cscOptions, decompilerSettings: settings);
}
[Test]
public void CS72_PrivateProtected([ValueSource(nameof(roslyn2OrNewerOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void AsyncForeach([ValueSource(nameof(dotnetCoreOnlyOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void AsyncMain([ValueSource(nameof(roslyn2OrNewerOptions))] CompilerOptions cscOptions)
{
Run(cscOptions: cscOptions);
}
[Test]
public void AsyncStreams([ValueSource(nameof(dotnetCoreOnlyOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void AsyncUsing([ValueSource(nameof(dotnetCoreOnlyOptions))] CompilerOptions cscOptions)
{
RunForLibrary(
cscOptions: cscOptions,
decompilerSettings: new DecompilerSettings { UseEnhancedUsing = false }
);
}
[Test]
public void CustomTaskType([ValueSource(nameof(roslyn2OrNewerOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void NullableRefTypes([ValueSource(nameof(roslynLatestOnlyOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void NativeInts([ValueSource(nameof(roslynLatestOnlyOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions | CompilerOptions.Preview);
}
[Test]
public void FunctionPointers([ValueSource(nameof(roslynLatestOnlyOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions | CompilerOptions.Preview);
}
[Test]
public void Records([ValueSource(nameof(roslynLatestOnlyOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions | CompilerOptions.Preview);
}
[Test]
public void NullPropagation([ValueSource(nameof(roslynOnlyOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void CS6_StringInterpolation([ValueSource(nameof(roslynOnlyOptions))] CompilerOptions cscOptions)
{
Run(cscOptions: cscOptions);
}
[Test]
public void CS73_StackAllocInitializers([ValueSource(nameof(roslynLatestOnlyOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void RefLocalsAndReturns([ValueSource(nameof(roslyn2OrNewerOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void ThrowExpressions([ValueSource(nameof(roslyn2OrNewerOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void WellKnownConstants([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void QualifierTests([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void TupleTests([ValueSource(nameof(roslyn2OrNewerOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void NamedArguments([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void OptionalArguments([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions | CompilerOptions.Preview);
}
[Test]
public void ConstantsTests([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void Issue1080([ValueSource(nameof(roslynOnlyOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void AssemblyCustomAttributes([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void CustomAttributes([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void CustomAttributes2([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void CustomAttributeConflicts([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void CustomAttributeSamples([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void MemberTests([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void MultidimensionalArray([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void EnumTests([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void InterfaceTests([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions | CompilerOptions.ReferenceCore);
}
[Test]
public void TypeMemberTests([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void YieldReturn([ValueSource(nameof(defaultOptionsWithMcs))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void UserDefinedConversions([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void Discards([ValueSource(nameof(roslyn2OrNewerOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void DeconstructionTests([ValueSource(nameof(roslyn2OrNewerOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void CS9_ExtensionGetEnumerator([ValueSource(nameof(dotnetCoreOnlyOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions | CompilerOptions.Preview);
}
void RunForLibrary([CallerMemberName] string testName = null, AssemblerOptions asmOptions = AssemblerOptions.None, CompilerOptions cscOptions = CompilerOptions.None, DecompilerSettings decompilerSettings = null)
{
Run(testName, asmOptions | AssemblerOptions.Library, cscOptions | CompilerOptions.Library, decompilerSettings);
}
void Run([CallerMemberName] string testName = null, AssemblerOptions asmOptions = AssemblerOptions.None, CompilerOptions cscOptions = CompilerOptions.None, DecompilerSettings decompilerSettings = null)
{
var csFile = Path.Combine(TestCasePath, testName + ".cs");
var exeFile = Path.Combine(TestCasePath, testName) + Tester.GetSuffix(cscOptions) + ".exe";
if (cscOptions.HasFlag(CompilerOptions.Library))
{
exeFile = Path.ChangeExtension(exeFile, ".dll");
}
// 1. Compile
CompilerResults output = null;
try
{
output = Tester.CompileCSharp(csFile, cscOptions, exeFile);
}
finally
{
if (output != null)
output.TempFiles.Delete();
}
// 2. Decompile
var decompiled = Tester.DecompileCSharp(exeFile, decompilerSettings ?? Tester.GetSettings(cscOptions));
// 3. Compile
CodeAssert.FilesAreEqual(csFile, decompiled, Tester.GetPreprocessorSymbols(cscOptions).ToArray());
}
}
}
| 29.952459 | 213 | 0.762903 | [
"MIT"
] | BMBH/ILSpy | ICSharpCode.Decompiler.Tests/PrettyTestRunner.cs | 18,273 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace Grid___WPF
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
| 18 | 42 | 0.703704 | [
"MIT"
] | TruyenLam/C-WPF | Grid___WPF/Grid___WPF/App.xaml.cs | 326 | C# |
namespace Ucrs.Data.Models
{
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Ucrs.Common;
using Ucrs.Data.Common.Models;
public class Course : BaseDeletableModel<int>
{
public Course()
{
this.ApplicationUsersInCourses = new HashSet<ApplicationUserCourse>();
}
[Required]
[MaxLength(GlobalConstants.CourseTitleMaxLength)]
public string Title { get; set; }
[Required]
[Range(GlobalConstants.CoursePointsMinValue, GlobalConstants.CoursePointsMaxValue)]
public int Points { get; set; }
public virtual ICollection<ApplicationUserCourse> ApplicationUsersInCourses { get; set; }
}
}
| 27.37037 | 97 | 0.67253 | [
"MIT"
] | YanaSlavcheva/UcrsApp | Data/Ucrs.Data.Models/Course.cs | 741 | C# |
// -------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// -------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using EnsureThat;
using Hl7.Fhir.Model;
using MediatR;
using Microsoft.Health.Fhir.Core.Features.Persistence;
using Microsoft.Health.Fhir.Core.Messages.Create;
using Microsoft.Health.Fhir.Core.Messages.Delete;
using Microsoft.Health.Fhir.Core.Messages.Get;
using Microsoft.Health.Fhir.Core.Messages.Search;
using Microsoft.Health.Fhir.Core.Messages.Upsert;
using Microsoft.Health.Fhir.Core.Models;
namespace Microsoft.Health.Fhir.Core.Extensions
{
public static class FhirMediatorExtensions
{
public static async Task<Resource> CreateResourceAsync(this IMediator mediator, Resource resource, CancellationToken cancellationToken = default)
{
EnsureArg.IsNotNull(mediator, nameof(mediator));
EnsureArg.IsNotNull(resource, nameof(resource));
UpsertResourceResponse result = await mediator.Send<UpsertResourceResponse>(new CreateResourceRequest(resource), cancellationToken);
return result.Outcome.Resource;
}
public static async Task<SaveOutcome> UpsertResourceAsync(this IMediator mediator, Resource resource, WeakETag weakETag = null, CancellationToken cancellationToken = default)
{
EnsureArg.IsNotNull(mediator, nameof(mediator));
EnsureArg.IsNotNull(resource, nameof(resource));
UpsertResourceResponse result = await mediator.Send<UpsertResourceResponse>(new UpsertResourceRequest(resource, weakETag), cancellationToken);
return result.Outcome;
}
public static async Task<Resource> GetResourceAsync(this IMediator mediator, ResourceKey key, CancellationToken cancellationToken = default)
{
EnsureArg.IsNotNull(mediator, nameof(mediator));
EnsureArg.IsNotNull(key, nameof(key));
GetResourceResponse result = await mediator.Send(new GetResourceRequest(key), cancellationToken);
return result.Resource;
}
public static async Task<DeleteResourceResponse> DeleteResourceAsync(this IMediator mediator, ResourceKey key, bool hardDelete, CancellationToken cancellationToken = default)
{
EnsureArg.IsNotNull(mediator, nameof(mediator));
EnsureArg.IsNotNull(key, nameof(key));
var result = await mediator.Send(new DeleteResourceRequest(key, hardDelete), cancellationToken);
return result;
}
public static async Task<Bundle> SearchResourceAsync(this IMediator mediator, string type, IReadOnlyList<Tuple<string, string>> queries, CancellationToken cancellationToken = default)
{
EnsureArg.IsNotNull(mediator, nameof(mediator));
var result = await mediator.Send(new SearchResourceRequest(type, queries), cancellationToken);
return result.Bundle;
}
public static async Task<Bundle> SearchResourceHistoryAsync(this IMediator mediator, PartialDateTime since = null, PartialDateTime at = null, int? count = null, string continuationToken = null, CancellationToken cancellationToken = default)
{
EnsureArg.IsNotNull(mediator, nameof(mediator));
var result = await mediator.Send(new SearchResourceHistoryRequest(since, at, count, continuationToken), cancellationToken);
return result.Bundle;
}
public static async Task<Bundle> SearchResourceHistoryAsync(this IMediator mediator, string resourceType, PartialDateTime since = null, PartialDateTime at = null, int? count = null, string continuationToken = null, CancellationToken cancellationToken = default)
{
EnsureArg.IsNotNull(mediator, nameof(mediator));
var result = await mediator.Send(new SearchResourceHistoryRequest(resourceType, since, at, count, continuationToken), cancellationToken);
return result.Bundle;
}
public static async Task<Bundle> SearchResourceHistoryAsync(this IMediator mediator, string resourceType, string resourceId, PartialDateTime since = null, PartialDateTime at = null, int? count = null, string continuationToken = null, CancellationToken cancellationToken = default)
{
EnsureArg.IsNotNull(mediator, nameof(mediator));
var result = await mediator.Send(new SearchResourceHistoryRequest(resourceType, resourceId, since, at, count, continuationToken), cancellationToken);
return result.Bundle;
}
public static async Task<Bundle> SearchResourceCompartmentAsync(this IMediator mediator, string compartmentType, string compartmentId, string resourceType, IReadOnlyList<Tuple<string, string>> queries, CancellationToken cancellationToken = default)
{
EnsureArg.IsNotNull(mediator, nameof(mediator));
var result = await mediator.Send(new CompartmentResourceRequest(compartmentType, compartmentId, resourceType, queries), cancellationToken);
return result.Bundle;
}
public static async Task<CapabilityStatement> GetCapabilitiesAsync(this IMediator mediator, bool isSystem = false, CancellationToken cancellationToken = default)
{
EnsureArg.IsNotNull(mediator, nameof(mediator));
if (isSystem)
{
var sysResponse = await mediator.Send(new GetSystemCapabilitiesRequest(), cancellationToken);
return sysResponse.CapabilityStatement;
}
var response = await mediator.Send(new GetCapabilitiesRequest(), cancellationToken);
return response.CapabilityStatement;
}
}
}
| 48.272 | 288 | 0.696387 | [
"MIT"
] | ardavanhashemzadeh/fhir-server | src/Microsoft.Health.Fhir.Core/Extensions/FhirMediatorExtensions.cs | 6,034 | C# |
using System.Linq;
using Mindscape.Raygun4Net.Storage;
using NUnit.Framework;
namespace Mindscape.Raygun4Net.Tests.Storage
{
[TestFixture]
public class RaygunOfflineStorageTests
{
private IRaygunOfflineStorage _storageOne;
private IRaygunOfflineStorage _storageTwo;
private const string TestApiKey = "DummyApiKey";
[SetUp]
public void SetUp()
{
_storageOne = new IsolatedRaygunOfflineStorage();
_storageTwo = new IsolatedRaygunOfflineStorage();
}
[TearDown]
public void TearDown()
{
// Clear all files from storage.
var filesOne = _storageOne.FetchAll(TestApiKey);
foreach (var file in filesOne)
{
_storageOne.Remove(file.Name, TestApiKey);
}
var filesTwo = _storageTwo.FetchAll(TestApiKey);
foreach (var file in filesTwo)
{
_storageTwo.Remove(file.Name, TestApiKey);
}
}
[Test]
public void Store_UsingInvalidMessageValue_ReturnFalse()
{
Assert.IsFalse(_storageOne.Store(null, TestApiKey));
Assert.IsFalse(_storageOne.Store("", TestApiKey));
}
[Test]
public void Store_UsingInvalidApiKeyValue_ReturnFalse()
{
Assert.IsFalse(_storageOne.Store("DummyData", null));
Assert.IsFalse(_storageOne.Store("DummyData", ""));
}
[Test]
public void FetchAll_UsingInvalidApiKeyValue_ReturnEmptyResult()
{
Assert.IsEmpty(_storageOne.FetchAll(null));
Assert.IsEmpty(_storageOne.FetchAll(""));
}
[Test]
public void Remove_UsingInvalidNameValue_ReturnFalse()
{
Assert.IsFalse(_storageOne.Remove(null, TestApiKey));
Assert.IsFalse(_storageOne.Remove("", TestApiKey));
}
[Test]
public void Remove_UsingInvalidApiKeyValue_ReturnFalse()
{
Assert.IsFalse(_storageOne.Remove("DummyName", null));
Assert.IsFalse(_storageOne.Remove("DummyName", ""));
}
[Test]
public void Store_WriteASingleMessageToStorage_OneMessageIsAvailableFromStorage()
{
// Ensure there are no files in storage.
var files = _storageOne.FetchAll(TestApiKey);
Assert.That(files.Count, Is.EqualTo(0));
RaygunSettings.Settings.MaxCrashReportsStoredOffline = 1;
// Save one message to storage.
_storageOne.Store("DummyData", TestApiKey);
files = _storageOne.FetchAll(TestApiKey);
// Ensure only one file was created.
Assert.That(files.Count, Is.EqualTo(1));
Assert.That(files.First().Contents, Is.EqualTo("DummyData"));
}
[Test]
public void Store_WriteMultipleMessagesToStorage_MaxReportsLimitIsRespected()
{
// Ensure there are no files in storage.
var files = _storageOne.FetchAll(TestApiKey);
Assert.That(files.Count, Is.EqualTo(0));
RaygunSettings.Settings.MaxCrashReportsStoredOffline = 1;
// Save two messages to storage.
_storageOne.Store("DummyData1", TestApiKey);
_storageOne.Store("DummyData2", TestApiKey);
files = _storageOne.FetchAll(TestApiKey);
// Ensure only one file was created.
Assert.That(files.Count, Is.EqualTo(1));
Assert.That(files.First().Contents, Is.EqualTo("DummyData1"));
}
[Test]
public void Remove_TwoMessagesStoredAndOneRemoved_OnlyOneMessageRemainsInStorage()
{
// Ensure there are no files in storage.
var files = _storageOne.FetchAll(TestApiKey);
Assert.That(files.Count, Is.EqualTo(0));
RaygunSettings.Settings.MaxCrashReportsStoredOffline = 2;
// Save two messages to storage.
Assert.IsTrue(_storageOne.Store("DummyData1", TestApiKey));
Assert.IsTrue(_storageOne.Store("DummyData2", TestApiKey));
files = _storageOne.FetchAll(TestApiKey);
// Ensure two files were created.
Assert.That(files.Count, Is.EqualTo(2));
// Remove the first file.
Assert.IsTrue(_storageOne.Remove(files.First().Name, TestApiKey));
// Ensure only one file remains.
files = _storageOne.FetchAll(TestApiKey);
Assert.That(files.Count, Is.EqualTo(1));
}
[Test]
public void Store_StoreUnderFirstKeyAndFetchWithSecondKey_NoFilesFoundForSecondKey()
{
const string apiKeyOne = "KEY_ONE";
const string apiKeyTwo = "KEY_TWO";
// Ensure there are no files in storage under the first API key.
Assert.That(_storageOne.FetchAll(apiKeyOne).Count, Is.EqualTo(0));
// Ensure there are no files in storage under the second API key.
Assert.That(_storageTwo.FetchAll(apiKeyTwo).Count, Is.EqualTo(0));
RaygunSettings.Settings.MaxCrashReportsStoredOffline = 1;
// Save one messages to storage under the first API key.
_storageOne.Store("DummyData1", apiKeyOne);
// There should be one file under the first API key.
Assert.That(_storageOne.FetchAll(apiKeyOne).Count, Is.EqualTo(1));
Assert.That(_storageTwo.FetchAll(apiKeyTwo).Count, Is.EqualTo(0));
}
}
} | 30.714286 | 88 | 0.687563 | [
"MIT"
] | Havunen/raygun4net | Mindscape.Raygun4Net.Tests/Storage/RaygunOfflineStorageTests.cs | 4,945 | C# |
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/aspnet-contrib/AspNet.Security.OAuth.Providers
* for more information concerning the license and the contributors participating to this project.
*/
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
using Xunit.Abstractions;
namespace AspNet.Security.OAuth.EVEOnline
{
public class EVEOnlineTests : OAuthTests<EVEOnlineAuthenticationOptions>
{
public EVEOnlineTests(ITestOutputHelper outputHelper)
{
OutputHelper = outputHelper;
}
public override string DefaultScheme => EVEOnlineAuthenticationDefaults.AuthenticationScheme;
protected internal override void RegisterAuthentication(AuthenticationBuilder builder)
{
builder.AddEVEOnline(options => ConfigureDefaults(builder, options));
}
[Theory]
[InlineData(ClaimTypes.NameIdentifier, "my-id")]
[InlineData(ClaimTypes.Name, "John Smith")]
[InlineData(ClaimTypes.Expiration, "2019-12-31T23:59:59+00:00")]
[InlineData("urn:eveonline:scopes", "my-scopes")]
public async Task Can_Sign_In_Using_EVE_Online(string claimType, string claimValue)
{
// Arrange
using (var server = CreateTestServer())
{
// Act
var claims = await AuthenticateUserAsync(server);
// Assert
AssertClaim(claims, claimType, claimValue);
}
}
}
}
| 34.183673 | 101 | 0.673433 | [
"Apache-2.0"
] | couven92/AspNet.Security.OAuth.Providers | test/AspNet.Security.OAuth.Providers.Tests/EVEOnline/EVEOnlineTests.cs | 1,677 | C# |
using Dotnet9.Application.Contracts.Blogs;
namespace Dotnet9.Web.ViewModels.Blogs;
public class BlogPostListViewModel
{
public string Name { get; set; } = null!;
public List<BlogPostBriefDto>? Items { get; set; }
} | 25 | 54 | 0.737778 | [
"MIT"
] | dotnet9/Dotnet9 | src/Dotnet9.Web/ViewModels/Blogs/BlogPostListViewModel.cs | 227 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("FireAlarmSystem")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FireAlarmSystem")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c9e5eb59-05eb-4384-8b48-c8777cac3054")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.861111 | 84 | 0.749817 | [
"Apache-2.0"
] | 463-archaic-codebase/Fire-Alarm-System | FireAlarmSystem/FireAlarmSystem/Properties/AssemblyInfo.cs | 1,366 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace ContosoPizza
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 25.703704 | 70 | 0.645533 | [
"MIT"
] | WashinRibeiro/ContosoPizza | Program.cs | 694 | C# |
namespace HotChocolate.ApolloFederation;
internal static class WellKnownArgumentNames
{
public const string Fields = "fields";
public const string Representations = "representations";
}
| 24.375 | 60 | 0.789744 | [
"MIT"
] | ScriptBox99/hotchocolate | src/HotChocolate/ApolloFederation/src/ApolloFederation/WellKnownArgumentNames.cs | 195 | C# |
using Logic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace Model
{
//This class copes with visual representation of spheres.
public class PresentationSphere: ISphere
{
//Meant for string representation of color we pick.
public string Color { get; set; }
//Here we go with diameter instead of radian, cause it works better with GUI.
public double Diameter { get; }
public int Id { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
private double y;
private double x;
public double Y
{
get { return y; }
set
{
if (y == value) return;
y = value;
RaisePropertyChanged();
}
}
public double X
{
get { return x; }
set
{
if (x == value) return;
x = value;
RaisePropertyChanged();
}
}
//Constructor for visual representation of the sphere. Default color is 'red'.
public PresentationSphere(int id, double top, double left, double radius, string c = "red")
{
this.Id = id;
this.Color = c;
this.y = top;
this.x = left;
this.Diameter = 2 * radius;
}
private void RaisePropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
| 27.741379 | 99 | 0.53325 | [
"Apache-2.0"
] | KacperKuchciak/Prog_Wspolbiezne_2022 | GeneralSolution/Model/PresentationSphere.cs | 1,611 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using UniversalProcessor.SDD.Common;
namespace UniversalProcessor.SDD.IT
{
public class SDDUrl : SDDDataViewDefinition
{
public readonly static Guid UrlIdentifier = new Guid("e737eea1-9198-44e9-8f02-5e020fe9a916");
private const int ID_WHOLESTRING_LENGTH = 0;
private const int FUNC_GetScheme = 1;
private const int FUNC_GetHost = 2;
private const int FUNC_GetPort = 3;
private const int FUNC_GetPath = 4;
private const int FUNC_GetQueryString = 5;
private readonly Uri value;
public SDDUrl() : base(UrlIdentifier)
{
value = null;
//this.Calculators.Add(FUNC_GetLength, (SSDCalculateSingle)(() => { return MainProcessor.Describe(value.Length); }));
//this.Add(ID_WHOLESTRING_LENGTH, "Length", CommonDefinitions.SDDInteger, FUNC_GetLength);
this.Calculators.Add(FUNC_GetScheme, (SSDCalculateSingle)(() => { return ProcessorAPI.Describe(value.Scheme); }));
this.Calculators.Add(FUNC_GetHost, (SSDCalculateSingle)(() => { return ProcessorAPI.Describe(value.DnsSafeHost); }));
this.Calculators.Add(FUNC_GetPort, (SSDCalculateSingle)(() => { return ProcessorAPI.Describe(value.Port); }));
this.Calculators.Add(FUNC_GetPath, (SSDCalculateSingle)(() => { return ProcessorAPI.Describe(value.LocalPath); }));
this.Calculators.Add(FUNC_GetQueryString, (SSDCalculateSingle)(() => { return ProcessorAPI.Describe(value.Query); }));
this.Add(ID_WHOLESTRING_LENGTH, "Scheme", CommonDefinitions.SDDString, FUNC_GetScheme);
this.Add(ID_WHOLESTRING_LENGTH, "Host", CommonDefinitions.SDDString, FUNC_GetHost);
this.Add(ID_WHOLESTRING_LENGTH, "Port", CommonDefinitions.SDDInteger, FUNC_GetPort);
this.Add(ID_WHOLESTRING_LENGTH, "Path", CommonDefinitions.SDDString, FUNC_GetPath);
this.Add(ID_WHOLESTRING_LENGTH, "Query", CommonDefinitions.SDDString, FUNC_GetQueryString);
}
public SDDUrl(string initValue) : this()
{
value = new Uri(initValue);
}
public override string DisplayValue()
{
return value.OriginalString;
}
}
}
| 46.26 | 130 | 0.671422 | [
"MIT"
] | Jones-Adam/UniversalProcessor | UniversalProcessor/SDD.IT/SDDUrl.cs | 2,315 | C# |
using System.Threading.Tasks;
using Daniel15.SimpleIdentity;
using Daniel15.Web.ViewModels.Account;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace Daniel15.Web.Controllers
{
/// <summary>
/// Handles logging in and out
/// </summary>
[Route("account")]
public partial class AccountController : Controller
{
private readonly SignInManager<SimpleIdentityUser> _signInManager;
public AccountController(SignInManager<SimpleIdentityUser> signInManager)
{
_signInManager = signInManager;
}
/// <summary>
/// Displays the login page
/// </summary>
/// <param name="returnUrl">URL to return to after logging in</param>
/// <returns></returns>
[Route("login")]
public virtual ActionResult Login(string returnUrl)
{
return View(new LoginViewModel { ReturnUrl = returnUrl });
}
/// <summary>
/// Actually log the user in.
/// </summary>
/// <param name="model">Login model</param>
/// <param name="returnUrl">URL to return to after logging in</param>
/// <returns></returns>
[HttpPost("login")]
[ValidateAntiForgeryToken]
public virtual async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, isPersistent: false, lockoutOnFailure: false);
if (result.Succeeded)
{
return RedirectToLocal(returnUrl);
}
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError(string.Empty, "The user name or password provided is incorrect.");
return View(model);
}
/// <summary>
/// Redirect to the specified URL if it's local to this site. Otherwise, redirect to the index.
/// </summary>
/// <param name="returnUrl">URL to redirect to</param>
/// <returns>Redirect</returns>
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
// TODO: Redirect to admin home
return RedirectToAction("Index", "Site");
}
}
}
}
| 27.578947 | 136 | 0.69895 | [
"MIT",
"Unlicense"
] | DLN-India/Website | Daniel15.Web/Controllers/AccountController.cs | 2,096 | C# |
namespace RP_Server_Scripts.Network
{
public interface IScriptMessageHandlerSelector
{
bool TryGetMessageHandler(RP_Shared_Script.ScriptMessages message, out IScriptMessageHandler handler);
}
}
| 26.875 | 110 | 0.786047 | [
"BSD-2-Clause"
] | JulianVo/SumpfkrautOnline-Khorinis | RP_Server_Scripts/Network/IScriptMessageHandlerSelector.cs | 217 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Autodesk.DesignScript.Interfaces;
using System.Collections;
using Autodesk.DesignScript.Geometry;
namespace DSGeometry
{
/*
class MeshTopologyEntity : ITopologyEntity, IBRepEntity
{
private ISubDMeshEntity mesh;
private IBRepEntity brep = null;
private bool mbAutoDispose;
public MeshTopologyEntity(ISubDMeshEntity mesh, bool bAutoDispose = true)
{
// TODO: Complete member initialization
this.mesh = mesh;
mbAutoDispose = bAutoDispose;
}
public object Owner
{
get;
private set;
}
public void SetOwner(object owner)
{
this.Owner = owner;
}
public void Dispose()
{
if (mbAutoDispose && mesh != null)
mesh.Dispose();
mesh = null;
}
private IBRepEntity GetBRepEntity()
{
if (brep == null)
{
ISurfaceEntity geometry = mesh.ConvertToSurface(false);
brep = geometry as IBRepEntity;
}
return brep;
}
public IFaceEntity[] GetFaces()
{
return GetBRepEntity().GetFaces();
}
public IEdgeEntity[] GetEdges()
{
return GetBRepEntity().GetEdges();
}
public IVertexEntity[] GetVertices()
{
return GetBRepEntity().GetVertices();
}
public int GetVertexCount()
{
return GetBRepEntity().GetVertexCount();
}
public int GetEdgeCount()
{
return GetBRepEntity().GetEdgeCount();
}
public int GetFaceCount()
{
return GetBRepEntity().GetFaceCount();
}
}
class PointComparer : IEqualityComparer<IPointEntity>, IEqualityComparer
{
public bool Equals(IPointEntity x, IPointEntity y)
{
return GeometryExtension.EqualsTo(x.X, y.X) &&
GeometryExtension.EqualsTo(x.Y, y.Y) &&
GeometryExtension.EqualsTo(x.Z, y.Z);
}
public int GetHashCode(IPointEntity obj)
{
unchecked
{
var hash = 0;
hash = (hash * 397) ^ obj.X.GetHashCode();
hash = (hash * 397) ^ obj.Y.GetHashCode();
hash = (hash * 397) ^ obj.Z.GetHashCode();
return hash;
}
}
public bool Equals(object x, object y)
{
IPointEntity first = x as IPointEntity;
IPointEntity second = y as IPointEntity;
if (first != null && second != null)
return this.Equals(first, second);
return x.Equals(y);
}
public int GetHashCode(object obj)
{
IPointEntity pt = obj as IPointEntity;
if (pt != null)
return GetHashCode(pt);
return obj.GetHashCode();
}
}*/
class MeshEntity : TopologyEntity, IMeshEntity
{
ISolidEntity mSolid = new SolidEntity();
public IGeometryEntity Geometry
{
get { return mSolid; }
}
public IFaceEntity[] GetFaces()
{
return mSolid.GetFaces();
}
public IEdgeEntity[] GetEdges()
{
return mSolid.GetEdges();
}
public IVertexEntity[] GetVertices()
{
return mSolid.GetVertices();
}
public int GetVertexCount()
{
return mSolid.GetVertexCount();
}
public int GetEdgeCount()
{
return mSolid.GetEdgeCount();
}
public int GetFaceCount()
{
return mSolid.GetFaceCount();
}
}
}
| 24.981707 | 82 | 0.492067 | [
"Apache-2.0"
] | DynamoDS/designscript-archive | Libraries/DSGeometry/MeshEntity.cs | 4,099 | C# |
using System;
using Content.Server.Cloning;
using Content.Server.Mind.Components;
using Content.Server.Power.Components;
using Content.Server.Preferences.Managers;
using Content.Server.UserInterface;
using Content.Shared.ActionBlocker;
using Content.Shared.Acts;
using Content.Shared.Damage;
using Content.Shared.DragDrop;
using Content.Shared.Interaction;
using Content.Shared.MedicalScanner;
using Content.Shared.MobState;
using Content.Shared.Popups;
using Content.Shared.Preferences;
using Robust.Server.GameObjects;
using Robust.Shared.Containers;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Maths;
using Robust.Shared.Network;
using Robust.Shared.ViewVariables;
namespace Content.Server.Medical.Components
{
[RegisterComponent]
[ComponentReference(typeof(IActivate))]
[ComponentReference(typeof(SharedMedicalScannerComponent))]
public class MedicalScannerComponent : SharedMedicalScannerComponent, IActivate, IDestroyAct
{
[Dependency] private readonly IServerPreferencesManager _prefsManager = null!;
public static readonly TimeSpan InternalOpenAttemptDelay = TimeSpan.FromSeconds(0.5);
public TimeSpan LastInternalOpenAttempt;
private ContainerSlot _bodyContainer = default!;
private readonly Vector2 _ejectOffset = new(0f, 0f);
[ViewVariables]
private bool Powered => !Owner.TryGetComponent(out ApcPowerReceiverComponent? receiver) || receiver.Powered;
[ViewVariables]
private BoundUserInterface? UserInterface => Owner.GetUIOrNull(MedicalScannerUiKey.Key);
public bool IsOccupied => _bodyContainer.ContainedEntity != null;
protected override void Initialize()
{
base.Initialize();
if (UserInterface != null)
{
UserInterface.OnReceiveMessage += OnUiReceiveMessage;
}
_bodyContainer = ContainerHelpers.EnsureContainer<ContainerSlot>(Owner, $"{Name}-bodyContainer");
// TODO: write this so that it checks for a change in power events and acts accordingly.
var newState = GetUserInterfaceState();
UserInterface?.SetState(newState);
UpdateUserInterface();
}
private static readonly MedicalScannerBoundUserInterfaceState EmptyUIState =
new(
null,
null,
false);
private MedicalScannerBoundUserInterfaceState GetUserInterfaceState()
{
var body = _bodyContainer.ContainedEntity;
if (body == null)
{
if (Owner.TryGetComponent(out AppearanceComponent? appearance))
{
appearance?.SetData(MedicalScannerVisuals.Status, MedicalScannerStatus.Open);
}
return EmptyUIState;
}
if (!body.TryGetComponent(out DamageableComponent? damageable))
{
return EmptyUIState;
}
if (_bodyContainer.ContainedEntity?.Uid == null)
{
return new MedicalScannerBoundUserInterfaceState(body.Uid, damageable, true);
}
var cloningSystem = EntitySystem.Get<CloningSystem>();
var scanned = _bodyContainer.ContainedEntity.TryGetComponent(out MindComponent? mindComponent) &&
mindComponent.Mind != null &&
cloningSystem.HasDnaScan(mindComponent.Mind);
return new MedicalScannerBoundUserInterfaceState(body.Uid, damageable, scanned);
}
private void UpdateUserInterface()
{
if (!Powered)
{
return;
}
var newState = GetUserInterfaceState();
UserInterface?.SetState(newState);
}
private MedicalScannerStatus GetStatusFromDamageState(IMobStateComponent state)
{
if (state.IsAlive())
{
return MedicalScannerStatus.Green;
}
else if (state.IsCritical())
{
return MedicalScannerStatus.Red;
}
else if (state.IsDead())
{
return MedicalScannerStatus.Death;
}
else
{
return MedicalScannerStatus.Yellow;
}
}
private MedicalScannerStatus GetStatus()
{
if (Powered)
{
var body = _bodyContainer.ContainedEntity;
var state = body?.GetComponentOrNull<IMobStateComponent>();
return state == null
? MedicalScannerStatus.Open
: GetStatusFromDamageState(state);
}
return MedicalScannerStatus.Off;
}
private void UpdateAppearance()
{
if (Owner.TryGetComponent(out AppearanceComponent? appearance))
{
appearance.SetData(MedicalScannerVisuals.Status, GetStatus());
}
}
void IActivate.Activate(ActivateEventArgs args)
{
if (!args.User.TryGetComponent(out ActorComponent? actor))
{
return;
}
if (!Powered)
return;
UserInterface?.Open(actor.PlayerSession);
}
public void InsertBody(IEntity user)
{
_bodyContainer.Insert(user);
UpdateUserInterface();
UpdateAppearance();
}
public void EjectBody()
{
var containedEntity = _bodyContainer.ContainedEntity;
if (containedEntity == null) return;
_bodyContainer.Remove(containedEntity);
containedEntity.Transform.WorldPosition += _ejectOffset;
UpdateUserInterface();
UpdateAppearance();
}
public void Update(float frameTime)
{
UpdateUserInterface();
UpdateAppearance();
}
private void OnUiReceiveMessage(ServerBoundUserInterfaceMessage obj)
{
if (obj.Message is not UiButtonPressedMessage message) return;
switch (message.Button)
{
case UiButton.ScanDNA:
if (_bodyContainer.ContainedEntity != null)
{
var cloningSystem = EntitySystem.Get<CloningSystem>();
if (!_bodyContainer.ContainedEntity.TryGetComponent(out MindComponent? mindComp) || mindComp.Mind == null)
{
obj.Session.AttachedEntity?.PopupMessageCursor(Loc.GetString("medical-scanner-component-msg-no-soul"));
break;
}
// Null suppression based on above check. Yes, it's explicitly needed
var mind = mindComp.Mind!;
// We need the HumanoidCharacterProfile
// TODO: Move this further 'outwards' into a DNAComponent or somesuch.
// Ideally this ends with GameTicker & CloningSystem handing DNA to a function that sets up a body for that DNA.
var mindUser = mind.UserId;
if (mindUser == null)
{
// For now assume this means soul departed
obj.Session.AttachedEntity?.PopupMessageCursor(Loc.GetString("medical-scanner-component-msg-soul-broken"));
break;
}
// has to be explicit cast like this, IDK why, null suppression operators seem to not work
var profile = GetPlayerProfileAsync((NetUserId) mindUser);
cloningSystem.AddToDnaScans(new ClonerDNAEntry(mind, profile));
}
break;
default:
throw new ArgumentOutOfRangeException();
}
}
public override bool DragDropOn(DragDropEvent eventArgs)
{
_bodyContainer.Insert(eventArgs.Dragged);
return true;
}
void IDestroyAct.OnDestroy(DestructionEventArgs eventArgs)
{
EjectBody();
}
private HumanoidCharacterProfile GetPlayerProfileAsync(NetUserId userId)
{
return (HumanoidCharacterProfile) _prefsManager.GetPreferences(userId).SelectedCharacter;
}
}
}
| 34.289683 | 136 | 0.582456 | [
"MIT"
] | Day-OS/space-station-14 | Content.Server/Medical/Components/MedicalScannerComponent.cs | 8,641 | C# |
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
/* ReadRecordCommand.cs --
* Ars Magna project, http://arsmagna.ru
* -------------------------------------------------------
* Status: poor
*/
#region Using directives
using System;
using System.Text;
using AM;
using AM.Logging;
using JetBrains.Annotations;
using ManagedIrbis.Client;
using ManagedIrbis.Direct;
using MoonSharp.Interpreter;
#endregion
namespace ManagedIrbis.Server.Commands
{
/// <summary>
///
/// </summary>
[PublicAPI]
[MoonSharpUserData]
public class ReadRecordCommand
: ServerCommand
{
#region Construction
/// <summary>
/// Constructor.
/// </summary>
public ReadRecordCommand
(
[NotNull] WorkData data
)
: base(data)
{
}
#endregion
#region Private members
/// <summary>
/// Кодирование записи в клиентское представление.
/// </summary>
public static string EncodeRecord
(
MarcRecord record
)
{
StringBuilder result = new StringBuilder();
result.AppendFormat
(
"{0}#{1}",
record.Mfn.ToInvariantString(),
((int)record.Status).ToInvariantString()
);
result.Append("\r\n");
result.AppendFormat
(
"0#{0}",
record.Version.ToInvariantString()
);
result.Append("\r\n");
foreach (RecordField field in record.Fields)
{
result.AppendFormat
(
"{0}#",
field.Tag.ToInvariantString()
);
result.Append(field.Value);
foreach (SubField subField in field.SubFields)
{
result.AppendFormat
(
"{0}{1}{2}",
SubField.Delimiter,
subField.Code,
subField.Value
);
}
result.Append("\r\n");
}
return result.ToString();
}
#endregion
#region ServerCommand members
/// <inheritdoc cref="ServerCommand.Execute" />
public override void Execute()
{
// TODO перейти на RawRecord, если не требуется форматирование
// В случае физически удаленной записи возвращается 2 строки:
// 1-я строка - ZERO
// 2-я строка – UTF-8(ЗАПИСЬ ФИЗИЧЕСКИ УДАЛЕНА)
IrbisServerEngine engine = Data.Engine.ThrowIfNull();
engine.OnBeforeExecute(Data);
try
{
ServerContext context = engine.RequireContext(Data);
Data.Context = context;
UpdateContext();
ClientRequest request = Data.Request.ThrowIfNull();
string database = request.RequireAnsiString();
int mfn = request.GetInt32();
int needLock = request.GetInt32();
string format = request.GetAutoString();
string formatted = null;
MarcRecord record;
using (LocalProvider provider = engine.GetProvider(database))
{
record = provider.ReadRecord(mfn);
if (!string.IsNullOrEmpty(format)
&& !ReferenceEquals(record, null))
{
formatted = provider.FormatRecord(record, format);
formatted = IrbisText.WindowsToIrbis(formatted);
}
}
if (needLock != 0)
{
using (DirectAccess64 direct = engine.GetDatabase(database))
{
direct.Xrf.LockRecord(mfn, true);
}
}
ServerResponse response = Data.Response.ThrowIfNull();
response.WriteInt32(0).NewLine();
if (!ReferenceEquals(record, null))
{
string recordText = EncodeRecord(record);
response.WriteUtfString(recordText).NewLine();
}
if (!string.IsNullOrEmpty(formatted))
{
response.WriteUtfString("#").NewLine();
response.WriteInt32(0).NewLine();
response.WriteUtfString(formatted).NewLine();
}
SendResponse();
}
catch (IrbisException exception)
{
SendError(exception.ErrorCode);
}
catch (Exception exception)
{
Log.TraceException("ReadRecordCommand::Execute", exception);
SendError(-8888);
}
engine.OnAfterExecute(Data);
}
#endregion
}
}
| 28.5 | 84 | 0.46727 | [
"MIT"
] | amironov73/ManagedClient.45 | Source/Classic/Libs/ManagedIrbis/Source/Server/Commands/ReadRecordCommand.cs | 5,469 | C# |
using System.Threading.Tasks;
namespace KartURL.Common
{
public interface IFileDialog
{
Task<string> ShowAsync();
}
} | 15.444444 | 33 | 0.661871 | [
"MIT"
] | QuantumToasted/KartURL | Common/IFileDialog.cs | 141 | 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.Globalization;
using System.Linq;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Metadata;
namespace Microsoft.EntityFrameworkCore.Update
{
/// <summary>
/// Extension methods for <see cref="IUpdateEntry" />.
/// </summary>
public static class UpdateEntryExtensions
{
/// <summary>
/// Creates a formatted string representation of the given properties and their current
/// values such as is useful when throwing exceptions about keys, indexes, etc. that use
/// the properties.
/// </summary>
/// <param name="entry"> The entry from which values will be obtained. </param>
/// <param name="properties"> The properties to format. </param>
/// <returns> The string representation. </returns>
public static string BuildCurrentValuesString(
[NotNull] this IUpdateEntry entry,
[NotNull] IEnumerable<IPropertyBase> properties)
=> "{" + string.Join(", ", properties.Select(p => p.Name + ": " + Convert.ToString(entry.GetCurrentValue(p), CultureInfo.InvariantCulture))) + "}";
/// <summary>
/// Creates a formatted string representation of the given properties and their original
/// values such as is useful when throwing exceptions about keys, indexes, etc. that use
/// the properties.
/// </summary>
/// <param name="entry"> The entry from which values will be obtained. </param>
/// <param name="properties"> The properties to format. </param>
/// <returns> The string representation. </returns>
public static string BuildOriginalValuesString(
[NotNull] this IUpdateEntry entry,
[NotNull] IEnumerable<IPropertyBase> properties)
=> "{" + string.Join(", ", properties.Select(p => p.Name + ": " + Convert.ToString(entry.GetOriginalValue(p), CultureInfo.InvariantCulture))) + "}";
}
}
| 48.8 | 160 | 0.651639 | [
"Apache-2.0"
] | CygnusBill/EntityFrameworkCore | src/EFCore/Update/UpdateEntryExtensions.cs | 2,196 | C# |
using System;
using System.Data.Common;
using System.Diagnostics;
using System.Net;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace PlatformRacing3.Common.Server
{
public class ServerDetails : IXmlSerializable
{
public uint Id { get; }
public string Name { get; internal set; }
public EndPoint EndPoint { get; internal set; }
private string _Status;
/// <summary>
/// If last update is more than server status timeout we will show server status timeout message instead
/// </summary>
internal Stopwatch LastStatusUpdate { get; set; }
private ServerDetails()
{
}
public ServerDetails(DbDataReader reader)
{
this.Id = (uint)(int)reader["id"];
this.Name = (string)reader["name"];
string ip = (string)reader["ip"];
int port = (int)reader["port"];
if (IPAddress.TryParse(ip, out IPAddress address))
{
this.EndPoint = new IPEndPoint(address, port);
}
else
{
this.EndPoint = new DnsEndPoint(ip, port);
}
this._Status = ServerManager.SERVER_STATUS_TIMEOUT_MESSAGE; //Lets show this by default
this.LastStatusUpdate = new Stopwatch();
}
public string Status => this.LastStatusUpdate.Elapsed.TotalSeconds > ServerManager.SERVER_STATUS_TIMEOUT ? ServerManager.SERVER_STATUS_TIMEOUT_MESSAGE : this._Status;
public string IP => this.EndPoint switch
{
IPEndPoint ip => ip.Address.ToString(),
DnsEndPoint dns => dns.Host,
_ => throw new NotSupportedException()
};
public int Port => this.EndPoint switch
{
IPEndPoint ip => ip.Port,
DnsEndPoint dns => dns.Port,
_ => throw new NotSupportedException()
};
internal void SetStatus(string status)
{
this._Status = status;
this.LastStatusUpdate.Restart();
}
public XmlSchema GetSchema() => null;
public void ReadXml(XmlReader reader) => throw new NotSupportedException();
public void WriteXml(XmlWriter writer)
{
writer.WriteElementString("server_name", this.Name);
writer.WriteElementString("status", this.Status);
writer.WriteElementString("address", this.IP);
writer.WriteElementString("port", this.Port.ToString());
}
}
}
| 30.023256 | 174 | 0.59024 | [
"MIT"
] | CoralCOasa/PlatformRacing3 | PlatformRacing3.Common/Server/ServerDetails.cs | 2,584 | C# |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Apis.CertificateAuthorityService.v1
{
/// <summary>The CertificateAuthorityService Service.</summary>
public class CertificateAuthorityServiceService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public CertificateAuthorityServiceService() : this(new Google.Apis.Services.BaseClientService.Initializer())
{
}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public CertificateAuthorityServiceService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer)
{
Projects = new ProjectsResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features => new string[0];
/// <summary>Gets the service name.</summary>
public override string Name => "privateca";
/// <summary>Gets the service base URI.</summary>
public override string BaseUri =>
#if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45
BaseUriOverride ?? "https://privateca.googleapis.com/";
#else
"https://privateca.googleapis.com/";
#endif
/// <summary>Gets the service base path.</summary>
public override string BasePath => "";
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri => "https://privateca.googleapis.com/batch";
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath => "batch";
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Certificate Authority API.</summary>
public class Scope
{
/// <summary>
/// See, edit, configure, and delete your Google Cloud data and see the email address for your Google
/// Account.
/// </summary>
public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
}
/// <summary>Available OAuth 2.0 scope constants for use with the Certificate Authority API.</summary>
public static class ScopeConstants
{
/// <summary>
/// See, edit, configure, and delete your Google Cloud data and see the email address for your Google
/// Account.
/// </summary>
public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
}
/// <summary>Gets the Projects resource.</summary>
public virtual ProjectsResource Projects { get; }
}
/// <summary>A base abstract class for CertificateAuthorityService requests.</summary>
public abstract class CertificateAuthorityServiceBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
/// <summary>Constructs a new CertificateAuthorityServiceBaseServiceRequest instance.</summary>
protected CertificateAuthorityServiceBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1 = 0,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2 = 1,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json = 0,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media = 1,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto = 2,
}
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>
/// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required
/// unless you provide an OAuth 2.0 token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>
/// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a
/// user, but should not exceed 40 characters.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes CertificateAuthorityService parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "projects" collection of methods.</summary>
public class ProjectsResource
{
private const string Resource = "projects";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ProjectsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
Locations = new LocationsResource(service);
}
/// <summary>Gets the Locations resource.</summary>
public virtual LocationsResource Locations { get; }
/// <summary>The "locations" collection of methods.</summary>
public class LocationsResource
{
private const string Resource = "locations";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public LocationsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
CaPools = new CaPoolsResource(service);
CertificateTemplates = new CertificateTemplatesResource(service);
Operations = new OperationsResource(service);
}
/// <summary>Gets the CaPools resource.</summary>
public virtual CaPoolsResource CaPools { get; }
/// <summary>The "caPools" collection of methods.</summary>
public class CaPoolsResource
{
private const string Resource = "caPools";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public CaPoolsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
CertificateAuthorities = new CertificateAuthoritiesResource(service);
Certificates = new CertificatesResource(service);
}
/// <summary>Gets the CertificateAuthorities resource.</summary>
public virtual CertificateAuthoritiesResource CertificateAuthorities { get; }
/// <summary>The "certificateAuthorities" collection of methods.</summary>
public class CertificateAuthoritiesResource
{
private const string Resource = "certificateAuthorities";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public CertificateAuthoritiesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
CertificateRevocationLists = new CertificateRevocationListsResource(service);
}
/// <summary>Gets the CertificateRevocationLists resource.</summary>
public virtual CertificateRevocationListsResource CertificateRevocationLists { get; }
/// <summary>The "certificateRevocationLists" collection of methods.</summary>
public class CertificateRevocationListsResource
{
private const string Resource = "certificateRevocationLists";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public CertificateRevocationListsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Returns a CertificateRevocationList.</summary>
/// <param name="name">Required. The name of the CertificateRevocationList to get.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Returns a CertificateRevocationList.</summary>
public class GetRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.CertificateRevocationList>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>Required. The name of the CertificateRevocationList to get.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/caPools/[^/]+/certificateAuthorities/[^/]+/certificateRevocationLists/[^/]+$",
});
}
}
/// <summary>
/// Gets the access control policy for a resource. Returns an empty policy if the resource
/// exists and does not have a policy set.
/// </summary>
/// <param name="resource">
/// REQUIRED: The resource for which the policy is being requested. See the operation
/// documentation for the appropriate value for this field.
/// </param>
public virtual GetIamPolicyRequest GetIamPolicy(string resource)
{
return new GetIamPolicyRequest(service, resource);
}
/// <summary>
/// Gets the access control policy for a resource. Returns an empty policy if the resource
/// exists and does not have a policy set.
/// </summary>
public class GetIamPolicyRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.Policy>
{
/// <summary>Constructs a new GetIamPolicy request.</summary>
public GetIamPolicyRequest(Google.Apis.Services.IClientService service, string resource) : base(service)
{
Resource = resource;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy is being requested. See the operation
/// documentation for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>
/// Optional. The maximum policy version that will be used to format the policy. Valid
/// values are 0, 1, and 3. Requests specifying an invalid value will be rejected. Requests
/// for policies with any conditional role bindings must specify version 3. Policies with no
/// conditional role bindings may specify any valid value or leave the field unset. The
/// policy in the response might use the policy version that you specified, or it might use
/// a lower policy version. For example, if you specify version 3, but the policy has no
/// conditional role bindings, the response uses version 1. To learn which resources support
/// conditions in their IAM policies, see the [IAM
/// documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("options.requestedPolicyVersion", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> OptionsRequestedPolicyVersion { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "getIamPolicy";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+resource}:getIamPolicy";
/// <summary>Initializes GetIamPolicy parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/caPools/[^/]+/certificateAuthorities/[^/]+/certificateRevocationLists/[^/]+$",
});
RequestParameters.Add("options.requestedPolicyVersion", new Google.Apis.Discovery.Parameter
{
Name = "options.requestedPolicyVersion",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Lists CertificateRevocationLists.</summary>
/// <param name="parent">
/// Required. The resource name of the location associated with the CertificateRevocationLists,
/// in the format `projects/*/locations/*/caPools/*/certificateAuthorities/*`.
/// </param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Lists CertificateRevocationLists.</summary>
public class ListRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.ListCertificateRevocationListsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>
/// Required. The resource name of the location associated with the
/// CertificateRevocationLists, in the format
/// `projects/*/locations/*/caPools/*/certificateAuthorities/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>
/// Optional. Only include resources that match the filter in the response.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>Optional. Specify how the results should be sorted.</summary>
[Google.Apis.Util.RequestParameterAttribute("orderBy", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OrderBy { get; set; }
/// <summary>
/// Optional. Limit on the number of CertificateRevocationLists to include in the response.
/// Further CertificateRevocationLists can subsequently be obtained by including the
/// ListCertificateRevocationListsResponse.next_page_token in a subsequent request. If
/// unspecified, the server will pick an appropriate default.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// Optional. Pagination token, returned earlier via
/// ListCertificateRevocationListsResponse.next_page_token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/certificateRevocationLists";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/caPools/[^/]+/certificateAuthorities/[^/]+$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("orderBy", new Google.Apis.Discovery.Parameter
{
Name = "orderBy",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Update a CertificateRevocationList.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// Output only. The resource name for this CertificateRevocationList in the format
/// `projects/*/locations/*/caPools/*certificateAuthorities/*/ certificateRevocationLists/*`.
/// </param>
public virtual PatchRequest Patch(Google.Apis.CertificateAuthorityService.v1.Data.CertificateRevocationList body, string name)
{
return new PatchRequest(service, body, name);
}
/// <summary>Update a CertificateRevocationList.</summary>
public class PatchRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.Operation>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.CertificateAuthorityService.v1.Data.CertificateRevocationList body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// Output only. The resource name for this CertificateRevocationList in the format
/// `projects/*/locations/*/caPools/*certificateAuthorities/*/
/// certificateRevocationLists/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// Optional. An ID to identify requests. Specify a unique request ID so that if you must
/// retry your request, the server will know to ignore the request if it has already been
/// completed. The server will guarantee that for at least 60 minutes since the first
/// request. For example, consider a situation where you make an initial request and t he
/// request times out. If you make the request again with the same request ID, the server
/// can check if original operation with the same request ID was received, and if so, will
/// ignore the second request. This prevents clients from accidentally creating duplicate
/// commitments. The request ID must be a valid UUID with the exception that zero UUID is
/// not supported (00000000-0000-0000-0000-000000000000).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("requestId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string RequestId { get; set; }
/// <summary>Required. A list of fields to be updated in this request.</summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CertificateAuthorityService.v1.Data.CertificateRevocationList Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "patch";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "PATCH";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/caPools/[^/]+/certificateAuthorities/[^/]+/certificateRevocationLists/[^/]+$",
});
RequestParameters.Add("requestId", new Google.Apis.Discovery.Parameter
{
Name = "requestId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any existing policy. Can
/// return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="resource">
/// REQUIRED: The resource for which the policy is being specified. See the operation
/// documentation for the appropriate value for this field.
/// </param>
public virtual SetIamPolicyRequest SetIamPolicy(Google.Apis.CertificateAuthorityService.v1.Data.SetIamPolicyRequest body, string resource)
{
return new SetIamPolicyRequest(service, body, resource);
}
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any existing policy. Can
/// return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors.
/// </summary>
public class SetIamPolicyRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.Policy>
{
/// <summary>Constructs a new SetIamPolicy request.</summary>
public SetIamPolicyRequest(Google.Apis.Services.IClientService service, Google.Apis.CertificateAuthorityService.v1.Data.SetIamPolicyRequest body, string resource) : base(service)
{
Resource = resource;
Body = body;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy is being specified. See the operation
/// documentation for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CertificateAuthorityService.v1.Data.SetIamPolicyRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "setIamPolicy";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+resource}:setIamPolicy";
/// <summary>Initializes SetIamPolicy parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/caPools/[^/]+/certificateAuthorities/[^/]+/certificateRevocationLists/[^/]+$",
});
}
}
/// <summary>
/// Returns permissions that a caller has on the specified resource. If the resource does not
/// exist, this will return an empty set of permissions, not a `NOT_FOUND` error. Note: This
/// operation is designed to be used for building permission-aware UIs and command-line tools,
/// not for authorization checking. This operation may "fail open" without warning.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="resource">
/// REQUIRED: The resource for which the policy detail is being requested. See the operation
/// documentation for the appropriate value for this field.
/// </param>
public virtual TestIamPermissionsRequest TestIamPermissions(Google.Apis.CertificateAuthorityService.v1.Data.TestIamPermissionsRequest body, string resource)
{
return new TestIamPermissionsRequest(service, body, resource);
}
/// <summary>
/// Returns permissions that a caller has on the specified resource. If the resource does not
/// exist, this will return an empty set of permissions, not a `NOT_FOUND` error. Note: This
/// operation is designed to be used for building permission-aware UIs and command-line tools,
/// not for authorization checking. This operation may "fail open" without warning.
/// </summary>
public class TestIamPermissionsRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.TestIamPermissionsResponse>
{
/// <summary>Constructs a new TestIamPermissions request.</summary>
public TestIamPermissionsRequest(Google.Apis.Services.IClientService service, Google.Apis.CertificateAuthorityService.v1.Data.TestIamPermissionsRequest body, string resource) : base(service)
{
Resource = resource;
Body = body;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy detail is being requested. See the operation
/// documentation for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CertificateAuthorityService.v1.Data.TestIamPermissionsRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "testIamPermissions";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+resource}:testIamPermissions";
/// <summary>Initializes TestIamPermissions parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/caPools/[^/]+/certificateAuthorities/[^/]+/certificateRevocationLists/[^/]+$",
});
}
}
}
/// <summary>
/// Activate a CertificateAuthority that is in state AWAITING_USER_ACTIVATION and is of type
/// SUBORDINATE. After the parent Certificate Authority signs a certificate signing request from
/// FetchCertificateAuthorityCsr, this method can complete the activation process.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// Required. The resource name for this CertificateAuthority in the format
/// `projects/*/locations/*/caPools/*/certificateAuthorities/*`.
/// </param>
public virtual ActivateRequest Activate(Google.Apis.CertificateAuthorityService.v1.Data.ActivateCertificateAuthorityRequest body, string name)
{
return new ActivateRequest(service, body, name);
}
/// <summary>
/// Activate a CertificateAuthority that is in state AWAITING_USER_ACTIVATION and is of type
/// SUBORDINATE. After the parent Certificate Authority signs a certificate signing request from
/// FetchCertificateAuthorityCsr, this method can complete the activation process.
/// </summary>
public class ActivateRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.Operation>
{
/// <summary>Constructs a new Activate request.</summary>
public ActivateRequest(Google.Apis.Services.IClientService service, Google.Apis.CertificateAuthorityService.v1.Data.ActivateCertificateAuthorityRequest body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The resource name for this CertificateAuthority in the format
/// `projects/*/locations/*/caPools/*/certificateAuthorities/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CertificateAuthorityService.v1.Data.ActivateCertificateAuthorityRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "activate";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}:activate";
/// <summary>Initializes Activate parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/caPools/[^/]+/certificateAuthorities/[^/]+$",
});
}
}
/// <summary>Create a new CertificateAuthority in a given Project and Location.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">
/// Required. The resource name of the CaPool associated with the CertificateAuthorities, in the
/// format `projects/*/locations/*/caPools/*`.
/// </param>
public virtual CreateRequest Create(Google.Apis.CertificateAuthorityService.v1.Data.CertificateAuthority body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>Create a new CertificateAuthority in a given Project and Location.</summary>
public class CreateRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.Operation>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.CertificateAuthorityService.v1.Data.CertificateAuthority body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The resource name of the CaPool associated with the CertificateAuthorities, in the
/// format `projects/*/locations/*/caPools/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>
/// Required. It must be unique within a location and match the regular expression
/// `[a-zA-Z0-9_-]{1,63}`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("certificateAuthorityId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string CertificateAuthorityId { get; set; }
/// <summary>
/// Optional. An ID to identify requests. Specify a unique request ID so that if you must retry
/// your request, the server will know to ignore the request if it has already been completed.
/// The server will guarantee that for at least 60 minutes since the first request. For example,
/// consider a situation where you make an initial request and t he request times out. If you
/// make the request again with the same request ID, the server can check if original operation
/// with the same request ID was received, and if so, will ignore the second request. This
/// prevents clients from accidentally creating duplicate commitments. The request ID must be a
/// valid UUID with the exception that zero UUID is not supported
/// (00000000-0000-0000-0000-000000000000).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("requestId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string RequestId { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CertificateAuthorityService.v1.Data.CertificateAuthority Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "create";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/certificateAuthorities";
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/caPools/[^/]+$",
});
RequestParameters.Add("certificateAuthorityId", new Google.Apis.Discovery.Parameter
{
Name = "certificateAuthorityId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("requestId", new Google.Apis.Discovery.Parameter
{
Name = "requestId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Delete a CertificateAuthority.</summary>
/// <param name="name">
/// Required. The resource name for this CertificateAuthority in the format
/// `projects/*/locations/*/caPools/*/certificateAuthorities/*`.
/// </param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>Delete a CertificateAuthority.</summary>
public class DeleteRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.Operation>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The resource name for this CertificateAuthority in the format
/// `projects/*/locations/*/caPools/*/certificateAuthorities/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// Optional. This field allows the CA to be deleted even if the CA has active certs. Active
/// certs include both unrevoked and unexpired certs.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("ignoreActiveCertificates", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> IgnoreActiveCertificates { get; set; }
/// <summary>
/// Optional. An ID to identify requests. Specify a unique request ID so that if you must retry
/// your request, the server will know to ignore the request if it has already been completed.
/// The server will guarantee that for at least 60 minutes since the first request. For example,
/// consider a situation where you make an initial request and t he request times out. If you
/// make the request again with the same request ID, the server can check if original operation
/// with the same request ID was received, and if so, will ignore the second request. This
/// prevents clients from accidentally creating duplicate commitments. The request ID must be a
/// valid UUID with the exception that zero UUID is not supported
/// (00000000-0000-0000-0000-000000000000).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("requestId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string RequestId { get; set; }
/// <summary>
/// Optional. If this flag is set, the Certificate Authority will be deleted as soon as possible
/// without a 30-day grace period where undeletion would have been allowed. If you proceed,
/// there will be no way to recover this CA.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("skipGracePeriod", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> SkipGracePeriod { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "delete";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "DELETE";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/caPools/[^/]+/certificateAuthorities/[^/]+$",
});
RequestParameters.Add("ignoreActiveCertificates", new Google.Apis.Discovery.Parameter
{
Name = "ignoreActiveCertificates",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("requestId", new Google.Apis.Discovery.Parameter
{
Name = "requestId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("skipGracePeriod", new Google.Apis.Discovery.Parameter
{
Name = "skipGracePeriod",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Disable a CertificateAuthority.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// Required. The resource name for this CertificateAuthority in the format
/// `projects/*/locations/*/caPools/*/certificateAuthorities/*`.
/// </param>
public virtual DisableRequest Disable(Google.Apis.CertificateAuthorityService.v1.Data.DisableCertificateAuthorityRequest body, string name)
{
return new DisableRequest(service, body, name);
}
/// <summary>Disable a CertificateAuthority.</summary>
public class DisableRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.Operation>
{
/// <summary>Constructs a new Disable request.</summary>
public DisableRequest(Google.Apis.Services.IClientService service, Google.Apis.CertificateAuthorityService.v1.Data.DisableCertificateAuthorityRequest body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The resource name for this CertificateAuthority in the format
/// `projects/*/locations/*/caPools/*/certificateAuthorities/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CertificateAuthorityService.v1.Data.DisableCertificateAuthorityRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "disable";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}:disable";
/// <summary>Initializes Disable parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/caPools/[^/]+/certificateAuthorities/[^/]+$",
});
}
}
/// <summary>Enable a CertificateAuthority.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// Required. The resource name for this CertificateAuthority in the format
/// `projects/*/locations/*/caPools/*/certificateAuthorities/*`.
/// </param>
public virtual EnableRequest Enable(Google.Apis.CertificateAuthorityService.v1.Data.EnableCertificateAuthorityRequest body, string name)
{
return new EnableRequest(service, body, name);
}
/// <summary>Enable a CertificateAuthority.</summary>
public class EnableRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.Operation>
{
/// <summary>Constructs a new Enable request.</summary>
public EnableRequest(Google.Apis.Services.IClientService service, Google.Apis.CertificateAuthorityService.v1.Data.EnableCertificateAuthorityRequest body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The resource name for this CertificateAuthority in the format
/// `projects/*/locations/*/caPools/*/certificateAuthorities/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CertificateAuthorityService.v1.Data.EnableCertificateAuthorityRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "enable";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}:enable";
/// <summary>Initializes Enable parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/caPools/[^/]+/certificateAuthorities/[^/]+$",
});
}
}
/// <summary>
/// Fetch a certificate signing request (CSR) from a CertificateAuthority that is in state
/// AWAITING_USER_ACTIVATION and is of type SUBORDINATE. The CSR must then be signed by the desired
/// parent Certificate Authority, which could be another CertificateAuthority resource, or could be
/// an on-prem certificate authority. See also ActivateCertificateAuthority.
/// </summary>
/// <param name="name">
/// Required. The resource name for this CertificateAuthority in the format
/// `projects/*/locations/*/caPools/*/certificateAuthorities/*`.
/// </param>
public virtual FetchRequest Fetch(string name)
{
return new FetchRequest(service, name);
}
/// <summary>
/// Fetch a certificate signing request (CSR) from a CertificateAuthority that is in state
/// AWAITING_USER_ACTIVATION and is of type SUBORDINATE. The CSR must then be signed by the desired
/// parent Certificate Authority, which could be another CertificateAuthority resource, or could be
/// an on-prem certificate authority. See also ActivateCertificateAuthority.
/// </summary>
public class FetchRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.FetchCertificateAuthorityCsrResponse>
{
/// <summary>Constructs a new Fetch request.</summary>
public FetchRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The resource name for this CertificateAuthority in the format
/// `projects/*/locations/*/caPools/*/certificateAuthorities/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "fetch";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}:fetch";
/// <summary>Initializes Fetch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/caPools/[^/]+/certificateAuthorities/[^/]+$",
});
}
}
/// <summary>Returns a CertificateAuthority.</summary>
/// <param name="name">Required. The name of the CertificateAuthority to get.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Returns a CertificateAuthority.</summary>
public class GetRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.CertificateAuthority>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>Required. The name of the CertificateAuthority to get.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/caPools/[^/]+/certificateAuthorities/[^/]+$",
});
}
}
/// <summary>Lists CertificateAuthorities.</summary>
/// <param name="parent">
/// Required. The resource name of the CaPool associated with the CertificateAuthorities, in the
/// format `projects/*/locations/*/caPools/*`.
/// </param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Lists CertificateAuthorities.</summary>
public class ListRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.ListCertificateAuthoritiesResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>
/// Required. The resource name of the CaPool associated with the CertificateAuthorities, in the
/// format `projects/*/locations/*/caPools/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Optional. Only include resources that match the filter in the response.</summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>Optional. Specify how the results should be sorted.</summary>
[Google.Apis.Util.RequestParameterAttribute("orderBy", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OrderBy { get; set; }
/// <summary>
/// Optional. Limit on the number of CertificateAuthorities to include in the response. Further
/// CertificateAuthorities can subsequently be obtained by including the
/// ListCertificateAuthoritiesResponse.next_page_token in a subsequent request. If unspecified,
/// the server will pick an appropriate default.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// Optional. Pagination token, returned earlier via
/// ListCertificateAuthoritiesResponse.next_page_token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/certificateAuthorities";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/caPools/[^/]+$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("orderBy", new Google.Apis.Discovery.Parameter
{
Name = "orderBy",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Update a CertificateAuthority.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// Output only. The resource name for this CertificateAuthority in the format
/// `projects/*/locations/*/caPools/*/certificateAuthorities/*`.
/// </param>
public virtual PatchRequest Patch(Google.Apis.CertificateAuthorityService.v1.Data.CertificateAuthority body, string name)
{
return new PatchRequest(service, body, name);
}
/// <summary>Update a CertificateAuthority.</summary>
public class PatchRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.Operation>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.CertificateAuthorityService.v1.Data.CertificateAuthority body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// Output only. The resource name for this CertificateAuthority in the format
/// `projects/*/locations/*/caPools/*/certificateAuthorities/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// Optional. An ID to identify requests. Specify a unique request ID so that if you must retry
/// your request, the server will know to ignore the request if it has already been completed.
/// The server will guarantee that for at least 60 minutes since the first request. For example,
/// consider a situation where you make an initial request and t he request times out. If you
/// make the request again with the same request ID, the server can check if original operation
/// with the same request ID was received, and if so, will ignore the second request. This
/// prevents clients from accidentally creating duplicate commitments. The request ID must be a
/// valid UUID with the exception that zero UUID is not supported
/// (00000000-0000-0000-0000-000000000000).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("requestId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string RequestId { get; set; }
/// <summary>Required. A list of fields to be updated in this request.</summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CertificateAuthorityService.v1.Data.CertificateAuthority Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "patch";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "PATCH";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/caPools/[^/]+/certificateAuthorities/[^/]+$",
});
RequestParameters.Add("requestId", new Google.Apis.Discovery.Parameter
{
Name = "requestId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Undelete a CertificateAuthority that has been deleted.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// Required. The resource name for this CertificateAuthority in the format
/// `projects/*/locations/*/caPools/*/certificateAuthorities/*`.
/// </param>
public virtual UndeleteRequest Undelete(Google.Apis.CertificateAuthorityService.v1.Data.UndeleteCertificateAuthorityRequest body, string name)
{
return new UndeleteRequest(service, body, name);
}
/// <summary>Undelete a CertificateAuthority that has been deleted.</summary>
public class UndeleteRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.Operation>
{
/// <summary>Constructs a new Undelete request.</summary>
public UndeleteRequest(Google.Apis.Services.IClientService service, Google.Apis.CertificateAuthorityService.v1.Data.UndeleteCertificateAuthorityRequest body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The resource name for this CertificateAuthority in the format
/// `projects/*/locations/*/caPools/*/certificateAuthorities/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CertificateAuthorityService.v1.Data.UndeleteCertificateAuthorityRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "undelete";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}:undelete";
/// <summary>Initializes Undelete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/caPools/[^/]+/certificateAuthorities/[^/]+$",
});
}
}
}
/// <summary>Gets the Certificates resource.</summary>
public virtual CertificatesResource Certificates { get; }
/// <summary>The "certificates" collection of methods.</summary>
public class CertificatesResource
{
private const string Resource = "certificates";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public CertificatesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>
/// Create a new Certificate in a given Project, Location from a particular CaPool.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">
/// Required. The resource name of the CaPool associated with the Certificate, in the format
/// `projects/*/locations/*/caPools/*`.
/// </param>
public virtual CreateRequest Create(Google.Apis.CertificateAuthorityService.v1.Data.Certificate body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>
/// Create a new Certificate in a given Project, Location from a particular CaPool.
/// </summary>
public class CreateRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.Certificate>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.CertificateAuthorityService.v1.Data.Certificate body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The resource name of the CaPool associated with the Certificate, in the format
/// `projects/*/locations/*/caPools/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>
/// Optional. It must be unique within a location and match the regular expression
/// `[a-zA-Z0-9_-]{1,63}`. This field is required when using a CertificateAuthority in the
/// Enterprise CertificateAuthority.Tier, but is optional and its value is ignored otherwise.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("certificateId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string CertificateId { get; set; }
/// <summary>
/// Optional. The resource ID of the CertificateAuthority that should issue the certificate.
/// This optional field will ignore the load-balancing scheme of the Pool and directly issue the
/// certificate from the CA with the specified ID, contained in the same CaPool referenced by
/// `parent`. Per-CA quota rules apply. If left empty, a CertificateAuthority will be chosen
/// from the CaPool by the service. For example, to issue a Certificate from a Certificate
/// Authority with resource name
/// "projects/my-project/locations/us-central1/caPools/my-pool/certificateAuthorities/my-ca",
/// you can set the parent to "projects/my-project/locations/us-central1/caPools/my-pool" and
/// the issuing_certificate_authority_id to "my-ca".
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("issuingCertificateAuthorityId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string IssuingCertificateAuthorityId { get; set; }
/// <summary>
/// Optional. An ID to identify requests. Specify a unique request ID so that if you must retry
/// your request, the server will know to ignore the request if it has already been completed.
/// The server will guarantee that for at least 60 minutes since the first request. For example,
/// consider a situation where you make an initial request and the request times out. If you
/// make the request again with the same request ID, the server can check if original operation
/// with the same request ID was received, and if so, will ignore the second request. This
/// prevents clients from accidentally creating duplicate commitments. The request ID must be a
/// valid UUID with the exception that zero UUID is not supported
/// (00000000-0000-0000-0000-000000000000).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("requestId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string RequestId { get; set; }
/// <summary>
/// Optional. If this is true, no Certificate resource will be persisted regardless of the
/// CaPool's tier, and the returned Certificate will not contain the pem_certificate field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("validateOnly", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> ValidateOnly { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CertificateAuthorityService.v1.Data.Certificate Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "create";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/certificates";
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/caPools/[^/]+$",
});
RequestParameters.Add("certificateId", new Google.Apis.Discovery.Parameter
{
Name = "certificateId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("issuingCertificateAuthorityId", new Google.Apis.Discovery.Parameter
{
Name = "issuingCertificateAuthorityId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("requestId", new Google.Apis.Discovery.Parameter
{
Name = "requestId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("validateOnly", new Google.Apis.Discovery.Parameter
{
Name = "validateOnly",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Returns a Certificate.</summary>
/// <param name="name">Required. The name of the Certificate to get.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Returns a Certificate.</summary>
public class GetRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.Certificate>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>Required. The name of the Certificate to get.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/caPools/[^/]+/certificates/[^/]+$",
});
}
}
/// <summary>Lists Certificates.</summary>
/// <param name="parent">
/// Required. The resource name of the location associated with the Certificates, in the format
/// `projects/*/locations/*/caPools/*`.
/// </param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Lists Certificates.</summary>
public class ListRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.ListCertificatesResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>
/// Required. The resource name of the location associated with the Certificates, in the format
/// `projects/*/locations/*/caPools/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>
/// Optional. Only include resources that match the filter in the response. For details on
/// supported filters and syntax, see [Certificates Filtering
/// documentation](https://cloud.google.com/certificate-authority-service/docs/sorting-filtering-certificates#filtering_support).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>
/// Optional. Specify how the results should be sorted. For details on supported fields and
/// syntax, see [Certificates Sorting
/// documentation](https://cloud.google.com/certificate-authority-service/docs/sorting-filtering-certificates#sorting_support).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("orderBy", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OrderBy { get; set; }
/// <summary>
/// Optional. Limit on the number of Certificates to include in the response. Further
/// Certificates can subsequently be obtained by including the
/// ListCertificatesResponse.next_page_token in a subsequent request. If unspecified, the server
/// will pick an appropriate default.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// Optional. Pagination token, returned earlier via ListCertificatesResponse.next_page_token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/certificates";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/caPools/[^/]+$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("orderBy", new Google.Apis.Discovery.Parameter
{
Name = "orderBy",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>
/// Update a Certificate. Currently, the only field you can update is the labels field.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// Output only. The resource name for this Certificate in the format
/// `projects/*/locations/*/caPools/*/certificates/*`.
/// </param>
public virtual PatchRequest Patch(Google.Apis.CertificateAuthorityService.v1.Data.Certificate body, string name)
{
return new PatchRequest(service, body, name);
}
/// <summary>
/// Update a Certificate. Currently, the only field you can update is the labels field.
/// </summary>
public class PatchRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.Certificate>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.CertificateAuthorityService.v1.Data.Certificate body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// Output only. The resource name for this Certificate in the format
/// `projects/*/locations/*/caPools/*/certificates/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// Optional. An ID to identify requests. Specify a unique request ID so that if you must retry
/// your request, the server will know to ignore the request if it has already been completed.
/// The server will guarantee that for at least 60 minutes since the first request. For example,
/// consider a situation where you make an initial request and t he request times out. If you
/// make the request again with the same request ID, the server can check if original operation
/// with the same request ID was received, and if so, will ignore the second request. This
/// prevents clients from accidentally creating duplicate commitments. The request ID must be a
/// valid UUID with the exception that zero UUID is not supported
/// (00000000-0000-0000-0000-000000000000).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("requestId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string RequestId { get; set; }
/// <summary>Required. A list of fields to be updated in this request.</summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CertificateAuthorityService.v1.Data.Certificate Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "patch";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "PATCH";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/caPools/[^/]+/certificates/[^/]+$",
});
RequestParameters.Add("requestId", new Google.Apis.Discovery.Parameter
{
Name = "requestId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Revoke a Certificate.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// Required. The resource name for this Certificate in the format
/// `projects/*/locations/*/caPools/*/certificates/*`.
/// </param>
public virtual RevokeRequest Revoke(Google.Apis.CertificateAuthorityService.v1.Data.RevokeCertificateRequest body, string name)
{
return new RevokeRequest(service, body, name);
}
/// <summary>Revoke a Certificate.</summary>
public class RevokeRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.Certificate>
{
/// <summary>Constructs a new Revoke request.</summary>
public RevokeRequest(Google.Apis.Services.IClientService service, Google.Apis.CertificateAuthorityService.v1.Data.RevokeCertificateRequest body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The resource name for this Certificate in the format
/// `projects/*/locations/*/caPools/*/certificates/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CertificateAuthorityService.v1.Data.RevokeCertificateRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "revoke";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}:revoke";
/// <summary>Initializes Revoke parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/caPools/[^/]+/certificates/[^/]+$",
});
}
}
}
/// <summary>Create a CaPool.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">
/// Required. The resource name of the location associated with the CaPool, in the format
/// `projects/*/locations/*`.
/// </param>
public virtual CreateRequest Create(Google.Apis.CertificateAuthorityService.v1.Data.CaPool body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>Create a CaPool.</summary>
public class CreateRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.Operation>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.CertificateAuthorityService.v1.Data.CaPool body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The resource name of the location associated with the CaPool, in the format
/// `projects/*/locations/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>
/// Required. It must be unique within a location and match the regular expression
/// `[a-zA-Z0-9_-]{1,63}`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("caPoolId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string CaPoolId { get; set; }
/// <summary>
/// Optional. An ID to identify requests. Specify a unique request ID so that if you must retry your
/// request, the server will know to ignore the request if it has already been completed. The server
/// will guarantee that for at least 60 minutes since the first request. For example, consider a
/// situation where you make an initial request and t he request times out. If you make the request
/// again with the same request ID, the server can check if original operation with the same request
/// ID was received, and if so, will ignore the second request. This prevents clients from
/// accidentally creating duplicate commitments. The request ID must be a valid UUID with the
/// exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("requestId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string RequestId { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CertificateAuthorityService.v1.Data.CaPool Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "create";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/caPools";
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+$",
});
RequestParameters.Add("caPoolId", new Google.Apis.Discovery.Parameter
{
Name = "caPoolId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("requestId", new Google.Apis.Discovery.Parameter
{
Name = "requestId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Delete a CaPool.</summary>
/// <param name="name">
/// Required. The resource name for this CaPool in the format `projects/*/locations/*/caPools/*`.
/// </param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>Delete a CaPool.</summary>
public class DeleteRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.Operation>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The resource name for this CaPool in the format `projects/*/locations/*/caPools/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// Optional. An ID to identify requests. Specify a unique request ID so that if you must retry your
/// request, the server will know to ignore the request if it has already been completed. The server
/// will guarantee that for at least 60 minutes since the first request. For example, consider a
/// situation where you make an initial request and t he request times out. If you make the request
/// again with the same request ID, the server can check if original operation with the same request
/// ID was received, and if so, will ignore the second request. This prevents clients from
/// accidentally creating duplicate commitments. The request ID must be a valid UUID with the
/// exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("requestId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string RequestId { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "delete";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "DELETE";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/caPools/[^/]+$",
});
RequestParameters.Add("requestId", new Google.Apis.Discovery.Parameter
{
Name = "requestId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>
/// FetchCaCerts returns the current trust anchor for the CaPool. This will include CA certificate
/// chains for all ACTIVE CertificateAuthority resources in the CaPool.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="caPool">
/// Required. The resource name for the CaPool in the format `projects/*/locations/*/caPools/*`.
/// </param>
public virtual FetchCaCertsRequest FetchCaCerts(Google.Apis.CertificateAuthorityService.v1.Data.FetchCaCertsRequest body, string caPool)
{
return new FetchCaCertsRequest(service, body, caPool);
}
/// <summary>
/// FetchCaCerts returns the current trust anchor for the CaPool. This will include CA certificate
/// chains for all ACTIVE CertificateAuthority resources in the CaPool.
/// </summary>
public class FetchCaCertsRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.FetchCaCertsResponse>
{
/// <summary>Constructs a new FetchCaCerts request.</summary>
public FetchCaCertsRequest(Google.Apis.Services.IClientService service, Google.Apis.CertificateAuthorityService.v1.Data.FetchCaCertsRequest body, string caPool) : base(service)
{
CaPool = caPool;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The resource name for the CaPool in the format `projects/*/locations/*/caPools/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("caPool", Google.Apis.Util.RequestParameterType.Path)]
public virtual string CaPool { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CertificateAuthorityService.v1.Data.FetchCaCertsRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "fetchCaCerts";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+caPool}:fetchCaCerts";
/// <summary>Initializes FetchCaCerts parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("caPool", new Google.Apis.Discovery.Parameter
{
Name = "caPool",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/caPools/[^/]+$",
});
}
}
/// <summary>Returns a CaPool.</summary>
/// <param name="name">Required. The name of the CaPool to get.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Returns a CaPool.</summary>
public class GetRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.CaPool>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>Required. The name of the CaPool to get.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/caPools/[^/]+$",
});
}
}
/// <summary>
/// Gets the access control policy for a resource. Returns an empty policy if the resource exists and
/// does not have a policy set.
/// </summary>
/// <param name="resource">
/// REQUIRED: The resource for which the policy is being requested. See the operation documentation for
/// the appropriate value for this field.
/// </param>
public virtual GetIamPolicyRequest GetIamPolicy(string resource)
{
return new GetIamPolicyRequest(service, resource);
}
/// <summary>
/// Gets the access control policy for a resource. Returns an empty policy if the resource exists and
/// does not have a policy set.
/// </summary>
public class GetIamPolicyRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.Policy>
{
/// <summary>Constructs a new GetIamPolicy request.</summary>
public GetIamPolicyRequest(Google.Apis.Services.IClientService service, string resource) : base(service)
{
Resource = resource;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy is being requested. See the operation documentation
/// for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>
/// Optional. The maximum policy version that will be used to format the policy. Valid values are 0,
/// 1, and 3. Requests specifying an invalid value will be rejected. Requests for policies with any
/// conditional role bindings must specify version 3. Policies with no conditional role bindings may
/// specify any valid value or leave the field unset. The policy in the response might use the
/// policy version that you specified, or it might use a lower policy version. For example, if you
/// specify version 3, but the policy has no conditional role bindings, the response uses version 1.
/// To learn which resources support conditions in their IAM policies, see the [IAM
/// documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("options.requestedPolicyVersion", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> OptionsRequestedPolicyVersion { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "getIamPolicy";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+resource}:getIamPolicy";
/// <summary>Initializes GetIamPolicy parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/caPools/[^/]+$",
});
RequestParameters.Add("options.requestedPolicyVersion", new Google.Apis.Discovery.Parameter
{
Name = "options.requestedPolicyVersion",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Lists CaPools.</summary>
/// <param name="parent">
/// Required. The resource name of the location associated with the CaPools, in the format
/// `projects/*/locations/*`.
/// </param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Lists CaPools.</summary>
public class ListRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.ListCaPoolsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>
/// Required. The resource name of the location associated with the CaPools, in the format
/// `projects/*/locations/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Optional. Only include resources that match the filter in the response.</summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>Optional. Specify how the results should be sorted.</summary>
[Google.Apis.Util.RequestParameterAttribute("orderBy", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OrderBy { get; set; }
/// <summary>
/// Optional. Limit on the number of CaPools to include in the response. Further CaPools can
/// subsequently be obtained by including the ListCaPoolsResponse.next_page_token in a subsequent
/// request. If unspecified, the server will pick an appropriate default.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// Optional. Pagination token, returned earlier via ListCaPoolsResponse.next_page_token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/caPools";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("orderBy", new Google.Apis.Discovery.Parameter
{
Name = "orderBy",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Update a CaPool.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// Output only. The resource name for this CaPool in the format `projects/*/locations/*/caPools/*`.
/// </param>
public virtual PatchRequest Patch(Google.Apis.CertificateAuthorityService.v1.Data.CaPool body, string name)
{
return new PatchRequest(service, body, name);
}
/// <summary>Update a CaPool.</summary>
public class PatchRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.Operation>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.CertificateAuthorityService.v1.Data.CaPool body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// Output only. The resource name for this CaPool in the format `projects/*/locations/*/caPools/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// Optional. An ID to identify requests. Specify a unique request ID so that if you must retry your
/// request, the server will know to ignore the request if it has already been completed. The server
/// will guarantee that for at least 60 minutes since the first request. For example, consider a
/// situation where you make an initial request and t he request times out. If you make the request
/// again with the same request ID, the server can check if original operation with the same request
/// ID was received, and if so, will ignore the second request. This prevents clients from
/// accidentally creating duplicate commitments. The request ID must be a valid UUID with the
/// exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("requestId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string RequestId { get; set; }
/// <summary>Required. A list of fields to be updated in this request.</summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CertificateAuthorityService.v1.Data.CaPool Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "patch";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "PATCH";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/caPools/[^/]+$",
});
RequestParameters.Add("requestId", new Google.Apis.Discovery.Parameter
{
Name = "requestId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any existing policy. Can return
/// `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="resource">
/// REQUIRED: The resource for which the policy is being specified. See the operation documentation for
/// the appropriate value for this field.
/// </param>
public virtual SetIamPolicyRequest SetIamPolicy(Google.Apis.CertificateAuthorityService.v1.Data.SetIamPolicyRequest body, string resource)
{
return new SetIamPolicyRequest(service, body, resource);
}
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any existing policy. Can return
/// `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors.
/// </summary>
public class SetIamPolicyRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.Policy>
{
/// <summary>Constructs a new SetIamPolicy request.</summary>
public SetIamPolicyRequest(Google.Apis.Services.IClientService service, Google.Apis.CertificateAuthorityService.v1.Data.SetIamPolicyRequest body, string resource) : base(service)
{
Resource = resource;
Body = body;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy is being specified. See the operation documentation
/// for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CertificateAuthorityService.v1.Data.SetIamPolicyRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "setIamPolicy";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+resource}:setIamPolicy";
/// <summary>Initializes SetIamPolicy parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/caPools/[^/]+$",
});
}
}
/// <summary>
/// Returns permissions that a caller has on the specified resource. If the resource does not exist,
/// this will return an empty set of permissions, not a `NOT_FOUND` error. Note: This operation is
/// designed to be used for building permission-aware UIs and command-line tools, not for authorization
/// checking. This operation may "fail open" without warning.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="resource">
/// REQUIRED: The resource for which the policy detail is being requested. See the operation
/// documentation for the appropriate value for this field.
/// </param>
public virtual TestIamPermissionsRequest TestIamPermissions(Google.Apis.CertificateAuthorityService.v1.Data.TestIamPermissionsRequest body, string resource)
{
return new TestIamPermissionsRequest(service, body, resource);
}
/// <summary>
/// Returns permissions that a caller has on the specified resource. If the resource does not exist,
/// this will return an empty set of permissions, not a `NOT_FOUND` error. Note: This operation is
/// designed to be used for building permission-aware UIs and command-line tools, not for authorization
/// checking. This operation may "fail open" without warning.
/// </summary>
public class TestIamPermissionsRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.TestIamPermissionsResponse>
{
/// <summary>Constructs a new TestIamPermissions request.</summary>
public TestIamPermissionsRequest(Google.Apis.Services.IClientService service, Google.Apis.CertificateAuthorityService.v1.Data.TestIamPermissionsRequest body, string resource) : base(service)
{
Resource = resource;
Body = body;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy detail is being requested. See the operation
/// documentation for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CertificateAuthorityService.v1.Data.TestIamPermissionsRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "testIamPermissions";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+resource}:testIamPermissions";
/// <summary>Initializes TestIamPermissions parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/caPools/[^/]+$",
});
}
}
}
/// <summary>Gets the CertificateTemplates resource.</summary>
public virtual CertificateTemplatesResource CertificateTemplates { get; }
/// <summary>The "certificateTemplates" collection of methods.</summary>
public class CertificateTemplatesResource
{
private const string Resource = "certificateTemplates";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public CertificateTemplatesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Create a new CertificateTemplate in a given Project and Location.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">
/// Required. The resource name of the location associated with the CertificateTemplate, in the format
/// `projects/*/locations/*`.
/// </param>
public virtual CreateRequest Create(Google.Apis.CertificateAuthorityService.v1.Data.CertificateTemplate body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>Create a new CertificateTemplate in a given Project and Location.</summary>
public class CreateRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.Operation>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.CertificateAuthorityService.v1.Data.CertificateTemplate body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The resource name of the location associated with the CertificateTemplate, in the
/// format `projects/*/locations/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>
/// Required. It must be unique within a location and match the regular expression
/// `[a-zA-Z0-9_-]{1,63}`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("certificateTemplateId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string CertificateTemplateId { get; set; }
/// <summary>
/// Optional. An ID to identify requests. Specify a unique request ID so that if you must retry your
/// request, the server will know to ignore the request if it has already been completed. The server
/// will guarantee that for at least 60 minutes since the first request. For example, consider a
/// situation where you make an initial request and t he request times out. If you make the request
/// again with the same request ID, the server can check if original operation with the same request
/// ID was received, and if so, will ignore the second request. This prevents clients from
/// accidentally creating duplicate commitments. The request ID must be a valid UUID with the
/// exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("requestId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string RequestId { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CertificateAuthorityService.v1.Data.CertificateTemplate Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "create";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/certificateTemplates";
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+$",
});
RequestParameters.Add("certificateTemplateId", new Google.Apis.Discovery.Parameter
{
Name = "certificateTemplateId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("requestId", new Google.Apis.Discovery.Parameter
{
Name = "requestId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>DeleteCertificateTemplate deletes a CertificateTemplate.</summary>
/// <param name="name">
/// Required. The resource name for this CertificateTemplate in the format
/// `projects/*/locations/*/certificateTemplates/*`.
/// </param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>DeleteCertificateTemplate deletes a CertificateTemplate.</summary>
public class DeleteRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.Operation>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The resource name for this CertificateTemplate in the format
/// `projects/*/locations/*/certificateTemplates/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// Optional. An ID to identify requests. Specify a unique request ID so that if you must retry your
/// request, the server will know to ignore the request if it has already been completed. The server
/// will guarantee that for at least 60 minutes since the first request. For example, consider a
/// situation where you make an initial request and t he request times out. If you make the request
/// again with the same request ID, the server can check if original operation with the same request
/// ID was received, and if so, will ignore the second request. This prevents clients from
/// accidentally creating duplicate commitments. The request ID must be a valid UUID with the
/// exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("requestId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string RequestId { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "delete";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "DELETE";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/certificateTemplates/[^/]+$",
});
RequestParameters.Add("requestId", new Google.Apis.Discovery.Parameter
{
Name = "requestId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Returns a CertificateTemplate.</summary>
/// <param name="name">Required. The name of the CertificateTemplate to get.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Returns a CertificateTemplate.</summary>
public class GetRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.CertificateTemplate>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>Required. The name of the CertificateTemplate to get.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/certificateTemplates/[^/]+$",
});
}
}
/// <summary>
/// Gets the access control policy for a resource. Returns an empty policy if the resource exists and
/// does not have a policy set.
/// </summary>
/// <param name="resource">
/// REQUIRED: The resource for which the policy is being requested. See the operation documentation for
/// the appropriate value for this field.
/// </param>
public virtual GetIamPolicyRequest GetIamPolicy(string resource)
{
return new GetIamPolicyRequest(service, resource);
}
/// <summary>
/// Gets the access control policy for a resource. Returns an empty policy if the resource exists and
/// does not have a policy set.
/// </summary>
public class GetIamPolicyRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.Policy>
{
/// <summary>Constructs a new GetIamPolicy request.</summary>
public GetIamPolicyRequest(Google.Apis.Services.IClientService service, string resource) : base(service)
{
Resource = resource;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy is being requested. See the operation documentation
/// for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>
/// Optional. The maximum policy version that will be used to format the policy. Valid values are 0,
/// 1, and 3. Requests specifying an invalid value will be rejected. Requests for policies with any
/// conditional role bindings must specify version 3. Policies with no conditional role bindings may
/// specify any valid value or leave the field unset. The policy in the response might use the
/// policy version that you specified, or it might use a lower policy version. For example, if you
/// specify version 3, but the policy has no conditional role bindings, the response uses version 1.
/// To learn which resources support conditions in their IAM policies, see the [IAM
/// documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("options.requestedPolicyVersion", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> OptionsRequestedPolicyVersion { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "getIamPolicy";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+resource}:getIamPolicy";
/// <summary>Initializes GetIamPolicy parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/certificateTemplates/[^/]+$",
});
RequestParameters.Add("options.requestedPolicyVersion", new Google.Apis.Discovery.Parameter
{
Name = "options.requestedPolicyVersion",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Lists CertificateTemplates.</summary>
/// <param name="parent">
/// Required. The resource name of the location associated with the CertificateTemplates, in the format
/// `projects/*/locations/*`.
/// </param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Lists CertificateTemplates.</summary>
public class ListRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.ListCertificateTemplatesResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>
/// Required. The resource name of the location associated with the CertificateTemplates, in the
/// format `projects/*/locations/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Optional. Only include resources that match the filter in the response.</summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>Optional. Specify how the results should be sorted.</summary>
[Google.Apis.Util.RequestParameterAttribute("orderBy", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OrderBy { get; set; }
/// <summary>
/// Optional. Limit on the number of CertificateTemplates to include in the response. Further
/// CertificateTemplates can subsequently be obtained by including the
/// ListCertificateTemplatesResponse.next_page_token in a subsequent request. If unspecified, the
/// server will pick an appropriate default.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// Optional. Pagination token, returned earlier via
/// ListCertificateTemplatesResponse.next_page_token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/certificateTemplates";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("orderBy", new Google.Apis.Discovery.Parameter
{
Name = "orderBy",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Update a CertificateTemplate.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// Output only. The resource name for this CertificateTemplate in the format
/// `projects/*/locations/*/certificateTemplates/*`.
/// </param>
public virtual PatchRequest Patch(Google.Apis.CertificateAuthorityService.v1.Data.CertificateTemplate body, string name)
{
return new PatchRequest(service, body, name);
}
/// <summary>Update a CertificateTemplate.</summary>
public class PatchRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.Operation>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.CertificateAuthorityService.v1.Data.CertificateTemplate body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// Output only. The resource name for this CertificateTemplate in the format
/// `projects/*/locations/*/certificateTemplates/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// Optional. An ID to identify requests. Specify a unique request ID so that if you must retry your
/// request, the server will know to ignore the request if it has already been completed. The server
/// will guarantee that for at least 60 minutes since the first request. For example, consider a
/// situation where you make an initial request and t he request times out. If you make the request
/// again with the same request ID, the server can check if original operation with the same request
/// ID was received, and if so, will ignore the second request. This prevents clients from
/// accidentally creating duplicate commitments. The request ID must be a valid UUID with the
/// exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("requestId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string RequestId { get; set; }
/// <summary>Required. A list of fields to be updated in this request.</summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CertificateAuthorityService.v1.Data.CertificateTemplate Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "patch";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "PATCH";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/certificateTemplates/[^/]+$",
});
RequestParameters.Add("requestId", new Google.Apis.Discovery.Parameter
{
Name = "requestId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any existing policy. Can return
/// `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="resource">
/// REQUIRED: The resource for which the policy is being specified. See the operation documentation for
/// the appropriate value for this field.
/// </param>
public virtual SetIamPolicyRequest SetIamPolicy(Google.Apis.CertificateAuthorityService.v1.Data.SetIamPolicyRequest body, string resource)
{
return new SetIamPolicyRequest(service, body, resource);
}
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any existing policy. Can return
/// `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors.
/// </summary>
public class SetIamPolicyRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.Policy>
{
/// <summary>Constructs a new SetIamPolicy request.</summary>
public SetIamPolicyRequest(Google.Apis.Services.IClientService service, Google.Apis.CertificateAuthorityService.v1.Data.SetIamPolicyRequest body, string resource) : base(service)
{
Resource = resource;
Body = body;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy is being specified. See the operation documentation
/// for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CertificateAuthorityService.v1.Data.SetIamPolicyRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "setIamPolicy";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+resource}:setIamPolicy";
/// <summary>Initializes SetIamPolicy parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/certificateTemplates/[^/]+$",
});
}
}
/// <summary>
/// Returns permissions that a caller has on the specified resource. If the resource does not exist,
/// this will return an empty set of permissions, not a `NOT_FOUND` error. Note: This operation is
/// designed to be used for building permission-aware UIs and command-line tools, not for authorization
/// checking. This operation may "fail open" without warning.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="resource">
/// REQUIRED: The resource for which the policy detail is being requested. See the operation
/// documentation for the appropriate value for this field.
/// </param>
public virtual TestIamPermissionsRequest TestIamPermissions(Google.Apis.CertificateAuthorityService.v1.Data.TestIamPermissionsRequest body, string resource)
{
return new TestIamPermissionsRequest(service, body, resource);
}
/// <summary>
/// Returns permissions that a caller has on the specified resource. If the resource does not exist,
/// this will return an empty set of permissions, not a `NOT_FOUND` error. Note: This operation is
/// designed to be used for building permission-aware UIs and command-line tools, not for authorization
/// checking. This operation may "fail open" without warning.
/// </summary>
public class TestIamPermissionsRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.TestIamPermissionsResponse>
{
/// <summary>Constructs a new TestIamPermissions request.</summary>
public TestIamPermissionsRequest(Google.Apis.Services.IClientService service, Google.Apis.CertificateAuthorityService.v1.Data.TestIamPermissionsRequest body, string resource) : base(service)
{
Resource = resource;
Body = body;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy detail is being requested. See the operation
/// documentation for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CertificateAuthorityService.v1.Data.TestIamPermissionsRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "testIamPermissions";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+resource}:testIamPermissions";
/// <summary>Initializes TestIamPermissions parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/certificateTemplates/[^/]+$",
});
}
}
}
/// <summary>Gets the Operations resource.</summary>
public virtual OperationsResource Operations { get; }
/// <summary>The "operations" collection of methods.</summary>
public class OperationsResource
{
private const string Resource = "operations";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public OperationsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>
/// Starts asynchronous cancellation on a long-running operation. The server makes a best effort to
/// cancel the operation, but success is not guaranteed. If the server doesn't support this method, it
/// returns `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to
/// check whether the cancellation succeeded or whether the operation completed despite cancellation. On
/// successful cancellation, the operation is not deleted; instead, it becomes an operation with an
/// Operation.error value with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">The name of the operation resource to be cancelled.</param>
public virtual CancelRequest Cancel(Google.Apis.CertificateAuthorityService.v1.Data.CancelOperationRequest body, string name)
{
return new CancelRequest(service, body, name);
}
/// <summary>
/// Starts asynchronous cancellation on a long-running operation. The server makes a best effort to
/// cancel the operation, but success is not guaranteed. If the server doesn't support this method, it
/// returns `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to
/// check whether the cancellation succeeded or whether the operation completed despite cancellation. On
/// successful cancellation, the operation is not deleted; instead, it becomes an operation with an
/// Operation.error value with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.
/// </summary>
public class CancelRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.Empty>
{
/// <summary>Constructs a new Cancel request.</summary>
public CancelRequest(Google.Apis.Services.IClientService service, Google.Apis.CertificateAuthorityService.v1.Data.CancelOperationRequest body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>The name of the operation resource to be cancelled.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CertificateAuthorityService.v1.Data.CancelOperationRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "cancel";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}:cancel";
/// <summary>Initializes Cancel parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/operations/[^/]+$",
});
}
}
/// <summary>
/// Deletes a long-running operation. This method indicates that the client is no longer interested in
/// the operation result. It does not cancel the operation. If the server doesn't support this method,
/// it returns `google.rpc.Code.UNIMPLEMENTED`.
/// </summary>
/// <param name="name">The name of the operation resource to be deleted.</param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>
/// Deletes a long-running operation. This method indicates that the client is no longer interested in
/// the operation result. It does not cancel the operation. If the server doesn't support this method,
/// it returns `google.rpc.Code.UNIMPLEMENTED`.
/// </summary>
public class DeleteRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.Empty>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the operation resource to be deleted.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "delete";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "DELETE";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/operations/[^/]+$",
});
}
}
/// <summary>
/// Gets the latest state of a long-running operation. Clients can use this method to poll the operation
/// result at intervals as recommended by the API service.
/// </summary>
/// <param name="name">The name of the operation resource.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>
/// Gets the latest state of a long-running operation. Clients can use this method to poll the operation
/// result at intervals as recommended by the API service.
/// </summary>
public class GetRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.Operation>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the operation resource.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/operations/[^/]+$",
});
}
}
/// <summary>
/// Lists operations that match the specified filter in the request. If the server doesn't support this
/// method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to override the
/// binding to use different resource name schemes, such as `users/*/operations`. To override the
/// binding, API services can add a binding such as `"/v1/{name=users/*}/operations"` to their service
/// configuration. For backwards compatibility, the default name includes the operations collection id,
/// however overriding users must ensure the name binding is the parent resource, without the operations
/// collection id.
/// </summary>
/// <param name="name">The name of the operation's parent resource.</param>
public virtual ListRequest List(string name)
{
return new ListRequest(service, name);
}
/// <summary>
/// Lists operations that match the specified filter in the request. If the server doesn't support this
/// method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to override the
/// binding to use different resource name schemes, such as `users/*/operations`. To override the
/// binding, API services can add a binding such as `"/v1/{name=users/*}/operations"` to their service
/// configuration. For backwards compatibility, the default name includes the operations collection id,
/// however overriding users must ensure the name binding is the parent resource, without the operations
/// collection id.
/// </summary>
public class ListRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.ListOperationsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the operation's parent resource.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>The standard list filter.</summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>The standard list page size.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>The standard list page token.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}/operations";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>Gets information about a location.</summary>
/// <param name="name">Resource name for the location.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets information about a location.</summary>
public class GetRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.Location>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>Resource name for the location.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+$",
});
}
}
/// <summary>Lists information about the supported locations for this service.</summary>
/// <param name="name">The resource that owns the locations collection, if applicable.</param>
public virtual ListRequest List(string name)
{
return new ListRequest(service, name);
}
/// <summary>Lists information about the supported locations for this service.</summary>
public class ListRequest : CertificateAuthorityServiceBaseServiceRequest<Google.Apis.CertificateAuthorityService.v1.Data.ListLocationsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>The resource that owns the locations collection, if applicable.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// A filter to narrow down results to a preferred subset. The filtering language accepts strings like
/// `"displayName=tokyo"`, and is documented in more detail in [AIP-160](https://google.aip.dev/160).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>
/// The maximum number of results to return. If not set, the service selects a default.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// A page token received from the `next_page_token` field in the response. Send that page token to
/// receive the subsequent page.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}/locations";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
}
namespace Google.Apis.CertificateAuthorityService.v1.Data
{
/// <summary>URLs where a CertificateAuthority will publish content.</summary>
public class AccessUrls : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The URL where this CertificateAuthority's CA certificate is published. This will only be set for CAs that
/// have been activated.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("caCertificateAccessUrl")]
public virtual string CaCertificateAccessUrl { get; set; }
/// <summary>
/// The URLs where this CertificateAuthority's CRLs are published. This will only be set for CAs that have been
/// activated.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("crlAccessUrls")]
public virtual System.Collections.Generic.IList<string> CrlAccessUrls { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request message for CertificateAuthorityService.ActivateCertificateAuthority.</summary>
public class ActivateCertificateAuthorityRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Required. The signed CA certificate issued from FetchCertificateAuthorityCsrResponse.pem_csr.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("pemCaCertificate")]
public virtual string PemCaCertificate { get; set; }
/// <summary>
/// Optional. An ID to identify requests. Specify a unique request ID so that if you must retry your request,
/// the server will know to ignore the request if it has already been completed. The server will guarantee that
/// for at least 60 minutes since the first request. For example, consider a situation where you make an initial
/// request and t he request times out. If you make the request again with the same request ID, the server can
/// check if original operation with the same request ID was received, and if so, will ignore the second
/// request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a
/// valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("requestId")]
public virtual string RequestId { get; set; }
/// <summary>
/// Required. Must include information about the issuer of 'pem_ca_certificate', and any further issuers until
/// the self-signed CA.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("subordinateConfig")]
public virtual SubordinateConfig SubordinateConfig { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Describes a "type" of key that may be used in a Certificate issued from a CaPool. Note that a single
/// AllowedKeyType may refer to either a fully-qualified key algorithm, such as RSA 4096, or a family of key
/// algorithms, such as any RSA key.
/// </summary>
public class AllowedKeyType : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Represents an allowed Elliptic Curve key type.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("ellipticCurve")]
public virtual EcKeyType EllipticCurve { get; set; }
/// <summary>Represents an allowed RSA key type.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("rsa")]
public virtual RsaKeyType Rsa { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Specifies the audit configuration for a service. The configuration determines which permission types are logged,
/// and what identities, if any, are exempted from logging. An AuditConfig must have one or more AuditLogConfigs. If
/// there are AuditConfigs for both `allServices` and a specific service, the union of the two AuditConfigs is used
/// for that service: the log_types specified in each AuditConfig are enabled, and the exempted_members in each
/// AuditLogConfig are exempted. Example Policy with multiple AuditConfigs: { "audit_configs": [ { "service":
/// "allServices", "audit_log_configs": [ { "log_type": "DATA_READ", "exempted_members": [ "user:jose@example.com" ]
/// }, { "log_type": "DATA_WRITE" }, { "log_type": "ADMIN_READ" } ] }, { "service": "sampleservice.googleapis.com",
/// "audit_log_configs": [ { "log_type": "DATA_READ" }, { "log_type": "DATA_WRITE", "exempted_members": [
/// "user:aliya@example.com" ] } ] } ] } For sampleservice, this policy enables DATA_READ, DATA_WRITE and ADMIN_READ
/// logging. It also exempts jose@example.com from DATA_READ logging, and aliya@example.com from DATA_WRITE logging.
/// </summary>
public class AuditConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The configuration for logging of each type of permission.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("auditLogConfigs")]
public virtual System.Collections.Generic.IList<AuditLogConfig> AuditLogConfigs { get; set; }
/// <summary>
/// Specifies a service that will be enabled for audit logging. For example, `storage.googleapis.com`,
/// `cloudsql.googleapis.com`. `allServices` is a special value that covers all services.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("service")]
public virtual string Service { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Provides the configuration for logging a type of permissions. Example: { "audit_log_configs": [ { "log_type":
/// "DATA_READ", "exempted_members": [ "user:jose@example.com" ] }, { "log_type": "DATA_WRITE" } ] } This enables
/// 'DATA_READ' and 'DATA_WRITE' logging, while exempting jose@example.com from DATA_READ logging.
/// </summary>
public class AuditLogConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Specifies the identities that do not cause logging for this type of permission. Follows the same format of
/// Binding.members.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("exemptedMembers")]
public virtual System.Collections.Generic.IList<string> ExemptedMembers { get; set; }
/// <summary>The log type that this config enables.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("logType")]
public virtual string LogType { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Associates `members`, or principals, with a `role`.</summary>
public class Binding : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The condition that is associated with this binding. If the condition evaluates to `true`, then this binding
/// applies to the current request. If the condition evaluates to `false`, then this binding does not apply to
/// the current request. However, a different role binding might grant the same role to one or more of the
/// principals in this binding. To learn which resources support conditions in their IAM policies, see the [IAM
/// documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("condition")]
public virtual Expr Condition { get; set; }
/// <summary>
/// Specifies the principals requesting access for a Google Cloud resource. `members` can have the following
/// values: * `allUsers`: A special identifier that represents anyone who is on the internet; with or without a
/// Google account. * `allAuthenticatedUsers`: A special identifier that represents anyone who is authenticated
/// with a Google account or a service account. * `user:{emailid}`: An email address that represents a specific
/// Google account. For example, `alice@example.com` . * `serviceAccount:{emailid}`: An email address that
/// represents a service account. For example, `my-other-app@appspot.gserviceaccount.com`. * `group:{emailid}`:
/// An email address that represents a Google group. For example, `admins@example.com`. *
/// `deleted:user:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a user that
/// has been recently deleted. For example, `alice@example.com?uid=123456789012345678901`. If the user is
/// recovered, this value reverts to `user:{emailid}` and the recovered user retains the role in the binding. *
/// `deleted:serviceAccount:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a
/// service account that has been recently deleted. For example,
/// `my-other-app@appspot.gserviceaccount.com?uid=123456789012345678901`. If the service account is undeleted,
/// this value reverts to `serviceAccount:{emailid}` and the undeleted service account retains the role in the
/// binding. * `deleted:group:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing
/// a Google group that has been recently deleted. For example, `admins@example.com?uid=123456789012345678901`.
/// If the group is recovered, this value reverts to `group:{emailid}` and the recovered group retains the role
/// in the binding. * `domain:{domain}`: The G Suite domain (primary) that represents all the users of that
/// domain. For example, `google.com` or `example.com`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("members")]
public virtual System.Collections.Generic.IList<string> Members { get; set; }
/// <summary>
/// Role that is assigned to the list of `members`, or principals. For example, `roles/viewer`, `roles/editor`,
/// or `roles/owner`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("role")]
public virtual string Role { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Describes values that are relevant in a CA certificate.</summary>
public class CaOptions : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Optional. Refers to the "CA" X.509 extension, which is a boolean value. When this value is missing, the
/// extension will be omitted from the CA certificate.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("isCa")]
public virtual System.Nullable<bool> IsCa { get; set; }
/// <summary>
/// Optional. Refers to the path length restriction X.509 extension. For a CA certificate, this value describes
/// the depth of subordinate CA certificates that are allowed. If this value is less than 0, the request will
/// fail. If this value is missing, the max path length will be omitted from the CA certificate.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("maxIssuerPathLength")]
public virtual System.Nullable<int> MaxIssuerPathLength { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// A CaPool represents a group of CertificateAuthorities that form a trust anchor. A CaPool can be used to manage
/// issuance policies for one or more CertificateAuthority resources and to rotate CA certificates in and out of the
/// trust anchor.
/// </summary>
public class CaPool : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. The IssuancePolicy to control how Certificates will be issued from this CaPool.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("issuancePolicy")]
public virtual IssuancePolicy IssuancePolicy { get; set; }
/// <summary>Optional. Labels with user-defined metadata.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("labels")]
public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; }
/// <summary>
/// Output only. The resource name for this CaPool in the format `projects/*/locations/*/caPools/*`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>
/// Optional. The PublishingOptions to follow when issuing Certificates from any CertificateAuthority in this
/// CaPool.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("publishingOptions")]
public virtual PublishingOptions PublishingOptions { get; set; }
/// <summary>Required. Immutable. The Tier of this CaPool.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("tier")]
public virtual string Tier { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The request message for Operations.CancelOperation.</summary>
public class CancelOperationRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
public class CertChain : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The certificates that form the CA chain, from leaf to root order.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("certificates")]
public virtual System.Collections.Generic.IList<string> Certificates { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A Certificate corresponds to a signed X.509 certificate issued by a CertificateAuthority.</summary>
public class Certificate : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. A structured description of the issued X.509 certificate.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("certificateDescription")]
public virtual CertificateDescription CertificateDescription { get; set; }
/// <summary>
/// Immutable. The resource name for a CertificateTemplate used to issue this certificate, in the format
/// `projects/*/locations/*/certificateTemplates/*`. If this is specified, the caller must have the necessary
/// permission to use this template. If this is omitted, no template will be used. This template must be in the
/// same location as the Certificate.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("certificateTemplate")]
public virtual string CertificateTemplate { get; set; }
/// <summary>Immutable. A description of the certificate and key that does not require X.509 or ASN.1.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("config")]
public virtual CertificateConfig Config { get; set; }
/// <summary>Output only. The time at which this Certificate was created.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("createTime")]
public virtual object CreateTime { get; set; }
/// <summary>
/// Output only. The resource name of the issuing CertificateAuthority in the format
/// `projects/*/locations/*/caPools/*/certificateAuthorities/*`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("issuerCertificateAuthority")]
public virtual string IssuerCertificateAuthority { get; set; }
/// <summary>Optional. Labels with user-defined metadata.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("labels")]
public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; }
/// <summary>
/// Required. Immutable. The desired lifetime of a certificate. Used to create the "not_before_time" and
/// "not_after_time" fields inside an X.509 certificate. Note that the lifetime may be truncated if it would
/// extend past the life of any certificate authority in the issuing chain.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("lifetime")]
public virtual object Lifetime { get; set; }
/// <summary>
/// Output only. The resource name for this Certificate in the format
/// `projects/*/locations/*/caPools/*/certificates/*`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Output only. The pem-encoded, signed X.509 certificate.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("pemCertificate")]
public virtual string PemCertificate { get; set; }
/// <summary>
/// Output only. The chain that may be used to verify the X.509 certificate. Expected to be in issuer-to-root
/// order according to RFC 5246.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("pemCertificateChain")]
public virtual System.Collections.Generic.IList<string> PemCertificateChain { get; set; }
/// <summary>Immutable. A pem-encoded X.509 certificate signing request (CSR).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("pemCsr")]
public virtual string PemCsr { get; set; }
/// <summary>
/// Output only. Details regarding the revocation of this Certificate. This Certificate is considered revoked if
/// and only if this field is present.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("revocationDetails")]
public virtual RevocationDetails RevocationDetails { get; set; }
/// <summary>
/// Immutable. Specifies how the Certificate's identity fields are to be decided. If this is omitted, the
/// `DEFAULT` subject mode will be used.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("subjectMode")]
public virtual string SubjectMode { get; set; }
/// <summary>Output only. The time at which this Certificate was updated.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateTime")]
public virtual object UpdateTime { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// A CertificateAuthority represents an individual Certificate Authority. A CertificateAuthority can be used to
/// create Certificates.
/// </summary>
public class CertificateAuthority : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Output only. URLs for accessing content published by this CA, such as the CA certificate and CRLs.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("accessUrls")]
public virtual AccessUrls AccessUrls { get; set; }
/// <summary>
/// Output only. A structured description of this CertificateAuthority's CA certificate and its issuers. Ordered
/// as self-to-root.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("caCertificateDescriptions")]
public virtual System.Collections.Generic.IList<CertificateDescription> CaCertificateDescriptions { get; set; }
/// <summary>Required. Immutable. The config used to create a self-signed X.509 certificate or CSR.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("config")]
public virtual CertificateConfig Config { get; set; }
/// <summary>Output only. The time at which this CertificateAuthority was created.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("createTime")]
public virtual object CreateTime { get; set; }
/// <summary>
/// Output only. The time at which this CertificateAuthority was soft deleted, if it is in the DELETED state.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("deleteTime")]
public virtual object DeleteTime { get; set; }
/// <summary>
/// Output only. The time at which this CertificateAuthority will be permanently purged, if it is in the DELETED
/// state.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("expireTime")]
public virtual object ExpireTime { get; set; }
/// <summary>
/// Immutable. The name of a Cloud Storage bucket where this CertificateAuthority will publish content, such as
/// the CA certificate and CRLs. This must be a bucket name, without any prefixes (such as `gs://`) or suffixes
/// (such as `.googleapis.com`). For example, to use a bucket named `my-bucket`, you would simply specify
/// `my-bucket`. If not specified, a managed bucket will be created.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("gcsBucket")]
public virtual string GcsBucket { get; set; }
/// <summary>
/// Required. Immutable. Used when issuing certificates for this CertificateAuthority. If this
/// CertificateAuthority is a self-signed CertificateAuthority, this key is also used to sign the self-signed CA
/// certificate. Otherwise, it is used to sign a CSR.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("keySpec")]
public virtual KeyVersionSpec KeySpec { get; set; }
/// <summary>Optional. Labels with user-defined metadata.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("labels")]
public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; }
/// <summary>
/// Required. Immutable. The desired lifetime of the CA certificate. Used to create the "not_before_time" and
/// "not_after_time" fields inside an X.509 certificate.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("lifetime")]
public virtual object Lifetime { get; set; }
/// <summary>
/// Output only. The resource name for this CertificateAuthority in the format
/// `projects/*/locations/*/caPools/*/certificateAuthorities/*`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>
/// Output only. This CertificateAuthority's certificate chain, including the current CertificateAuthority's
/// certificate. Ordered such that the root issuer is the final element (consistent with RFC 5246). For a
/// self-signed CA, this will only list the current CertificateAuthority's certificate.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("pemCaCertificates")]
public virtual System.Collections.Generic.IList<string> PemCaCertificates { get; set; }
/// <summary>Output only. The State for this CertificateAuthority.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("state")]
public virtual string State { get; set; }
/// <summary>
/// Optional. If this is a subordinate CertificateAuthority, this field will be set with the subordinate
/// configuration, which describes its issuers. This may be updated, but this CertificateAuthority must continue
/// to validate.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("subordinateConfig")]
public virtual SubordinateConfig SubordinateConfig { get; set; }
/// <summary>Output only. The CaPool.Tier of the CaPool that includes this CertificateAuthority.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("tier")]
public virtual string Tier { get; set; }
/// <summary>Required. Immutable. The Type of this CertificateAuthority.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("type")]
public virtual string Type { get; set; }
/// <summary>Output only. The time at which this CertificateAuthority was last updated.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateTime")]
public virtual object UpdateTime { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// A CertificateConfig describes an X.509 certificate or CSR that is to be created, as an alternative to using
/// ASN.1.
/// </summary>
public class CertificateConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Optional. The public key that corresponds to this config. This is, for example, used when issuing
/// Certificates, but not when creating a self-signed CertificateAuthority or CertificateAuthority CSR.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("publicKey")]
public virtual PublicKey PublicKey { get; set; }
/// <summary>Required. Specifies some of the values in a certificate that are related to the subject.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("subjectConfig")]
public virtual SubjectConfig SubjectConfig { get; set; }
/// <summary>
/// Required. Describes how some of the technical X.509 fields in a certificate should be populated.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("x509Config")]
public virtual X509Parameters X509Config { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// A CertificateDescription describes an X.509 certificate or CSR that has been issued, as an alternative to using
/// ASN.1 / X.509.
/// </summary>
public class CertificateDescription : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Describes lists of issuer CA certificate URLs that appear in the "Authority Information Access" extension in
/// the certificate.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("aiaIssuingCertificateUrls")]
public virtual System.Collections.Generic.IList<string> AiaIssuingCertificateUrls { get; set; }
/// <summary>
/// Identifies the subject_key_id of the parent certificate, per
/// https://tools.ietf.org/html/rfc5280#section-4.2.1.1
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("authorityKeyId")]
public virtual KeyId AuthorityKeyId { get; set; }
/// <summary>The hash of the x.509 certificate.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("certFingerprint")]
public virtual CertificateFingerprint CertFingerprint { get; set; }
/// <summary>
/// Describes a list of locations to obtain CRL information, i.e. the DistributionPoint.fullName described by
/// https://tools.ietf.org/html/rfc5280#section-4.2.1.13
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("crlDistributionPoints")]
public virtual System.Collections.Generic.IList<string> CrlDistributionPoints { get; set; }
/// <summary>The public key that corresponds to an issued certificate.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("publicKey")]
public virtual PublicKey PublicKey { get; set; }
/// <summary>
/// Describes some of the values in a certificate that are related to the subject and lifetime.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("subjectDescription")]
public virtual SubjectDescription SubjectDescription { get; set; }
/// <summary>
/// Provides a means of identifiying certificates that contain a particular public key, per
/// https://tools.ietf.org/html/rfc5280#section-4.2.1.2.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("subjectKeyId")]
public virtual KeyId SubjectKeyId { get; set; }
/// <summary>Describes some of the technical X.509 fields in a certificate.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("x509Description")]
public virtual X509Parameters X509Description { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Describes a set of X.509 extensions that may be part of some certificate issuance controls.</summary>
public class CertificateExtensionConstraints : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Optional. A set of ObjectIds identifying custom X.509 extensions. Will be combined with known_extensions to
/// determine the full set of X.509 extensions.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("additionalExtensions")]
public virtual System.Collections.Generic.IList<ObjectId> AdditionalExtensions { get; set; }
/// <summary>
/// Optional. A set of named X.509 extensions. Will be combined with additional_extensions to determine the full
/// set of X.509 extensions.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("knownExtensions")]
public virtual System.Collections.Generic.IList<string> KnownExtensions { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A group of fingerprints for the x509 certificate.</summary>
public class CertificateFingerprint : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The SHA 256 hash, encoded in hexadecimal, of the DER x509 certificate.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sha256Hash")]
public virtual string Sha256Hash { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Describes constraints on a Certificate's Subject and SubjectAltNames.</summary>
public class CertificateIdentityConstraints : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Required. If this is true, the SubjectAltNames extension may be copied from a certificate request into the
/// signed certificate. Otherwise, the requested SubjectAltNames will be discarded.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("allowSubjectAltNamesPassthrough")]
public virtual System.Nullable<bool> AllowSubjectAltNamesPassthrough { get; set; }
/// <summary>
/// Required. If this is true, the Subject field may be copied from a certificate request into the signed
/// certificate. Otherwise, the requested Subject will be discarded.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("allowSubjectPassthrough")]
public virtual System.Nullable<bool> AllowSubjectPassthrough { get; set; }
/// <summary>
/// Optional. A CEL expression that may be used to validate the resolved X.509 Subject and/or Subject
/// Alternative Name before a certificate is signed. To see the full allowed syntax and some examples, see
/// https://cloud.google.com/certificate-authority-service/docs/using-cel
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("celExpression")]
public virtual Expr CelExpression { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// A CertificateRevocationList corresponds to a signed X.509 certificate Revocation List (CRL). A CRL contains the
/// serial numbers of certificates that should no longer be trusted.
/// </summary>
public class CertificateRevocationList : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. The location where 'pem_crl' can be accessed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("accessUrl")]
public virtual string AccessUrl { get; set; }
/// <summary>Output only. The time at which this CertificateRevocationList was created.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("createTime")]
public virtual object CreateTime { get; set; }
/// <summary>Optional. Labels with user-defined metadata.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("labels")]
public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; }
/// <summary>
/// Output only. The resource name for this CertificateRevocationList in the format
/// `projects/*/locations/*/caPools/*certificateAuthorities/*/ certificateRevocationLists/*`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Output only. The PEM-encoded X.509 CRL.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("pemCrl")]
public virtual string PemCrl { get; set; }
/// <summary>
/// Output only. The revision ID of this CertificateRevocationList. A new revision is committed whenever a new
/// CRL is published. The format is an 8-character hexadecimal string.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("revisionId")]
public virtual string RevisionId { get; set; }
/// <summary>Output only. The revoked serial numbers that appear in pem_crl.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("revokedCertificates")]
public virtual System.Collections.Generic.IList<RevokedCertificate> RevokedCertificates { get; set; }
/// <summary>Output only. The CRL sequence number that appears in pem_crl.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sequenceNumber")]
public virtual System.Nullable<long> SequenceNumber { get; set; }
/// <summary>Output only. The State for this CertificateRevocationList.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("state")]
public virtual string State { get; set; }
/// <summary>Output only. The time at which this CertificateRevocationList was updated.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateTime")]
public virtual object UpdateTime { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A CertificateTemplate refers to a managed template for certificate issuance.</summary>
public class CertificateTemplate : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. The time at which this CertificateTemplate was created.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("createTime")]
public virtual object CreateTime { get; set; }
/// <summary>Optional. A human-readable description of scenarios this template is intended for.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("description")]
public virtual string Description { get; set; }
/// <summary>
/// Optional. Describes constraints on identities that may be appear in Certificates issued using this template.
/// If this is omitted, then this template will not add restrictions on a certificate's identity.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("identityConstraints")]
public virtual CertificateIdentityConstraints IdentityConstraints { get; set; }
/// <summary>Optional. Labels with user-defined metadata.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("labels")]
public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; }
/// <summary>
/// Output only. The resource name for this CertificateTemplate in the format
/// `projects/*/locations/*/certificateTemplates/*`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>
/// Optional. Describes the set of X.509 extensions that may appear in a Certificate issued using this
/// CertificateTemplate. If a certificate request sets extensions that don't appear in the
/// passthrough_extensions, those extensions will be dropped. If the issuing CaPool's IssuancePolicy defines
/// baseline_values that don't appear here, the certificate issuance request will fail. If this is omitted, then
/// this template will not add restrictions on a certificate's X.509 extensions. These constraints do not apply
/// to X.509 extensions set in this CertificateTemplate's predefined_values.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("passthroughExtensions")]
public virtual CertificateExtensionConstraints PassthroughExtensions { get; set; }
/// <summary>
/// Optional. A set of X.509 values that will be applied to all issued certificates that use this template. If
/// the certificate request includes conflicting values for the same properties, they will be overwritten by the
/// values defined here. If the issuing CaPool's IssuancePolicy defines conflicting baseline_values for the same
/// properties, the certificate issuance request will fail.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("predefinedValues")]
public virtual X509Parameters PredefinedValues { get; set; }
/// <summary>Output only. The time at which this CertificateTemplate was updated.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateTime")]
public virtual object UpdateTime { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request message for CertificateAuthorityService.DisableCertificateAuthority.</summary>
public class DisableCertificateAuthorityRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Optional. An ID to identify requests. Specify a unique request ID so that if you must retry your request,
/// the server will know to ignore the request if it has already been completed. The server will guarantee that
/// for at least 60 minutes since the first request. For example, consider a situation where you make an initial
/// request and t he request times out. If you make the request again with the same request ID, the server can
/// check if original operation with the same request ID was received, and if so, will ignore the second
/// request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a
/// valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("requestId")]
public virtual string RequestId { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Describes an Elliptic Curve key that may be used in a Certificate issued from a CaPool.</summary>
public class EcKeyType : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Optional. A signature algorithm that must be used. If this is omitted, any EC-based signature algorithm will
/// be allowed.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("signatureAlgorithm")]
public virtual string SignatureAlgorithm { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical
/// example is to use it as the request or the response type of an API method. For instance: service Foo { rpc
/// Bar(google.protobuf.Empty) returns (google.protobuf.Empty); }
/// </summary>
public class Empty : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request message for CertificateAuthorityService.EnableCertificateAuthority.</summary>
public class EnableCertificateAuthorityRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Optional. An ID to identify requests. Specify a unique request ID so that if you must retry your request,
/// the server will know to ignore the request if it has already been completed. The server will guarantee that
/// for at least 60 minutes since the first request. For example, consider a situation where you make an initial
/// request and t he request times out. If you make the request again with the same request ID, the server can
/// check if original operation with the same request ID was received, and if so, will ignore the second
/// request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a
/// valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("requestId")]
public virtual string RequestId { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Represents a textual expression in the Common Expression Language (CEL) syntax. CEL is a C-like expression
/// language. The syntax and semantics of CEL are documented at https://github.com/google/cel-spec. Example
/// (Comparison): title: "Summary size limit" description: "Determines if a summary is less than 100 chars"
/// expression: "document.summary.size() &lt; 100" Example (Equality): title: "Requestor is owner" description:
/// "Determines if requestor is the document owner" expression: "document.owner == request.auth.claims.email"
/// Example (Logic): title: "Public documents" description: "Determine whether the document should be publicly
/// visible" expression: "document.type != 'private' &amp;&amp; document.type != 'internal'" Example (Data
/// Manipulation): title: "Notification string" description: "Create a notification string with a timestamp."
/// expression: "'New message received at ' + string(document.create_time)" The exact variables and functions that
/// may be referenced within an expression are determined by the service that evaluates it. See the service
/// documentation for additional information.
/// </summary>
public class Expr : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Optional. Description of the expression. This is a longer text which describes the expression, e.g. when
/// hovered over it in a UI.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("description")]
public virtual string Description { get; set; }
/// <summary>Textual representation of an expression in Common Expression Language syntax.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("expression")]
public virtual string Expression { get; set; }
/// <summary>
/// Optional. String indicating the location of the expression for error reporting, e.g. a file name and a
/// position in the file.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("location")]
public virtual string Location { get; set; }
/// <summary>
/// Optional. Title for the expression, i.e. a short string describing its purpose. This can be used e.g. in UIs
/// which allow to enter the expression.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("title")]
public virtual string Title { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// KeyUsage.ExtendedKeyUsageOptions has fields that correspond to certain common OIDs that could be specified as an
/// extended key usage value.
/// </summary>
public class ExtendedKeyUsageOptions : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Corresponds to OID 1.3.6.1.5.5.7.3.2. Officially described as "TLS WWW client authentication", though
/// regularly used for non-WWW TLS.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("clientAuth")]
public virtual System.Nullable<bool> ClientAuth { get; set; }
/// <summary>
/// Corresponds to OID 1.3.6.1.5.5.7.3.3. Officially described as "Signing of downloadable executable code
/// client authentication".
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("codeSigning")]
public virtual System.Nullable<bool> CodeSigning { get; set; }
/// <summary>Corresponds to OID 1.3.6.1.5.5.7.3.4. Officially described as "Email protection".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("emailProtection")]
public virtual System.Nullable<bool> EmailProtection { get; set; }
/// <summary>Corresponds to OID 1.3.6.1.5.5.7.3.9. Officially described as "Signing OCSP responses".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("ocspSigning")]
public virtual System.Nullable<bool> OcspSigning { get; set; }
/// <summary>
/// Corresponds to OID 1.3.6.1.5.5.7.3.1. Officially described as "TLS WWW server authentication", though
/// regularly used for non-WWW TLS.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("serverAuth")]
public virtual System.Nullable<bool> ServerAuth { get; set; }
/// <summary>
/// Corresponds to OID 1.3.6.1.5.5.7.3.8. Officially described as "Binding the hash of an object to a time".
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("timeStamping")]
public virtual System.Nullable<bool> TimeStamping { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request message for CertificateAuthorityService.FetchCaCerts.</summary>
public class FetchCaCertsRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Optional. An ID to identify requests. Specify a unique request ID so that if you must retry your request,
/// the server will know to ignore the request if it has already been completed. The server will guarantee that
/// for at least 60 minutes since the first request. For example, consider a situation where you make an initial
/// request and t he request times out. If you make the request again with the same request ID, the server can
/// check if original operation with the same request ID was received, and if so, will ignore the second
/// request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a
/// valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("requestId")]
public virtual string RequestId { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for CertificateAuthorityService.FetchCaCerts.</summary>
public class FetchCaCertsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The PEM encoded CA certificate chains of all ACTIVE CertificateAuthority resources in this CaPool.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("caCerts")]
public virtual System.Collections.Generic.IList<CertChain> CaCerts { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for CertificateAuthorityService.FetchCertificateAuthorityCsr.</summary>
public class FetchCertificateAuthorityCsrResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. The PEM-encoded signed certificate signing request (CSR).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("pemCsr")]
public virtual string PemCsr { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// IssuanceModes specifies the allowed ways in which Certificates may be requested from this CaPool.
/// </summary>
public class IssuanceModes : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Optional. When true, allows callers to create Certificates by specifying a CertificateConfig.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("allowConfigBasedIssuance")]
public virtual System.Nullable<bool> AllowConfigBasedIssuance { get; set; }
/// <summary>Optional. When true, allows callers to create Certificates by specifying a CSR.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("allowCsrBasedIssuance")]
public virtual System.Nullable<bool> AllowCsrBasedIssuance { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Defines controls over all certificate issuance within a CaPool.</summary>
public class IssuancePolicy : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Optional. If specified, then only methods allowed in the IssuanceModes may be used to issue Certificates.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("allowedIssuanceModes")]
public virtual IssuanceModes AllowedIssuanceModes { get; set; }
/// <summary>
/// Optional. If any AllowedKeyType is specified, then the certificate request's public key must match one of
/// the key types listed here. Otherwise, any key may be used.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("allowedKeyTypes")]
public virtual System.Collections.Generic.IList<AllowedKeyType> AllowedKeyTypes { get; set; }
/// <summary>
/// Optional. A set of X.509 values that will be applied to all certificates issued through this CaPool. If a
/// certificate request includes conflicting values for the same properties, they will be overwritten by the
/// values defined here. If a certificate request uses a CertificateTemplate that defines conflicting
/// predefined_values for the same properties, the certificate issuance request will fail.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("baselineValues")]
public virtual X509Parameters BaselineValues { get; set; }
/// <summary>
/// Optional. Describes constraints on identities that may appear in Certificates issued through this CaPool. If
/// this is omitted, then this CaPool will not add restrictions on a certificate's identity.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("identityConstraints")]
public virtual CertificateIdentityConstraints IdentityConstraints { get; set; }
/// <summary>
/// Optional. The maximum lifetime allowed for issued Certificates. Note that if the issuing
/// CertificateAuthority expires before a Certificate's requested maximum_lifetime, the effective lifetime will
/// be explicitly truncated to match it.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("maximumLifetime")]
public virtual object MaximumLifetime { get; set; }
/// <summary>
/// Optional. Describes the set of X.509 extensions that may appear in a Certificate issued through this CaPool.
/// If a certificate request sets extensions that don't appear in the passthrough_extensions, those extensions
/// will be dropped. If a certificate request uses a CertificateTemplate with predefined_values that don't
/// appear here, the certificate issuance request will fail. If this is omitted, then this CaPool will not add
/// restrictions on a certificate's X.509 extensions. These constraints do not apply to X.509 extensions set in
/// this CaPool's baseline_values.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("passthroughExtensions")]
public virtual CertificateExtensionConstraints PassthroughExtensions { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A KeyId identifies a specific public key, usually by hashing the public key.</summary>
public class KeyId : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Optional. The value of this KeyId encoded in lowercase hexadecimal. This is most likely the 160 bit SHA-1
/// hash of the public key.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("keyId")]
public virtual string KeyIdValue { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A KeyUsage describes key usage values that may appear in an X.509 certificate.</summary>
public class KeyUsage : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Describes high-level ways in which a key may be used.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("baseKeyUsage")]
public virtual KeyUsageOptions BaseKeyUsage { get; set; }
/// <summary>Detailed scenarios in which a key may be used.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("extendedKeyUsage")]
public virtual ExtendedKeyUsageOptions ExtendedKeyUsage { get; set; }
/// <summary>
/// Used to describe extended key usages that are not listed in the KeyUsage.ExtendedKeyUsageOptions message.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("unknownExtendedKeyUsages")]
public virtual System.Collections.Generic.IList<ObjectId> UnknownExtendedKeyUsages { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// KeyUsage.KeyUsageOptions corresponds to the key usage values described in
/// https://tools.ietf.org/html/rfc5280#section-4.2.1.3.
/// </summary>
public class KeyUsageOptions : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The key may be used to sign certificates.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("certSign")]
public virtual System.Nullable<bool> CertSign { get; set; }
/// <summary>
/// The key may be used for cryptographic commitments. Note that this may also be referred to as
/// "non-repudiation".
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("contentCommitment")]
public virtual System.Nullable<bool> ContentCommitment { get; set; }
/// <summary>The key may be used sign certificate revocation lists.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("crlSign")]
public virtual System.Nullable<bool> CrlSign { get; set; }
/// <summary>The key may be used to encipher data.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("dataEncipherment")]
public virtual System.Nullable<bool> DataEncipherment { get; set; }
/// <summary>The key may be used to decipher only.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("decipherOnly")]
public virtual System.Nullable<bool> DecipherOnly { get; set; }
/// <summary>The key may be used for digital signatures.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("digitalSignature")]
public virtual System.Nullable<bool> DigitalSignature { get; set; }
/// <summary>The key may be used to encipher only.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("encipherOnly")]
public virtual System.Nullable<bool> EncipherOnly { get; set; }
/// <summary>The key may be used in a key agreement protocol.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("keyAgreement")]
public virtual System.Nullable<bool> KeyAgreement { get; set; }
/// <summary>The key may be used to encipher other keys.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("keyEncipherment")]
public virtual System.Nullable<bool> KeyEncipherment { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A Cloud KMS key configuration that a CertificateAuthority will use.</summary>
public class KeyVersionSpec : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The algorithm to use for creating a managed Cloud KMS key for a for a simplified experience. All managed
/// keys will be have their ProtectionLevel as `HSM`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("algorithm")]
public virtual string Algorithm { get; set; }
/// <summary>
/// The resource name for an existing Cloud KMS CryptoKeyVersion in the format
/// `projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*`. This option enables full flexibility
/// in the key's capabilities and properties.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("cloudKmsKeyVersion")]
public virtual string CloudKmsKeyVersion { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for CertificateAuthorityService.ListCaPools.</summary>
public class ListCaPoolsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The list of CaPools.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("caPools")]
public virtual System.Collections.Generic.IList<CaPool> CaPools { get; set; }
/// <summary>
/// A token to retrieve next page of results. Pass this value in
/// ListCertificateAuthoritiesRequest.next_page_token to retrieve the next page of results.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>A list of locations (e.g. "us-west1") that could not be reached.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("unreachable")]
public virtual System.Collections.Generic.IList<string> Unreachable { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for CertificateAuthorityService.ListCertificateAuthorities.</summary>
public class ListCertificateAuthoritiesResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The list of CertificateAuthorities.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("certificateAuthorities")]
public virtual System.Collections.Generic.IList<CertificateAuthority> CertificateAuthorities { get; set; }
/// <summary>
/// A token to retrieve next page of results. Pass this value in
/// ListCertificateAuthoritiesRequest.next_page_token to retrieve the next page of results.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>A list of locations (e.g. "us-west1") that could not be reached.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("unreachable")]
public virtual System.Collections.Generic.IList<string> Unreachable { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for CertificateAuthorityService.ListCertificateRevocationLists.</summary>
public class ListCertificateRevocationListsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The list of CertificateRevocationLists.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("certificateRevocationLists")]
public virtual System.Collections.Generic.IList<CertificateRevocationList> CertificateRevocationLists { get; set; }
/// <summary>
/// A token to retrieve next page of results. Pass this value in
/// ListCertificateRevocationListsRequest.next_page_token to retrieve the next page of results.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>A list of locations (e.g. "us-west1") that could not be reached.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("unreachable")]
public virtual System.Collections.Generic.IList<string> Unreachable { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for CertificateAuthorityService.ListCertificateTemplates.</summary>
public class ListCertificateTemplatesResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The list of CertificateTemplates.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("certificateTemplates")]
public virtual System.Collections.Generic.IList<CertificateTemplate> CertificateTemplates { get; set; }
/// <summary>
/// A token to retrieve next page of results. Pass this value in ListCertificateTemplatesRequest.next_page_token
/// to retrieve the next page of results.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>A list of locations (e.g. "us-west1") that could not be reached.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("unreachable")]
public virtual System.Collections.Generic.IList<string> Unreachable { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for CertificateAuthorityService.ListCertificates.</summary>
public class ListCertificatesResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The list of Certificates.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("certificates")]
public virtual System.Collections.Generic.IList<Certificate> Certificates { get; set; }
/// <summary>
/// A token to retrieve next page of results. Pass this value in ListCertificatesRequest.next_page_token to
/// retrieve the next page of results.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>A list of locations (e.g. "us-west1") that could not be reached.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("unreachable")]
public virtual System.Collections.Generic.IList<string> Unreachable { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response message for Locations.ListLocations.</summary>
public class ListLocationsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A list of locations that matches the specified filter in the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("locations")]
public virtual System.Collections.Generic.IList<Location> Locations { get; set; }
/// <summary>The standard List next-page token.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response message for Operations.ListOperations.</summary>
public class ListOperationsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The standard List next-page token.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>A list of operations that matches the specified filter in the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("operations")]
public virtual System.Collections.Generic.IList<Operation> Operations { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A resource that represents Google Cloud Platform location.</summary>
public class Location : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The friendly name for this location, typically a nearby city name. For example, "Tokyo".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("displayName")]
public virtual string DisplayName { get; set; }
/// <summary>
/// Cross-service attributes for the location. For example {"cloud.googleapis.com/region": "us-east1"}
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("labels")]
public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; }
/// <summary>The canonical id for this location. For example: `"us-east1"`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("locationId")]
public virtual string LocationId { get; set; }
/// <summary>Service-specific metadata. For example the available capacity at the given location.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("metadata")]
public virtual System.Collections.Generic.IDictionary<string, object> Metadata { get; set; }
/// <summary>
/// Resource name for the location, which may vary between implementations. For example:
/// `"projects/example-project/locations/us-east1"`
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// An ObjectId specifies an object identifier (OID). These provide context and describe types in ASN.1 messages.
/// </summary>
public class ObjectId : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The parts of an OID path. The most significant parts of the path come first.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("objectIdPath")]
public virtual System.Collections.Generic.IList<System.Nullable<int>> ObjectIdPath { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>This resource represents a long-running operation that is the result of a network API call.</summary>
public class Operation : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed,
/// and either `error` or `response` is available.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("done")]
public virtual System.Nullable<bool> Done { get; set; }
/// <summary>The error result of the operation in case of failure or cancellation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("error")]
public virtual Status Error { get; set; }
/// <summary>
/// Service-specific metadata associated with the operation. It typically contains progress information and
/// common metadata such as create time. Some services might not provide such metadata. Any method that returns
/// a long-running operation should document the metadata type, if any.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("metadata")]
public virtual System.Collections.Generic.IDictionary<string, object> Metadata { get; set; }
/// <summary>
/// The server-assigned name, which is only unique within the same service that originally returns it. If you
/// use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>
/// The normal response of the operation in case of success. If the original method returns no data on success,
/// such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard
/// `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have
/// the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name is
/// `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("response")]
public virtual System.Collections.Generic.IDictionary<string, object> Response { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents the metadata of the long-running operation.</summary>
public class OperationMetadata : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. API version used to start the operation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("apiVersion")]
public virtual string ApiVersion { get; set; }
/// <summary>Output only. The time the operation was created.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("createTime")]
public virtual object CreateTime { get; set; }
/// <summary>Output only. The time the operation finished running.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("endTime")]
public virtual object EndTime { get; set; }
/// <summary>
/// Output only. Identifies whether the user has requested cancellation of the operation. Operations that have
/// successfully been cancelled have Operation.error value with a google.rpc.Status.code of 1, corresponding to
/// `Code.CANCELLED`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("requestedCancellation")]
public virtual System.Nullable<bool> RequestedCancellation { get; set; }
/// <summary>Output only. Human-readable status of the operation, if any.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("statusMessage")]
public virtual string StatusMessage { get; set; }
/// <summary>Output only. Server-defined resource path for the target of the operation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("target")]
public virtual string Target { get; set; }
/// <summary>Output only. Name of the verb executed by the operation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("verb")]
public virtual string Verb { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// An Identity and Access Management (IAM) policy, which specifies access controls for Google Cloud resources. A
/// `Policy` is a collection of `bindings`. A `binding` binds one or more `members`, or principals, to a single
/// `role`. Principals can be user accounts, service accounts, Google groups, and domains (such as G Suite). A
/// `role` is a named list of permissions; each `role` can be an IAM predefined role or a user-created custom role.
/// For some types of Google Cloud resources, a `binding` can also specify a `condition`, which is a logical
/// expression that allows access to a resource only if the expression evaluates to `true`. A condition can add
/// constraints based on attributes of the request, the resource, or both. To learn which resources support
/// conditions in their IAM policies, see the [IAM
/// documentation](https://cloud.google.com/iam/help/conditions/resource-policies). **JSON example:** { "bindings":
/// [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com",
/// "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] },
/// { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": {
/// "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time
/// &lt; timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 } **YAML example:**
/// bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com -
/// serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin -
/// members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable
/// access description: Does not grant access after Sep 2020 expression: request.time &lt;
/// timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3 For a description of IAM and its features,
/// see the [IAM documentation](https://cloud.google.com/iam/docs/).
/// </summary>
public class Policy : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Specifies cloud audit logging configuration for this policy.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("auditConfigs")]
public virtual System.Collections.Generic.IList<AuditConfig> AuditConfigs { get; set; }
/// <summary>
/// Associates a list of `members`, or principals, with a `role`. Optionally, may specify a `condition` that
/// determines how and when the `bindings` are applied. Each of the `bindings` must contain at least one
/// principal. The `bindings` in a `Policy` can refer to up to 1,500 principals; up to 250 of these principals
/// can be Google groups. Each occurrence of a principal counts towards these limits. For example, if the
/// `bindings` grant 50 different roles to `user:alice@example.com`, and not to any other principal, then you
/// can add another 1,450 principals to the `bindings` in the `Policy`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("bindings")]
public virtual System.Collections.Generic.IList<Binding> Bindings { get; set; }
/// <summary>
/// `etag` is used for optimistic concurrency control as a way to help prevent simultaneous updates of a policy
/// from overwriting each other. It is strongly suggested that systems make use of the `etag` in the
/// read-modify-write cycle to perform policy updates in order to avoid race conditions: An `etag` is returned
/// in the response to `getIamPolicy`, and systems are expected to put that etag in the request to
/// `setIamPolicy` to ensure that their change will be applied to the same version of the policy. **Important:**
/// If you use IAM Conditions, you must include the `etag` field whenever you call `setIamPolicy`. If you omit
/// this field, then IAM allows you to overwrite a version `3` policy with a version `1` policy, and all of the
/// conditions in the version `3` policy are lost.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>
/// Specifies the format of the policy. Valid values are `0`, `1`, and `3`. Requests that specify an invalid
/// value are rejected. Any operation that affects conditional role bindings must specify version `3`. This
/// requirement applies to the following operations: * Getting a policy that includes a conditional role binding
/// * Adding a conditional role binding to a policy * Changing a conditional role binding in a policy * Removing
/// any role binding, with or without a condition, from a policy that includes conditions **Important:** If you
/// use IAM Conditions, you must include the `etag` field whenever you call `setIamPolicy`. If you omit this
/// field, then IAM allows you to overwrite a version `3` policy with a version `1` policy, and all of the
/// conditions in the version `3` policy are lost. If a policy does not include any conditions, operations on
/// that policy may specify any valid version or leave the field unset. To learn which resources support
/// conditions in their IAM policies, see the [IAM
/// documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("version")]
public virtual System.Nullable<int> Version { get; set; }
}
/// <summary>A PublicKey describes a public key.</summary>
public class PublicKey : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The format of the public key.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("format")]
public virtual string Format { get; set; }
/// <summary>
/// Required. A public key. The padding and encoding must match with the `KeyFormat` value specified for the
/// `format` field.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("key")]
public virtual string Key { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Options relating to the publication of each CertificateAuthority's CA certificate and CRLs and their inclusion
/// as extensions in issued Certificates. The options set here apply to certificates issued by any
/// CertificateAuthority in the CaPool.
/// </summary>
public class PublishingOptions : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Optional. When true, publishes each CertificateAuthority's CA certificate and includes its URL in the
/// "Authority Information Access" X.509 extension in all issued Certificates. If this is false, the CA
/// certificate will not be published and the corresponding X.509 extension will not be written in issued
/// certificates.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("publishCaCert")]
public virtual System.Nullable<bool> PublishCaCert { get; set; }
/// <summary>
/// Optional. When true, publishes each CertificateAuthority's CRL and includes its URL in the "CRL Distribution
/// Points" X.509 extension in all issued Certificates. If this is false, CRLs will not be published and the
/// corresponding X.509 extension will not be written in issued certificates. CRLs will expire 7 days from their
/// creation. However, we will rebuild daily. CRLs are also rebuilt shortly after a certificate is revoked.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("publishCrl")]
public virtual System.Nullable<bool> PublishCrl { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Operation metadata returned by the CLH during resource state reconciliation.</summary>
public class ReconciliationOperationMetadata : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>DEPRECATED. Use exclusive_action instead.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("deleteResource")]
public virtual System.Nullable<bool> DeleteResource { get; set; }
[Newtonsoft.Json.JsonPropertyAttribute("exclusiveAction")]
public virtual string ExclusiveAction { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Describes fields that are relavent to the revocation of a Certificate.</summary>
public class RevocationDetails : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Indicates why a Certificate was revoked.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("revocationState")]
public virtual string RevocationState { get; set; }
/// <summary>The time at which this Certificate was revoked.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("revocationTime")]
public virtual object RevocationTime { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request message for CertificateAuthorityService.RevokeCertificate.</summary>
public class RevokeCertificateRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The RevocationReason for revoking this certificate.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("reason")]
public virtual string Reason { get; set; }
/// <summary>
/// Optional. An ID to identify requests. Specify a unique request ID so that if you must retry your request,
/// the server will know to ignore the request if it has already been completed. The server will guarantee that
/// for at least 60 minutes since the first request. For example, consider a situation where you make an initial
/// request and t he request times out. If you make the request again with the same request ID, the server can
/// check if original operation with the same request ID was received, and if so, will ignore the second
/// request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a
/// valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("requestId")]
public virtual string RequestId { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Describes a revoked Certificate.</summary>
public class RevokedCertificate : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The resource name for the Certificate in the format `projects/*/locations/*/caPools/*/certificates/*`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("certificate")]
public virtual string Certificate { get; set; }
/// <summary>The serial number of the Certificate.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("hexSerialNumber")]
public virtual string HexSerialNumber { get; set; }
/// <summary>The reason the Certificate was revoked.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("revocationReason")]
public virtual string RevocationReason { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Describes an RSA key that may be used in a Certificate issued from a CaPool.</summary>
public class RsaKeyType : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Optional. The maximum allowed RSA modulus size (inclusive), in bits. If this is not set, or if set to zero,
/// the service will not enforce an explicit upper bound on RSA modulus sizes.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("maxModulusSize")]
public virtual System.Nullable<long> MaxModulusSize { get; set; }
/// <summary>
/// Optional. The minimum allowed RSA modulus size (inclusive), in bits. If this is not set, or if set to zero,
/// the service-level min RSA modulus size will continue to apply.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("minModulusSize")]
public virtual System.Nullable<long> MinModulusSize { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request message for `SetIamPolicy` method.</summary>
public class SetIamPolicyRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// REQUIRED: The complete policy to be applied to the `resource`. The size of the policy is limited to a few
/// 10s of KB. An empty policy is a valid policy but certain Google Cloud services (such as Projects) might
/// reject them.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("policy")]
public virtual Policy Policy { get; set; }
/// <summary>
/// OPTIONAL: A FieldMask specifying which fields of the policy to modify. Only the fields in the mask will be
/// modified. If no mask is provided, the following default mask is used: `paths: "bindings, etag"`
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateMask")]
public virtual object UpdateMask { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// The `Status` type defines a logical error model that is suitable for different programming environments,
/// including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains
/// three pieces of data: error code, error message, and error details. You can find out more about this error model
/// and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors).
/// </summary>
public class Status : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The status code, which should be an enum value of google.rpc.Code.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("code")]
public virtual System.Nullable<int> Code { get; set; }
/// <summary>
/// A list of messages that carry the error details. There is a common set of message types for APIs to use.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("details")]
public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string, object>> Details { get; set; }
/// <summary>
/// A developer-facing error message, which should be in English. Any user-facing error message should be
/// localized and sent in the google.rpc.Status.details field, or localized by the client.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("message")]
public virtual string Message { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Subject describes parts of a distinguished name that, in turn, describes the subject of the certificate.
/// </summary>
public class Subject : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The "common name" of the subject.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("commonName")]
public virtual string CommonName { get; set; }
/// <summary>The country code of the subject.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("countryCode")]
public virtual string CountryCode { get; set; }
/// <summary>The locality or city of the subject.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("locality")]
public virtual string Locality { get; set; }
/// <summary>The organization of the subject.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("organization")]
public virtual string Organization { get; set; }
/// <summary>The organizational_unit of the subject.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("organizationalUnit")]
public virtual string OrganizationalUnit { get; set; }
/// <summary>The postal code of the subject.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("postalCode")]
public virtual string PostalCode { get; set; }
/// <summary>The province, territory, or regional state of the subject.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("province")]
public virtual string Province { get; set; }
/// <summary>The street address of the subject.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("streetAddress")]
public virtual string StreetAddress { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// SubjectAltNames corresponds to a more modern way of listing what the asserted identity is in a certificate
/// (i.e., compared to the "common name" in the distinguished name).
/// </summary>
public class SubjectAltNames : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Contains additional subject alternative name values. For each custom_san, the `value` field must contain an
/// ASN.1 encoded UTF8String.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("customSans")]
public virtual System.Collections.Generic.IList<X509Extension> CustomSans { get; set; }
/// <summary>Contains only valid, fully-qualified host names.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("dnsNames")]
public virtual System.Collections.Generic.IList<string> DnsNames { get; set; }
/// <summary>Contains only valid RFC 2822 E-mail addresses.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("emailAddresses")]
public virtual System.Collections.Generic.IList<string> EmailAddresses { get; set; }
/// <summary>Contains only valid 32-bit IPv4 addresses or RFC 4291 IPv6 addresses.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("ipAddresses")]
public virtual System.Collections.Generic.IList<string> IpAddresses { get; set; }
/// <summary>Contains only valid RFC 3986 URIs.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("uris")]
public virtual System.Collections.Generic.IList<string> Uris { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// These values are used to create the distinguished name and subject alternative name fields in an X.509
/// certificate.
/// </summary>
public class SubjectConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Required. Contains distinguished name fields such as the common name, location and organization.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("subject")]
public virtual Subject Subject { get; set; }
/// <summary>Optional. The subject alternative name fields.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("subjectAltName")]
public virtual SubjectAltNames SubjectAltName { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// These values describe fields in an issued X.509 certificate such as the distinguished name, subject alternative
/// names, serial number, and lifetime.
/// </summary>
public class SubjectDescription : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The serial number encoded in lowercase hexadecimal.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("hexSerialNumber")]
public virtual string HexSerialNumber { get; set; }
/// <summary>For convenience, the actual lifetime of an issued certificate.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("lifetime")]
public virtual object Lifetime { get; set; }
/// <summary>
/// The time after which the certificate is expired. Per RFC 5280, the validity period for a certificate is the
/// period of time from not_before_time through not_after_time, inclusive. Corresponds to 'not_before_time' +
/// 'lifetime' - 1 second.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("notAfterTime")]
public virtual object NotAfterTime { get; set; }
/// <summary>The time at which the certificate becomes valid.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("notBeforeTime")]
public virtual object NotBeforeTime { get; set; }
/// <summary>Contains distinguished name fields such as the common name, location and / organization.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("subject")]
public virtual Subject Subject { get; set; }
/// <summary>The subject alternative name fields.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("subjectAltName")]
public virtual SubjectAltNames SubjectAltName { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Describes a subordinate CA's issuers. This is either a resource name to a known issuing CertificateAuthority, or
/// a PEM issuer certificate chain.
/// </summary>
public class SubordinateConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Required. This can refer to a CertificateAuthority that was used to create a subordinate
/// CertificateAuthority. This field is used for information and usability purposes only. The resource name is
/// in the format `projects/*/locations/*/caPools/*/certificateAuthorities/*`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("certificateAuthority")]
public virtual string CertificateAuthority { get; set; }
/// <summary>
/// Required. Contains the PEM certificate chain for the issuers of this CertificateAuthority, but not pem
/// certificate for this CA itself.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("pemIssuerChain")]
public virtual SubordinateConfigChain PemIssuerChain { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// This message describes a subordinate CA's issuer certificate chain. This wrapper exists for compatibility
/// reasons.
/// </summary>
public class SubordinateConfigChain : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. Expected to be in leaf-to-root order according to RFC 5246.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("pemCertificates")]
public virtual System.Collections.Generic.IList<string> PemCertificates { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request message for `TestIamPermissions` method.</summary>
public class TestIamPermissionsRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The set of permissions to check for the `resource`. Permissions with wildcards (such as `*` or `storage.*`)
/// are not allowed. For more information see [IAM
/// Overview](https://cloud.google.com/iam/docs/overview#permissions).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("permissions")]
public virtual System.Collections.Generic.IList<string> Permissions { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for `TestIamPermissions` method.</summary>
public class TestIamPermissionsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A subset of `TestPermissionsRequest.permissions` that the caller is allowed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("permissions")]
public virtual System.Collections.Generic.IList<string> Permissions { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request message for CertificateAuthorityService.UndeleteCertificateAuthority.</summary>
public class UndeleteCertificateAuthorityRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Optional. An ID to identify requests. Specify a unique request ID so that if you must retry your request,
/// the server will know to ignore the request if it has already been completed. The server will guarantee that
/// for at least 60 minutes since the first request. For example, consider a situation where you make an initial
/// request and t he request times out. If you make the request again with the same request ID, the server can
/// check if original operation with the same request ID was received, and if so, will ignore the second
/// request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a
/// valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("requestId")]
public virtual string RequestId { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// An X509Extension specifies an X.509 extension, which may be used in different parts of X.509 objects like
/// certificates, CSRs, and CRLs.
/// </summary>
public class X509Extension : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Optional. Indicates whether or not this extension is critical (i.e., if the client does not know how to
/// handle this extension, the client should consider this to be an error).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("critical")]
public virtual System.Nullable<bool> Critical { get; set; }
/// <summary>Required. The OID for this X.509 extension.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("objectId")]
public virtual ObjectId ObjectId { get; set; }
/// <summary>Required. The value of this X.509 extension.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("value")]
public virtual string Value { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// An X509Parameters is used to describe certain fields of an X.509 certificate, such as the key usage fields,
/// fields specific to CA certificates, certificate policy extensions and custom extensions.
/// </summary>
public class X509Parameters : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. Describes custom X.509 extensions.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("additionalExtensions")]
public virtual System.Collections.Generic.IList<X509Extension> AdditionalExtensions { get; set; }
/// <summary>
/// Optional. Describes Online Certificate Status Protocol (OCSP) endpoint addresses that appear in the
/// "Authority Information Access" extension in the certificate.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("aiaOcspServers")]
public virtual System.Collections.Generic.IList<string> AiaOcspServers { get; set; }
/// <summary>Optional. Describes options in this X509Parameters that are relevant in a CA certificate.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("caOptions")]
public virtual CaOptions CaOptions { get; set; }
/// <summary>Optional. Indicates the intended use for keys that correspond to a certificate.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("keyUsage")]
public virtual KeyUsage KeyUsage { get; set; }
/// <summary>
/// Optional. Describes the X.509 certificate policy object identifiers, per
/// https://tools.ietf.org/html/rfc5280#section-4.2.1.4.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("policyIds")]
public virtual System.Collections.Generic.IList<ObjectId> PolicyIds { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| 56.031211 | 218 | 0.556999 | [
"Apache-2.0"
] | ScriptBox99/google-api-dotnet-client | Src/Generated/Google.Apis.CertificateAuthorityService.v1/Google.Apis.CertificateAuthorityService.v1.cs | 317,753 | C# |
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// © Component Factory Pty Ltd, 2006-2019, All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to license terms.
//
// Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2019. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.490)
// Version 5.490.0.0 www.ComponentFactory.com
// *****************************************************************************
using System.Drawing;
using System.Diagnostics;
using ComponentFactory.Krypton.Toolkit;
namespace ComponentFactory.Krypton.Ribbon
{
internal class RibbonRecentDocsEntryToContent : RibbonToContent
{
#region Instance Fields
private readonly IPaletteRibbonText _ribbonRecentDocEntryText;
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the RibbonRecentDocsEntryToContent class.
/// </summary>
/// <param name="ribbonGeneral">Source for general ribbon settings.</param>
/// <param name="ribbonRecentDocEntryText">Source for ribbon recent document entry settings.</param>
public RibbonRecentDocsEntryToContent(PaletteRibbonGeneral ribbonGeneral,
IPaletteRibbonText ribbonRecentDocEntryText)
: base(ribbonGeneral)
{
Debug.Assert(ribbonRecentDocEntryText != null);
_ribbonRecentDocEntryText = ribbonRecentDocEntryText;
}
#endregion
#region IPaletteContent
/// <summary>
/// Gets the horizontal relative alignment of the short text.
/// </summary>
/// <param name="state">Palette value should be applicable to this state.</param>
/// <returns>RelativeAlignment value.</returns>
public override PaletteRelativeAlign GetContentShortTextH(PaletteState state)
{
return PaletteRelativeAlign.Near;
}
/// <summary>
/// Gets the text trimming to use for short text.
/// </summary>
/// <param name="state">Palette value should be applicable to this state.</param>
/// <returns>PaletteTextTrim value.</returns>
public override PaletteTextTrim GetContentShortTextTrim(PaletteState state)
{
return PaletteTextTrim.EllipsisPath;
}
/// <summary>
/// Gets the first back color for the short text.
/// </summary>
/// <param name="state">Palette value should be applicable to this state.</param>
/// <returns>Color value.</returns>
public override Color GetContentShortTextColor1(PaletteState state)
{
return _ribbonRecentDocEntryText.GetRibbonTextColor(state);
}
/// <summary>
/// Gets the second back color for the short text.
/// </summary>
/// <param name="state">Palette value should be applicable to this state.</param>
/// <returns>Color value.</returns>
public override Color GetContentShortTextColor2(PaletteState state)
{
return _ribbonRecentDocEntryText.GetRibbonTextColor(state);
}
/// <summary>
/// Gets the horizontal relative alignment of the long text.
/// </summary>
/// <param name="state">Palette value should be applicable to this state.</param>
/// <returns>RelativeAlignment value.</returns>
public override PaletteRelativeAlign GetContentLongTextH(PaletteState state)
{
return PaletteRelativeAlign.Far;
}
/// <summary>
/// Gets the text trimming to use for long text.
/// </summary>
/// <param name="state">Palette value should be applicable to this state.</param>
/// <returns>PaletteTextTrim value.</returns>
public override PaletteTextTrim GetContentLongTextTrim(PaletteState state)
{
return PaletteTextTrim.EllipsisPath;
}
/// <summary>
/// Gets the first back color for the long text.
/// </summary>
/// <param name="state">Palette value should be applicable to this state.</param>
/// <returns>Color value.</returns>
public override Color GetContentLongTextColor1(PaletteState state)
{
return _ribbonRecentDocEntryText.GetRibbonTextColor(state);
}
/// <summary>
/// Gets the second back color for the long text.
/// </summary>
/// <param name="state">Palette value should be applicable to this state.</param>
/// <returns>Color value.</returns>
public override Color GetContentLongTextColor2(PaletteState state)
{
return _ribbonRecentDocEntryText.GetRibbonTextColor(state);
}
#endregion
}
}
| 41.909836 | 157 | 0.624291 | [
"BSD-3-Clause"
] | Smurf-IV/Krypton-Toolkit-Suite-NET-Core | Source/Krypton Components/ComponentFactory.Krypton.Ribbon/Palette/RibbonRecentDocsEntryToContent.cs | 5,116 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.IO;
using System.Xml;
using Xunit;
namespace System.Data.Tests
{
public class DataSetReadXmlTest
{
private const string xml1 = "";
private const string xml2 = "<root/>";
private const string xml3 = "<root></root>";
private const string xml4 = "<root> </root>";
private const string xml5 = "<root>test</root>";
private const string xml6 = "<root><test>1</test></root>";
private const string xml7 = "<root><test>1</test><test2>a</test2></root>";
private const string xml8 = "<dataset><table><col1>foo</col1><col2>bar</col2></table></dataset>";
private const string xml29 = @"<PersonalSite><License Name='Sum Wang' Email='sumwang@somewhere.net' Mode='Trial' StartDate='01/01/2004' Serial='aaa' /></PersonalSite>";
private const string diff1 = @"<diffgr:diffgram xmlns:msdata='urn:schemas-microsoft-com:xml-msdata' xmlns:diffgr='urn:schemas-microsoft-com:xml-diffgram-v1'>
<NewDataSet>
<Table1 diffgr:id='Table11' msdata:rowOrder='0' diffgr:hasChanges='inserted'>
<Column1_1>ppp</Column1_1>
<Column1_2>www</Column1_2>
<Column1_3>xxx</Column1_3>
</Table1>
</NewDataSet>
</diffgr:diffgram>";
private const string diff2 = diff1 + xml8;
private const string schema1 = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:element name='Root'>
<xs:complexType>
<xs:sequence>
<xs:element name='Child' type='xs:string' />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>";
private const string schema2 = schema1 + xml8;
[Fact]
public void ReadSimpleAuto()
{
DataSet ds;
// empty XML
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "EmptyString", xml1,
XmlReadMode.Auto, XmlReadMode.Auto,
"NewDataSet", 0);
// simple element
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "EmptyElement", xml2,
XmlReadMode.Auto, XmlReadMode.InferSchema,
"root", 0);
// simple element2
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "StartEndTag", xml3,
XmlReadMode.Auto, XmlReadMode.InferSchema,
"root", 0);
// whitespace in simple element
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "Whitespace", xml4,
XmlReadMode.Auto, XmlReadMode.InferSchema,
"root", 0);
// text in simple element
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "SingleText", xml5,
XmlReadMode.Auto, XmlReadMode.InferSchema,
"root", 0);
// simple table pattern:
// root becomes a table and test becomes a column.
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "SimpleTable", xml6,
XmlReadMode.Auto, XmlReadMode.InferSchema,
"NewDataSet", 1);
DataSetAssertion.AssertDataTable("xml6", ds.Tables[0], "root", 1, 1, 0, 0, 0, 0);
// simple table with 2 columns:
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "SimpleTable2", xml7,
XmlReadMode.Auto, XmlReadMode.InferSchema,
"NewDataSet", 1);
DataSetAssertion.AssertDataTable("xml7", ds.Tables[0], "root", 2, 1, 0, 0, 0, 0);
// simple dataset with 1 table:
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "SimpleDataSet", xml8,
XmlReadMode.Auto, XmlReadMode.InferSchema,
"dataset", 1);
DataSetAssertion.AssertDataTable("xml8", ds.Tables[0], "table", 2, 1, 0, 0, 0, 0);
}
[Fact]
public void ReadSimpleDiffgram()
{
DataSet ds;
// empty XML
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "EmptyString", xml1,
XmlReadMode.DiffGram, XmlReadMode.DiffGram,
"NewDataSet", 0);
// simple element
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "EmptyElement", xml2,
XmlReadMode.DiffGram, XmlReadMode.DiffGram,
"NewDataSet", 0);
// simple element2
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "StartEndTag", xml3,
XmlReadMode.DiffGram, XmlReadMode.DiffGram,
"NewDataSet", 0);
// whitespace in simple element
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "Whitespace", xml4,
XmlReadMode.DiffGram, XmlReadMode.DiffGram,
"NewDataSet", 0);
// text in simple element
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "SingleText", xml5,
XmlReadMode.DiffGram, XmlReadMode.DiffGram,
"NewDataSet", 0);
// simple table pattern:
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "SimpleTable", xml6,
XmlReadMode.DiffGram, XmlReadMode.DiffGram,
"NewDataSet", 0);
// simple table with 2 columns:
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "SimpleTable2", xml7,
XmlReadMode.DiffGram, XmlReadMode.DiffGram,
"NewDataSet", 0);
// simple dataset with 1 table:
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "SimpleDataSet", xml8,
XmlReadMode.DiffGram, XmlReadMode.DiffGram,
"NewDataSet", 0);
}
[Fact]
public void ReadSimpleFragment()
{
DataSet ds;
// empty XML
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "EmptyString", xml1,
XmlReadMode.Fragment, XmlReadMode.Fragment,
"NewDataSet", 0);
// simple element
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "EmptyElement", xml2,
XmlReadMode.Fragment, XmlReadMode.Fragment,
"NewDataSet", 0);
// simple element2
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "StartEndTag", xml3,
XmlReadMode.Fragment, XmlReadMode.Fragment,
"NewDataSet", 0);
// whitespace in simple element
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "Whitespace", xml4,
XmlReadMode.Fragment, XmlReadMode.Fragment,
"NewDataSet", 0);
// text in simple element
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "SingleText", xml5,
XmlReadMode.Fragment, XmlReadMode.Fragment,
"NewDataSet", 0);
// simple table pattern:
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "SimpleTable", xml6,
XmlReadMode.Fragment, XmlReadMode.Fragment,
"NewDataSet", 0);
// simple table with 2 columns:
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "SimpleTable2", xml7,
XmlReadMode.Fragment, XmlReadMode.Fragment,
"NewDataSet", 0);
// simple dataset with 1 table:
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "SimpleDataSet", xml8,
XmlReadMode.Fragment, XmlReadMode.Fragment,
"NewDataSet", 0);
}
[Fact]
public void ReadSimpleIgnoreSchema()
{
DataSet ds;
// empty XML
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "EmptyString", xml1,
XmlReadMode.IgnoreSchema, XmlReadMode.IgnoreSchema,
"NewDataSet", 0);
// simple element
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "EmptyElement", xml2,
XmlReadMode.IgnoreSchema, XmlReadMode.IgnoreSchema,
"NewDataSet", 0);
// simple element2
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "StartEndTag", xml3,
XmlReadMode.IgnoreSchema, XmlReadMode.IgnoreSchema,
"NewDataSet", 0);
// whitespace in simple element
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "Whitespace", xml4,
XmlReadMode.IgnoreSchema, XmlReadMode.IgnoreSchema,
"NewDataSet", 0);
// text in simple element
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "SingleText", xml5,
XmlReadMode.IgnoreSchema, XmlReadMode.IgnoreSchema,
"NewDataSet", 0);
// simple table pattern:
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "SimpleTable", xml6,
XmlReadMode.IgnoreSchema, XmlReadMode.IgnoreSchema,
"NewDataSet", 0);
// simple table with 2 columns:
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "SimpleTable2", xml7,
XmlReadMode.IgnoreSchema, XmlReadMode.IgnoreSchema,
"NewDataSet", 0);
// simple dataset with 1 table:
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "SimpleDataSet", xml8,
XmlReadMode.IgnoreSchema, XmlReadMode.IgnoreSchema,
"NewDataSet", 0);
}
[Fact]
public void ReadSimpleInferSchema()
{
DataSet ds;
// empty XML
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "EmptyString", xml1,
XmlReadMode.InferSchema, XmlReadMode.InferSchema,
"NewDataSet", 0);
// simple element
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "EmptyElement", xml2,
XmlReadMode.InferSchema, XmlReadMode.InferSchema,
"root", 0);
// simple element2
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "StartEndTag", xml3,
XmlReadMode.InferSchema, XmlReadMode.InferSchema,
"root", 0);
// whitespace in simple element
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "Whitespace", xml4,
XmlReadMode.InferSchema, XmlReadMode.InferSchema,
"root", 0);
// text in simple element
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "SingleText", xml5,
XmlReadMode.InferSchema, XmlReadMode.InferSchema,
"root", 0);
// simple table pattern:
// root becomes a table and test becomes a column.
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "SimpleTable", xml6,
XmlReadMode.InferSchema, XmlReadMode.InferSchema,
"NewDataSet", 1);
DataSetAssertion.AssertDataTable("xml6", ds.Tables[0], "root", 1, 1, 0, 0, 0, 0);
// simple table with 2 columns:
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "SimpleTable2", xml7,
XmlReadMode.InferSchema, XmlReadMode.InferSchema,
"NewDataSet", 1);
DataSetAssertion.AssertDataTable("xml7", ds.Tables[0], "root", 2, 1, 0, 0, 0, 0);
// simple dataset with 1 table:
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "SimpleDataSet", xml8,
XmlReadMode.InferSchema, XmlReadMode.InferSchema,
"dataset", 1);
DataSetAssertion.AssertDataTable("xml8", ds.Tables[0], "table", 2, 1, 0, 0, 0, 0);
}
[Fact]
public void ReadSimpleReadSchema()
{
DataSet ds;
// empty XML
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "EmptyString", xml1,
XmlReadMode.ReadSchema, XmlReadMode.ReadSchema,
"NewDataSet", 0);
// simple element
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "EmptyElement", xml2,
XmlReadMode.ReadSchema, XmlReadMode.ReadSchema,
"NewDataSet", 0);
// simple element2
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "StartEndTag", xml3,
XmlReadMode.ReadSchema, XmlReadMode.ReadSchema,
"NewDataSet", 0);
// whitespace in simple element
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "Whitespace", xml4,
XmlReadMode.ReadSchema, XmlReadMode.ReadSchema,
"NewDataSet", 0);
// text in simple element
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "SingleText", xml5,
XmlReadMode.ReadSchema, XmlReadMode.ReadSchema,
"NewDataSet", 0);
// simple table pattern:
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "SimpleTable", xml6,
XmlReadMode.ReadSchema, XmlReadMode.ReadSchema,
"NewDataSet", 0);
// simple table with 2 columns:
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "SimpleTable2", xml7,
XmlReadMode.ReadSchema, XmlReadMode.ReadSchema,
"NewDataSet", 0);
// simple dataset with 1 table:
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "SimpleDataSet", xml8,
XmlReadMode.ReadSchema, XmlReadMode.ReadSchema,
"NewDataSet", 0);
}
[Fact]
public void TestSimpleDiffXmlAll()
{
DataSet ds;
// ignored
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "Fragment", diff1,
XmlReadMode.Fragment, XmlReadMode.Fragment,
"NewDataSet", 0);
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "IgnoreSchema", diff1,
XmlReadMode.IgnoreSchema, XmlReadMode.IgnoreSchema,
"NewDataSet", 0);
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "InferSchema", diff1,
XmlReadMode.InferSchema, XmlReadMode.InferSchema,
"NewDataSet", 0);
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "ReadSchema", diff1,
XmlReadMode.ReadSchema, XmlReadMode.ReadSchema,
"NewDataSet", 0);
// Auto, DiffGram ... treated as DiffGram
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "Auto", diff1,
XmlReadMode.Auto, XmlReadMode.DiffGram,
"NewDataSet", 0);
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "DiffGram", diff1,
XmlReadMode.DiffGram, XmlReadMode.DiffGram,
"NewDataSet", 0);
}
[Fact]
public void TestSimpleDiffPlusContentAll()
{
DataSet ds;
// Fragment ... skipped
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "Fragment", diff2,
XmlReadMode.Fragment, XmlReadMode.Fragment,
"NewDataSet", 0);
// others ... kept
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "IgnoreSchema", diff2,
XmlReadMode.IgnoreSchema, XmlReadMode.IgnoreSchema,
"NewDataSet", 0, ReadState.Interactive);
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "InferSchema", diff2,
XmlReadMode.InferSchema, XmlReadMode.InferSchema,
"NewDataSet", 0, ReadState.Interactive);
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "ReadSchema", diff2,
XmlReadMode.ReadSchema, XmlReadMode.ReadSchema,
"NewDataSet", 0, ReadState.Interactive);
// Auto, DiffGram ... treated as DiffGram
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "Auto", diff2,
XmlReadMode.Auto, XmlReadMode.DiffGram,
"NewDataSet", 0, ReadState.Interactive);
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "DiffGram", diff2,
XmlReadMode.DiffGram, XmlReadMode.DiffGram,
"NewDataSet", 0, ReadState.Interactive);
}
[Fact]
public void TestSimpleSchemaXmlAll()
{
DataSet ds;
// ignored
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "IgnoreSchema", schema1,
XmlReadMode.IgnoreSchema, XmlReadMode.IgnoreSchema,
"NewDataSet", 0);
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "InferSchema", schema1,
XmlReadMode.InferSchema, XmlReadMode.InferSchema,
"NewDataSet", 0);
// misc ... consume schema
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "Fragment", schema1,
XmlReadMode.Fragment, XmlReadMode.Fragment,
"NewDataSet", 1);
DataSetAssertion.AssertDataTable("fragment", ds.Tables[0], "Root", 1, 0, 0, 0, 0, 0);
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "ReadSchema", schema1,
XmlReadMode.ReadSchema, XmlReadMode.ReadSchema,
"NewDataSet", 1);
DataSetAssertion.AssertDataTable("readschema", ds.Tables[0], "Root", 1, 0, 0, 0, 0, 0);
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "Auto", schema1,
XmlReadMode.Auto, XmlReadMode.ReadSchema,
"NewDataSet", 1);
DataSetAssertion.AssertDataTable("auto", ds.Tables[0], "Root", 1, 0, 0, 0, 0, 0);
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "DiffGram", schema1,
XmlReadMode.DiffGram, XmlReadMode.DiffGram,
"NewDataSet", 1);
}
[Fact]
public void TestSimpleSchemaPlusContentAll()
{
DataSet ds;
// ignored
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "IgnoreSchema", schema2,
XmlReadMode.IgnoreSchema, XmlReadMode.IgnoreSchema,
"NewDataSet", 0, ReadState.Interactive);
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "InferSchema", schema2,
XmlReadMode.InferSchema, XmlReadMode.InferSchema,
"NewDataSet", 0, ReadState.Interactive);
// Fragment ... consumed both
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "Fragment", schema2,
XmlReadMode.Fragment, XmlReadMode.Fragment,
"NewDataSet", 1);
DataSetAssertion.AssertDataTable("fragment", ds.Tables[0], "Root", 1, 0, 0, 0, 0, 0);
// rest ... treated as schema
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "Auto", schema2,
XmlReadMode.Auto, XmlReadMode.ReadSchema,
"NewDataSet", 1, ReadState.Interactive);
DataSetAssertion.AssertDataTable("auto", ds.Tables[0], "Root", 1, 0, 0, 0, 0, 0);
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "DiffGram", schema2,
XmlReadMode.DiffGram, XmlReadMode.DiffGram,
"NewDataSet", 1, ReadState.Interactive);
DataSetAssertion.AssertDataTable("diffgram", ds.Tables[0], "Root", 1, 0, 0, 0, 0, 0);
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "ReadSchema", schema2,
XmlReadMode.ReadSchema, XmlReadMode.ReadSchema,
"NewDataSet", 1, ReadState.Interactive);
}
[Fact]
public void SequentialRead1()
{
// simple element -> simple table
var ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "SingleText", xml5,
XmlReadMode.Auto, XmlReadMode.InferSchema,
"root", 0);
DataSetAssertion.AssertReadXml(ds, "SimpleTable", xml6,
XmlReadMode.Auto, XmlReadMode.InferSchema,
"NewDataSet", 1);
DataSetAssertion.AssertDataTable("seq1", ds.Tables[0], "root", 1, 1, 0, 0, 0, 0);
}
[Fact]
public void SequentialRead2()
{
// simple element -> simple dataset
var ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "SingleText", xml5,
XmlReadMode.Auto, XmlReadMode.InferSchema,
"root", 0);
DataSetAssertion.AssertReadXml(ds, "SimpleTable2", xml7,
XmlReadMode.Auto, XmlReadMode.InferSchema,
"NewDataSet", 1);
DataSetAssertion.AssertDataTable("#1", ds.Tables[0], "root", 2, 1, 0, 0, 0, 0);
// simple table -> simple dataset
ds = new DataSet();
DataSetAssertion.AssertReadXml(ds, "SimpleTable", xml6,
XmlReadMode.Auto, XmlReadMode.InferSchema,
"NewDataSet", 1);
DataSetAssertion.AssertDataTable("#2", ds.Tables[0], "root", 1, 1, 0, 0, 0, 0);
// Return value became IgnoreSchema, since there is
// already schema information in the dataset.
// Columns are kept 1 as old table holds.
// Rows are up to 2 because of accumulative read.
DataSetAssertion.AssertReadXml(ds, "SimpleTable2-2", xml7,
XmlReadMode.Auto, XmlReadMode.IgnoreSchema,
"NewDataSet", 1);
DataSetAssertion.AssertDataTable("#3", ds.Tables[0], "root", 1, 2, 0, 0, 0, 0);
}
[Fact]
public void ReadComplexElementDocument()
{
var ds = new DataSet();
ds.ReadXml(new StringReader(xml29));
}
[Fact]
public void IgnoreSchemaShouldFillData()
{
// no such dataset
string xml1 = "<set><tab><col>test</col></tab></set>";
// no wrapper element
string xml2 = "<tab><col>test</col></tab>";
// no such table
string xml3 = "<tar><col>test</col></tar>";
var ds = new DataSet();
DataTable dt = new DataTable("tab");
ds.Tables.Add(dt);
dt.Columns.Add("col");
ds.ReadXml(new StringReader(xml1), XmlReadMode.IgnoreSchema);
DataSetAssertion.AssertDataSet("ds", ds, "NewDataSet", 1, 0);
Assert.Equal(1, dt.Rows.Count);
dt.Clear();
ds.ReadXml(new StringReader(xml2), XmlReadMode.IgnoreSchema);
Assert.Equal(1, dt.Rows.Count);
dt.Clear();
ds.ReadXml(new StringReader(xml3), XmlReadMode.IgnoreSchema);
Assert.Equal(0, dt.Rows.Count);
}
[Fact]
public void NameConflictDSAndTable()
{
string xml = @"<PriceListDetails>
<PriceListList>
<Id>1</Id>
</PriceListList>
<PriceListDetails>
<Id>1</Id>
<Status>0</Status>
</PriceListDetails>
</PriceListDetails>";
var ds = new DataSet();
ds.ReadXml(new StringReader(xml));
Assert.NotNull(ds.Tables["PriceListDetails"]);
}
[Fact]
public void ColumnOrder()
{
string xml = "<?xml version=\"1.0\" standalone=\"yes\"?>" +
"<NewDataSet>" +
" <Table>" +
" <Name>Miguel</Name>" +
" <FirstName>de Icaza</FirstName>" +
" <Income>4000</Income>" +
" </Table>" +
" <Table>" +
" <Name>25</Name>" +
" <FirstName>250</FirstName>" +
" <Address>Belgium</Address>" +
" <Income>5000</Income>" +
"</Table>" +
"</NewDataSet>";
var ds = new DataSet();
ds.ReadXml(new StringReader(xml));
Assert.Equal(1, ds.Tables.Count);
Assert.Equal("Table", ds.Tables[0].TableName);
Assert.Equal(4, ds.Tables[0].Columns.Count);
Assert.Equal("Name", ds.Tables[0].Columns[0].ColumnName);
Assert.Equal(0, ds.Tables[0].Columns[0].Ordinal);
Assert.Equal("FirstName", ds.Tables[0].Columns[1].ColumnName);
Assert.Equal(1, ds.Tables[0].Columns[1].Ordinal);
Assert.Equal("Address", ds.Tables[0].Columns[2].ColumnName);
Assert.Equal(2, ds.Tables[0].Columns[2].Ordinal);
Assert.Equal("Income", ds.Tables[0].Columns[3].ColumnName);
Assert.Equal(3, ds.Tables[0].Columns[3].Ordinal);
}
[Fact]
public void XmlSpace()
{
string xml = "<?xml version=\"1.0\" standalone=\"yes\"?>" +
"<NewDataSet>" +
" <Table>" +
" <Name>Miguel</Name>" +
" <FirstName xml:space=\"preserve\"> de Icaza</FirstName>" +
" <Income>4000</Income>" +
" </Table>" +
" <Table>" +
" <Name>Chris</Name>" +
" <FirstName xml:space=\"preserve\">Toshok </FirstName>" +
" <Income>3000</Income>" +
" </Table>" +
"</NewDataSet>";
var ds = new DataSet();
ds.ReadXml(new StringReader(xml));
Assert.Equal(1, ds.Tables.Count);
Assert.Equal("Table", ds.Tables[0].TableName);
Assert.Equal(3, ds.Tables[0].Columns.Count);
Assert.Equal("Name", ds.Tables[0].Columns[0].ColumnName);
Assert.Equal(0, ds.Tables[0].Columns[0].Ordinal);
Assert.Equal("FirstName", ds.Tables[0].Columns[1].ColumnName);
Assert.Equal(1, ds.Tables[0].Columns[1].Ordinal);
Assert.Equal("Income", ds.Tables[0].Columns[2].ColumnName);
Assert.Equal(2, ds.Tables[0].Columns[2].Ordinal);
}
[Fact]
public void TestSameParentChildName()
{
string xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><resource type=\"parent\">" +
"<resource type=\"child\" /></resource>";
var ds = new DataSet();
ds.ReadXml(new StringReader(xml));
DataSetAssertion.AssertReadXml(ds, "SameNameParentChild", xml,
XmlReadMode.Auto, XmlReadMode.IgnoreSchema,
"NewDataSet", 1);
}
[Fact]
public void TestSameColumnName()
{
string xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><resource resource_Id_0=\"parent\">" +
"<resource resource_Id_0=\"child\" /></resource>";
var ds = new DataSet();
ds.ReadXml(new StringReader(xml));
DataSetAssertion.AssertReadXml(ds, "SameColumnName", xml,
XmlReadMode.Auto, XmlReadMode.IgnoreSchema,
"NewDataSet", 1);
}
[Fact]
public void DataSetExtendedPropertiesTest()
{
DataSet dataSet1 = new DataSet();
dataSet1.ExtendedProperties.Add("DS1", "extended0");
DataTable table = new DataTable("TABLE1");
table.ExtendedProperties.Add("T1", "extended1");
table.Columns.Add("C1", typeof(int));
table.Columns.Add("C2", typeof(string));
table.Columns[1].MaxLength = 20;
table.Columns[0].ExtendedProperties.Add("C1Ext1", "extended2");
table.Columns[1].ExtendedProperties.Add("C2Ext1", "extended3");
dataSet1.Tables.Add(table);
table.LoadDataRow(new object[] { 1, "One" }, false);
table.LoadDataRow(new object[] { 2, "Two" }, false);
string file = Path.Combine(Path.GetTempPath(), "schemas-test.xml");
try
{
dataSet1.WriteXml(file, XmlWriteMode.WriteSchema);
}
catch (Exception ex)
{
Assert.False(true);
}
finally
{
File.Delete(file);
}
DataSet dataSet2 = new DataSet();
dataSet2.ReadXml(new StringReader(
@"<?xml version=""1.0"" standalone=""yes""?>
<NewDataSet>
<xs:schema id=""NewDataSet"" xmlns=""""
xmlns:xs=""http://www.w3.org/2001/XMLSchema""
xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata""
xmlns:msprop=""urn:schemas-microsoft-com:xml-msprop"">
<xs:element name=""NewDataSet"" msdata:IsDataSet=""true""
msdata:UseCurrentLocale=""true"" msprop:DS1=""extended0"">
<xs:complexType>
<xs:choice minOccurs=""0"" maxOccurs=""unbounded"">
<xs:element name=""TABLE1"" msprop:T1=""extended1"">
<xs:complexType>
<xs:sequence>
<xs:element name=""C1"" type=""xs:int"" minOccurs=""0""
msprop:C1Ext1=""extended2"" />
<xs:element name=""C2"" type=""xs:string"" minOccurs=""0""
msprop:C2Ext1=""extended3"" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
<TABLE1>
<C1>1</C1>
<C2>One</C2>
</TABLE1>
<TABLE1>
<C1>2</C1>
<C2>Two</C2>
</TABLE1>
</NewDataSet>"), XmlReadMode.ReadSchema);
Assert.Equal(dataSet1.ExtendedProperties["DS1"], dataSet2.ExtendedProperties["DS1"]);
Assert.Equal(dataSet1.Tables[0].ExtendedProperties["T1"], dataSet2.Tables[0].ExtendedProperties["T1"]);
Assert.Equal(dataSet1.Tables[0].Columns[0].ExtendedProperties["C1Ext1"],
dataSet2.Tables[0].Columns[0].ExtendedProperties["C1Ext1"]);
Assert.Equal(dataSet1.Tables[0].Columns[1].ExtendedProperties["C2Ext1"],
dataSet2.Tables[0].Columns[1].ExtendedProperties["C2Ext1"]);
}
}
}
| 39.592953 | 176 | 0.540954 | [
"MIT"
] | Mattlk13/corefx | src/System.Data.Common/tests/System/Data/DataSetReadXmlTest.cs | 32,585 | C# |
using System.Windows.Media.Effects;
namespace Paint.Effects
{
public class ReflectEffect : BlendEffect
{
static PixelShader pixelShader = new PixelShader();
static ReflectEffect()
{
pixelShader.UriSource = Resource(nameof(ReflectEffect));
}
public ReflectEffect()
{
PixelShader = pixelShader;
}
}
}
| 19 | 68 | 0.618421 | [
"BSD-2-Clause"
] | lwFace/Imagin.NET | Apps.Paint/Effects/Blend/ReflectEffect.cs | 382 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.Media.Playback
{
#if false || false || NET461 || __WASM__ || false
[global::Uno.NotImplemented]
#endif
public partial class MediaPlaybackSession
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::Windows.Media.MediaProperties.StereoscopicVideoPackingMode StereoscopicVideoPackingMode
{
get
{
throw new global::System.NotImplementedException("The member StereoscopicVideoPackingMode MediaPlaybackSession.StereoscopicVideoPackingMode is not implemented in Uno.");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "StereoscopicVideoPackingMode MediaPlaybackSession.StereoscopicVideoPackingMode");
}
}
#endif
#if false || false || NET461 || __WASM__ || false
[global::Uno.NotImplemented]
public global::System.TimeSpan Position
{
get
{
throw new global::System.NotImplementedException("The member TimeSpan MediaPlaybackSession.Position is not implemented in Uno.");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "TimeSpan MediaPlaybackSession.Position");
}
}
#endif
#if false || false || NET461 || __WASM__ || false
[global::Uno.NotImplemented]
public double PlaybackRate
{
get
{
throw new global::System.NotImplementedException("The member double MediaPlaybackSession.PlaybackRate is not implemented in Uno.");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "double MediaPlaybackSession.PlaybackRate");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::Windows.Foundation.Rect NormalizedSourceRect
{
get
{
throw new global::System.NotImplementedException("The member Rect MediaPlaybackSession.NormalizedSourceRect is not implemented in Uno.");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "Rect MediaPlaybackSession.NormalizedSourceRect");
}
}
#endif
#if false || false || NET461 || __WASM__ || false
[global::Uno.NotImplemented]
public double BufferingProgress
{
get
{
throw new global::System.NotImplementedException("The member double MediaPlaybackSession.BufferingProgress is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public bool CanPause
{
get
{
throw new global::System.NotImplementedException("The member bool MediaPlaybackSession.CanPause is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public bool CanSeek
{
get
{
throw new global::System.NotImplementedException("The member bool MediaPlaybackSession.CanSeek is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public double DownloadProgress
{
get
{
throw new global::System.NotImplementedException("The member double MediaPlaybackSession.DownloadProgress is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public bool IsProtected
{
get
{
throw new global::System.NotImplementedException("The member bool MediaPlaybackSession.IsProtected is not implemented in Uno.");
}
}
#endif
#if false || false || NET461 || __WASM__ || false
[global::Uno.NotImplemented]
public global::Windows.Media.Playback.MediaPlayer MediaPlayer
{
get
{
throw new global::System.NotImplementedException("The member MediaPlayer MediaPlaybackSession.MediaPlayer is not implemented in Uno.");
}
}
#endif
#if false || false || NET461 || __WASM__ || false
[global::Uno.NotImplemented]
public global::System.TimeSpan NaturalDuration
{
get
{
throw new global::System.NotImplementedException("The member TimeSpan MediaPlaybackSession.NaturalDuration is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public uint NaturalVideoHeight
{
get
{
throw new global::System.NotImplementedException("The member uint MediaPlaybackSession.NaturalVideoHeight is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public uint NaturalVideoWidth
{
get
{
throw new global::System.NotImplementedException("The member uint MediaPlaybackSession.NaturalVideoWidth is not implemented in Uno.");
}
}
#endif
#if false || false || NET461 || __WASM__ || false
[global::Uno.NotImplemented]
public global::Windows.Media.Playback.MediaPlaybackState PlaybackState
{
get
{
throw new global::System.NotImplementedException("The member MediaPlaybackState MediaPlaybackSession.PlaybackState is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public bool IsMirroring
{
get
{
throw new global::System.NotImplementedException("The member bool MediaPlaybackSession.IsMirroring is not implemented in Uno.");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "bool MediaPlaybackSession.IsMirroring");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::Windows.Media.Playback.MediaPlaybackSphericalVideoProjection SphericalVideoProjection
{
get
{
throw new global::System.NotImplementedException("The member MediaPlaybackSphericalVideoProjection MediaPlaybackSession.SphericalVideoProjection is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::Windows.Media.MediaProperties.MediaRotation PlaybackRotation
{
get
{
throw new global::System.NotImplementedException("The member MediaRotation MediaPlaybackSession.PlaybackRotation is not implemented in Uno.");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "MediaRotation MediaPlaybackSession.PlaybackRotation");
}
}
#endif
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.PlaybackStateChanged.add
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.PlaybackStateChanged.remove
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.PlaybackRateChanged.add
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.PlaybackRateChanged.remove
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.SeekCompleted.add
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.SeekCompleted.remove
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.BufferingStarted.add
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.BufferingStarted.remove
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.BufferingEnded.add
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.BufferingEnded.remove
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.BufferingProgressChanged.add
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.BufferingProgressChanged.remove
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.DownloadProgressChanged.add
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.DownloadProgressChanged.remove
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.NaturalDurationChanged.add
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.NaturalDurationChanged.remove
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.PositionChanged.add
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.PositionChanged.remove
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.NaturalVideoSizeChanged.add
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.NaturalVideoSizeChanged.remove
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.MediaPlayer.get
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.NaturalDuration.get
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.Position.get
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.Position.set
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.PlaybackState.get
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.CanSeek.get
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.CanPause.get
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.IsProtected.get
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.PlaybackRate.get
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.PlaybackRate.set
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.BufferingProgress.get
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.DownloadProgress.get
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.NaturalVideoHeight.get
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.NaturalVideoWidth.get
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.NormalizedSourceRect.get
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.NormalizedSourceRect.set
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.StereoscopicVideoPackingMode.get
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.StereoscopicVideoPackingMode.set
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.BufferedRangesChanged.add
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.BufferedRangesChanged.remove
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.PlayedRangesChanged.add
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.PlayedRangesChanged.remove
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.SeekableRangesChanged.add
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.SeekableRangesChanged.remove
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.SupportedPlaybackRatesChanged.add
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.SupportedPlaybackRatesChanged.remove
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.SphericalVideoProjection.get
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.IsMirroring.get
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.IsMirroring.set
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::System.Collections.Generic.IReadOnlyList<global::Windows.Media.MediaTimeRange> GetBufferedRanges()
{
throw new global::System.NotImplementedException("The member IReadOnlyList<MediaTimeRange> MediaPlaybackSession.GetBufferedRanges() is not implemented in Uno.");
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::System.Collections.Generic.IReadOnlyList<global::Windows.Media.MediaTimeRange> GetPlayedRanges()
{
throw new global::System.NotImplementedException("The member IReadOnlyList<MediaTimeRange> MediaPlaybackSession.GetPlayedRanges() is not implemented in Uno.");
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::System.Collections.Generic.IReadOnlyList<global::Windows.Media.MediaTimeRange> GetSeekableRanges()
{
throw new global::System.NotImplementedException("The member IReadOnlyList<MediaTimeRange> MediaPlaybackSession.GetSeekableRanges() is not implemented in Uno.");
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public bool IsSupportedPlaybackRateRange( double rate1, double rate2)
{
throw new global::System.NotImplementedException("The member bool MediaPlaybackSession.IsSupportedPlaybackRateRange(double rate1, double rate2) is not implemented in Uno.");
}
#endif
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.PlaybackRotation.get
// Forced skipping of method Windows.Media.Playback.MediaPlaybackSession.PlaybackRotation.set
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::Windows.Media.Playback.MediaPlaybackSessionOutputDegradationPolicyState GetOutputDegradationPolicyState()
{
throw new global::System.NotImplementedException("The member MediaPlaybackSessionOutputDegradationPolicyState MediaPlaybackSession.GetOutputDegradationPolicyState() is not implemented in Uno.");
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public event global::Windows.Foundation.TypedEventHandler<global::Windows.Media.Playback.MediaPlaybackSession, object> BufferingEnded
{
[global::Uno.NotImplemented]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "event TypedEventHandler<MediaPlaybackSession, object> MediaPlaybackSession.BufferingEnded");
}
[global::Uno.NotImplemented]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "event TypedEventHandler<MediaPlaybackSession, object> MediaPlaybackSession.BufferingEnded");
}
}
#endif
#if false || false || NET461 || __WASM__ || false
[global::Uno.NotImplemented]
public event global::Windows.Foundation.TypedEventHandler<global::Windows.Media.Playback.MediaPlaybackSession, object> BufferingProgressChanged
{
[global::Uno.NotImplemented]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "event TypedEventHandler<MediaPlaybackSession, object> MediaPlaybackSession.BufferingProgressChanged");
}
[global::Uno.NotImplemented]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "event TypedEventHandler<MediaPlaybackSession, object> MediaPlaybackSession.BufferingProgressChanged");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public event global::Windows.Foundation.TypedEventHandler<global::Windows.Media.Playback.MediaPlaybackSession, object> BufferingStarted
{
[global::Uno.NotImplemented]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "event TypedEventHandler<MediaPlaybackSession, object> MediaPlaybackSession.BufferingStarted");
}
[global::Uno.NotImplemented]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "event TypedEventHandler<MediaPlaybackSession, object> MediaPlaybackSession.BufferingStarted");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public event global::Windows.Foundation.TypedEventHandler<global::Windows.Media.Playback.MediaPlaybackSession, object> DownloadProgressChanged
{
[global::Uno.NotImplemented]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "event TypedEventHandler<MediaPlaybackSession, object> MediaPlaybackSession.DownloadProgressChanged");
}
[global::Uno.NotImplemented]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "event TypedEventHandler<MediaPlaybackSession, object> MediaPlaybackSession.DownloadProgressChanged");
}
}
#endif
#if false || false || NET461 || __WASM__ || false
[global::Uno.NotImplemented]
public event global::Windows.Foundation.TypedEventHandler<global::Windows.Media.Playback.MediaPlaybackSession, object> NaturalDurationChanged
{
[global::Uno.NotImplemented]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "event TypedEventHandler<MediaPlaybackSession, object> MediaPlaybackSession.NaturalDurationChanged");
}
[global::Uno.NotImplemented]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "event TypedEventHandler<MediaPlaybackSession, object> MediaPlaybackSession.NaturalDurationChanged");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public event global::Windows.Foundation.TypedEventHandler<global::Windows.Media.Playback.MediaPlaybackSession, object> NaturalVideoSizeChanged
{
[global::Uno.NotImplemented]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "event TypedEventHandler<MediaPlaybackSession, object> MediaPlaybackSession.NaturalVideoSizeChanged");
}
[global::Uno.NotImplemented]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "event TypedEventHandler<MediaPlaybackSession, object> MediaPlaybackSession.NaturalVideoSizeChanged");
}
}
#endif
#if false || false || NET461 || __WASM__ || false
[global::Uno.NotImplemented]
public event global::Windows.Foundation.TypedEventHandler<global::Windows.Media.Playback.MediaPlaybackSession, object> PlaybackRateChanged
{
[global::Uno.NotImplemented]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "event TypedEventHandler<MediaPlaybackSession, object> MediaPlaybackSession.PlaybackRateChanged");
}
[global::Uno.NotImplemented]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "event TypedEventHandler<MediaPlaybackSession, object> MediaPlaybackSession.PlaybackRateChanged");
}
}
#endif
#if false || false || NET461 || __WASM__ || false
[global::Uno.NotImplemented]
public event global::Windows.Foundation.TypedEventHandler<global::Windows.Media.Playback.MediaPlaybackSession, object> PlaybackStateChanged
{
[global::Uno.NotImplemented]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "event TypedEventHandler<MediaPlaybackSession, object> MediaPlaybackSession.PlaybackStateChanged");
}
[global::Uno.NotImplemented]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "event TypedEventHandler<MediaPlaybackSession, object> MediaPlaybackSession.PlaybackStateChanged");
}
}
#endif
#if false || false || NET461 || __WASM__ || false
[global::Uno.NotImplemented]
public event global::Windows.Foundation.TypedEventHandler<global::Windows.Media.Playback.MediaPlaybackSession, object> PositionChanged
{
[global::Uno.NotImplemented]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "event TypedEventHandler<MediaPlaybackSession, object> MediaPlaybackSession.PositionChanged");
}
[global::Uno.NotImplemented]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "event TypedEventHandler<MediaPlaybackSession, object> MediaPlaybackSession.PositionChanged");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public event global::Windows.Foundation.TypedEventHandler<global::Windows.Media.Playback.MediaPlaybackSession, object> SeekCompleted
{
[global::Uno.NotImplemented]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "event TypedEventHandler<MediaPlaybackSession, object> MediaPlaybackSession.SeekCompleted");
}
[global::Uno.NotImplemented]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "event TypedEventHandler<MediaPlaybackSession, object> MediaPlaybackSession.SeekCompleted");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public event global::Windows.Foundation.TypedEventHandler<global::Windows.Media.Playback.MediaPlaybackSession, object> BufferedRangesChanged
{
[global::Uno.NotImplemented]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "event TypedEventHandler<MediaPlaybackSession, object> MediaPlaybackSession.BufferedRangesChanged");
}
[global::Uno.NotImplemented]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "event TypedEventHandler<MediaPlaybackSession, object> MediaPlaybackSession.BufferedRangesChanged");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public event global::Windows.Foundation.TypedEventHandler<global::Windows.Media.Playback.MediaPlaybackSession, object> PlayedRangesChanged
{
[global::Uno.NotImplemented]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "event TypedEventHandler<MediaPlaybackSession, object> MediaPlaybackSession.PlayedRangesChanged");
}
[global::Uno.NotImplemented]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "event TypedEventHandler<MediaPlaybackSession, object> MediaPlaybackSession.PlayedRangesChanged");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public event global::Windows.Foundation.TypedEventHandler<global::Windows.Media.Playback.MediaPlaybackSession, object> SeekableRangesChanged
{
[global::Uno.NotImplemented]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "event TypedEventHandler<MediaPlaybackSession, object> MediaPlaybackSession.SeekableRangesChanged");
}
[global::Uno.NotImplemented]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "event TypedEventHandler<MediaPlaybackSession, object> MediaPlaybackSession.SeekableRangesChanged");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public event global::Windows.Foundation.TypedEventHandler<global::Windows.Media.Playback.MediaPlaybackSession, object> SupportedPlaybackRatesChanged
{
[global::Uno.NotImplemented]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "event TypedEventHandler<MediaPlaybackSession, object> MediaPlaybackSession.SupportedPlaybackRatesChanged");
}
[global::Uno.NotImplemented]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Playback.MediaPlaybackSession", "event TypedEventHandler<MediaPlaybackSession, object> MediaPlaybackSession.SupportedPlaybackRatesChanged");
}
}
#endif
}
}
| 48.587209 | 233 | 0.787164 | [
"Apache-2.0"
] | jabak/uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Media.Playback/MediaPlaybackSession.cs | 25,071 | C# |
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEditor.Build.Reporting;
using UnityEngine;
namespace com.lenovo.thinkreality.ipd
{
public class BuildSlave
{
static string GAME_NAME = "ipdsetting";
static string VERSION = Application.version;
public static string APP_FOLDER = Directory.GetCurrentDirectory();
public static string ANDROID_FOLDER = string.Format("{0}/Builds/Android/", APP_FOLDER);
public static string ANDROID_DEVELOPMENT_FILE =
string.Format("{0}/Builds/Android/{1}.{2}.development.apk", APP_FOLDER, GAME_NAME, VERSION);
public static string ANDROID_RELEASE_FILE =
string.Format("{0}/Builds/Android/{1}.{2}.release.apk", APP_FOLDER, GAME_NAME, VERSION);
[MenuItem("Lenovo/Export Android APK")]
public static void ExportAndroidAPK()
{
AndroidRelease();
}
static void AndroidDevelopment()
{
// PlayerSettings.SetScriptingBackend (BuildTargetGroup.Android, ScriptingImplementation.IL2CPP);
PlayerSettings.SetScriptingBackend(BuildTargetGroup.Android, ScriptingImplementation.Mono2x);
// PlayerSettings.SetScriptingDefineSymbolsForGroup (BuildTargetGroup.Android, "DEV");
EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTargetGroup.Android, BuildTarget.Android);
// EditorUserBuildSettings.development = true;
// EditorUserBuildSettings.androidETC2Fallback = AndroidETC2Fallback.Quality32Bit;
BuildReport report = BuildPipeline.BuildPlayer(GetScenes(), ANDROID_DEVELOPMENT_FILE, BuildTarget.Android,
BuildOptions.None);
int code = (report.summary.result == BuildResult.Succeeded) ? 0 : 1;
// EditorApplication.Exit (code);
}
static void AndroidRelease()
{
BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions();
buildPlayerOptions.scenes = GetScenes();
buildPlayerOptions.locationPathName = "ipdsetting";
buildPlayerOptions.target = BuildTarget.Android;
buildPlayerOptions.options = BuildOptions.None;
BuildReport report = BuildPipeline.BuildPlayer(buildPlayerOptions);
BuildSummary summary = report.summary;
if (summary.result == BuildResult.Succeeded)
{
Debug.Log("Build succeeded: " + summary.totalSize + " bytes");
}
if (summary.result == BuildResult.Failed)
{
Debug.Log("Build failed");
}
}
static string[] GetScenes()
{
List<string> scenes = new List<string>();
for (int i = 0; i < EditorBuildSettings.scenes.Length; i++)
{
if (EditorBuildSettings.scenes[i].enabled)
{
scenes.Add(EditorBuildSettings.scenes[i].path);
}
}
return scenes.ToArray();
}
}
} | 38.75 | 118 | 0.630645 | [
"MIT"
] | iwentao/UnityGitTemplate | Assets/Scripts/Editor/BuildSlave.cs | 3,100 | C# |
// Copyright (c) 2012, Event Store LLP
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the Event Store LLP nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Diagnostics;
using System.IO;
using EventStore.Common.Utils;
using EventStore.Core.TransactionLog.Chunks.TFChunk;
namespace EventStore.Core.TransactionLog.Chunks
{
public class TFChunkBulkReader : IDisposable
{
public TFChunk.TFChunk Chunk { get { return _chunk; } }
internal Stream Stream { get { return _stream; } }
private readonly TFChunk.TFChunk _chunk;
private readonly Stream _stream;
private bool _disposed;
internal TFChunkBulkReader(TFChunk.TFChunk chunk, Stream streamToUse)
{
Ensure.NotNull(chunk, "chunk");
Ensure.NotNull(streamToUse, "stream");
_chunk = chunk;
_stream = streamToUse;
}
~TFChunkBulkReader()
{
Dispose();
}
public void SetRawPosition(int rawPosition)
{
if (rawPosition >= _stream.Length)
throw new ArgumentOutOfRangeException("rawPosition", string.Format("Raw position {0} is out of bounds.", rawPosition));
_stream.Position = rawPosition;
}
public void SetDataPosition(long dataPosition)
{
var rawPos = dataPosition + ChunkHeader.Size;
if (rawPos >= _stream.Length)
throw new ArgumentOutOfRangeException("dataPosition", string.Format("Data position {0} is out of bounds.", dataPosition));
_stream.Position = rawPos;
}
public void Release()
{
_stream.Close();
_stream.Dispose();
_disposed = true;
_chunk.ReleaseReader(this);
}
public BulkReadResult ReadNextRawBytes(int count, byte[] buffer)
{
Ensure.NotNull(buffer, "buffer");
Ensure.Nonnegative(count, "count");
if (count > buffer.Length)
count = buffer.Length;
var oldPos = (int)_stream.Position;
int bytesRead = _stream.Read(buffer, 0, count);
return new BulkReadResult(oldPos, bytesRead, isEof: _stream.Length == _stream.Position);
}
public BulkReadResult ReadNextDataBytes(int count, byte[] buffer)
{
Ensure.NotNull(buffer, "buffer");
Ensure.Nonnegative(count, "count");
if (_stream.Position == 0)
_stream.Position = ChunkHeader.Size;
if (count > buffer.Length)
count = buffer.Length;
var oldPos = (int)_stream.Position - ChunkHeader.Size;
var toRead = Math.Min(_chunk.PhysicalDataSize - oldPos, count);
Debug.Assert(toRead >= 0);
_stream.Position = _stream.Position; // flush read buffer
int bytesRead = _stream.Read(buffer, 0, toRead);
return new BulkReadResult(oldPos,
bytesRead,
isEof: _chunk.IsReadOnly && oldPos + bytesRead == _chunk.PhysicalDataSize);
}
public void Dispose()
{
if(_disposed)
return;
Release();
GC.SuppressFinalize(this);
}
}
} | 38.290323 | 138 | 0.637953 | [
"BSD-3-Clause"
] | ianbattersby/EventStore | src/EventStore/EventStore.Core/TransactionLog/Chunks/TFChunkBulkReader.cs | 4,748 | C# |
//[?] 컬렉션 이니셜라이저(C# 3.0 특징)
using System;
using System.Collections.Generic;
class Choice
{
public int Id { get; set; }
public string ChoiceText { get; set; }
public bool IsAnswer { get; set; }
}
class CollectionInitializer
{
static void Main()
{
List<Choice> choices = new List<Choice>() {
new Choice() { Id = 1, ChoiceText = "1", IsAnswer = false },
new Choice() { Id = 2, ChoiceText = "2", IsAnswer = true },
new Choice() { Id = 3, ChoiceText = "3", IsAnswer = false }
};
Console.WriteLine("(문제) 1 + 1은?");
foreach (var c in choices)
{
Console.WriteLine($"{c.Id}: {c.ChoiceText} ({c.IsAnswer})");
}
}
}
| 26 | 72 | 0.537088 | [
"MIT"
] | VisualAcademy/DotNet | DotNet/DotNet/48_Generic/_/CollectionInitializer.cs | 758 | C# |
using MicroflowModels;
using System.Collections.Generic;
using System.Linq;
namespace MicroflowSDK
{
public static class StepsManager
{
public static void AddParentSteps(this Step step, params Step[] parents)
{
foreach (var parentStep in parents)
{
parentStep.SubSteps.Add(step.StepNumber);
}
}
public static void AddSubSteps(this Step step, params int[] subSteps)
{
foreach (var subStep in subSteps)
{
step.SubSteps.Add(subStep);
}
}
public static void AddSubStepRange(this Step step, List<Step> steps, int fromId, int toId)
{
List<Step> li = steps.FindAll(s => s.StepNumber >= fromId && s.StepNumber <= toId);
step.SubSteps.AddRange(from s in li select s.StepNumber);
}
public static void SetRetryForStep(this Step step, int delaySeconds = 5, int maxDelaySeconds = 60, int maxRetries = 5, int timeOutSeconds = 60, int backoffCoefficient = 1)
{
var retryOptions = new MicroflowRetryOptions()
{
DelaySeconds = delaySeconds,
MaxDelaySeconds = maxDelaySeconds,
MaxRetries = maxRetries,
TimeOutSeconds = timeOutSeconds,
BackoffCoefficient = backoffCoefficient
};
step.RetryOptions = retryOptions;
}
public static void SetRetryForSteps(int delaySeconds = 5, int maxDelaySeconds = 60, int maxRetries = 5, int timeOutSeconds = 30, int backoffCoefficient = 1, params Step[] steps)
{
var retryOptions = new MicroflowRetryOptions()
{
DelaySeconds = delaySeconds,
MaxDelaySeconds = maxDelaySeconds,
MaxRetries = maxRetries,
TimeOutSeconds = timeOutSeconds,
BackoffCoefficient = backoffCoefficient
};
foreach(var step in steps)
{
step.RetryOptions = retryOptions;
}
}
}
}
| 33.730159 | 185 | 0.573176 | [
"MIT"
] | andre-maree/Microflow | MicroflowSDK/StepsManager.cs | 2,127 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using DryIoc.UnitTests.CUT;
using NUnit.Framework;
using static FastExpressionCompiler.LightExpression.Expression;
namespace DryIoc.UnitTests
{
[TestFixture]
public class RulesTests
{
[Test]
public void Given_service_with_two_ctors_I_can_specify_what_ctor_to_choose_for_resolve()
{
var container = new Container();
container.Register(typeof(Bla<>), made: Made.Of(
t => t.GetConstructorOrNull(typeof(Func<>).MakeGenericType(t.GetGenericParamsAndArgs()[0]))));
container.Register(typeof(SomeService), typeof(SomeService));
var bla = container.Resolve<Bla<SomeService>>();
Assert.That(bla.Factory(), Is.InstanceOf<SomeService>());
}
[Test]
public void I_should_be_able_to_add_rule_to_resolve_not_registered_service()
{
var container = new Container(Rules.Default.WithUnknownServiceResolvers(request =>
!request.ServiceType.IsValueType() && !request.ServiceType.IsAbstract()
? new ReflectionFactory(request.ServiceType)
: null));
var service = container.Resolve<NotRegisteredService>();
Assert.That(service, Is.Not.Null);
}
[Test]
public void I_can_remove_rule_to_resolve_not_registered_service()
{
Rules.UnknownServiceResolver unknownServiceResolver = request =>
!request.ServiceType.IsValueType() && !request.ServiceType.IsAbstract()
? new ReflectionFactory(request.ServiceType)
: null;
IContainer container = new Container(Rules.Default.WithUnknownServiceResolvers(unknownServiceResolver));
Assert.IsNotNull(container.Resolve<NotRegisteredService>());
container = container
.With(rules => rules.WithoutUnknownServiceResolver(unknownServiceResolver))
.WithoutCache(); // Important to remove cache
Assert.IsNull(container.Resolve<NotRegisteredService>(IfUnresolved.ReturnDefault));
}
[Test]
public void I_can_add_rule_to_resolve_any_unknown_concrete_type()
{
IContainer container = new Container(
rules => rules.WithConcreteTypeDynamicRegistrations());
var x = container.Resolve<X>();
Assert.IsInstanceOf<X>(x);
Assert.IsInstanceOf<Y>(x.Dep);
}
[Test]
public void I_can_Not_resolve_unknown_concrete_type_on_specific_condition()
{
IContainer container = new Container(rules => rules
.WithConcreteTypeDynamicRegistrations((serviceType, _) => serviceType != typeof(X)));
Assert.Throws<ContainerException>(() =>
container.Resolve<X>());
}
[Test]
public void I_can_resolve_unknown_concrete_type_on_specific_condition()
{
IContainer container = new Container(rules => rules
.WithConcreteTypeDynamicRegistrations((serviceType, _) => serviceType != typeof(X)));
container.Register<X>(Reuse.Singleton);
var x = container.Resolve<X>();
Assert.IsInstanceOf<X>(x);
Assert.IsInstanceOf<Y>(x.Dep);
}
[Test]
public void Can_resolve_unknown_concrete_type_as_Func_with_required_type()
{
var container = new Container(rules => rules.WithConcreteTypeDynamicRegistrations());
var getX = container.Resolve<Func<Y, object>>(typeof(X));
var x = getX(new Y());
Assert.IsInstanceOf<X>(x);
}
[Test]
public void Cannot_resolve_unknown_concrete_type_as_Func_with_required_type()
{
var container = new Container(rules => rules.WithConcreteTypeDynamicRegistrations());
var getX = container.Resolve<Func<Y, object>>(typeof(A));
var x = getX(new Y());
Assert.IsInstanceOf<A>(x);
}
[Test]
public void Can_collect_unresolved_concrete_type_dependency()
{
var unresolvedTypes = new List<Type>();
var container = new Container(rules => rules
.WithConcreteTypeDynamicRegistrations()
.WithUnknownServiceHandler(req => unresolvedTypes.Add(req.ServiceType)));
var ex = Assert.Throws<ContainerException>(() =>
container.Resolve<Xx>());
Assert.AreEqual(Error.NameOf(Error.UnableToResolveFromRegisteredServices), Error.NameOf(ex.Error));
CollectionAssert.AreEqual(new[] { typeof(IMissing), typeof(Xx) }, unresolvedTypes);
}
[Test]
public void Can_fallback_to_next_rule_if_AutoConcreteResolution_is_unable_to_resolve_concrete_type()
{
var container = new Container(rules => rules
.WithConcreteTypeDynamicRegistrations()
.WithUnknownServiceResolvers(r => r.ServiceType == typeof(Xx) ?
new DelegateFactory(_ => new Xx(null)) : null));
var xx = container.Resolve<Xx>();
Assert.IsInstanceOf<Xx>(xx);
}
public class X
{
public Y Dep { get; }
public X(Y dep)
{
Dep = dep;
}
}
public interface IMissing { }
public class Xx
{
public IMissing Dep { get; set; }
public Xx(IMissing dep)
{
Dep = dep;
}
}
public class Y { }
[Test]
public void When_service_registered_with_name_Then_it_could_be_resolved_with_ctor_parameter_ImportAttribute()
{
var container = new Container(rules => rules.With(parameters: GetServiceInfoFromImportAttribute));
container.Register(typeof(INamedService), typeof(NamedService));
container.Register(typeof(INamedService), typeof(AnotherNamedService), serviceKey: "blah");
container.Register(typeof(ServiceWithImportedCtorParameter));
var service = container.Resolve<ServiceWithImportedCtorParameter>();
Assert.That(service.NamedDependency, Is.InstanceOf<AnotherNamedService>());
}
[Test]
public void I_should_be_able_to_import_single_service_based_on_specified_metadata()
{
var container = new Container(rules => rules.With(parameters: GetServiceFromWithMetadataAttribute));
container.Register(typeof(IFooService), typeof(FooHey), setup: Setup.With(metadataOrFuncOfMetadata: FooMetadata.Hey));
container.Register(typeof(IFooService), typeof(FooBlah), setup: Setup.With(metadataOrFuncOfMetadata: FooMetadata.Blah));
container.Register(typeof(FooConsumer));
var service = container.Resolve<FooConsumer>();
Assert.That(service.Foo.Value, Is.InstanceOf<FooBlah>());
GC.KeepAlive(container);
}
[Test]
public void Can_specify_rules_to_resolve_last_registration_from_multiple_available()
{
var container = new Container(Rules.Default.WithFactorySelector(Rules.SelectLastRegisteredFactory()));
container.Register(typeof(IService), typeof(Service));
container.Register(typeof(IService), typeof(AnotherService));
var service = container.Resolve(typeof(IService));
Assert.IsInstanceOf<AnotherService>(service);
}
[Test]
public void Can_specify_rules_to_resolve_last_registration_from_mixed_open_and_closed_generics()
{
var container = new Container(r => r.WithFactorySelector(Rules.SelectLastRegisteredFactory()));
container.Register(typeof(IService<>), typeof(Service<>));
container.Register(typeof(IService<int>), typeof(IntService));
var service = container.Resolve<IService<int>>();
Assert.IsInstanceOf<IntService>(service);
}
class IntService : IService<int>
{
public int Dependency { get; set; }
}
[Test]
public void You_can_specify_rules_to_disable_registration_based_on_reuse_type()
{
var container = new Container(Rules.Default.WithFactorySelector(
(request, factories) => factories.FirstOrDefault(f => f.Key.Equals(request.ServiceKey) && !(f.Value.Reuse is SingletonReuse)).Value));
container.Register<IService, Service>(Reuse.Singleton);
var service = container.Resolve(typeof(IService), IfUnresolved.ReturnDefault);
Assert.IsNull(service);
}
public static Func<ParameterInfo, ParameterServiceInfo> GetServiceInfoFromImportAttribute(Request request)
{
return parameter =>
{
var import = (ImportAttribute)parameter.GetAttributes(typeof(ImportAttribute)).FirstOrDefault();
var details = import == null ? ServiceDetails.Default
: ServiceDetails.Of(import.ContractType, import.ContractName);
return ParameterServiceInfo.Of(parameter).WithDetails(details);
};
}
public static Func<ParameterInfo, ParameterServiceInfo> GetServiceFromWithMetadataAttribute(Request request)
{
return parameter =>
{
var import = (ImportWithMetadataAttribute)parameter.GetAttributes(typeof(ImportWithMetadataAttribute))
.FirstOrDefault();
if (import == null)
return null;
var registry = request.Container;
var serviceType = parameter.ParameterType;
serviceType = registry.GetWrappedType(serviceType, request.RequiredServiceType);
var metadata = import.Metadata;
var factory = registry.GetAllServiceFactories(serviceType)
.FirstOrDefault(kv => metadata.Equals(kv.Value.Setup.Metadata))
.ThrowIfNull();
return ParameterServiceInfo.Of(parameter).WithDetails(ServiceDetails.Of(serviceType, factory.Key));
};
}
[Test]
public void Can_turn_Off_singleton_optimization()
{
var container = new Container(r => r.WithoutEagerCachingSingletonForFasterAccess());
container.Register<FooHey>(Reuse.Singleton);
var singleton = container.Resolve<LambdaExpression>(typeof(FooHey));
// expression contains item creation delegate / lambda
StringAssert.Contains("r => r.SingletonScope.GetOrAddViaFactoryDelegate", singleton.ToString());
}
internal class XX { }
internal class YY { }
internal class ZZ { }
[Test]
public void AutoFallback_resolution_rule_should_respect_IfUnresolved_policy_in_case_of_multiple_registrations()
{
var container = new Container()
.WithAutoFallbackDynamicRegistrations(typeof(Me), typeof(MiniMe));
var me = container.Resolve<IMe>(IfUnresolved.ReturnDefault);
Assert.IsNull(me);
}
[Test]
public void AutoFallback_resolution_rule_should_respect_IfUnresolved_policy_in_case_of_multiple_registrations_from_assemblies()
{
var container = new Container()
.WithAutoFallbackDynamicRegistrations(typeof(Me).GetAssembly());
var me = container.Resolve<IMe>(IfUnresolved.ReturnDefault);
Assert.IsNull(me);
}
[Test]
public void Can_specify_condition_to_exclude_unwanted_services_from_AutoFallback_resolution_rule()
{
var container = new Container()
.WithAutoFallbackDynamicRegistrations(Reuse.Singleton,
Setup.With(condition: req => req.Parent.ImplementationType.Name.Contains("Green")),
typeof(Me));
container.Register<RedMe>();
var redMe = container.Resolve<RedMe>(IfUnresolved.ReturnDefault);
Assert.IsNull(redMe);
}
public interface IMe { }
internal class Me : IMe { }
internal class MiniMe : IMe { }
internal class GreenMe
{
public IMe Mee { get; set; }
public GreenMe(IMe mee)
{
Mee = mee;
}
}
internal class RedMe
{
public IMe Mee { get; set; }
public RedMe(IMe mee)
{
Mee = mee;
}
}
[Test]
public void Exist_support_for_non_primitive_value_injection_via_container_rule()
{
var container = new Container(rules => rules.WithItemToExpressionConverter(
(item, type) => type == typeof(ConnectionString)
? New(type.SingleConstructor(), Constant(((ConnectionString)item).Value))
: null));
var s = new ConnectionString("aaa");
container.Register(Made.Of(() => new ConStrUser(Arg.Index<ConnectionString>(0)), r => s));
var user = container.Resolve<ConStrUser>();
Assert.AreEqual("aaa", user.S.Value);
}
[Test]
public void Container_rule_for_serializing_custom_value_to_expression_should_throw_proper_exception_for_not_supported_type()
{
var container = new Container(rules => rules.WithThrowIfRuntimeStateRequired());
var s = new ConnectionString("aaa");
container.Register(Made.Of(() => new ConStrUser(Arg.Index<ConnectionString>(0)), r => s));
var ex = Assert.Throws<ContainerException>(() => container.Resolve<ConStrUser>());
Assert.AreEqual(Error.StateIsRequiredToUseItem, ex.Error);
}
public class ConnectionString
{
public string Value;
public ConnectionString(string value)
{
Value = value;
}
}
public class ConStrUser
{
public ConnectionString S { get; set; }
public ConStrUser(ConnectionString s)
{
S = s;
}
}
[Test]
public void Container_should_throw_on_registering_disposable_transient()
{
var container = new Container();
var ex = Assert.Throws<ContainerException>(() =>
container.Register<AD>());
Assert.AreEqual(Error.RegisteredDisposableTransientWontBeDisposedByContainer, ex.Error);
}
[Test]
public void I_can_silence_throw_on_registering_disposable_transient_for_specific_registration()
{
var container = new Container();
Assert.DoesNotThrow(() =>
container.Register<AD>(setup: Setup.With(allowDisposableTransient: true)));
}
[Test]
public void I_can_silence_throw_on_registering_disposable_transient_for_whole_container()
{
var container = new Container(rules => rules.WithoutThrowOnRegisteringDisposableTransient());
Assert.DoesNotThrow(() =>
container.Register<AD>());
}
[Test]
public void Should_track_transient_disposable_dependency_in_singleton_scope()
{
var container = new Container(rules => rules.WithTrackingDisposableTransients());
container.Register<AD>();
container.Register<ADConsumer>(Reuse.Singleton);
var singleton = container.Resolve<ADConsumer>();
container.Dispose();
Assert.IsTrue(singleton.Ad.IsDisposed);
}
[Test]
public void Should_not_track_func_of_transient_disposable_dependency_in_singleton_scope()
{
var container = new Container(rules => rules.WithTrackingDisposableTransients());
container.Register<AD>();
container.Register<ADFuncConsumer>(Reuse.Singleton);
var singleton = container.Resolve<ADFuncConsumer>();
container.Dispose();
Assert.IsFalse(singleton.Ad.IsDisposed);
}
[Test]
public void Should_track_lazy_of_transient_disposable_dependency_in_singleton_scope()
{
var container = new Container(rules => rules.WithTrackingDisposableTransients());
container.Register<AD>();
container.Register<ADLazyConsumer>(Reuse.Singleton);
var singleton = container.Resolve<ADLazyConsumer>();
container.Dispose();
Assert.IsTrue(singleton.Ad.IsDisposed);
}
[Test]
public void Should_track_transient_disposable_dependency_in_current_scope()
{
var container = new Container(rules => rules.WithTrackingDisposableTransients());
container.Register<AD>();
container.Register<ADConsumer>(Reuse.InCurrentScope);
ADConsumer scoped;
using (var scope = container.OpenScope())
{
scoped = scope.Resolve<ADConsumer>();
}
Assert.IsTrue(scoped.Ad.IsDisposed);
}
[Test]
public void Should_track_transient_disposable_dependency_in_singleton_scope_even_if_resolved_in_the_scope()
{
var container = new Container(rules => rules.WithTrackingDisposableTransients());
container.Register<AD>();
container.Register<ADConsumer>(Reuse.Singleton);
ADConsumer singleton;
using (var scope = container.OpenScope())
{
singleton = scope.Resolve<ADConsumer>();
}
Assert.IsFalse(singleton.Ad.IsDisposed);
container.Dispose();
Assert.IsTrue(singleton.Ad.IsDisposed);
}
[Test]
public void Should_track_transient_service_in_open_scope_if_present()
{
var container = new Container();
container.Register<AD>(setup: Setup.With(trackDisposableTransient: true));
AD ad;
using (var scope = container.OpenScope())
ad = scope.Resolve<AD>();
Assert.IsTrue(ad.IsDisposed);
}
[Test]
public void Tracked_disposables_should_be_different()
{
var container = new Container();
container.Register<AD>(setup: Setup.With(trackDisposableTransient: true));
using (var scope = container.OpenScope())
{
var ad = scope.Resolve<AD>();
Assert.AreNotSame(ad, scope.Resolve<AD>());
}
}
[Test]
public void Should_track_transient_service_in_open_scope_of_any_name_if_present()
{
var container = new Container();
container.Register<AD>(setup: Setup.With(trackDisposableTransient: true));
AD ad;
using (var scope = container.OpenScope("hey"))
ad = scope.Resolve<AD>();
Assert.IsTrue(ad.IsDisposed);
}
[Test]
public void Should_track_transient_service_in_singleton_scope_if_no_open_scope()
{
var container = new Container();
container.Register<AD>(setup: Setup.With(trackDisposableTransient: true));
var ad = container.Resolve<AD>();
container.Dispose();
Assert.IsTrue(ad.IsDisposed);
}
public class AD : IDisposable
{
public bool IsDisposed { get; private set; }
public void Dispose()
{
IsDisposed = true;
}
}
public class ADConsumer
{
public AD Ad { get; }
public AD Ad2 { get; }
public ADConsumer(AD ad, AD ad2)
{
Ad = ad;
Ad2 = ad2;
}
}
public class ADFuncConsumer
{
public AD Ad { get; }
public ADFuncConsumer(Func<AD> ad)
{
Ad = ad();
}
}
public class ADLazyConsumer
{
public AD Ad { get; }
public ADLazyConsumer(Lazy<AD> ad)
{
Ad = ad.Value;
}
}
[Test]
public void Can_specify_IfAlreadyRegistered_per_Container()
{
var container = new Container(rules => rules
.WithDefaultIfAlreadyRegistered(IfAlreadyRegistered.Keep));
container.Register<I, A>();
container.Register<I, B>();
var i = container.Resolve<I>();
Assert.IsInstanceOf<A>(i);
}
[Test]
public void If_IfAlreadyRegistered_per_Container_is_overriden_by_individual_registrations()
{
var container = new Container(rules => rules
.WithDefaultIfAlreadyRegistered(IfAlreadyRegistered.Keep));
container.Register<I, A>();
container.Register<I, B>(ifAlreadyRegistered: IfAlreadyRegistered.Replace);
var i = container.Resolve<I>();
Assert.IsInstanceOf<B>(i);
}
[Test]
public void If_IfAlreadyRegistered_per_Container_affects_RegisterMany_as_expected()
{
var container = new Container(rules => rules
.WithDefaultIfAlreadyRegistered(IfAlreadyRegistered.Keep));
container.RegisterMany(new[] { typeof(A), typeof(B) });
var i = container.Resolve<I>();
Assert.IsInstanceOf<A>(i);
}
[Test]
public void Can_specify_to_capture_stack_trace_and_display_it_disposed_exception()
{
var container = new Container(rules => rules
.WithCaptureContainerDisposeStackTrace());
var scope = container.OpenScope();
scope.Dispose();
var ex = Assert.Throws<ContainerException>(() =>
scope.Resolve<string>());
Assert.AreEqual(Error.NameOf(Error.ContainerIsDisposed), Error.NameOf(ex.Error));
StringAssert.Contains("stack-trace", ex.Message);
}
[Test]
public void DisposedContainer_error_message_should_include_tip_how_to_enable_stack_trace()
{
var container = new Container();
container.Dispose();
var ex = Assert.Throws<ContainerException>(() =>
container.Resolve<string>());
Assert.AreEqual(Error.NameOf(Error.ContainerIsDisposed), Error.NameOf(ex.Error));
StringAssert.Contains("WithCaptureContainerDisposeStackTrace", ex.Message);
}
#region CUT
public interface I { }
public class A : I { }
public class B : I { }
public class SomeService { }
public class Bla<T>
{
public string Message { get; set; }
public Func<T> Factory { get; set; }
public Bla(string message)
{
Message = message;
}
public Bla(Func<T> factory)
{
Factory = factory;
}
}
enum FooMetadata { Hey, Blah }
public interface IFooService
{
}
public class FooHey : IFooService
{
}
public class FooBlah : IFooService
{
}
[AttributeUsage(AttributeTargets.Parameter)]
public class ImportWithMetadataAttribute : Attribute
{
public ImportWithMetadataAttribute(object metadata)
{
Metadata = metadata.ThrowIfNull();
}
public readonly object Metadata;
}
public class FooConsumer
{
public Lazy<IFooService> Foo { get; set; }
public FooConsumer([ImportWithMetadata(FooMetadata.Blah)] Lazy<IFooService> foo)
{
Foo = foo;
}
}
public class TransientOpenGenericService<T>
{
public T Value { get; set; }
}
public interface INamedService
{
}
public class NamedService : INamedService
{
}
public class AnotherNamedService : INamedService
{
}
public class ServiceWithImportedCtorParameter
{
public INamedService NamedDependency { get; set; }
public ServiceWithImportedCtorParameter([Import("blah")]INamedService namedDependency)
{
NamedDependency = namedDependency;
}
}
// ReSharper disable once ClassNeverInstantiated.Local
class NotRegisteredService
{
}
#endregion
}
} | 33.032982 | 150 | 0.593674 | [
"MIT"
] | 0000duck/DryIoc | test/DryIoc.UnitTests/RulesTests.cs | 25,039 | C# |
using System.IO;
using System.IO.Compression;
using Executorlibs.Bilibili.Protocol.Invokers;
using Executorlibs.Bilibili.Protocol.Options;
using Executorlibs.Bilibili.Protocol.Services;
using Microsoft.Extensions.Options;
namespace Executorlibs.Bilibili.Protocol.Clients
{
public class WsDanmakuClientV2 : WsDanmakuClientBase
{
protected override byte Version => 2;
public WsDanmakuClientV2(IBilibiliMessageHandlerInvoker invoker, IBilibiliMessageSubscriptionResolver resolver, IOptionsSnapshot<DanmakuClientOptions> options, DanmakuServerProvider credentialProvider) : base(invoker, resolver, options, credentialProvider)
{
}
protected override void HandlePayload(ref ReceiveMethodLocals locals)
{
#if BIGENDIAN
const long gzipCompressed = 0x0500000002001000L; // Magic = 0x10; Version = 0x2; Action = 0x5, cmp once
#else
const long gzipCompressed = 0x0000000500020010L;
#endif
// Skip PacketLength (4 bytes)
if (locals.Protocol.CompressedFlag == gzipCompressed)
{
ProcessGZipPayload(locals.payloadLength, locals.protocolBuffer, locals.payload, ref locals.decompressBuffer);
}
else
{
base.HandlePayload(ref locals);
}
}
private void ProcessGZipPayload(int payloadLength, byte[] protocolBuffer, byte[] payload, ref byte[] decompressBuffer)
{
using MemoryStream ms = new MemoryStream(payload, 2, payloadLength - 2); // skip 0x78 0xDA
using DeflateStream deflate = new DeflateStream(ms, CompressionMode.Decompress);
ref BilibiliDanmakuProtocol protocol = ref Interpret(protocolBuffer);
while (deflate.Read(protocolBuffer, 0, 16) > 0)
{
protocol.ChangeEndian();
payloadLength = protocol.PacketLength - 16;
if (decompressBuffer.Length < payloadLength)
{
decompressBuffer = new byte[payloadLength];
}
deflate.Read(decompressBuffer, 0, payloadLength);
base.ProcessDanmaku(in protocol, decompressBuffer);
}
}
}
}
| 40.125 | 264 | 0.655096 | [
"MIT"
] | Executor-Cheng/Executorlibs | src/Executorlibs.Bilibili.Protocol/Clients/WsDanmakuClientV2.cs | 2,247 | C# |
using System.Collections;
using UnityEngine;
using System;
namespace SilCilSystem.Variables
{
internal static class TweenVariablesExtensions
{
internal static IEnumerator Tween<T>(this Variable<T> variable, T start, T end, float time, Func<T, T, float, T> lerp, Func<float, float> curve)
{
float timer = 0f;
while (timer < time)
{
timer += Time.deltaTime;
variable.Value = lerp(start, end, curve(Mathf.Clamp01(timer / time)));
yield return null;
}
variable.Value = lerp(start, end, curve(1f));
}
}
} | 30.714286 | 152 | 0.573643 | [
"MIT"
] | TeamAojilu/sukisukisukiman_u1w202012_akeru | Assets/SilCilSystem/Scripts/Variables/Utility/Tween/Base.cs | 647 | C# |
using UnityEngine;
using UnityEngine.Events;
namespace DSC.Event.Helper
{
public class DSC_Event_RunEventsByEvent : MonoBehaviour
{
#region Variable
#region Variable - Inspector
#pragma warning disable 0649
[SerializeField] protected EventCondition[] m_arrCondition;
[SerializeField] protected UnityEvent preRunEvents;
[SerializeField] protected UnityEvent runEvents;
[SerializeField] protected UnityEvent postRunEvents;
#pragma warning restore 0649
#endregion
protected EventConditionData m_hConditionData;
#endregion
#region Base - Mono
protected virtual void Awake()
{
m_hConditionData = new EventConditionData(transform);
}
#endregion
#region Main
public virtual void RunEvents()
{
if (!IsPassCondition())
return;
preRunEvents?.Invoke();
runEvents?.Invoke();
postRunEvents?.Invoke();
}
public void SetCondition(params EventCondition[] arrCondition)
{
m_arrCondition = arrCondition;
}
public void SetPreRunEvents(UnityEvent hEvent)
{
preRunEvents = hEvent;
}
public void SetRunEvents(UnityEvent hEvent)
{
runEvents = hEvent;
}
public void SetPostRunEvents(UnityEvent hEvent)
{
postRunEvents = hEvent;
}
#endregion
#region Helper
protected bool IsPassCondition()
{
return m_arrCondition.PassAllCondition(m_hConditionData);
}
#endregion
}
} | 22.051948 | 70 | 0.594229 | [
"MIT"
] | DeStiCap/DSC-Event | Scripts/Helper/RunEvent/DSC_Event_RunEventsByEvent.cs | 1,700 | C# |
// ClassicalSharp copyright 2014-2016 UnknownShadow200 | Licensed under MIT
using System;
using System.Drawing;
using ClassicalSharp;
using Launcher.Gui.Widgets;
using OpenTK.Input;
namespace Launcher.Gui.Screens {
public abstract class Screen {
protected internal LauncherWindow game;
protected internal IDrawer2D drawer;
protected bool mouseMoved = false;
static bool supressMove = true;
public Screen(LauncherWindow game) {
this.game = game;
drawer = game.Drawer;
}
/// <summary> Function called to setup the widgets and other data for this screen. </summary>
public virtual void Init() {
game.Window.Mouse.Move += MouseMove;
game.Window.Mouse.ButtonDown += MouseButtonDown;
game.Window.Keyboard.KeyDown += KeyDown;
game.Window.Keyboard.KeyUp += KeyUp;
}
/// <summary> Function that is repeatedly called multiple times every second. </summary>
public abstract void Tick();
/// <summary> Function called to redraw all widgets in this screen. </summary>
public abstract void Resize();
/// <summary> Cleans up all native resources held by this screen. </summary>
public virtual void Dispose() {
game.Window.Mouse.Move -= MouseMove;
game.Window.Mouse.ButtonDown -= MouseButtonDown;
game.Window.Keyboard.KeyDown -= KeyDown;
game.Window.Keyboard.KeyUp -= KeyUp;
}
/// <summary> Function called when the pixels from the framebuffer
/// are about to be transferred to the window. </summary>
public virtual void OnDisplay() { }
protected Widget selectedWidget;
protected Widget[] widgets;
/// <summary> Called when the user has moved their mouse away from a previously selected widget. </summary>
protected virtual void UnselectWidget(Widget widget) {
if (widget != null) widget.Active = false;
ChangedActiveState(widget);
}
/// <summary> Called when user has moved their mouse over a given widget. </summary>
protected virtual void SelectWidget(Widget widget, int mouseX, int mouseY) {
if (widget != null) widget.Active = true;
ChangedActiveState(widget);
}
void ChangedActiveState(Widget widget) {
ButtonWidget button = widget as ButtonWidget;
if (button != null) {
button.RedrawBackground();
RedrawWidget(button);
}
LabelWidget label = widget as LabelWidget;
if (label != null && label.DarkenWhenInactive) {
game.ResetArea(label.X, label.Y, label.Width, label.Height);
RedrawWidget(label);
}
BitmapWidget bitmap = widget as BitmapWidget;
if (bitmap != null) RedrawWidget(bitmap);
}
/// <summary>Redraws the given widget and marks the window as needing to be redrawn. </summary>
protected void RedrawWidget(Widget widget) {
using (drawer) {
drawer.SetBitmap(game.Framebuffer);
widget.Redraw(drawer);
}
game.Dirty = true;
}
protected Widget lastClicked;
void MouseButtonDown(object sender, MouseButtonEventArgs e) {
MouseButtonDown(e.X, e.Y, e.Button);
}
void MouseMove(object sender, MouseMoveEventArgs e) {
MouseMove(e.X, e.Y, e.XDelta, e.YDelta);
}
protected virtual void MouseButtonDown(int x, int y, MouseButton button) {
if (button != MouseButton.Left) return;
if (lastClicked != null && lastClicked != selectedWidget)
WidgetUnclicked(lastClicked);
if (selectedWidget != null && selectedWidget.OnClick != null)
selectedWidget.OnClick(x, y);
lastClicked = selectedWidget;
}
protected virtual void WidgetUnclicked(Widget widget) { }
protected virtual void MouseMove(int x, int y, int xDelta, int yDelta) {
if (supressMove) { supressMove = false; return; }
mouseMoved = true;
for (int i = 0; i < widgets.Length; i++) {
Widget widget = widgets[i];
if (!widget.Visible) continue;
int width = widget.Width, height = widget.Height;
if (widgets[i] is InputWidget)
width = ((InputWidget)widgets[i]).RealWidth;
if (x >= widget.X && y >= widget.Y &&
x < widget.X + width && y < widget.Y + height) {
if (selectedWidget == widget) return;
if (selectedWidget != null)
UnselectWidget(selectedWidget);
SelectWidget(widget, x, y);
selectedWidget = widget;
return;
}
}
if (selectedWidget == null) return;
UnselectWidget(selectedWidget);
selectedWidget = null;
}
protected virtual void KeyDown(object sender, KeyboardKeyEventArgs e) {
if (e.Key == Key.Tab) {
HandleTab();
} else if (e.Key == Key.Enter) {
Widget widget = selectedWidget;
if (widget != null && widget.OnClick != null)
widget.OnClick(0, 0);
}
}
protected virtual void KeyUp(object sender, KeyboardKeyEventArgs e) {
if (e.Key == Key.Tab)
tabDown = false;
}
protected int IndexOfWidget(Widget w) {
for (int i = 0; i < widgets.Length; i++) {
if (widgets[i] == w) return i;
}
return -1;
}
protected bool tabDown = false;
protected void HandleTab() {
if (tabDown) return;
tabDown = true;
bool shiftDown = game.Window.Keyboard[Key.ShiftLeft]
|| game.Window.Keyboard[Key.ShiftRight];
int dir = shiftDown ? -1 : 1;
int index = 0;
if (lastClicked != null) {
index = IndexOfWidget(lastClicked);
index += dir;
}
for (int j = 0; j < widgets.Length * 2; j++) {
int i = (index + j * dir) % widgets.Length;
if (i < 0) i += widgets.Length;
if (!widgets[i].Visible || !widgets[i].TabSelectable) continue;
Widget widget = widgets[i];
int width = widget.Width;
if (widgets[i] is InputWidget)
width = ((InputWidget)widgets[i]).RealWidth;
int mouseX = widget.X + width / 2;
int mouseY = widget.Y + widget.Height / 2;
MouseMove(mouseX, mouseY, 0, 0);
Point p = game.Window.PointToScreen(Point.Empty);
p.Offset(mouseX, mouseY);
game.Window.DesktopCursorPos = p;
lastClicked = widget;
if (widgets[i] is InputWidget) {
MouseButtonDown(mouseX, mouseY, MouseButton.Left);
((InputWidget)widgets[i]).Chars.CaretPos = -1;
}
break;
}
}
}
}
| 31.024752 | 110 | 0.64321 | [
"BSD-3-Clause"
] | Andresian/ClassicalSharp | Launcher2/Gui/Screens/Screen.cs | 6,068 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using UnityEngine;
using XRTK.Attributes;
using XRTK.Definitions.Utilities;
using XRTK.Interfaces.Providers.Controllers;
namespace XRTK.Definitions.InputSystem
{
[Serializable]
public struct ControllerDataProviderConfiguration
{
/// <summary>
/// Constructor.
/// </summary>
/// <param name="dataProviderType"></param>
/// <param name="dataProviderName"></param>
/// <param name="priority"></param>
/// <param name="runtimePlatform"></param>
public ControllerDataProviderConfiguration(SystemType dataProviderType, string dataProviderName, uint priority, SupportedPlatforms runtimePlatform)
{
this.dataProviderType = dataProviderType;
this.dataProviderName = dataProviderName;
this.priority = priority;
this.runtimePlatform = runtimePlatform;
}
[SerializeField]
[Tooltip("The concrete type of controller data provider to register.")]
[Implements(typeof(IMixedRealityControllerDataProvider), TypeGrouping.ByNamespaceFlat)]
private SystemType dataProviderType;
/// <summary>
/// The concrete type to use for this controller data provider.
/// </summary>
public SystemType DataProviderType => dataProviderType;
[SerializeField]
private string dataProviderName;
/// <summary>
/// The simple, human readable name for the system, feature, or manager.
/// </summary>
public string DataProviderName => dataProviderName;
[SerializeField]
private uint priority;
/// <summary>
/// The priority this system, feature, or manager will be initialized in.
/// </summary>
public uint Priority => priority;
[EnumFlags]
[SerializeField]
private SupportedPlatforms runtimePlatform;
/// <summary>
/// The runtime platform(s) to run this system, feature, or manager on.
/// </summary>
public SupportedPlatforms RuntimePlatform => runtimePlatform;
}
} | 34.846154 | 155 | 0.654746 | [
"MIT"
] | hridpath/XRTK-Core | XRTK-Core/Assets/XRTK/Definitions/InputSystem/ControllerDataProviderConfiguration.cs | 2,267 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DevGuild.AspNetCore.Services.Data.Relational;
namespace DevGuild.AspNetCore.Services.EntitySequences
{
/// <summary>
/// Default implementation of the service for entity-base sequence number generation.
/// </summary>
/// <seealso cref="IEntitySequenceService" />
public class EntitySequenceService : IEntitySequenceService
{
private readonly IDbConnectionFactory connectionFactory;
public EntitySequenceService(IDbConnectionFactory connectionFactory)
{
this.connectionFactory = connectionFactory;
}
/// <summary>
/// Asynchronously peeks the next number in the sequence of the specified entity.
/// </summary>
/// <param name="key">The key of the entity.</param>
/// <returns>
/// The next value to be returned by the sequence.
/// </returns>
public async Task<Int64> PeekNextNumberAsync(String key)
{
using (var connection = this.connectionFactory.CreateConnection())
{
await connection.OpenAsync();
using (var transaction = connection.BeginTransaction())
{
try
{
using (var command = connection.CreateCommand())
{
command.Transaction = transaction;
command.CommandType = CommandType.Text;
command.CommandText = @"select [Id], [NextSequenceId] from [EntitySequences] where [Id] = @key";
command.AddParameter("key", DbType.String, key);
using (var reader = await command.ExecuteReaderAsync())
{
if (await reader.ReadAsync())
{
return reader.GetInt64(reader.GetOrdinal("NextSequenceId"));
}
else
{
return 1;
}
}
}
}
finally
{
transaction.Rollback();
}
}
}
}
/// <summary>
/// Asynchronously takes the next number from the sequence of the specified entity.
/// </summary>
/// <param name="key">The key of the entity.</param>
/// <returns>
/// The next value of the sequence.
/// </returns>
public async Task<Int64> TakeNextNumberAsync(String key)
{
async Task<(Boolean Success, Int64 Payload)> TryUpdate()
{
try
{
using (var connection = this.connectionFactory.CreateConnection())
{
await connection.OpenAsync();
using (var transaction = connection.BeginTransaction())
{
var success = false;
try
{
using (var command = connection.CreateCommand())
{
command.Transaction = transaction;
command.CommandType = CommandType.Text;
command.CommandText = @"update [EntitySequences] set [NextSequenceId] = [NextSequenceId] + 1
output deleted.[NextSequenceId] as [PreviousId]
where [Id] = @key";
command.AddParameter("key", DbType.String, key);
using (var reader = await command.ExecuteReaderAsync())
{
if (await reader.ReadAsync())
{
success = true;
return (true, reader.GetInt64(0));
}
else
{
throw new InvalidOperationException();
}
}
}
}
finally
{
if (success)
{
transaction.Commit();
}
else
{
transaction.Rollback();
}
}
}
}
}
catch
{
return (false, 0);
}
}
async Task<Boolean> TryInsert()
{
try
{
using (var connection = this.connectionFactory.CreateConnection())
{
await connection.OpenAsync();
using (var transaction = connection.BeginTransaction())
using (var command = connection.CreateCommand())
{
command.Transaction = transaction;
command.CommandType = CommandType.Text;
command.CommandText = @"insert [EntitySequences] ([Id], [NextSequenceId]) values (@key, 2)";
command.AddParameter("key", DbType.String, key);
var changed = await command.ExecuteNonQueryAsync();
if (changed > 0)
{
transaction.Commit();
return true;
}
else
{
transaction.Rollback();
return false;
}
}
}
}
catch
{
return false;
}
}
var delay = 1;
while (true)
{
var (success, payload) = await TryUpdate();
if (success)
{
return payload;
}
success = await TryInsert();
if (success)
{
return 1;
}
await Task.Delay(50 * delay);
delay *= 2;
}
}
/// <summary>
/// Asynchronously Takes the multiple numbers from the sequence of the specified entity.
/// </summary>
/// <param name="key">The key of the entity.</param>
/// <param name="count">The number of numbers to take.</param>
/// <returns>
/// An array of taken numbers.
/// </returns>
public async Task<Int64[]> TakeMultipleNumbersAsync(String key, Int64 count)
{
async Task<(Boolean Success, Int64 Payload)> TryUpdate()
{
try
{
using (var connection = this.connectionFactory.CreateConnection())
{
await connection.OpenAsync();
using (var transaction = connection.BeginTransaction())
{
var success = false;
try
{
using (var command = connection.CreateCommand())
{
command.Transaction = transaction;
command.CommandType = CommandType.Text;
command.CommandText = @"update [EntitySequences] set [NextSequenceId] = [NextSequenceId] + @count
output deleted.[NextSequenceId] as [PreviousId]
where [Id] = @key";
command.AddParameter("count", DbType.Int64, count);
command.AddParameter("key", DbType.String, key);
using (var reader = await command.ExecuteReaderAsync())
{
if (await reader.ReadAsync())
{
success = true;
return (true, reader.GetInt64(0));
}
else
{
throw new InvalidOperationException();
}
}
}
}
finally
{
if (success)
{
transaction.Commit();
}
else
{
transaction.Rollback();
}
}
}
}
}
catch
{
return (false, 0);
}
}
async Task<Boolean> TryInsert()
{
try
{
using (var connection = this.connectionFactory.CreateConnection())
{
await connection.OpenAsync();
using (var transaction = connection.BeginTransaction())
using (var command = connection.CreateCommand())
{
command.Transaction = transaction;
command.CommandType = CommandType.Text;
command.CommandText = @"insert [EntitySequences] ([Id], [NextSequenceId]) values (@key, @count + 1)";
command.AddParameter("key", DbType.String, key);
command.AddParameter("count", DbType.Int64, count);
var changed = await command.ExecuteNonQueryAsync();
if (changed > 0)
{
transaction.Commit();
return true;
}
else
{
transaction.Rollback();
return false;
}
}
}
}
catch
{
return false;
}
}
var delay = 1;
while (true)
{
var (success, payload) = await TryUpdate();
if (success)
{
return Enumerable.Range(0, (Int32)count).Select(x => payload + x).ToArray();
}
success = await TryInsert();
if (success)
{
return Enumerable.Range(0, (Int32)count).Select(x => 1L + x).ToArray();
}
await Task.Delay(50 * delay);
delay *= 2;
}
}
}
}
| 39.192308 | 133 | 0.361057 | [
"MIT"
] | DevGuildRu/libraries-aspnetcore | DevGuild.AspNetCore.Services.EntitySequences/EntitySequenceService.cs | 12,230 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("LwipMibViewer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LwipMibViewer")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("7ffbd1c1-1c64-45bb-b243-2400446c649d")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 41.216216 | 107 | 0.742295 | [
"Apache-2.0"
] | dawmlight/vendor_oh_fun | hihope_neptune-oh_hid/00_src/v0.1/device/winnermicro/neptune/sdk_liteos/src/network/lwip2.0.3/apps/snmp/LwipMibCompiler/LwipMibViewer/Properties/AssemblyInfo.cs | 1,543 | C# |
using FotoStorio.Shared.Models;
namespace FotoStorio.Server.Contracts
{
public interface IProductRepository : IRepositoryBase<Product>
{
}
}
| 17.222222 | 66 | 0.748387 | [
"MIT"
] | DavidAJohn/FotoStorio | FotoStorio.Server/Contracts/IProductRepository.cs | 157 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting
{
internal sealed class RetargetingPropertySymbol : WrappedPropertySymbol
{
/// <summary>
/// Owning RetargetingModuleSymbol.
/// </summary>
private readonly RetargetingModuleSymbol _retargetingModule;
//we want to compute this lazily since it may be expensive for the underlying symbol
private ImmutableArray<PropertySymbol> _lazyExplicitInterfaceImplementations;
private ImmutableArray<ParameterSymbol> _lazyParameters;
private CustomModifiersTuple _lazyCustomModifiers;
/// <summary>
/// Retargeted custom attributes
/// </summary>
private ImmutableArray<CSharpAttributeData> _lazyCustomAttributes;
private DiagnosticInfo _lazyUseSiteDiagnostic = CSDiagnosticInfo.EmptyErrorInfo; // Indicates unknown state.
private TypeSymbol _lazyType;
public RetargetingPropertySymbol(RetargetingModuleSymbol retargetingModule, PropertySymbol underlyingProperty)
: base(underlyingProperty)
{
Debug.Assert((object)retargetingModule != null);
Debug.Assert(!(underlyingProperty is RetargetingPropertySymbol));
_retargetingModule = retargetingModule;
}
private RetargetingModuleSymbol.RetargetingSymbolTranslator RetargetingTranslator
{
get
{
return _retargetingModule.RetargetingTranslator;
}
}
public RetargetingModuleSymbol RetargetingModule
{
get
{
return _retargetingModule;
}
}
public override TypeSymbol Type
{
get
{
if ((object)_lazyType == null)
{
var type = this.RetargetingTranslator.Retarget(_underlyingProperty.Type, RetargetOptions.RetargetPrimitiveTypesByTypeCode);
_lazyType = type.AsDynamicIfNoPia(this.ContainingType);
}
return _lazyType;
}
}
public override ImmutableArray<CustomModifier> TypeCustomModifiers
{
get
{
return CustomModifiersTuple.TypeCustomModifiers;
}
}
public override ImmutableArray<CustomModifier> RefCustomModifiers
{
get
{
return CustomModifiersTuple.RefCustomModifiers;
}
}
private CustomModifiersTuple CustomModifiersTuple
{
get
{
return RetargetingTranslator.RetargetModifiers(
_underlyingProperty.TypeCustomModifiers, _underlyingProperty.RefCustomModifiers,
ref _lazyCustomModifiers);
}
}
public override ImmutableArray<ParameterSymbol> Parameters
{
get
{
if (_lazyParameters.IsDefault)
{
ImmutableInterlocked.InterlockedCompareExchange(ref _lazyParameters, this.RetargetParameters(), default(ImmutableArray<ParameterSymbol>));
}
return _lazyParameters;
}
}
private ImmutableArray<ParameterSymbol> RetargetParameters()
{
var list = _underlyingProperty.Parameters;
int count = list.Length;
if (count == 0)
{
return ImmutableArray<ParameterSymbol>.Empty;
}
else
{
ParameterSymbol[] parameters = new ParameterSymbol[count];
for (int i = 0; i < count; i++)
{
parameters[i] = new RetargetingPropertyParameterSymbol(this, list[i]);
}
return parameters.AsImmutableOrNull();
}
}
public override MethodSymbol GetMethod
{
get
{
return (object)_underlyingProperty.GetMethod == null
? null
: this.RetargetingTranslator.Retarget(_underlyingProperty.GetMethod);
}
}
public override MethodSymbol SetMethod
{
get
{
return (object)_underlyingProperty.SetMethod == null
? null
: this.RetargetingTranslator.Retarget(_underlyingProperty.SetMethod);
}
}
internal override bool IsExplicitInterfaceImplementation
{
get
{
return _underlyingProperty.IsExplicitInterfaceImplementation;
}
}
public override ImmutableArray<PropertySymbol> ExplicitInterfaceImplementations
{
get
{
if (_lazyExplicitInterfaceImplementations.IsDefault)
{
ImmutableInterlocked.InterlockedCompareExchange(
ref _lazyExplicitInterfaceImplementations,
this.RetargetExplicitInterfaceImplementations(),
default(ImmutableArray<PropertySymbol>));
}
return _lazyExplicitInterfaceImplementations;
}
}
private ImmutableArray<PropertySymbol> RetargetExplicitInterfaceImplementations()
{
var impls = _underlyingProperty.ExplicitInterfaceImplementations;
if (impls.IsEmpty)
{
Debug.Assert(!impls.IsDefault);
return impls;
}
// CONSIDER: we could skip the builder until the first time we see a different method after retargeting
var builder = ArrayBuilder<PropertySymbol>.GetInstance();
for (int i = 0; i < impls.Length; i++)
{
var retargeted = this.RetargetingTranslator.Retarget(impls[i], MemberSignatureComparer.RetargetedExplicitImplementationComparer);
if ((object)retargeted != null)
{
builder.Add(retargeted);
}
}
return builder.ToImmutableAndFree();
}
public override Symbol ContainingSymbol
{
get
{
return this.RetargetingTranslator.Retarget(_underlyingProperty.ContainingSymbol);
}
}
public override AssemblySymbol ContainingAssembly
{
get
{
return _retargetingModule.ContainingAssembly;
}
}
internal override ModuleSymbol ContainingModule
{
get
{
return _retargetingModule;
}
}
public override ImmutableArray<CSharpAttributeData> GetAttributes()
{
return this.RetargetingTranslator.GetRetargetedAttributes(_underlyingProperty.GetAttributes(), ref _lazyCustomAttributes);
}
internal override IEnumerable<CSharpAttributeData> GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder)
{
return this.RetargetingTranslator.RetargetAttributes(_underlyingProperty.GetCustomAttributesToEmit(moduleBuilder));
}
internal override bool MustCallMethodsDirectly
{
get
{
return _underlyingProperty.MustCallMethodsDirectly;
}
}
internal override DiagnosticInfo GetUseSiteDiagnostic()
{
if (ReferenceEquals(_lazyUseSiteDiagnostic, CSDiagnosticInfo.EmptyErrorInfo))
{
DiagnosticInfo result = null;
CalculateUseSiteDiagnostic(ref result);
_lazyUseSiteDiagnostic = result;
}
return _lazyUseSiteDiagnostic;
}
internal sealed override CSharpCompilation DeclaringCompilation // perf, not correctness
{
get { return null; }
}
}
}
| 32.269663 | 161 | 0.591342 | [
"Apache-2.0"
] | AdamSpeight2008/roslyn-1 | src/Compilers/CSharp/Portable/Symbols/Retargeting/RetargetingPropertySymbol.cs | 8,618 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System.Collections.Concurrent;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Squidex.ClientLibrary;
namespace Squidex.Identity.Model
{
public sealed class SquidexClientManagerFactory
{
private readonly SquidexClientManager appDefault;
private readonly SquidexOptionsPerHost appPerHost;
private readonly ConcurrentDictionary<string, object> cache = new ConcurrentDictionary<string, object>();
private readonly IHttpContextAccessor httpContextAccessor;
public SquidexClientManagerFactory(
IOptions<SquidexOptions> appDefault,
IOptions<SquidexOptionsPerHost> appPerHost,
IHttpContextAccessor httpContextAccessor)
{
this.appDefault = new SquidexClientManager(appDefault.Value);
this.appPerHost = appPerHost.Value;
this.httpContextAccessor = httpContextAccessor;
}
public IContentsClient<TEntity, TData> GetContentsClient<TEntity, TData>(string schemaName)
where TEntity : Content<TData>
where TData : class, new()
{
var cacheKey = $"{schemaName}_{GetHostName()}";
return (IContentsClient<TEntity, TData>)cache.GetOrAdd(cacheKey, x =>
{
var clientManager = GetClientManager();
return clientManager.CreateContentsClient<TEntity, TData>(schemaName);
});
}
public ISquidexClientManager GetClientManager()
{
var cacheKey = GetHostName();
if (string.IsNullOrWhiteSpace(cacheKey))
{
return appDefault;
}
if (appPerHost.TryGetValue(cacheKey, out var options))
{
return (ISquidexClientManager)cache.GetOrAdd(cacheKey, x => new SquidexClientManager(options));
}
return appDefault;
}
private string GetHostName()
{
return httpContextAccessor?.HttpContext?.Request.Host.ToString().Replace(":", "_");
}
}
}
| 35.652174 | 113 | 0.580488 | [
"MIT"
] | Squidex/squidex-identity | Squidex.Identity/Model/SquidexClientManagerFactory.cs | 2,462 | C# |
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System;
using System.Collections;
using System.Collections.Generic;
[CustomEditor(typeof(UI_ListGrid))]
public class UI_ListGridEditor : Editor
{
public override void OnInspectorGUI()
{
UI_ListGrid grid = target as UI_ListGrid;
grid.LineMaxCount = EditorGUILayout.IntField("Line Max Count",grid.LineMaxCount);
grid.IntervalItem = EditorGUILayout.IntField("Interval Item",grid.IntervalItem);
grid.IntervalLine = EditorGUILayout.IntField("Interval Line",grid.IntervalLine);
grid.Dir = (UI_ListGrid.DIR)EditorGUILayout.EnumPopup("Direction",grid.Dir);
if(GUILayout.Button("Refresh"))
{
grid.Refresh();
}
}
}
| 25.172414 | 83 | 0.775342 | [
"MIT"
] | luzexi/kdm-client | u3d/Assets/scripts/ui/core/Editor/UI_ListGridEditor.cs | 730 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SingleResponsibilityPrincipal")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SingleResponsibilityPrincipal")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9d40a607-2ea6-4c9b-9d79-f704e0ebbe90")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.540541 | 84 | 0.753857 | [
"Apache-2.0"
] | omid7791/refactoring-techniques | RefactoringTechniques/SingleResponsibilityPrincipal/Properties/AssemblyInfo.cs | 1,429 | C# |
using System;
using System.Collections.Generic;
namespace SFA.DAS.Forecasting.Domain.AccountProjection
{
public class AccountProjectionExpiry
{
public long AccountId { get;}
public DateTime ProjectionGenerationDate { get; }
public List<ExpiryAmounts> ExpiryAmounts { get; }
public AccountProjectionExpiry(long accountId, DateTime projectionGenerationDate, List<ExpiryAmounts> expiryAmounts)
{
AccountId = accountId;
ProjectionGenerationDate = projectionGenerationDate;
ExpiryAmounts = expiryAmounts;
}
}
} | 31.789474 | 124 | 0.69702 | [
"MIT"
] | SkillsFundingAgency/das-forecasting-api | src/SFA.DAS.Forecasting.Domain/AccountProjection/AccountProjectionExpiry.cs | 606 | C# |
namespace FinderNET.Database {
public class Addons {
public Int64 Id { get; set; }
public List<string> addons { get; set; } = new List<string>();
}
} | 28.833333 | 70 | 0.595376 | [
"MIT"
] | FinderDiscord/FinderNET | FinderNET/Database/Addons.cs | 173 | C# |
namespace Shkolo.Test.Routing
{
using MyTested.AspNetCore.Mvc;
using NUnit.Framework;
using Shkolo.Controllers;
public class HomeControllerTest
{
[Test]
public void ErrorRouteShouldBeMapped()
=> MyRouting
.Configuration()
.ShouldMap("/Home/Error")
.To<HomeController>(c => c.Error());
}
}
| 24.375 | 52 | 0.571795 | [
"MIT"
] | DimitarAngov/ShkoloAspNetProject | Shkolo.Test/Routing/HomeControllerTest.cs | 392 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
using PizzaStore.Domain.Models;
namespace PizzaStore.Tests
{
public class PizzaTest
{
[Fact]
public void Test_PizzaDefault()
{
var sut = new Pizza();
Assert.True(sut.Toppings.Count == 3);
Assert.NotNull(sut.Crust);
Assert.True(sut.Size == PizzaSize.Medium);
Assert.True(sut.Price > 0);
}
//Pizza Type
[Fact]
public void Test_PepPizza()
{
var sut = new Pizza();
var expected = "Pepperoni Cheese Pizza";
var actual = sut.Pepperoni;
Assert.IsType(expected.GetType(), actual);
}
[Fact]
public void Test_CheesePizza()
{
var sut = new Pizza();
var expected = "Cheese Pizza";
var actual = sut.Cheese;
Assert.IsType(expected.GetType(), actual);
}
// //Size
// [Fact]
// public void Test_PizzaBasicSize()
// {
// var sut = new PizzaSize();
// var expected = "Basic";
// var actual = sut.BasicSize;
// Assert.IsType(expected.GetType(), actual);
// }
// [Fact]
// public void Test_PizzaExtraSize()
// {
// var sut = new PizzaSize();
// var expected = "Extra";
// var actual = sut.ExtraSize;
// Assert.IsType(expected.GetType(), actual);
// }
// //Price
// [Fact]
// public void Test_BasicPizzaPrice()
// {
// var sut = new BasicPizza();
// var expected = 8.00;
// var actual = sut.Price;
// Assert.Equal(expected, actual);
// }
// [Fact]
// public void Test_ExtraPizzaPrice()
// {
// var sut = new ExtraPizza();
// var expected = 12.00;
// var actual = sut.Price;
// Assert.Equal(expected, actual);
// }
//}
}
| 19.990476 | 56 | 0.47737 | [
"MIT"
] | AJardine9/AJ-ms | PizzaStore/PizzaStore.Tests/PizzaTest.cs | 2,101 | C# |
using System;
using System.Activities;
using System.Activities.Statements;
using System.Threading;
using Utility;
using Utility.Activities;
namespace Airbrake.Activities.ValidationException
{
class Program
{
static void Main(string[] args)
{
Logging.LineSeparator("WORKFLOW EXAMPLE", 40, '=');
CreateWorkflowSequence();
Thread.Sleep(2000);
Logging.LineSeparator("TRY-CATCH EXAMPLE", 40, '=');
CreateTryCatchSequence();
}
/// <summary>
/// Create a Sequence and execute in a WorkflowApplication.
/// </summary>
internal static void CreateWorkflowSequence()
{
// Create a new Sequence activity.
Activity sequence = new Sequence
{
// Add Activities.
Activities =
{
// Output start of sequence.
new LoggerActivity
{
String = "Workflow sequence started.",
IsLineSeparator = true
},
// Throw a new InArgument<Exception> as new ValidationException.
new Throw
{
Exception = new InArgument<Exception>(env => new System.Activities.ValidationException("Uh oh, a ValidationException occurred in CreateWorkflowSequence()."))
},
// Output end of sequence.
new LoggerActivity
{
String = "Workflow sequence ended.",
IsLineSeparator = true
}
}
};
// Create WorkflowApplication from sequence Activity.
var workflowApplication = new WorkflowApplication(sequence)
{
// On UnhandledException event output Exception to log and terminate workflow.
OnUnhandledException = delegate(WorkflowApplicationUnhandledExceptionEventArgs e)
{
// Output expected UnhandledException.
Logging.Log(e.UnhandledException);
// Terminate the workflow.
return UnhandledExceptionAction.Terminate;
},
};
// Run the workflow application.
workflowApplication.Run();
}
/// <summary>
/// Create a TryCatch Activity with underlying Sequence as Try action.
/// </summary>
internal static void CreateTryCatchSequence()
{
// Exception type InArgument for later use.
var exception = new DelegateInArgument<Exception>()
{
Name = "Exception"
};
// ValidationException type InArgument for later use.
var validationException = new DelegateInArgument<System.Activities.ValidationException>()
{
Name = "ValidationException"
};
// Establish a Try-Catch Activity.
Activity tryCatchSequence = new TryCatch
{
// For Try Activity, create new Sequence.
Try = new Sequence
{
// Add Activities to Sequence.
Activities =
{
// Output sequence start.
new LoggerActivity
{
String = "Try-catch sequence started.",
IsLineSeparator = true
},
// Throw a new InArgument<Exception> as new ValidationException.
new Throw
{
Exception = new InArgument<Exception>(env => new System.Activities.ValidationException("Uh oh, a ValidationException occurred in CreateTryCatchSequence()."))
},
// Output sequence end.
new LoggerActivity
{
String = "Try-catch sequence ended.",
IsLineSeparator = true
}
}
},
// Specify catch blocks.
Catches =
{
// Catch ValidationExceptions.
new Catch<System.Activities.ValidationException>
{
// Action to take when ValidationException is caught.
Action = new ActivityAction<System.Activities.ValidationException>
{
// Pass local validationException instance as Argument.
Argument = validationException,
// Assign LoggerActivity.Exception to new InArgument<Exception> obtained from current ActivityContext.
Handler = new LoggerActivity
{
Exception = new InArgument<Exception>(env => validationException.Get(env))
}
}
},
// Catch Exception.
new Catch<Exception>
{
// Action to take when Exception is caught.
Action = new ActivityAction<Exception>
{
// Pass local exception instance as Argument.
Argument = exception,
// Assign LoggerActivity.Exception to new InArgument<Exception> obtained from current ActivityContext.
Handler = new LoggerActivity
{
Exception = new InArgument<Exception>(env => exception.Get(env))
}
}
}
},
// Ensure final Activity fires, outputting message to console.
Finally = new LoggerActivity
{
String = "Try-catch finally block.",
IsLineSeparator = true
}
};
// Invoke tryCatchSequence.
WorkflowInvoker.Invoke(tryCatchSequence);
// Pause automatic termination of process to allow workflows to finish.
Console.ReadLine();
}
}
}
| 39.54491 | 185 | 0.469564 | [
"MIT"
] | GabeStah/Airbrake.io | Exceptions/.NET/Airbrake.Activities.ValidationException/Program.cs | 6,606 | C# |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace MiniGame
{
public class MiniGame : Game
{
private GraphicsDeviceManager _graphics;
private SpriteBatch _spriteBatch;
private int _sirkaOkna = 800;
private int _vyskaOkna = 600;
private Ctverecek _ctverecek;
public MiniGame()
{
_graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
Window.Title = "MiniGame";
IsMouseVisible = true;
}
protected override void Initialize()
{
_graphics.PreferredBackBufferWidth = _sirkaOkna;
_graphics.PreferredBackBufferHeight = _vyskaOkna;
_graphics.ApplyChanges();
base.Initialize();
}
protected override void LoadContent()
{
_spriteBatch = new SpriteBatch(GraphicsDevice);
_ctverecek = new Ctverecek(
50, 5,
new Vector2((_sirkaOkna - 50) / 2, (_vyskaOkna - 50) / 2),
new SmeroveOvladani(Keys.Left, Keys.Right, Keys.Up, Keys.Down),
new Rectangle(0, 0, _sirkaOkna, _vyskaOkna),
Color.Black, GraphicsDevice
);
}
protected override void Update(GameTime gameTime)
{
KeyboardState klavesnice = Keyboard.GetState();
if (klavesnice.IsKeyDown(Keys.Escape))
Exit();
_ctverecek.Aktualizovat(klavesnice);
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.White);
_spriteBatch.Begin();
_ctverecek.Vykreslit(_spriteBatch);
_spriteBatch.End();
base.Draw(gameTime);
}
}
}
| 26.887324 | 79 | 0.573075 | [
"MIT"
] | Vladyslav272/Zm-na-barvy-podle-pozice | MiniGame/MiniGame.cs | 1,911 | C# |
//-----------------------------------------------------------------------
// <copyright file="UnityEventFormatter.cs" company="Sirenix IVS">
// Copyright (c) 2018 Sirenix IVS
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------
using OdinSerializer;
[assembly: RegisterFormatter(typeof(UnityEventFormatter<>))]
namespace OdinSerializer
{
using UnityEngine.Events;
/// <summary>
/// Custom generic formatter for the <see cref="UnityEvent{T0}"/>, <see cref="UnityEvent{T0, T1}"/>, <see cref="UnityEvent{T0, T1, T2}"/> and <see cref="UnityEvent{T0, T1, T2, T3}"/> types.
/// </summary>
/// <typeparam name="T">The type of UnityEvent that this formatter can serialize and deserialize.</typeparam>
/// <seealso cref="ReflectionFormatter{UnityEngine.Events.UnityEvent}" />
public class UnityEventFormatter<T> : ReflectionFormatter<T> where T : UnityEventBase, new()
{
/// <summary>
/// Get an uninitialized object of type <see cref="T" />.
/// </summary>
/// <returns>
/// An uninitialized object of type <see cref="T" />.
/// </returns>
protected override T GetUninitializedObject()
{
return new T();
}
}
} | 40.444444 | 193 | 0.614835 | [
"MIT"
] | CodingJinxx/gameoff2020 | Gameoff2020/Assets/Plugins/OdinSerializer/Unity Integration/Formatters/UnityEventFormatter.cs | 1,820 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Enclave.NET.Http.Entities
{
public class EncryptedResult
{
public string Value { get; set; }
}
public class EncryptRequest
{
public object Value { get; set; }
}
}
| 16.647059 | 41 | 0.646643 | [
"MIT"
] | SteveSyfuhs/Enclave.NET | Enclave.NET/Http/Entities/EncryptRequest.cs | 285 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.