content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System.Collections.Concurrent; using System.Text.RegularExpressions; using Amqp.Framing; using Amqp.Listener; using Amqp.Transactions; namespace ActiveMQ.Artemis.Client.Testing; public class TestKit : IDisposable { private readonly ContainerHost _host; private readonly ConcurrentDictionary<string, MessageSource> _messageSources = new(StringComparer.InvariantCultureIgnoreCase); private readonly Dictionary<string, List<Action<Message>>> _messageSubscriptions = new(StringComparer.InvariantCultureIgnoreCase); public TestKit(Endpoint endpoint) { _host = new ContainerHost(endpoint.Address); _host.AddressResolver = AddressResolver; _host.Listeners[0].HandlerFactory = _ => new Handler(); _host.RegisterLinkProcessor(new TestLinkProcessor(OnMessage, OnMessageSource)); _host.Open(); } private string? AddressResolver(ContainerHost containerHost, Attach attach) { if (attach.Role) { return ((Source) attach.Source).Address; } if (attach.Target is Target target) { return target.Address; } if (attach.Target is Coordinator) { return attach.LinkName; } return null; } private void OnMessage(Message message) { if (string.IsNullOrEmpty(message.To)) return; var address = message.To; if (_messageSources.TryGetValue(address, out var messageSource)) { messageSource.Enqueue(message); } lock (_messageSubscriptions) { if (_messageSubscriptions.TryGetValue(address, out var subscriptions)) { foreach (var subscription in subscriptions) { subscription(message); } } } } private void OnMessageSource(string address, MessageSource messageSource) { var parsedAddress = GetAddress(address); _messageSources.TryAdd(parsedAddress, messageSource); } private string GetAddress(string address) { var fqqnMatch = Regex.Match(address, "(.+)::(.+)"); return fqqnMatch.Success ? fqqnMatch.Groups[1].Value : address; } public ISubscription Subscribe(string address) { var subscription = new Subscription(); lock (_messageSubscriptions) { if (!_messageSubscriptions.TryGetValue(address, out var subscriptions)) { subscriptions = new List<Action<Message>>(); _messageSubscriptions.Add(address, subscriptions); } subscriptions.Add(subscription.OnMessage); } subscription.Disposed += (_, _) => { lock (_messageSubscriptions) { if (_messageSubscriptions.TryGetValue(address, out var subscriptions)) { subscriptions.Remove(subscription.OnMessage); } } }; return subscription; } public async Task SendMessageAsync(string address, Message message) { var messageSource = await GetMessageSourceAsync(address); if (messageSource != null) { message.To = address; messageSource.Enqueue(message); } else { throw new InvalidOperationException($"No consumer registered on address {address}"); } } private async Task<MessageSource?> GetMessageSourceAsync(string address) { int delay = 1; while (delay <= 10) { if (_messageSources.TryGetValue(address, out var messageSource)) { return messageSource; } await Task.Delay(delay++); } return null; } public void Dispose() { _host.Close(); } }
28.258993
134
0.59445
[ "MIT" ]
Havret/ActiveMQ.Net
src/ArtemisNetClient.Testing/TestKit.cs
3,928
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.CloudAPI.Transform; using Aliyun.Acs.CloudAPI.Transform.V20160714; using System.Collections.Generic; namespace Aliyun.Acs.CloudAPI.Model.V20160714 { public class DescribeVpcAccessesRequest : RpcAcsRequest<DescribeVpcAccessesResponse> { public DescribeVpcAccessesRequest() : base("CloudAPI", "2016-07-14", "DescribeVpcAccesses") { } private int? pageNumber; private int? pageSize; public int? PageNumber { get { return pageNumber; } set { pageNumber = value; DictionaryUtil.Add(QueryParameters, "PageNumber", value.ToString()); } } public int? PageSize { get { return pageSize; } set { pageSize = value; DictionaryUtil.Add(QueryParameters, "PageSize", value.ToString()); } } public override DescribeVpcAccessesResponse GetResponse(Core.Transform.UnmarshallerContext unmarshallerContext) { return DescribeVpcAccessesResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
27.901408
119
0.713781
[ "Apache-2.0" ]
brightness007/unofficial-aliyun-openapi-net-sdk
aliyun-net-sdk-cloudapi/CloudAPI/Model/V20160714/DescribeVpcAccessesRequest.cs
1,981
C#
using ALE.ETLBox.ConnectionManager; namespace ALE.ETLBox.ControlFlow { /// <summary> /// Creates or updates a view. /// </summary> public class CreateViewTask : GenericTask, ITask { public override string TaskName => $"{CreateOrAlterSql} VIEW {ViewName}"; public void Execute() { IsExisting = new IfTableOrViewExistsTask(ViewName) { ConnectionManager = this.ConnectionManager, DisableLogging = true }.Exists(); if ( (ConnectionType == ConnectionManagerType.SQLite || ConnectionType == ConnectionManagerType.Postgres || ConnectionType == ConnectionManagerType.Access ) && IsExisting) new DropViewTask(ViewName) { ConnectionManager = this.ConnectionManager, DisableLogging = true }.Drop(); new SqlTask(this, Sql).ExecuteNonQuery(); } public string ViewName { get; set; } public ObjectNameDescriptor VN => new ObjectNameDescriptor(ViewName, ConnectionType); string CreateViewName => ConnectionType == ConnectionManagerType.Access ? VN.UnquotatedFullName : VN.QuotatedFullName; public string Definition { get; set; } public string Sql { get { return $@"{CreateOrAlterSql} VIEW {CreateViewName} AS {Definition} "; } } public CreateViewTask() { } public CreateViewTask(string viewName, string definition) : this() { this.ViewName = viewName; this.Definition = definition; } public static void CreateOrAlter(string viewName, string definition) => new CreateViewTask(viewName, definition).Execute(); public static void CreateOrAlter(IConnectionManager connectionManager, string viewName, string definition) => new CreateViewTask(viewName, definition) { ConnectionManager = connectionManager }.Execute(); bool IsExisting { get; set; } string CreateOrAlterSql => IsExisting && (ConnectionType != ConnectionManagerType.SQLite && ConnectionType != ConnectionManagerType.Postgres) ? "ALTER" : "CREATE"; } }
39.927273
211
0.637067
[ "MIT" ]
HaSaM-cz/etlbox
ETLBox/src/Toolbox/Database/CreateViewTask.cs
2,198
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 chime-2018-05-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Chime.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Chime.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for Invite Object /// </summary> public class InviteUnmarshaller : IUnmarshaller<Invite, XmlUnmarshallerContext>, IUnmarshaller<Invite, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> Invite IUnmarshaller<Invite, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public Invite Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; Invite unmarshalledObject = new Invite(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("EmailAddress", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.EmailAddress = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("EmailStatus", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.EmailStatus = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("InviteId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.InviteId = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Status", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Status = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static InviteUnmarshaller _instance = new InviteUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static InviteUnmarshaller Instance { get { return _instance; } } } }
34.981818
131
0.601871
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/Chime/Generated/Model/Internal/MarshallTransformations/InviteUnmarshaller.cs
3,848
C#
using System.IO; using System.Runtime.Serialization; using GameEstate.Red.Formats.Red.CR2W.Reflection; using FastMember; using static GameEstate.Red.Formats.Red.Records.Enums; namespace GameEstate.Red.Formats.Red.Types { [DataContract(Namespace = "")] [REDMeta] public class IThumbnailImageLoader : CObject { public IThumbnailImageLoader(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new IThumbnailImageLoader(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
32.086957
133
0.747967
[ "MIT" ]
bclnet/GameEstate
src/Estates/Red/GameEstate.Red.Format/Red/W3/RTTIConvert/IThumbnailImageLoader.cs
738
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v10/resources/campaign_shared_set.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Ads.GoogleAds.V10.Resources { /// <summary>Holder for reflection information generated from google/ads/googleads/v10/resources/campaign_shared_set.proto</summary> public static partial class CampaignSharedSetReflection { #region Descriptor /// <summary>File descriptor for google/ads/googleads/v10/resources/campaign_shared_set.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static CampaignSharedSetReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cjxnb29nbGUvYWRzL2dvb2dsZWFkcy92MTAvcmVzb3VyY2VzL2NhbXBhaWdu", "X3NoYXJlZF9zZXQucHJvdG8SImdvb2dsZS5hZHMuZ29vZ2xlYWRzLnYxMC5y", "ZXNvdXJjZXMaP2dvb2dsZS9hZHMvZ29vZ2xlYWRzL3YxMC9lbnVtcy9jYW1w", "YWlnbl9zaGFyZWRfc2V0X3N0YXR1cy5wcm90bxocZ29vZ2xlL2FwaS9hbm5v", "dGF0aW9ucy5wcm90bxofZ29vZ2xlL2FwaS9maWVsZF9iZWhhdmlvci5wcm90", "bxoZZ29vZ2xlL2FwaS9yZXNvdXJjZS5wcm90byLmAwoRQ2FtcGFpZ25TaGFy", "ZWRTZXQSSQoNcmVzb3VyY2VfbmFtZRgBIAEoCUIy4EEF+kEsCipnb29nbGVh", "ZHMuZ29vZ2xlYXBpcy5jb20vQ2FtcGFpZ25TaGFyZWRTZXQSQAoIY2FtcGFp", "Z24YBSABKAlCKeBBBfpBIwohZ29vZ2xlYWRzLmdvb2dsZWFwaXMuY29tL0Nh", "bXBhaWduSACIAQESQwoKc2hhcmVkX3NldBgGIAEoCUIq4EEF+kEkCiJnb29n", "bGVhZHMuZ29vZ2xlYXBpcy5jb20vU2hhcmVkU2V0SAGIAQESaAoGc3RhdHVz", "GAIgASgOMlMuZ29vZ2xlLmFkcy5nb29nbGVhZHMudjEwLmVudW1zLkNhbXBh", "aWduU2hhcmVkU2V0U3RhdHVzRW51bS5DYW1wYWlnblNoYXJlZFNldFN0YXR1", "c0ID4EEDOnnqQXYKKmdvb2dsZWFkcy5nb29nbGVhcGlzLmNvbS9DYW1wYWln", "blNoYXJlZFNldBJIY3VzdG9tZXJzL3tjdXN0b21lcl9pZH0vY2FtcGFpZ25T", "aGFyZWRTZXRzL3tjYW1wYWlnbl9pZH1+e3NoYXJlZF9zZXRfaWR9QgsKCV9j", "YW1wYWlnbkINCgtfc2hhcmVkX3NldEKIAgomY29tLmdvb2dsZS5hZHMuZ29v", "Z2xlYWRzLnYxMC5yZXNvdXJjZXNCFkNhbXBhaWduU2hhcmVkU2V0UHJvdG9Q", "AVpLZ29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBpcy9hZHMv", "Z29vZ2xlYWRzL3YxMC9yZXNvdXJjZXM7cmVzb3VyY2VzogIDR0FBqgIiR29v", "Z2xlLkFkcy5Hb29nbGVBZHMuVjEwLlJlc291cmNlc8oCIkdvb2dsZVxBZHNc", "R29vZ2xlQWRzXFYxMFxSZXNvdXJjZXPqAiZHb29nbGU6OkFkczo6R29vZ2xl", "QWRzOjpWMTA6OlJlc291cmNlc2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Ads.GoogleAds.V10.Enums.CampaignSharedSetStatusReflection.Descriptor, global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Api.FieldBehaviorReflection.Descriptor, global::Google.Api.ResourceReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V10.Resources.CampaignSharedSet), global::Google.Ads.GoogleAds.V10.Resources.CampaignSharedSet.Parser, new[]{ "ResourceName", "Campaign", "SharedSet", "Status" }, new[]{ "Campaign", "SharedSet" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// CampaignSharedSets are used for managing the shared sets associated with a /// campaign. /// </summary> public sealed partial class CampaignSharedSet : pb::IMessage<CampaignSharedSet> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<CampaignSharedSet> _parser = new pb::MessageParser<CampaignSharedSet>(() => new CampaignSharedSet()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<CampaignSharedSet> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V10.Resources.CampaignSharedSetReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public CampaignSharedSet() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public CampaignSharedSet(CampaignSharedSet other) : this() { resourceName_ = other.resourceName_; campaign_ = other.campaign_; sharedSet_ = other.sharedSet_; status_ = other.status_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public CampaignSharedSet Clone() { return new CampaignSharedSet(this); } /// <summary>Field number for the "resource_name" field.</summary> public const int ResourceNameFieldNumber = 1; private string resourceName_ = ""; /// <summary> /// Immutable. The resource name of the campaign shared set. /// Campaign shared set resource names have the form: /// /// `customers/{customer_id}/campaignSharedSets/{campaign_id}~{shared_set_id}` /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string ResourceName { get { return resourceName_; } set { resourceName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "campaign" field.</summary> public const int CampaignFieldNumber = 5; private string campaign_; /// <summary> /// Immutable. The campaign to which the campaign shared set belongs. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Campaign { get { return campaign_ ?? ""; } set { campaign_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Gets whether the "campaign" field is set</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool HasCampaign { get { return campaign_ != null; } } /// <summary>Clears the value of the "campaign" field</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearCampaign() { campaign_ = null; } /// <summary>Field number for the "shared_set" field.</summary> public const int SharedSetFieldNumber = 6; private string sharedSet_; /// <summary> /// Immutable. The shared set associated with the campaign. This may be a negative keyword /// shared set of another customer. This customer should be a manager of the /// other customer, otherwise the campaign shared set will exist but have no /// serving effect. Only negative keyword shared sets can be associated with /// Shopping campaigns. Only negative placement shared sets can be associated /// with Display mobile app campaigns. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string SharedSet { get { return sharedSet_ ?? ""; } set { sharedSet_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Gets whether the "shared_set" field is set</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool HasSharedSet { get { return sharedSet_ != null; } } /// <summary>Clears the value of the "shared_set" field</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearSharedSet() { sharedSet_ = null; } /// <summary>Field number for the "status" field.</summary> public const int StatusFieldNumber = 2; private global::Google.Ads.GoogleAds.V10.Enums.CampaignSharedSetStatusEnum.Types.CampaignSharedSetStatus status_ = global::Google.Ads.GoogleAds.V10.Enums.CampaignSharedSetStatusEnum.Types.CampaignSharedSetStatus.Unspecified; /// <summary> /// Output only. The status of this campaign shared set. Read only. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Ads.GoogleAds.V10.Enums.CampaignSharedSetStatusEnum.Types.CampaignSharedSetStatus Status { get { return status_; } set { status_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as CampaignSharedSet); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(CampaignSharedSet other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ResourceName != other.ResourceName) return false; if (Campaign != other.Campaign) return false; if (SharedSet != other.SharedSet) return false; if (Status != other.Status) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (ResourceName.Length != 0) hash ^= ResourceName.GetHashCode(); if (HasCampaign) hash ^= Campaign.GetHashCode(); if (HasSharedSet) hash ^= SharedSet.GetHashCode(); if (Status != global::Google.Ads.GoogleAds.V10.Enums.CampaignSharedSetStatusEnum.Types.CampaignSharedSetStatus.Unspecified) hash ^= Status.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (ResourceName.Length != 0) { output.WriteRawTag(10); output.WriteString(ResourceName); } if (Status != global::Google.Ads.GoogleAds.V10.Enums.CampaignSharedSetStatusEnum.Types.CampaignSharedSetStatus.Unspecified) { output.WriteRawTag(16); output.WriteEnum((int) Status); } if (HasCampaign) { output.WriteRawTag(42); output.WriteString(Campaign); } if (HasSharedSet) { output.WriteRawTag(50); output.WriteString(SharedSet); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (ResourceName.Length != 0) { output.WriteRawTag(10); output.WriteString(ResourceName); } if (Status != global::Google.Ads.GoogleAds.V10.Enums.CampaignSharedSetStatusEnum.Types.CampaignSharedSetStatus.Unspecified) { output.WriteRawTag(16); output.WriteEnum((int) Status); } if (HasCampaign) { output.WriteRawTag(42); output.WriteString(Campaign); } if (HasSharedSet) { output.WriteRawTag(50); output.WriteString(SharedSet); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (ResourceName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ResourceName); } if (HasCampaign) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Campaign); } if (HasSharedSet) { size += 1 + pb::CodedOutputStream.ComputeStringSize(SharedSet); } if (Status != global::Google.Ads.GoogleAds.V10.Enums.CampaignSharedSetStatusEnum.Types.CampaignSharedSetStatus.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Status); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(CampaignSharedSet other) { if (other == null) { return; } if (other.ResourceName.Length != 0) { ResourceName = other.ResourceName; } if (other.HasCampaign) { Campaign = other.Campaign; } if (other.HasSharedSet) { SharedSet = other.SharedSet; } if (other.Status != global::Google.Ads.GoogleAds.V10.Enums.CampaignSharedSetStatusEnum.Types.CampaignSharedSetStatus.Unspecified) { Status = other.Status; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { ResourceName = input.ReadString(); break; } case 16: { Status = (global::Google.Ads.GoogleAds.V10.Enums.CampaignSharedSetStatusEnum.Types.CampaignSharedSetStatus) input.ReadEnum(); break; } case 42: { Campaign = input.ReadString(); break; } case 50: { SharedSet = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { ResourceName = input.ReadString(); break; } case 16: { Status = (global::Google.Ads.GoogleAds.V10.Enums.CampaignSharedSetStatusEnum.Types.CampaignSharedSetStatus) input.ReadEnum(); break; } case 42: { Campaign = input.ReadString(); break; } case 50: { SharedSet = input.ReadString(); break; } } } } #endif } #endregion } #endregion Designer generated code
41.191283
292
0.689572
[ "Apache-2.0" ]
friedenberg/google-ads-dotnet
src/V10/Services/CampaignSharedSet.g.cs
17,012
C#
namespace Nancy.Tests.Unit.Extensions { using System; using System.Linq; using Nancy.Extensions; using Xunit; public class StringExtensionsFixture { [Fact] public void IsParameterized_should_return_false_when_there_are_parameters() { "route".IsParameterized().ShouldBeFalse(); } [Fact] public void IsParameterized_should_return_true_when_there_is_a_parameter() { "{param}".IsParameterized().ShouldBeTrue(); } [Fact] public void IsParameterized_should_return_false_for_empty_string() { string.Empty.IsParameterized().ShouldBeFalse(); } [Fact] public void GetParameterNames_should_throw_format_exception_when_there_are_no_parameters() { var exception = Record.Exception(() => "route".GetParameterNames()); exception.ShouldBeOfType<FormatException>(); } [Fact] public void GetParameterNames_should_return_parameter_name() { "{param}".GetParameterNames().First().ShouldEqual("param"); } } }
29.04878
99
0.606213
[ "MIT" ]
BilalHasanKhan/Nancy
src/Nancy.Tests/Unit/Extensions/StringExtensionsFixture.cs
1,191
C#
namespace EveEchoesPlanetaryProductionApi.Data.Models { using System.Collections.Generic; using EveEchoesPlanetaryProductionApi.Data.Common.Models; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; public class ItemType : NamedModel<long>, IEntityTypeConfiguration<ItemType> { public ItemType() { this.Items = new HashSet<Item>(); this.Blueprints = new HashSet<Blueprint>(); } /// <summary> /// Gets or sets all items of this type. /// </summary> public virtual IEnumerable<Item> Items { get; set; } public virtual IEnumerable<Blueprint> Blueprints { get; set; } public void Configure(EntityTypeBuilder<ItemType> itemType) { itemType .HasIndex(it => it.Name) .IsUnique(); } } }
27.606061
80
0.616905
[ "MIT" ]
pirocorp/Eve-Echoes-Industries
src/Data/EveEchoesPlanetaryProductionApi.Data.Models/ItemType.cs
913
C#
using System; using System.IO; using System.Linq; using System.Net.WebSockets; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; // There is a WebSocket without SignalR in AspDotNetCore. Great. We can easily implement that. // https://docs.microsoft.com/en-us/aspnet/core/fundamentals/websockets?view=aspnetcore-3.1 // https://docs.microsoft.com/en-us/aspnet/core/fundamentals/websockets?view=aspnetcore-3.1 // "For most applications, we recommend SignalR over raw WebSockets. SignalR provides transport fallback for environments where WebSockets is not available. // "It also provides a simple remote procedure call app model. And in most scenarios, SignalR has no significant performance disadvantage compared to using raw WebSockets." // So, they admit that there is performance disadvantage, but they say it is not big. // ***** Lesson: Native WebSocket speed advantage over bloated SignalR. // After WebSocket implementation communication is faster than SignalR // From localhost client to localhost server: // First user data (email) arrived: 69ms SignalR to 50ms WebSocket (saving -19ms = 0.02sec.) // First user data (email) arrived: 66ms SignalR to 61ms WebSocket (saving -5ms = 0.02sec.) // From London client to Dublin server // Cold (server start first), first user data (email) arrived: 390ms SignalR to 180ms WebSocket (saving -210ms = 0.21sec.), // Warm page load, first user data (email) arrived: 294ms SignalR to 135ms WebSocket (saving -170ms = 0.17sec.) // After the first user data (email), the Rt, NonRt data comes 1-2ms after. There is no difference between SignalR and WebSocket. // From the Bahamas to Dublin server the gain is astronomical. // Cold (server start first), first user data (email) arrived: 3647ms SignalR to 1695ms WebSocket (saving 2.0sec.), // Warm page load, first user data (email) arrived: 1594ms SignalR to 735ms WebSocket (saving 0.8sec.) // The conclusion is that SignalR does an extra round-trip at handshake, which is unnecessary for us, // and using native WebSocket we can save initial 0.2sec for London clients and 0.8-2.0 sec for Bahamas clients. // So, use WebSockets instead of SignalR if we can, but it is not cardinal if not. // 2021-02: removed SignalR code completely, before migrating to .Net 5.0. namespace SqCoreWeb { public class SqWebsocketMiddleware { private static readonly NLog.Logger gLogger = NLog.LogManager.GetCurrentClassLogger(); // the name of the logger will be the "Namespace.Class" readonly RequestDelegate _next; private static int g_nSocketsKeptAliveInLoop = 0; public SqWebsocketMiddleware(RequestDelegate next) { if (next == null) throw new ArgumentNullException(nameof(next)); _next = next; } public async Task Invoke(HttpContext httpContext) { if (httpContext == null) throw new ArgumentNullException(nameof(httpContext)); // https://github.com/dotnet/aspnetcore/issues/2713 search "/ws" instead of the intended "/ws/", otherwise it will be not found if (httpContext.Request.Path.StartsWithSegments("/ws", StringComparison.OrdinalIgnoreCase, out PathString remainingPathStr)) { if (httpContext.WebSockets.IsWebSocketRequest) { Interlocked.Increment(ref g_nSocketsKeptAliveInLoop); try { await WebSocketLoopKeptAlive(httpContext, remainingPathStr); // after WebSocket is Closed many minutes later, execution continues here. } finally { Interlocked.Decrement(ref g_nSocketsKeptAliveInLoop); } return; // it is handled, don't allow execution further, because 'StatusCode cannot be set because the response has already started.' } else { httpContext.Response.StatusCode = 400; // 400 Bad Request } } await _next(httpContext); } // When using a WebSocket, you must keep this middleware pipeline running for the duration of the connection. // The code receives a message and immediately sends back the same message. Messages are sent and received in a loop until the client closes the connection. private async Task WebSocketLoopKeptAlive(HttpContext context, string p_requestRemainigPath) { WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(); // this accept immediately send back the client that connection is accepted. switch (p_requestRemainigPath) { case "/dashboard": await DashboardWs.OnConnectedAsync(context, webSocket); break; case "/example-ws1": // client sets this URL: connectionUrl.value = scheme + "://" + document.location.hostname + port + "/ws/example-ws1" ; await ExampleWs.OnConnectedAsync(context, webSocket); break; case "/ExSvPush": await ExSvPushWs.OnConnectedAsync(context, webSocket); break; default: throw new Exception($"Unexpected websocket connection '{p_requestRemainigPath}' in WebSocketLoopKeptAlive()"); } ArraySegment<Byte> buffer = new ArraySegment<byte>(new Byte[8192]); string bufferStr = string.Empty; WebSocketReceiveResult? result = null; // loop until the client closes the connection. The server receives a disconnect message only if the client sends it, which can't be done if the internet connection is lost. // If the client isn't always sending messages and you don't want to timeout just because the connection goes idle, have the client use a timer to send a ping message every X seconds. // On the server, if a message hasn't arrived within 2*X seconds after the previous one, terminate the connection and report that the client disconnected. while (webSocket.State == WebSocketState.Open && (result?.CloseStatus == null || !result.CloseStatus.HasValue)) { try { // convert binary array to string message: https://stackoverflow.com/questions/24450109/how-to-send-receive-messages-through-a-web-socket-on-windows-phone-8-using-the-c bufferStr = string.Empty; using (var ms = new MemoryStream()) { do { result = await webSocket.ReceiveAsync(buffer, CancellationToken.None); // client can send CloseStatus = NormalClosure for initiating close ms.Write(buffer.Array!, buffer.Offset, result.Count); } while (!result.EndOfMessage); ms.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(ms, Encoding.UTF8)) bufferStr = reader.ReadToEnd(); } // gLogger.Trace($"WebSocketLoopKeptAlive(). received msg: '{bufferStr}'"); // logging takes 1ms // if result.CloseStatus = NormalClosure message received, or any other fault, don't pass msg to listeners. We manage complexity in this class. bool isGoodNonClientClosedConnection = webSocket.State == WebSocketState.Open && result != null && (result.CloseStatus == null || !result.CloseStatus.HasValue); if (isGoodNonClientClosedConnection && result != null) { switch (p_requestRemainigPath) { case "/dashboard": DashboardWs.OnReceiveAsync(context, webSocket, result, bufferStr); // no await. There is no need to Wait until all of its async inner methods are completed break; case "/example-ws1": ExampleWs.OnReceiveAsync(context, webSocket, result, bufferStr); break; case "/ExSvPush": ExSvPushWs.OnReceiveAsync(context, webSocket, result, bufferStr); break; default: throw new Exception($"Unexpected websocket connection '{p_requestRemainigPath}' in WebSocketLoopKeptAlive()"); } } // If Client never sent any proper data, and closes browser tabpage, ReceiveAsync() returns without Exception and result.CloseStatus = EndpointUnavailable // If Client sent any proper data, and closes browser tabpage, ReceiveAsync() returns with Exception WebSocketError.ConnectionClosedPrematurely } catch (System.Net.WebSockets.WebSocketException e) { if (e.WebSocketErrorCode == WebSocketError.ConnectionClosedPrematurely) // 'The remote party closed the WebSocket connection without completing the close handshake.' { gLogger.Trace($"WebSocketLoopKeptAlive(). Expected exception: '{e.Message}'"); } else throw; } } if (result?.CloseStatus != null) // if client sends Close request then result.CloseStatus = NormalClosure and websocket.State == CloseReceived. In that case, we just answer back that we are closing. await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None); } public static void ServerDiagnostic(StringBuilder p_sb) { // >Monitor that even though Dashboard clients exits to zero, whether zombie Websockets consume resources. // >If it is a problem, then solve it that the server close the WebSocket forcefully after some inactivity with a timeout. // >We don't want to store in server memory too many clients, because it consumes a thread context. So, we have to kick out non-active clients after a while. // >study how other people solve Websocket timeout in C# // >Do we need that at all? If client closes Tab page, Chrome sends termination (Either Exception, or Close will be received. Loop exits. So, if tab-page is closed, it is not a problem. The only way it is a problem, if tabpage is not closed. Like user laptop sleeps, hibernates, or user goes away. In those cases, after e.g. 1-3 hours inactivity, we can exit the loop. If the user comes back from laptop sleep, it is better that he Reload the page anyway. // >A fix 1h limit on server is not good, because what if user just went for lunch, but comes back. He doesn't want to Refresh all the time. // It is possible that user is connected for 3 hours. So the most human way for the user, if the clients are doing a heartbeat. (every 2 minutes). // Connection is closed after 4 minutes of no heartbeat. // If user hybernates the PC, then it either refreshes the page or clients realize heartbeat is not giving back anything, and the client reconnects with a new Websocket. // > If the client isn't always sending messages and you don't want to timeout just because the connection goes idle, have the client use a timer // to send a ping message every X seconds. On the server, if a message hasn't arrived within 2*X seconds after the previous one, // terminate the connection and report that the client disconnected. p_sb.Append("<H2>Websocket-Middleware</H2>"); p_sb.Append($"#Websockets kept alive in ASP-middleware loop: {g_nSocketsKeptAliveInLoop}<br>"); } } // class }
66.454054
467
0.63104
[ "MIT" ]
gyantal/SqCore
src/WebServer/SqCoreWeb/AspMiddleware/SqWebsocketMiddleware.cs
12,294
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Web.V20150801 { /// <summary> /// VnetRoute contract used to pass routing information for a vnet. /// </summary> [AzureNextGenResourceType("azure-nextgen:web/v20150801:ServerFarmRouteForVnet")] public partial class ServerFarmRouteForVnet : Pulumi.CustomResource { /// <summary> /// The ending address for this route. If the start address is specified in CIDR notation, this must be omitted. /// </summary> [Output("endAddress")] public Output<string?> EndAddress { get; private set; } = null!; /// <summary> /// Kind of resource /// </summary> [Output("kind")] public Output<string?> Kind { get; private set; } = null!; /// <summary> /// Resource Location /// </summary> [Output("location")] public Output<string> Location { get; private set; } = null!; /// <summary> /// Resource Name /// </summary> [Output("name")] public Output<string?> Name { get; private set; } = null!; /// <summary> /// The type of route this is: /// DEFAULT - By default, every web app has routes to the local address ranges specified by RFC1918 /// INHERITED - Routes inherited from the real Virtual Network routes /// STATIC - Static route set on the web app only /// /// These values will be used for syncing a Web App's routes with those from a Virtual Network. This operation will clear all DEFAULT and INHERITED routes and replace them /// with new INHERITED routes. /// </summary> [Output("routeType")] public Output<string?> RouteType { get; private set; } = null!; /// <summary> /// The starting address for this route. This may also include a CIDR notation, in which case the end address must not be specified. /// </summary> [Output("startAddress")] public Output<string?> StartAddress { get; private set; } = null!; /// <summary> /// Resource tags /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// Resource type /// </summary> [Output("type")] public Output<string?> Type { get; private set; } = null!; /// <summary> /// Create a ServerFarmRouteForVnet 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 ServerFarmRouteForVnet(string name, ServerFarmRouteForVnetArgs args, CustomResourceOptions? options = null) : base("azure-nextgen:web/v20150801:ServerFarmRouteForVnet", name, args ?? new ServerFarmRouteForVnetArgs(), MakeResourceOptions(options, "")) { } private ServerFarmRouteForVnet(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-nextgen:web/v20150801:ServerFarmRouteForVnet", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:web:ServerFarmRouteForVnet"}, new Pulumi.Alias { Type = "azure-nextgen:web/latest:ServerFarmRouteForVnet"}, new Pulumi.Alias { Type = "azure-nextgen:web/v20160901:ServerFarmRouteForVnet"}, new Pulumi.Alias { Type = "azure-nextgen:web/v20180201:ServerFarmRouteForVnet"}, new Pulumi.Alias { Type = "azure-nextgen:web/v20190801:ServerFarmRouteForVnet"}, new Pulumi.Alias { Type = "azure-nextgen:web/v20200601:ServerFarmRouteForVnet"}, new Pulumi.Alias { Type = "azure-nextgen:web/v20200901:ServerFarmRouteForVnet"}, new Pulumi.Alias { Type = "azure-nextgen:web/v20201001:ServerFarmRouteForVnet"}, }, }; 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 ServerFarmRouteForVnet 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="options">A bag of options that control this resource's behavior</param> public static ServerFarmRouteForVnet Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new ServerFarmRouteForVnet(name, id, options); } } public sealed class ServerFarmRouteForVnetArgs : Pulumi.ResourceArgs { /// <summary> /// The ending address for this route. If the start address is specified in CIDR notation, this must be omitted. /// </summary> [Input("endAddress")] public Input<string>? EndAddress { get; set; } /// <summary> /// Resource Id /// </summary> [Input("id")] public Input<string>? Id { get; set; } /// <summary> /// Kind of resource /// </summary> [Input("kind")] public Input<string>? Kind { get; set; } /// <summary> /// Resource Location /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// Resource Name /// </summary> [Input("name", required: true)] public Input<string> Name { get; set; } = null!; /// <summary> /// Name of resource group /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// Name of the virtual network route /// </summary> [Input("routeName")] public Input<string>? RouteName { get; set; } /// <summary> /// The type of route this is: /// DEFAULT - By default, every web app has routes to the local address ranges specified by RFC1918 /// INHERITED - Routes inherited from the real Virtual Network routes /// STATIC - Static route set on the web app only /// /// These values will be used for syncing a Web App's routes with those from a Virtual Network. This operation will clear all DEFAULT and INHERITED routes and replace them /// with new INHERITED routes. /// </summary> [Input("routeType")] public Input<string>? RouteType { get; set; } /// <summary> /// The starting address for this route. This may also include a CIDR notation, in which case the end address must not be specified. /// </summary> [Input("startAddress")] public Input<string>? StartAddress { get; set; } [Input("tags")] private InputMap<string>? _tags; /// <summary> /// Resource tags /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } /// <summary> /// Resource type /// </summary> [Input("type")] public Input<string>? Type { get; set; } /// <summary> /// Name of virtual network /// </summary> [Input("vnetName", required: true)] public Input<string> VnetName { get; set; } = null!; public ServerFarmRouteForVnetArgs() { } } }
40.760369
192
0.578632
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Web/V20150801/ServerFarmRouteForVnet.cs
8,845
C#
using System; using System.ComponentModel; using EfsTools.Attributes; using EfsTools.Utils; using Newtonsoft.Json; using EfsTools.Items.Data; namespace EfsTools.Items.Nv { [Serializable] [NvItemId(811)] [Attributes(9)] public class Vbatt3700MvAdc { [ElementsCount(1)] [ElementType("uint16")] [Description("")] public ushort Value { get; set; } } }
19.772727
42
0.611494
[ "MIT" ]
HomerSp/EfsTools
EfsTools/Items/Nv/Vbatt3700MvAdcI.cs
435
C#
/* * Copyright 2021 Google LLC All Rights Reserved. * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file or at * https://developers.google.com/open-source/licenses/bsd */ // <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/type/latlng.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Type { /// <summary>Holder for reflection information generated from google/type/latlng.proto</summary> public static partial class LatlngReflection { #region Descriptor /// <summary>File descriptor for google/type/latlng.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static LatlngReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Chhnb29nbGUvdHlwZS9sYXRsbmcucHJvdG8SC2dvb2dsZS50eXBlIi0KBkxh", "dExuZxIQCghsYXRpdHVkZRgBIAEoARIRCglsb25naXR1ZGUYAiABKAFCYwoP", "Y29tLmdvb2dsZS50eXBlQgtMYXRMbmdQcm90b1ABWjhnb29nbGUuZ29sYW5n", "Lm9yZy9nZW5wcm90by9nb29nbGVhcGlzL3R5cGUvbGF0bG5nO2xhdGxuZ/gB", "AaICA0dUUGIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Type.LatLng), global::Google.Type.LatLng.Parser, new[]{ "Latitude", "Longitude" }, null, null, null, null) })); } #endregion } #region Messages /// <summary> /// An object that represents a latitude/longitude pair. This is expressed as a /// pair of doubles to represent degrees latitude and degrees longitude. Unless /// specified otherwise, this must conform to the /// &lt;a href="http://www.unoosa.org/pdf/icg/2012/template/WGS_84.pdf">WGS84 /// standard&lt;/a>. Values must be within normalized ranges. /// </summary> public sealed partial class LatLng : pb::IMessage<LatLng> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<LatLng> _parser = new pb::MessageParser<LatLng>(() => new LatLng()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<LatLng> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Type.LatlngReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public LatLng() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public LatLng(LatLng other) : this() { latitude_ = other.latitude_; longitude_ = other.longitude_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public LatLng Clone() { return new LatLng(this); } /// <summary>Field number for the "latitude" field.</summary> public const int LatitudeFieldNumber = 1; private double latitude_; /// <summary> /// The latitude in degrees. It must be in the range [-90.0, +90.0]. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double Latitude { get { return latitude_; } set { latitude_ = value; } } /// <summary>Field number for the "longitude" field.</summary> public const int LongitudeFieldNumber = 2; private double longitude_; /// <summary> /// The longitude in degrees. It must be in the range [-180.0, +180.0]. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double Longitude { get { return longitude_; } set { longitude_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as LatLng); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(LatLng other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.Equals(Latitude, other.Latitude)) return false; if (!pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.Equals(Longitude, other.Longitude)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Latitude != 0D) hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode(Latitude); if (Longitude != 0D) hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode(Longitude); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Latitude != 0D) { output.WriteRawTag(9); output.WriteDouble(Latitude); } if (Longitude != 0D) { output.WriteRawTag(17); output.WriteDouble(Longitude); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Latitude != 0D) { output.WriteRawTag(9); output.WriteDouble(Latitude); } if (Longitude != 0D) { output.WriteRawTag(17); output.WriteDouble(Longitude); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Latitude != 0D) { size += 1 + 8; } if (Longitude != 0D) { size += 1 + 8; } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(LatLng other) { if (other == null) { return; } if (other.Latitude != 0D) { Latitude = other.Latitude; } if (other.Longitude != 0D) { Longitude = other.Longitude; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 9: { Latitude = input.ReadDouble(); break; } case 17: { Longitude = input.ReadDouble(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 9: { Latitude = input.ReadDouble(); break; } case 17: { Longitude = input.ReadDouble(); break; } } } } #endif } #endregion } #endregion Designer generated code
32.898182
170
0.658892
[ "BSD-3-Clause" ]
jskeet/gax-dotnet
Google.Api.CommonProtos/Type/Latlng.g.cs
9,047
C#
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Praetorium")] [assembly: AssemblyCopyright("Copyright © Jason Reimer 2008-2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.10")] [assembly: AssemblyFileVersion("1.0.10")]
33.307692
68
0.741339
[ "Apache-2.0" ]
jasonreimer/Praetorium
Source/CommonAssemblyInfo.cs
436
C#
using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using JsonApiDotNetCore.Resources; namespace JsonApiDotNetCore.Services { /// <inheritdoc /> public interface IAddToRelationshipService<TResource> : IAddToRelationshipService<TResource, int> where TResource : class, IIdentifiable<int> { } /// <summary /> public interface IAddToRelationshipService<TResource, in TId> where TResource : class, IIdentifiable<TId> { /// <summary> /// Handles a JSON:API request to add resources to a to-many relationship. /// </summary> /// <param name="primaryId">The identifier of the primary resource.</param> /// <param name="relationshipName">The relationship to add resources to.</param> /// <param name="secondaryResourceIds">The set of resources to add to the relationship.</param> /// <param name="cancellationToken">Propagates notification that request handling should be canceled.</param> Task AddToToManyRelationshipAsync(TId primaryId, string relationshipName, ISet<IIdentifiable> secondaryResourceIds, CancellationToken cancellationToken); } }
43.925926
161
0.718381
[ "MIT" ]
farturi/JsonApiDotNetCore
src/JsonApiDotNetCore/Services/IAddToRelationshipService.cs
1,186
C#
// Copyright 2020 New Relic, Inc. All rights reserved. // SPDX-License-Identifier: Apache-2.0 #nullable enable using NewRelic.Agent.Configuration; using NewRelic.Agent.Core.Aggregators; using NewRelic.Agent.Core.BrowserMonitoring; using NewRelic.Core.CodeAttributes; using NewRelic.Core.DistributedTracing; using NewRelic.Agent.Core.Errors; using NewRelic.Agent.Core.Events; using NewRelic.Agent.Core.Metric; using NewRelic.Agent.Core.Transactions; using NewRelic.Agent.Core.Transformers; using NewRelic.Agent.Core.Utilities; using NewRelic.Agent.Core.WireModels; using NewRelic.Agent.Extensions.Providers.Wrapper; using System; using System.Collections.Generic; using System.Globalization; using System.Reflection; using NewRelic.Agent.Core.Wrapper.AgentWrapperApi.Builders; using NewRelic.Core.Logging; using NewRelic.Agent.Api; using System.Linq; namespace NewRelic.Agent.Core.Api { public class AgentApiImplementation : IAgentApi { private static readonly char[] TrimPathChar = new[] { MetricNames.PathSeparatorChar }; private const string CustomMetricNamePrefixAndSeparator = MetricNames.Custom + MetricNames.PathSeparator; private const string DistributedTracingIsEnabledIgnoringCall = "Distributed tracing is enabled. Ignoring {0} call."; // Special case value for Path in ErrorTraceWireModel for errors outside Transactions private const string NoticeErrorPath = "NewRelic.Api.Agent.NoticeError API Call"; private readonly ITransactionService _transactionService; private readonly ICustomEventTransformer _customEventTransformer; private readonly IMetricBuilder _metricBuilder; private readonly IMetricAggregator _metricAggregator; private readonly ICustomErrorDataTransformer _customErrorDataTransformer; private readonly IBrowserMonitoringPrereqChecker _browserMonitoringPrereqChecker; private readonly IBrowserMonitoringScriptMaker _browserMonitoringScriptMaker; private readonly IConfigurationService _configurationService; private readonly IAgent _agent; private readonly AgentBridgeApi _agentBridgeApi; private readonly ITracePriorityManager _tracePriorityManager; private readonly IErrorService _errorService; public AgentApiImplementation(ITransactionService transactionService, ICustomEventTransformer customEventTransformer, IMetricBuilder metricBuilder, IMetricAggregator metricAggregator, ICustomErrorDataTransformer customErrorDataTransformer, IBrowserMonitoringPrereqChecker browserMonitoringPrereqChecker, IBrowserMonitoringScriptMaker browserMonitoringScriptMaker, IConfigurationService configurationService, IAgent agent, ITracePriorityManager tracePriorityManager, IApiSupportabilityMetricCounters apiSupportabilityMetricCounters, IErrorService errorService) { _transactionService = transactionService; _customEventTransformer = customEventTransformer; _metricBuilder = metricBuilder; _metricAggregator = metricAggregator; _customErrorDataTransformer = customErrorDataTransformer; _browserMonitoringPrereqChecker = browserMonitoringPrereqChecker; _browserMonitoringScriptMaker = browserMonitoringScriptMaker; _configurationService = configurationService; _agent = agent; _agentBridgeApi = new AgentBridgeApi(_agent, apiSupportabilityMetricCounters, _configurationService); _tracePriorityManager = tracePriorityManager; _errorService = errorService; } public void InitializePublicAgent(object publicAgent) { try { using (new IgnoreWork()) { Log.Info("Initializing the Agent API"); var method = publicAgent.GetType().GetMethod("SetWrappedAgent", BindingFlags.NonPublic | BindingFlags.Instance); method.Invoke(publicAgent, new[] { _agentBridgeApi }); } } catch (Exception ex) { try { Log.Error($"Failed to initialize the Agent API: {ex}"); } catch (Exception)//Swallow the error { } } } /// <summary> Record a custom analytics event represented by a name and a list of key-value pairs. </summary> /// /// <exception cref="ArgumentNullException"> Thrown when <paramref name="eventType"/> or /// <paramref name="attributes"/> are null. </exception> /// /// <param name="eventType"> The name of the event to record. Only the first 255 characters (256 /// including the null terminator) are retained. </param> /// <param name="attributes"> The attributes to associate with this event. </param> public void RecordCustomEvent(string eventType, IEnumerable<KeyValuePair<string, object>> attributes) { eventType = eventType ?? throw new ArgumentNullException(nameof(eventType)); attributes = attributes ?? throw new ArgumentNullException(nameof(attributes)); using (new IgnoreWork()) { var transaction = TryGetCurrentInternalTransaction(); float priority = transaction?.Priority ?? _tracePriorityManager.Create(); _customEventTransformer.Transform(eventType, attributes, priority); } } /// <summary> Record a named metric with the given duration. </summary> /// /// <param name="name"> The name of the metric to record. Only the first 1000 characters are /// retained. </param> /// <param name="value"> The number of seconds to associate with the named attribute. This can be /// negative, 0, or positive. </param> public void RecordMetric(string name, float value) { using (new IgnoreWork()) { var metricName = GetCustomMetricSuffix(name); //throws if name is null or empty var time = TimeSpan.FromSeconds(value); //throws if value is NaN, Neg Inf, or Pos Inf, < TimeSpan.MinValue, > TimeSpan.MaxValue var metric = _metricBuilder.TryBuildCustomTimingMetric(metricName, time); if (metric != null) { _metricAggregator.Collect(metric); } } } /// <summary> Record response time metric. </summary> /// /// <param name="name"> The name of the metric to record. Only the first 1000 characters are /// retained. </param> /// <param name="millis"> The milliseconds duration of the response time. </param> public void RecordResponseTimeMetric(string name, long millis) { using (new IgnoreWork()) { var metricName = GetCustomMetricSuffix(name); //throws if name is null or empty var time = TimeSpan.FromMilliseconds(millis); var metric = _metricBuilder.TryBuildCustomTimingMetric(metricName, time); if (metric != null) { _metricAggregator.Collect(metric); } } } /// <summary> Increment the metric counter for the given name. </summary> /// /// <exception cref="ArgumentNullException"> Thrown when <paramref name="name"/> is null. </exception> /// /// <param name="name"> The name of the metric to record. Only the first 1000 characters are /// retained. </param> public void IncrementCounter(string name) { name = name ?? throw new ArgumentNullException(nameof(name)); using (new IgnoreWork()) { // NOTE: Unlike Custom timing metrics, Custom count metrics are NOT restricted to only the "Custom" namespace. // This is probably a historical blunder -- it's not a good thing that we allow users to use whatever text they want for the first segment. // However, that is what the API currently allows and it would be difficult to take that feature away. var metric = _metricBuilder.TryBuildCustomCountMetric(name); if (metric != null) { _metricAggregator.Collect(metric); } } } /// <summary> Notice an error identified by an exception report it to the New Relic service. If /// this method is called within a transaction, the exception will be reported with the /// transaction when it finishes. If it is invoked outside of a transaction, a traced error will /// be created and reported to the New Relic service. Only the exception/parameter pair for the /// first call to NoticeError during the course of a transaction is retained. Supports web /// applications only. </summary> /// /// <exception cref="ArgumentNullException"> Thrown when <paramref name="exception"/> is null. </exception> /// /// <param name="exception"> The exception to be reported. Only part of the exception's /// information may be retained to prevent the report from being too large. </param> /// <param name="customAttributes"> Custom parameters to include in the traced error. May be /// null. Only 10,000 characters of combined key/value data is retained. </param> public void NoticeError(Exception exception, IDictionary<string, string>? customAttributes) { exception = exception ?? throw new ArgumentNullException(nameof(exception)); using (new IgnoreWork()) { var transaction = TryGetCurrentInternalTransaction(); if (IsCustomExceptionIgnored(exception, transaction)) return; var errorData = _errorService.FromException(exception, customAttributes); ProcessNoticedError(errorData, transaction); } } public void NoticeError(Exception exception, IDictionary<string, object>? customAttributes) { exception = exception ?? throw new ArgumentNullException(nameof(exception)); using (new IgnoreWork()) { var transaction = TryGetCurrentInternalTransaction(); if (IsCustomExceptionIgnored(exception, transaction)) return; var errorData = _errorService.FromException(exception, customAttributes); ProcessNoticedError(errorData, transaction); } } /// <summary> Notice an error identified by an exception report it to the New Relic service. If /// this method is called within a transaction, the exception will be reported with the /// transaction when it finishes. If it is invoked outside of a transaction, a traced error will /// be created and reported to the New Relic service. Only the exception/parameter pair for the /// first call to NoticeError during the course of a transaction is retained. Supports web /// applications only. </summary> /// /// <exception cref="ArgumentNullException"> Thrown when <paramref name="exception"/> is null. </exception> /// /// <param name="exception"> The exception to be reported. Only part of the exception's /// information may be retained to prevent the report from being too large. </param> public void NoticeError(Exception exception) { exception = exception ?? throw new ArgumentNullException(nameof(exception)); using (new IgnoreWork()) { var transaction = TryGetCurrentInternalTransaction(); if (IsCustomExceptionIgnored(exception, transaction)) return; var errorData = _errorService.FromException(exception); ProcessNoticedError(errorData, transaction); } } /// <summary> Notice an error identified by a simple message and report it to the New Relic /// service. If this method is called within a transaction, the exception will be reported with /// the transaction when it finishes. If it is invoked outside of a transaction, a traced error /// will be created and reported to the New Relic service. Only the string/parameter pair for the /// first call to NoticeError during the course of a transaction is retained. Supports web /// applications only. </summary> /// /// <exception cref="ArgumentNullException"> Thrown when <paramref name="message"/> is null. </exception> /// /// <param name="message"> The message to be displayed in the traced error. Only the /// first 1000 characters are retained. </param> /// <param name="customAttributes"> Custom parameters to include in the traced error. May be /// null. Only 10,000 characters of combined key/value data is retained. </param> public void NoticeError(string message, IDictionary<string, string>? customAttributes) { NoticeError(message, customAttributes, false); } public void NoticeError(string message, IDictionary<string, string>? customAttributes, bool isExpected) { message = message ?? throw new ArgumentNullException(nameof(message)); using (new IgnoreWork()) { var transaction = TryGetCurrentInternalTransaction(); if (IsErrorMessageIgnored(message)) return; var errorData = _errorService.FromMessage(message, customAttributes, isExpected); ProcessNoticedError(errorData, transaction); } } public void NoticeError(string message, IDictionary<string, object>? customAttributes) { NoticeError(message, customAttributes, false); } public void NoticeError(string message, IDictionary<string, object>? customAttributes, bool isExpected) { message = message ?? throw new ArgumentNullException(nameof(message)); using (new IgnoreWork()) { var transaction = TryGetCurrentInternalTransaction(); if (IsErrorMessageIgnored(message)) return; var errorData = _errorService.FromMessage(message, customAttributes, isExpected); ProcessNoticedError(errorData, transaction); } } private void ProcessNoticedError(ErrorData errorData, IInternalTransaction transaction) { if (transaction != null) { transaction.NoticeError(errorData); } else { errorData.Path = NoticeErrorPath; _customErrorDataTransformer.Transform(errorData, _tracePriorityManager.Create()); } } private bool IsCustomExceptionIgnored(Exception exception, IInternalTransaction transaction) { if (_errorService.ShouldIgnoreException(exception)) { if (transaction != null) transaction.TransactionMetadata.TransactionErrorState.SetIgnoreCustomErrors(); return true; } return false; } private bool IsErrorMessageIgnored(string message) { // The agent does not currently implement ignoring errors by error message. // The spec allows for this functionality: https://source.datanerd.us/agents/agent-specs/blob/master/Errors.md#ignore--expected-errors return false; } /// <summary> Add a key/value pair to the current transaction. These are reported in errors and /// transaction traces. Supports web applications only. </summary> /// /// <exception cref="ArgumentNullException"> Thrown when <paramref name="key"/> or /// <paramref name="value"/> is null. </exception> /// /// <param name="key"> The key name for the custom parameter. </param> /// <param name="value"> The value associated with the custom parameter. If the value is a float /// it is recorded as a number, otherwise, <paramref name="value"/> is converted to a string. /// (via <c>value.ToString(CultureInfo.InvariantCulture);</c> </param> [ToBeRemovedInFutureRelease("Use TransactionBridgeApi.AddCustomAttribute(string, object) instead")] public void AddCustomParameter(string key, IConvertible value) { key = key ?? throw new ArgumentNullException(nameof(key)); value = value ?? throw new ArgumentNullException(nameof(value)); using (new IgnoreWork()) { // float (32-bit) precision numbers are specially handled and actually stored as floating point numbers. Everything else is stored as a string. This is for historical reasons -- in the past Dirac only stored single-precision numbers, so integers and doubles had to be stored as strings to avoid losing precision. Now Dirac DOES support integers and doubles, but we can't just blindly start passing up integers and doubles where we used to pass strings because it could break customer queries. var normalizedValue = value is float ? value : value.ToString(CultureInfo.InvariantCulture); AddUserAttributeToCurrentTransaction(key, normalizedValue); } } /// <summary> A Add a key/value pair to the current transaction. These are reported in errors and /// transaction traces. Supports web applications only. </summary> /// /// <exception cref="ArgumentNullException"> Thrown when <paramref name="key"/> or /// <paramref name="value"/> is null. </exception> /// /// <param name="key"> The key name for the custom parameter. Only the first 1000 characters /// are retained. </param> /// <param name="value"> The value associated with the custom parameter. Only the first 1000 /// characters are retained. </param> [ToBeRemovedInFutureRelease("Use TransactionBridgeApi.AddCustomAttribute(string, object) instead")] public void AddCustomParameter(string key, string value) { key = key ?? throw new ArgumentNullException(nameof(key)); value = value ?? throw new ArgumentNullException(nameof(value)); using (new IgnoreWork()) { AddUserAttributeToCurrentTransaction(key, value); } } [ToBeRemovedInFutureRelease("Use TransactionBridgeApi.AddCustomAttribute(string, object) instead")] private void AddUserAttributeToCurrentTransaction(string key, object value) { if (_configurationService.Configuration.CaptureCustomParameters) { var transaction = GetCurrentInternalTransaction(); transaction.AddCustomAttribute(key, value); } } /// <summary> Set the name of the current transaction. Supports web applications only. </summary> /// /// <exception cref="ArgumentNullException"> Thrown when <paramref name="key"/> is null. </exception> /// /// <param name="category"> The category of this transaction, used to distinguish different types /// of transactions. Only the first 1000 characters are retained. If null is passed, the /// category defaults to "Custom". </param> /// <param name="name"> The name of the transaction starting with a forward slash. example: /// /store/order Only the first 1000 characters are retained. </param> public void SetTransactionName(string? category, string name) { name = name ?? throw new ArgumentNullException(nameof(name)); using (new IgnoreWork()) { // Default to "Custom" category if none provided if (category == null || string.IsNullOrWhiteSpace(category)) { category = MetricNames.Custom; } // Get rid of any slashes category = category.Trim(TrimPathChar); name = name.Trim(TrimPathChar); // Clamp the category and name to a predetermined length category = Clamper.ClampLength(category); name = Clamper.ClampLength(name); var transaction = GetCurrentInternalTransaction(); var currentTransactionName = transaction.CandidateTransactionName.CurrentTransactionName; var newTransactionName = currentTransactionName.IsWeb ? TransactionName.ForWebTransaction(category, name) : TransactionName.ForOtherTransaction(category, name); transaction.CandidateTransactionName.TrySet(newTransactionName, TransactionNamePriority.UserTransactionName); } } /// <summary> Sets transaction URI. </summary> /// /// <exception cref="ArgumentNullException"> Thrown when <paramref name="uri"/> is null. </exception> /// /// <param name="uri"> URI to be associated with the transaction. </param> public void SetTransactionUri(Uri uri) { uri = uri ?? throw new ArgumentNullException(nameof(uri)); using (new IgnoreWork()) { var transaction = _agent.CurrentTransaction; if (transaction != null) { transaction.SetUri(uri.AbsolutePath); transaction.SetOriginalUri(uri.AbsolutePath); transaction.SetWebTransactionNameFromPath(WebTransactionType.Custom, uri.AbsolutePath); } } } /// <summary> Sets the User Name, Account Name and Product Name to associate with the RUM /// JavaScript footer for the current web transaction. Supports web applications only. </summary> /// /// <param name="userName"> Name of the user to be associated with the transaction. </param> /// <param name="accountName"> Name of the account to be associated with the transaction. </param> /// <param name="productName"> Name of the product to be associated with the transaction. </param> public void SetUserParameters(string? userName, string? accountName, string? productName) { using (new IgnoreWork()) { if (_configurationService.Configuration.CaptureCustomParameters) { //var transactionMetadata = GetCurrentInternalTransaction().TransactionMetadata; var transaction = GetCurrentInternalTransaction(); if (userName != null && !string.IsNullOrEmpty(userName)) { transaction.AddCustomAttribute("user", userName.ToString(CultureInfo.InvariantCulture)); } if (accountName != null && !string.IsNullOrEmpty(accountName)) { transaction.AddCustomAttribute("account", accountName.ToString(CultureInfo.InvariantCulture)); } if (productName != null && !string.IsNullOrEmpty(productName)) { transaction.AddCustomAttribute("product", productName.ToString(CultureInfo.InvariantCulture)); } } } } /// <summary> Ignore the transaction that is currently in process. Supports web applications only. </summary> public void IgnoreTransaction() { using (new IgnoreWork()) { _agent.CurrentTransaction.Ignore(); } } /// <summary> Ignore the current transaction in the apdex computation. Supports web applications /// only. </summary> public void IgnoreApdex() { using (new IgnoreWork()) { GetCurrentInternalTransaction().IgnoreApdex(); } } /// <summary> Returns the HTML snippet to be inserted into the header of HTML pages to enable Real /// User Monitoring. The HTML will instruct the browser to fetch a small JavaScript file and /// start the page timer. Supports web applications only. </summary> /// /// <returns> An HTML string to be embedded in a page header. </returns> /// /// <example> <code> /// &lt;html&gt; /// &lt;head&gt; /// &lt;&#37;= NewRelic.Api.Agent.NewRelic.GetBrowserTimingHeader()&#37;&gt; /// &lt;/head&gt; /// &lt;body&gt; /// ... /// </code></example> public string GetBrowserTimingHeader() { return GetBrowserTimingHeader(string.Empty); } /// <summary> Returns the HTML snippet to be inserted into the header of HTML pages to enable Real /// User Monitoring. The HTML will instruct the browser to fetch a small JavaScript file and /// start the page timer. Supports web applications only. </summary> /// /// <returns> An HTML string to be embedded in a page header. </returns> /// /// <example> <code> /// &lt;html&gt; /// &lt;head&gt; /// &lt;&#37;= NewRelic.Api.Agent.NewRelic.GetBrowserTimingHeader("random-nonce")&#37;&gt; /// &lt;/head&gt; /// &lt;body&gt; /// ... /// </code></example> public string GetBrowserTimingHeader(string nonce) { using (new IgnoreWork()) { var transaction = TryGetCurrentInternalTransaction(); if (transaction == null) return string.Empty; var shouldInject = _browserMonitoringPrereqChecker.ShouldManuallyInject(transaction); if (!shouldInject) return string.Empty; transaction.IgnoreAllBrowserMonitoringForThisTx(); // The transaction's name must be frozen if we're going to generate a RUM script transaction.CandidateTransactionName.Freeze(TransactionNameFreezeReason.ManualBrowserScriptInjection); return _browserMonitoringScriptMaker.GetScript(transaction, nonce) ?? string.Empty; } } /// <summary> Disables the automatic instrumentation of browser monitoring hooks in individual /// pages Supports web applications only. </summary> /// /// <param name="overrideManual"> (Optional) True to override manual. </param> /// /// <example><code> /// NewRelic.Api.Agent.NewRelic.DisableBrowserMonitoring() /// </code></example> public void DisableBrowserMonitoring(bool overrideManual = false) { using (new IgnoreWork()) { var transaction = GetCurrentInternalTransaction(); if (overrideManual) transaction.IgnoreAllBrowserMonitoringForThisTx(); else transaction.IgnoreAutoBrowserMonitoringForThisTx(); } } /// <summary> (This API should only be used from the public API) Starts the agent (i.e. begin /// capturing data). Does nothing if the agent is already started. Useful if agent autostart is /// disabled via configuration, or if you want to ensure the agent is started before using other /// methods in the Agent API. </summary> /// /// <example><code> /// NewRelic.Api.Agent.NewRelic.StartAgent(); /// </code></example> public void StartAgent() { using (new IgnoreWork()) { EventBus<StartAgentEvent>.Publish(new StartAgentEvent()); } } /// <summary> Sets the name of the application to <paramref name="applicationName"/>. At least one /// given name must not be null. /// /// An application may also have up to two additional names. This can be useful, for example, to /// have multiple applications report under the same roll-up name. </summary> /// /// <exception cref="ArgumentException"> Thrown when <paramref name="applicationName"/>, /// <paramref name="applicationName2"/> and <paramref name="applicationName3"/> are all null. </exception> /// /// <param name="applicationName"> The main application name. </param> /// <param name="applicationName2"> (Optional) The second application name. </param> /// <param name="applicationName3"> (Optional) The third application name. </param> public void SetApplicationName(string applicationName, string? applicationName2 = null, string? applicationName3 = null) { var appNames = new List<string>(); if (applicationName != null) { appNames.Add(applicationName); } if (applicationName2 != null) { appNames.Add(applicationName2); } if (applicationName3 != null) { appNames.Add(applicationName3); } if (appNames.Count == 0) { throw new ArgumentException("At least one application name must be non-null."); } using (new IgnoreWork()) { EventBus<AppNameUpdateEvent>.Publish(new AppNameUpdateEvent(appNames)); } } private IInternalTransaction TryGetCurrentInternalTransaction() { return _transactionService.GetCurrentInternalTransaction(); } /// <summary> Gets the current transaction. Throws an exception if a transaction could not be /// found. Use TryGetCurrentInternlTransaction if you prefer getting a null return. </summary> /// /// <exception cref="InvalidOperationException"> . </exception> /// /// <returns> A transaction. </returns> private IInternalTransaction GetCurrentInternalTransaction() { return TryGetCurrentInternalTransaction() ?? throw new InvalidOperationException("The API method called is only valid from within a transaction. This error can occur if you call the API method from a thread other than the one the transaction started on."); } /// <summary> Gets custom metric suffix. </summary> /// <exception cref="ArgumentException"> Thrown if <paramref name="name"/> is null or empty. </exception> /// <param name="name"> The name to process. </param> /// <returns> The custom metric suffix. </returns> private static string GetCustomMetricSuffix(string name) { if (string.IsNullOrEmpty(name)) throw new ArgumentException("The name parameter must have a value that is not null or empty."); name = Clamper.ClampLength(name); // If the name provided already contains the "Custom/" prefix, remove it and use the remaining segment as the "name" if (name.StartsWith(CustomMetricNamePrefixAndSeparator, StringComparison.InvariantCultureIgnoreCase)) name = name.Substring(CustomMetricNamePrefixAndSeparator.Length); return name; } /// <summary> Gets the request metadata for the current transaction. </summary> /// /// <returns> A list of key-value pairs representing the request metadata. </returns> public IEnumerable<KeyValuePair<string, string>> GetRequestMetadata() { if (_configurationService.Configuration.DistributedTracingEnabled) { Log.FinestFormat(DistributedTracingIsEnabledIgnoringCall, nameof(GetRequestMetadata)); return Enumerable.Empty<KeyValuePair<string, string>>(); } return _agent.CurrentTransaction.GetRequestMetadata(); } /// <summary> Gets the response metadata for the current transaction. </summary> /// /// <returns> A list of key-value pairs representing the request metadata. </returns> public IEnumerable<KeyValuePair<string, string>> GetResponseMetadata() { if (_configurationService.Configuration.DistributedTracingEnabled) { Log.FinestFormat(DistributedTracingIsEnabledIgnoringCall, nameof(GetResponseMetadata)); return Enumerable.Empty<KeyValuePair<string, string>>(); } return _agent.CurrentTransaction.GetResponseMetadata(); } } } #nullable restore
48.164244
567
0.625223
[ "Apache-2.0" ]
SergeyKanzhelev/newrelic-dotnet-agent
src/Agent/NewRelic/Agent/Core/Api/AgentApiImplementation.cs
33,137
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 Internal.Runtime.InteropServices.WindowsRuntime; using System; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Diagnostics.Tracing; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.InteropServices.WindowsRuntime; using System.Security; using System.Threading; using Windows.Foundation; using Windows.UI.Core; namespace System.Threading { #if FEATURE_APPX [WindowsRuntimeImport] [Guid("DFA2DC9C-1A2D-4917-98F2-939AF1D6E0C8")] public delegate void DispatcherQueueHandler(); public enum DispatcherQueuePriority { Low = -10, Normal = 0, High = 10 } [ComImport] [WindowsRuntimeImport] [Guid("603E88E4-A338-4FFE-A457-A5CFB9CEB899")] internal interface IDispatcherQueue { // This returns a DispatcherQueueTimer but we don't use this method, so I // just made it 'object' to avoid declaring it. object CreateTimer(); bool TryEnqueue(DispatcherQueueHandler callback); bool TryEnqueue(DispatcherQueuePriority priority, DispatcherQueueHandler callback); } #region class WinRTSynchronizationContextFactory internal sealed class WinRTSynchronizationContextFactory { // // It's important that we always return the same SynchronizationContext object for any particular ICoreDispatcher // object, as long as any existing instance is still reachable. This allows reference equality checks against the // SynchronizationContext to determine if two instances represent the same dispatcher. Async frameworks rely on this. // To accomplish this, we use a ConditionalWeakTable to track which instances of WinRTSynchronizationContext are bound // to each ICoreDispatcher instance. // private static readonly ConditionalWeakTable<CoreDispatcher, WinRTCoreDispatcherBasedSynchronizationContext> s_coreDispatcherContextCache = new ConditionalWeakTable<CoreDispatcher, WinRTCoreDispatcherBasedSynchronizationContext>(); private static readonly ConditionalWeakTable<IDispatcherQueue, WinRTDispatcherQueueBasedSynchronizationContext> s_dispatcherQueueContextCache = new ConditionalWeakTable<IDispatcherQueue, WinRTDispatcherQueueBasedSynchronizationContext>(); // System.Private.Corelib will call WinRTSynchronizationContextFactory.Create() via reflection public static SynchronizationContext Create(object dispatcherObj) { Debug.Assert(dispatcherObj != null); Debug.Assert(dispatcherObj is CoreDispatcher || dispatcherObj is IDispatcherQueue); if (dispatcherObj is CoreDispatcher) { // // Get the RCW for the dispatcher // CoreDispatcher dispatcher = (CoreDispatcher)dispatcherObj; // // The dispatcher is supposed to belong to this thread // Debug.Assert(dispatcher == CoreWindow.GetForCurrentThread().Dispatcher); Debug.Assert(dispatcher.HasThreadAccess); // // Get the WinRTSynchronizationContext instance that represents this CoreDispatcher. // return s_coreDispatcherContextCache.GetValue(dispatcher, _dispatcher => new WinRTCoreDispatcherBasedSynchronizationContext(_dispatcher)); } else // dispatcherObj is IDispatcherQueue { // // Get the RCW for the dispatcher // IDispatcherQueue dispatcherQueue = (IDispatcherQueue)dispatcherObj; // // Get the WinRTSynchronizationContext instance that represents this IDispatcherQueue. // return s_dispatcherQueueContextCache.GetValue(dispatcherQueue, _dispatcherQueue => new WinRTDispatcherQueueBasedSynchronizationContext(_dispatcherQueue)); } } } #endregion class WinRTSynchronizationContextFactory #region class WinRTSynchronizationContext internal sealed class WinRTCoreDispatcherBasedSynchronizationContext : WinRTSynchronizationContextBase { private readonly CoreDispatcher _dispatcher; internal WinRTCoreDispatcherBasedSynchronizationContext(CoreDispatcher dispatcher) { _dispatcher = dispatcher; } public override void Post(SendOrPostCallback d, object state) { if (d == null) throw new ArgumentNullException(nameof(d)); Contract.EndContractBlock(); var ignored = _dispatcher.RunAsync(CoreDispatcherPriority.Normal, new Invoker(d, state).Invoke); } public override SynchronizationContext CreateCopy() { return new WinRTCoreDispatcherBasedSynchronizationContext(_dispatcher); } } internal sealed class WinRTDispatcherQueueBasedSynchronizationContext : WinRTSynchronizationContextBase { private readonly IDispatcherQueue _dispatcherQueue; internal WinRTDispatcherQueueBasedSynchronizationContext(IDispatcherQueue dispatcherQueue) { _dispatcherQueue = dispatcherQueue; } public override void Post(SendOrPostCallback d, object state) { if (d == null) throw new ArgumentNullException(nameof(d)); Contract.EndContractBlock(); // We explicitly choose to ignore the return value here. This enqueue operation might fail if the // dispatcher queue was shut down before we got here. In that case, we choose to just move on and // pretend nothing happened. var ignored = _dispatcherQueue.TryEnqueue(DispatcherQueuePriority.Normal, new Invoker(d, state).Invoke); } public override SynchronizationContext CreateCopy() { return new WinRTDispatcherQueueBasedSynchronizationContext(_dispatcherQueue); } } internal abstract class WinRTSynchronizationContextBase : SynchronizationContext { #region class WinRTSynchronizationContext.Invoker protected class Invoker { private readonly ExecutionContext _executionContext; private readonly SendOrPostCallback _callback; private readonly object _state; private static readonly ContextCallback s_contextCallback = new ContextCallback(InvokeInContext); public Invoker(SendOrPostCallback callback, object state) { _executionContext = ExecutionContext.Capture(); _callback = callback; _state = state; } public void Invoke() { if (_executionContext == null) InvokeCore(); else ExecutionContext.Run(_executionContext, s_contextCallback, this); } private static void InvokeInContext(object thisObj) { ((Invoker)thisObj).InvokeCore(); } private void InvokeCore() { try { _callback(_state); } catch (Exception ex) { // // If we let exceptions propagate to CoreDispatcher, it will swallow them with the idea that someone will // observe them later using the IAsyncInfo returned by CoreDispatcher.RunAsync. However, we ignore // that IAsyncInfo, because there's nothing Post can do with it (since Post returns void). // So, to avoid these exceptions being lost forever, we post them to the ThreadPool. // if (!(ex is ThreadAbortException)) { if (!ExceptionSupport.ReportUnhandledError(ex)) { var edi = ExceptionDispatchInfo.Capture(ex); ThreadPool.QueueUserWorkItem(o => ((ExceptionDispatchInfo)o).Throw(), edi); } } } } } #endregion class WinRTSynchronizationContext.Invoker public override void Send(SendOrPostCallback d, object state) { throw new NotSupportedException(SR.InvalidOperation_SendNotSupportedOnWindowsRTSynchronizationContext); } } #endregion class WinRTSynchronizationContext #endif //FEATURE_APPX } // namespace
39.699115
170
0.649354
[ "MIT" ]
2E0PGS/corefx
src/System.Runtime.WindowsRuntime/src/System/Threading/WindowsRuntimeSynchronizationContext.cs
8,972
C#
//----------------------------------------------------------------------------- // Copyright 2000-2022 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com) // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: Apache-2.0 //----------------------------------------------------------------------------- using System; using System.Runtime.InteropServices; namespace Arcane { public partial class ExternalRef { static ExternalRef() { //Console.WriteLine("[C#] Set ExternalRef DESTROY Functor!!!"); DestroyDelegate d = _DestroyObject; var h = GCHandle.Alloc(d,GCHandleType.Normal); _ArcaneWrapperCoreSetExternalRefDestroyFunctor(d); } static void _DestroyObject(IntPtr handle) { // ATTENTION: Cette méthode peut être appelée depuis un finalizer // de fin d'exécution et donc il est possible qu'il soit interdit // d'écrire sur la console. // Console.WriteLine("[C#] Destroy object"); var h = GCHandle.FromIntPtr(handle); if (h!=null) h.Free(); } static public ExternalRef Create(object o) { var h = GCHandle.Alloc(o,GCHandleType.Normal); Debug.Write("[C#] Create handle '{0}'",(IntPtr)h); return new ExternalRef((IntPtr)h); } public object GetReference() { IntPtr handle = _internalHandle(); if (handle==IntPtr.Zero) return null; GCHandle gchandle = GCHandle.FromIntPtr(handle); if (gchandle==null) return null; return gchandle.Target; } } }
31.612245
79
0.58683
[ "Apache-2.0" ]
AlexlHer/framework
arcane/tools/wrapper/core/csharp/ExternalRef.cs
1,554
C#
using System; namespace WindBot.Game.AI { [AttributeUsage(AttributeTargets.Class)] public class DeckAttribute : Attribute { public string Name { get; private set; } public string File { get; private set; } public string Level { get; private set; } public DeckAttribute(string name, string file = null, string level = "Normal") { if (String.IsNullOrEmpty(file)) file = name; Name = name; File = file; Level = level; } } }
25
87
0.535652
[ "MIT" ]
AstralHope/windbot
Game/AI/DeckAttribute.cs
577
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/SoftPub.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. namespace TerraFX.Interop { public unsafe partial struct CONFIG_CI_PROV_INFO { [NativeTypeName("DWORD")] public uint cbSize; [NativeTypeName("DWORD")] public uint dwPolicies; public CRYPT_DATA_BLOB* pPolicies; public CONFIG_CI_PROV_INFO_RESULT result; [NativeTypeName("DWORD")] public uint dwScenario; } }
28
145
0.696429
[ "MIT" ]
DaZombieKiller/terrafx.interop.windows
sources/Interop/Windows/um/SoftPub/CONFIG_CI_PROV_INFO.cs
674
C#
using System; using Halibut.Diagnostics; namespace Halibut.ServiceModel { class DefaultPendingRequestQueueFactory : IPendingRequestQueueFactory { readonly ILogFactory logFactory; public DefaultPendingRequestQueueFactory(ILogFactory logFactory) { this.logFactory = logFactory; } public IPendingRequestQueue CreateQueue(Uri endpoint) { return new PendingRequestQueue(logFactory.ForEndpoint(endpoint)); } } }
25.05
77
0.688623
[ "Apache-2.0" ]
OctopusDeploy/Halibut
source/Halibut/ServiceModel/DefaultPendingRequestQueueFactory.cs
503
C#
namespace Macabresoft.Macabre2D.UI.Common { using System; using System.Linq; using System.Reflection; using System.Threading.Tasks; using System.Windows.Input; using Avalonia; using Avalonia.Markup.Xaml; using Macabresoft.Macabre2D.Framework; using ReactiveUI; using Unity; public class AssetGuidEditor : ValueEditorControl<Guid> { public static readonly DirectProperty<AssetGuidEditor, ICommand> ClearCommandProperty = AvaloniaProperty.RegisterDirect<AssetGuidEditor, ICommand>( nameof(ClearCommand), editor => editor.ClearCommand); public static readonly DirectProperty<AssetGuidEditor, string> PathTextProperty = AvaloniaProperty.RegisterDirect<AssetGuidEditor, string>( nameof(PathText), editor => editor.PathText); public static readonly DirectProperty<AssetGuidEditor, ICommand> SelectCommandProperty = AvaloniaProperty.RegisterDirect<AssetGuidEditor, ICommand>( nameof(SelectCommand), editor => editor.SelectCommand); private readonly IAssetManager _assetManager; private readonly ICommonDialogService _dialogService; private readonly IUndoService _undoService; private Type _assetType; private ICommand _clearCommand; private string _pathText; public AssetGuidEditor() : this( Resolver.Resolve<IAssetManager>(), Resolver.Resolve<ICommonDialogService>(), Resolver.Resolve<IUndoService>()) { } [InjectionConstructor] public AssetGuidEditor( IAssetManager assetManager, ICommonDialogService dialogService, IUndoService undoService) { this._assetManager = assetManager; this._dialogService = dialogService; this._undoService = undoService; this.ClearCommand = ReactiveCommand.Create( this.Clear, this.WhenAny(x => x.Value, y => y.Value != Guid.Empty)); this.SelectCommand = ReactiveCommand.CreateFromTask(this.Select); this.InitializeComponent(); } public ICommand SelectCommand { get; } public ICommand ClearCommand { get => this._clearCommand; private set => this.SetAndRaise(ClearCommandProperty, ref this._clearCommand, value); } public string PathText { get => this._pathText; private set => this.SetAndRaise(PathTextProperty, ref this._pathText, value); } public override void Initialize(object value, Type valueType, string valuePropertyName, string title, object owner) { if (owner?.GetType() is Type ownerType) { var members = ownerType.GetMember(valuePropertyName); if (members.FirstOrDefault() is MemberInfo info && info.GetCustomAttribute<AssetGuidAttribute>() is AssetGuidAttribute attribute) { this._assetType = attribute.AssetType; } } base.Initialize(value, valueType, valuePropertyName, title, owner); } protected override void OnValueChanged() { base.OnValueChanged(); if (this.Value != Guid.Empty) { this.ResetPath(); } } private void Clear() { var originalValue = this.Value; if (originalValue != Guid.Empty) { this._undoService.Do( () => this.Value = Guid.Empty, () => { this.Value = originalValue; }); } } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void ResetPath() { this.PathText = null; if (this.Value != Guid.Empty && this.Value != Guid.Empty && this._assetManager.TryGetMetadata(this.Value, out var metadata) && metadata != null) { this.PathText = $"{metadata.GetContentPath()}{metadata.ContentFileExtension}"; } } private async Task Select() { var contentNode = await this._dialogService.OpenAssetSelectionDialog(this._assetType, false); if (contentNode is ContentFile { Metadata: ContentMetadata metadata }) { var originalId = this.Value; var contentId = metadata.ContentId; this._undoService.Do( () => { this.Value = contentId; }, () => { this.Value = originalId; }); } } } }
37.309524
147
0.596256
[ "MIT" ]
Macabresoft/Macabre2D
UI/Common/Controls/ValueEditors/Framework/AssetGuidEditor.axaml.cs
4,701
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class TutorialTurnSystem : MonoBehaviour { private int currentMyTurnTimer = 0; private int currentEnemyTurnTimer = 0; public Text displayTurnTimerTxt; private float time_; public Text mainTxt; public Text timerTxt; public GameObject turnSet; public GameObject dice; private FLOW beforeFlow; public TURN currentTurn; //최초 선공 정할시, enum 설정. public GameObject turnCountingUI; public float matchingCompleteTime = 5; static public bool isSetTerrainDone = false; static public bool enemyEventCardDefense = false; //이벤트 카드로 인해 상대방의 이벤트카드를 막는다. Coroutine myCoroutine; Coroutine enemyCoroutine; Coroutine TurnPassAndDisplayTextCor; //최적화 스크립트 private TutorialFlowSystem flowSystem; private TutorialSetTurn setTurn; private TutorialCardSystem cardsystem; static public TURN startTurn; private int initTurnCnt = 20; private bool[] chk = new bool[5]; private void Start() { flowSystem = gameObject.GetComponent<TutorialFlowSystem>(); setTurn = gameObject.GetComponent<TutorialSetTurn>(); cardsystem = gameObject.GetComponent<TutorialCardSystem>(); StartCoroutine(ReadyMatchingComplete()); } public void TurnChange(bool change) { setTurn = gameObject.GetComponent<TutorialSetTurn>(); cardsystem = gameObject.GetComponent<TutorialCardSystem>(); StartCoroutine(ReadyMatchingComplete()); } public void TurnSet() { gameObject.GetComponent<TerrainGainCounting>().CheckFlag(); //내턴일때의 코루틴 진입 if (currentTurn.Equals(TURN.MYTURN)) { if (startTurn.Equals(TURN.MYTURN)) { initTurnCnt -= 1; turnCountingUI.GetComponentInChildren<Text>().text = initTurnCnt.ToString() + "턴"; } flowSystem.currentFlow = FLOW.TO_ROLLINGDICE; flowSystem.diceCanvas.SetActive(true); if (myCoroutine != null) StopCoroutine(myCoroutine); } //내턴이아닐때의 코루틴 진입 else { if (startTurn.Equals(TURN.ENEMYTURN)) { initTurnCnt -= 1; turnCountingUI.GetComponentInChildren<Text>().text = initTurnCnt.ToString() + "턴"; } flowSystem.currentFlow = FLOW.ENEMYTURN_ROLLINGDICE; flowSystem.diceCanvas.SetActive(false); } } public void DisplayTextMessage(string value, float time) { StartCoroutine(DisplayTextMessageCor(value, time)); } IEnumerator DisplayTextMessageCor(string value, float time) { displayTurnTimerTxt.text = value; yield return new WaitForSeconds(time); displayTurnTimerTxt.text = ""; } IEnumerator ReadySetOrderTimer() { time_ = 0; mainTxt.text = "카드를 선택해 주세요."; timerTxt.text = ""; mainTxt.transform.localPosition = new Vector3(0, 263, 0); while (true) { yield return new WaitForEndOfFrame(); if (TutorialSetTurn.isDone) break; } yield return new WaitForSeconds(3); flowSystem.FlowChange(FLOW.READY_TURNORDER); Destroy(setTurn); StartCoroutine(ReadySetCardTimer()); } IEnumerator ReadySetCardTimer() { time_ = 0; mainTxt.text = "덱을 선택해 주세요."; mainTxt.transform.localPosition = new Vector3(276, 269, 0); timerTxt.transform.localPosition = new Vector3(463.3f, -146, 0); while (true) { for (int i = 0; i < chk.Length; i++) chk[i] = false; for (int i =0; i< cardsystem.cardSet.Length; i++) { if(i < 3) { if(cardsystem.cardSet[i].GetComponent<CardData>().data.currentCnt == 8) { chk[i] = true; } } else { if (cardsystem.cardSet[i].GetComponent<CardData>().data.currentCnt == 3) { chk[i] = true; } } } int cnt = 0; for (int i =0;i< chk.Length;i++) { if (chk[i] == true) cnt += 1; } if (cnt == 5) { gameObject.GetComponent<TutorialManager>().pointOff(); gameObject.GetComponent<TutorialManager>().panel.SetActive(true); break; } yield return new WaitForEndOfFrame(); } flowSystem.missionCanvas.transform.parent = flowSystem.missionSetParentTransform; flowSystem.missionCanvas.transform.localPosition = new Vector3(-318, flowSystem.missionCanvas.transform.localPosition.y, 0); flowSystem.FlowChange(FLOW.READY_SETCARD); } IEnumerator ReadyMatchingComplete() { time_ = 0; while (true) { time_ += Time.deltaTime; timerTxt.text = (matchingCompleteTime - (int)time_).ToString() + "초후에 게임에 입장합니다."; yield return new WaitForEndOfFrame(); if (time_ > matchingCompleteTime) break; } flowSystem.FlowChange(FLOW.READY_MATCHINGCOMPLETE); StartCoroutine(ReadySetOrderTimer()); } public void EnemyTurnPass() { flowSystem.currentFlow = FLOW.DISPLAYANIMATION_WAITING; flowSystem.displayTextImg.SetActive(true); flowSystem.displayTextImg.GetComponent<DisplayTextImg>().Performance(flowSystem.displayTextImg.GetComponent<DisplayTextImg>().sprs[1]); if (TurnPassAndDisplayTextCor != null) StopCoroutine(TurnPassAndDisplayTextCor); TurnPassAndDisplayTextCor = StartCoroutine(TurnPassAndDisplayText()); } IEnumerator TurnPassAndDisplayText() { yield return new WaitForSeconds(2.5f); currentTurn = TURN.MYTURN; } }
30.407767
143
0.579981
[ "MIT" ]
GameForPeople/TeamHSLD
HSLD/Assets/Scripts/Tutorial/TutorialTurnSystem.cs
6,444
C#
// // Copyright 2011-2013, Xamarin Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.IO; using System.Linq; using System.Threading.Tasks; #if __UNIFIED__ using CoreGraphics; using AssetsLibrary; using Foundation; using UIKit; using NSAction = global::System.Action; #else using MonoTouch.AssetsLibrary; using MonoTouch.Foundation; using MonoTouch.UIKit; using CGRect = global::System.Drawing.RectangleF; using nfloat = global::System.Single; #endif namespace Xamarin.Media { internal class MediaPickerDelegate : UIImagePickerControllerDelegate { internal MediaPickerDelegate (UIViewController viewController, UIImagePickerControllerSourceType sourceType, StoreCameraMediaOptions options) { this.viewController = viewController; this.source = sourceType; this.options = options ?? new StoreCameraMediaOptions(); if (viewController != null) { UIDevice.CurrentDevice.BeginGeneratingDeviceOrientationNotifications(); this.observer = NSNotificationCenter.DefaultCenter.AddObserver (UIDevice.OrientationDidChangeNotification, DidRotate); } } public UIPopoverController Popover { get; set; } public UIView View { get { return this.viewController.View; } } public Task<MediaFile> Task { get { return tcs.Task; } } public override void FinishedPickingMedia (UIImagePickerController picker, NSDictionary info) { MediaFile mediaFile; switch ((NSString)info[UIImagePickerController.MediaType]) { case MediaPicker.TypeImage: mediaFile = GetPictureMediaFile (info); break; case MediaPicker.TypeMovie: mediaFile = GetMovieMediaFile (info); break; default: throw new NotSupportedException(); } if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) { UIApplication.SharedApplication.SetStatusBarStyle(MediaPicker.StatusBarStyle, false); } Dismiss (picker, () => this.tcs.TrySetResult (mediaFile)); } public override void Canceled (UIImagePickerController picker) { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) { UIApplication.SharedApplication.SetStatusBarStyle(MediaPicker.StatusBarStyle, false); } Dismiss (picker, () => this.tcs.TrySetCanceled()); } public void DisplayPopover (bool hideFirst = false) { if (Popover == null) return; var swidth = UIScreen.MainScreen.Bounds.Width; var sheight= UIScreen.MainScreen.Bounds.Height; nfloat width = 400; nfloat height = 300; if (this.orientation == null) { if (IsValidInterfaceOrientation (UIDevice.CurrentDevice.Orientation)) this.orientation = UIDevice.CurrentDevice.Orientation; else this.orientation = GetDeviceOrientation (this.viewController.InterfaceOrientation); } nfloat x, y; if (this.orientation == UIDeviceOrientation.LandscapeLeft || this.orientation == UIDeviceOrientation.LandscapeRight) { y = (swidth / 2) - (height / 2); x = (sheight / 2) - (width / 2); } else { x = (swidth / 2) - (width / 2); y = (sheight / 2) - (height / 2); } if (hideFirst && Popover.PopoverVisible) Popover.Dismiss (animated: false); Popover.PresentFromRect (new CGRect (x, y, width, height), View, 0, animated: true); } private UIDeviceOrientation? orientation; private NSObject observer; private readonly UIViewController viewController; private readonly UIImagePickerControllerSourceType source; private TaskCompletionSource<MediaFile> tcs = new TaskCompletionSource<MediaFile>(); private readonly StoreCameraMediaOptions options; private bool IsCaptured { get { return this.source == UIImagePickerControllerSourceType.Camera; } } private void Dismiss (UIImagePickerController picker, NSAction onDismiss) { if (this.viewController == null) { onDismiss(); tcs = new TaskCompletionSource<MediaFile>(); } else { NSNotificationCenter.DefaultCenter.RemoveObserver (this.observer); UIDevice.CurrentDevice.EndGeneratingDeviceOrientationNotifications(); this.observer.Dispose(); if (Popover != null) { Popover.Dismiss (animated: true); Popover.Dispose(); Popover = null; onDismiss(); } else { picker.DismissViewController (true, onDismiss); picker.Dispose(); } } } private void DidRotate (NSNotification notice) { UIDevice device = (UIDevice)notice.Object; if (!IsValidInterfaceOrientation (device.Orientation) || Popover == null) return; if (this.orientation.HasValue && IsSameOrientationKind (this.orientation.Value, device.Orientation)) return; if (UIDevice.CurrentDevice.CheckSystemVersion (6, 0)) { if (!GetShouldRotate6 (device.Orientation)) return; } else if (!GetShouldRotate (device.Orientation)) return; UIDeviceOrientation? co = this.orientation; this.orientation = device.Orientation; if (co == null) return; DisplayPopover (hideFirst: true); } private bool GetShouldRotate (UIDeviceOrientation orientation) { UIInterfaceOrientation iorientation = UIInterfaceOrientation.Portrait; switch (orientation) { case UIDeviceOrientation.LandscapeLeft: iorientation = UIInterfaceOrientation.LandscapeLeft; break; case UIDeviceOrientation.LandscapeRight: iorientation = UIInterfaceOrientation.LandscapeRight; break; case UIDeviceOrientation.Portrait: iorientation = UIInterfaceOrientation.Portrait; break; case UIDeviceOrientation.PortraitUpsideDown: iorientation = UIInterfaceOrientation.PortraitUpsideDown; break; default: return false; } return this.viewController.ShouldAutorotateToInterfaceOrientation (iorientation); } private bool GetShouldRotate6 (UIDeviceOrientation orientation) { if (!this.viewController.ShouldAutorotate()) return false; UIInterfaceOrientationMask mask = UIInterfaceOrientationMask.Portrait; switch (orientation) { case UIDeviceOrientation.LandscapeLeft: mask = UIInterfaceOrientationMask.LandscapeLeft; break; case UIDeviceOrientation.LandscapeRight: mask = UIInterfaceOrientationMask.LandscapeRight; break; case UIDeviceOrientation.Portrait: mask = UIInterfaceOrientationMask.Portrait; break; case UIDeviceOrientation.PortraitUpsideDown: mask = UIInterfaceOrientationMask.PortraitUpsideDown; break; default: return false; } return this.viewController.GetSupportedInterfaceOrientations().HasFlag (mask); } private MediaFile GetPictureMediaFile (NSDictionary info) { var image = (UIImage)info[UIImagePickerController.EditedImage]; if (image == null) image = (UIImage)info[UIImagePickerController.OriginalImage]; string path = GetOutputPath (MediaPicker.TypeImage, options.Directory ?? ((IsCaptured) ? String.Empty : "temp"), options.Name); using (FileStream fs = File.OpenWrite (path)) using (Stream s = new NSDataStream (image.AsJPEG())) { s.CopyTo (fs); fs.Flush(); } Action<bool> dispose = null; if (this.source != UIImagePickerControllerSourceType.Camera) dispose = d => File.Delete (path); return new MediaFile (path, () => File.OpenRead (path), dispose); } private MediaFile GetMovieMediaFile (NSDictionary info) { NSUrl url = (NSUrl)info[UIImagePickerController.MediaURL]; string path = GetOutputPath (MediaPicker.TypeMovie, options.Directory ?? ((IsCaptured) ? String.Empty : "temp"), this.options.Name ?? Path.GetFileName (url.Path)); File.Move (url.Path, path); Action<bool> dispose = null; if (this.source != UIImagePickerControllerSourceType.Camera) dispose = d => File.Delete (path); return new MediaFile (path, () => File.OpenRead (path), dispose); } private static string GetUniquePath (string type, string path, string name) { bool isPhoto = (type == MediaPicker.TypeImage); string ext = Path.GetExtension (name); if (ext == String.Empty) ext = ((isPhoto) ? ".jpg" : ".mp4"); name = Path.GetFileNameWithoutExtension (name); string nname = name + ext; int i = 1; while (File.Exists (Path.Combine (path, nname))) nname = name + "_" + (i++) + ext; return Path.Combine (path, nname); } private static string GetOutputPath (string type, string path, string name) { path = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), path); Directory.CreateDirectory (path); if (String.IsNullOrWhiteSpace (name)) { string timestamp = DateTime.Now.ToString ("yyyMMdd_HHmmss"); if (type == MediaPicker.TypeImage) name = "IMG_" + timestamp + ".jpg"; else name = "VID_" + timestamp + ".mp4"; } return Path.Combine (path, GetUniquePath (type, path, name)); } private static bool IsValidInterfaceOrientation (UIDeviceOrientation self) { return (self != UIDeviceOrientation.FaceUp && self != UIDeviceOrientation.FaceDown && self != UIDeviceOrientation.Unknown); } private static bool IsSameOrientationKind (UIDeviceOrientation o1, UIDeviceOrientation o2) { if (o1 == UIDeviceOrientation.FaceDown || o1 == UIDeviceOrientation.FaceUp) return (o2 == UIDeviceOrientation.FaceDown || o2 == UIDeviceOrientation.FaceUp); if (o1 == UIDeviceOrientation.LandscapeLeft || o1 == UIDeviceOrientation.LandscapeRight) return (o2 == UIDeviceOrientation.LandscapeLeft || o2 == UIDeviceOrientation.LandscapeRight); if (o1 == UIDeviceOrientation.Portrait || o1 == UIDeviceOrientation.PortraitUpsideDown) return (o2 == UIDeviceOrientation.Portrait || o2 == UIDeviceOrientation.PortraitUpsideDown); return false; } private static UIDeviceOrientation GetDeviceOrientation (UIInterfaceOrientation self) { switch (self) { case UIInterfaceOrientation.LandscapeLeft: return UIDeviceOrientation.LandscapeLeft; case UIInterfaceOrientation.LandscapeRight: return UIDeviceOrientation.LandscapeRight; case UIInterfaceOrientation.Portrait: return UIDeviceOrientation.Portrait; case UIInterfaceOrientation.PortraitUpsideDown: return UIDeviceOrientation.PortraitUpsideDown; default: throw new InvalidOperationException(); } } } }
29.654987
143
0.709689
[ "Apache-2.0" ]
csnowbar/Xamarin.Mobile
MonoTouch/Xamarin.Mobile/Media/MediaPickerDelegate.cs
11,002
C#
using DeltaEngine.Core; using DeltaEngine.Platforms; using DeltaEngine.ScreenSpaces; using NUnit.Framework; namespace Breakout.Tests { public class GameTests : TestWithMocksOrVisually { [Test] public void Draw() { Resolve<Paddle>(); Resolve<RelativeScreenSpace>(); new Game(Resolve<Window>()); } [Test, CloseAfterFirstFrame] public void RemoveBallIfGameIsOver() { var score = Resolve<Score>(); bool isGameOver = false; score.GameOver += () => isGameOver = true; score.LifeLost(); score.LifeLost(); score.LifeLost(); Assert.IsTrue(isGameOver); } [Test, CloseAfterFirstFrame] public void KillingAllBricksShouldAdvanceToNextLevel() { bool isGameOver = false; var level = Resolve<Level>(); var score = Resolve<Score>(); Score remScore = score; remScore.GameOver += () => isGameOver = true; Assert.AreEqual(1, score.Level); DisposeAllBricks(level); Assert.AreEqual(0, level.BricksLeft); Assert.AreEqual(1, remScore.Level); Assert.IsFalse(isGameOver); } private static void DisposeAllBricks(Level level) { for (float x = 0; x < 1.0f; x += 0.1f) for (float y = 0; y < 1.0f; y += 0.1f) if (level.GetBrickAt(x, y) != null) level.GetBrickAt(x, y).IsVisible = false; } } }
25.075472
57
0.645598
[ "Apache-2.0" ]
DeltaEngine/DeltaEngine
Samples/Breakout/Tests/GameTests.cs
1,331
C#
// // ToolStripItemImageScaling.cs // // 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. // // Copyright (c) 2006 Novell, Inc. // // Authors: // Jonathan Pobst (monkey@jpobst.com) // namespace System.Windows.Forms { public enum ToolStripItemImageScaling { None = 0, SizeToFit = 1 } }
34.710526
73
0.749052
[ "Apache-2.0" ]
121468615/mono
mcs/class/Managed.Windows.Forms/System.Windows.Forms/ToolStripItemImageScaling.cs
1,319
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 10.03.2021. // // (double)string_column==double_column // using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D2.Query.CastAs.SET_001.String.Double{ //////////////////////////////////////////////////////////////////////////////// using T_SOURCE_VALUE=System.String; using T_TARGET_VALUE=System.Double; //////////////////////////////////////////////////////////////////////////////// //class TestSet__001__field public static class TestSet__001__field { private const string c_NameOf__TABLE="TEST_MODIFY_ROW2"; private const string c_NameOf__COL_SOURCE="COL_VARCHAR_128"; private const string c_NameOf__COL_TARGET="COL2_DOUBLE"; private const string c_NameOf__TARGET_SQL_TYPE="DOUBLE PRECISION"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("TEST_ID")] public System.Int64? TEST_ID { get; set; } [Column(c_NameOf__COL_SOURCE,TypeName="VARCHAR(128)")] public T_SOURCE_VALUE COL_SOURCE { get; set; } [Column(c_NameOf__COL_TARGET)] public T_TARGET_VALUE COL_TARGET { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001__m1_6() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_SOURCE_VALUE c_valueSource="-1.6"; const T_TARGET_VALUE c_valueTarget=-1.6; System.Int64? testID=Helper__InsertRow(db,c_valueSource,c_valueTarget); var recs=db.testTable.Where(r => (T_TARGET_VALUE)(object)r.COL_SOURCE==r.COL_TARGET && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_valueSource, r.COL_SOURCE); Assert.AreEqual (c_valueTarget, r.COL_TARGET); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_SOURCE).T(", ").N("t",c_NameOf__COL_TARGET).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (CAST(").N("t",c_NameOf__COL_SOURCE).T(" AS "+c_NameOf__TARGET_SQL_TYPE+") = ").N("t",c_NameOf__COL_TARGET).T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_001__m1_6 //----------------------------------------------------------------------- [Test] public static void Test_002__m1_5() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_SOURCE_VALUE c_valueSource="-1.5"; const T_TARGET_VALUE c_valueTarget=-1.5; System.Int64? testID=Helper__InsertRow(db,c_valueSource,c_valueTarget); var recs=db.testTable.Where(r => (T_TARGET_VALUE)(object)r.COL_SOURCE==r.COL_TARGET && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_valueSource, r.COL_SOURCE); Assert.AreEqual (c_valueTarget, r.COL_TARGET); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_SOURCE).T(", ").N("t",c_NameOf__COL_TARGET).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (CAST(").N("t",c_NameOf__COL_SOURCE).T(" AS "+c_NameOf__TARGET_SQL_TYPE+") = ").N("t",c_NameOf__COL_TARGET).T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_002__m1_5 //----------------------------------------------------------------------- [Test] public static void Test_003__m1_4() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_SOURCE_VALUE c_valueSource="-1.4"; const T_TARGET_VALUE c_valueTarget=-1.4; System.Int64? testID=Helper__InsertRow(db,c_valueSource,c_valueTarget); var recs=db.testTable.Where(r => (T_TARGET_VALUE)(object)r.COL_SOURCE==r.COL_TARGET && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_valueSource, r.COL_SOURCE); Assert.AreEqual (c_valueTarget, r.COL_TARGET); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_SOURCE).T(", ").N("t",c_NameOf__COL_TARGET).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (CAST(").N("t",c_NameOf__COL_SOURCE).T(" AS "+c_NameOf__TARGET_SQL_TYPE+") = ").N("t",c_NameOf__COL_TARGET).T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_003__m1_4 //----------------------------------------------------------------------- [Test] public static void Test_004__m1() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_SOURCE_VALUE c_valueSource="-1"; const T_TARGET_VALUE c_valueTarget=-1; System.Int64? testID=Helper__InsertRow(db,c_valueSource,c_valueTarget); var recs=db.testTable.Where(r => (T_TARGET_VALUE)(object)r.COL_SOURCE==r.COL_TARGET && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_valueSource, r.COL_SOURCE); Assert.AreEqual (c_valueTarget, r.COL_TARGET); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_SOURCE).T(", ").N("t",c_NameOf__COL_TARGET).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (CAST(").N("t",c_NameOf__COL_SOURCE).T(" AS "+c_NameOf__TARGET_SQL_TYPE+") = ").N("t",c_NameOf__COL_TARGET).T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_004__m1 //----------------------------------------------------------------------- [Test] public static void Test_005__0() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_SOURCE_VALUE c_valueSource="0"; const T_TARGET_VALUE c_valueTarget=0; System.Int64? testID=Helper__InsertRow(db,c_valueSource,c_valueTarget); var recs=db.testTable.Where(r => (T_TARGET_VALUE)(object)r.COL_SOURCE==r.COL_TARGET && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_valueSource, r.COL_SOURCE); Assert.AreEqual (c_valueTarget, r.COL_TARGET); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_SOURCE).T(", ").N("t",c_NameOf__COL_TARGET).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (CAST(").N("t",c_NameOf__COL_SOURCE).T(" AS "+c_NameOf__TARGET_SQL_TYPE+") = ").N("t",c_NameOf__COL_TARGET).T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_005__0 //----------------------------------------------------------------------- [Test] public static void Test_006__p1() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_SOURCE_VALUE c_valueSource="+1"; const T_TARGET_VALUE c_valueTarget=1; System.Int64? testID=Helper__InsertRow(db,c_valueSource,c_valueTarget); var recs=db.testTable.Where(r => (T_TARGET_VALUE)(object)r.COL_SOURCE==r.COL_TARGET && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_valueSource, r.COL_SOURCE); Assert.AreEqual (c_valueTarget, r.COL_TARGET); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_SOURCE).T(", ").N("t",c_NameOf__COL_TARGET).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (CAST(").N("t",c_NameOf__COL_SOURCE).T(" AS "+c_NameOf__TARGET_SQL_TYPE+") = ").N("t",c_NameOf__COL_TARGET).T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_006__p1 //----------------------------------------------------------------------- [Test] public static void Test_007__p1_4() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_SOURCE_VALUE c_valueSource="+1.4"; const T_TARGET_VALUE c_valueTarget=1.4; System.Int64? testID=Helper__InsertRow(db,c_valueSource,c_valueTarget); var recs=db.testTable.Where(r => (T_TARGET_VALUE)(object)r.COL_SOURCE==r.COL_TARGET && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_valueSource, r.COL_SOURCE); Assert.AreEqual (c_valueTarget, r.COL_TARGET); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_SOURCE).T(", ").N("t",c_NameOf__COL_TARGET).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (CAST(").N("t",c_NameOf__COL_SOURCE).T(" AS "+c_NameOf__TARGET_SQL_TYPE+") = ").N("t",c_NameOf__COL_TARGET).T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_007__p1_4 //----------------------------------------------------------------------- [Test] public static void Test_008__p1_5() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_SOURCE_VALUE c_valueSource="+1.5"; const T_TARGET_VALUE c_valueTarget=1.5; System.Int64? testID=Helper__InsertRow(db,c_valueSource,c_valueTarget); var recs=db.testTable.Where(r => (T_TARGET_VALUE)(object)r.COL_SOURCE==r.COL_TARGET && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_valueSource, r.COL_SOURCE); Assert.AreEqual (c_valueTarget, r.COL_TARGET); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_SOURCE).T(", ").N("t",c_NameOf__COL_TARGET).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (CAST(").N("t",c_NameOf__COL_SOURCE).T(" AS "+c_NameOf__TARGET_SQL_TYPE+") = ").N("t",c_NameOf__COL_TARGET).T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_008__p1_5 //----------------------------------------------------------------------- [Test] public static void Test_009__p1_6() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_SOURCE_VALUE c_valueSource="+1.6"; const T_TARGET_VALUE c_valueTarget=1.6; System.Int64? testID=Helper__InsertRow(db,c_valueSource,c_valueTarget); var recs=db.testTable.Where(r => (T_TARGET_VALUE)(object)r.COL_SOURCE==r.COL_TARGET && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_valueSource, r.COL_SOURCE); Assert.AreEqual (c_valueTarget, r.COL_TARGET); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_SOURCE).T(", ").N("t",c_NameOf__COL_TARGET).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (CAST(").N("t",c_NameOf__COL_SOURCE).T(" AS "+c_NameOf__TARGET_SQL_TYPE+") = ").N("t",c_NameOf__COL_TARGET).T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_009__p1_6 //----------------------------------------------------------------------- [Test] public static void Test_M01__minValue() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_SOURCE_VALUE c_valueSource="-1.7976931348623157E+308"; const T_TARGET_VALUE c_valueTarget=T_TARGET_VALUE.MinValue; System.Int64? testID=Helper__InsertRow(db,c_valueSource,c_valueTarget); var recs=db.testTable.Where(r => (T_TARGET_VALUE)(object)r.COL_SOURCE==r.COL_TARGET && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_valueSource, r.COL_SOURCE); Assert.AreEqual (c_valueTarget, r.COL_TARGET); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_SOURCE).T(", ").N("t",c_NameOf__COL_TARGET).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (CAST(").N("t",c_NameOf__COL_SOURCE).T(" AS "+c_NameOf__TARGET_SQL_TYPE+") = ").N("t",c_NameOf__COL_TARGET).T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_M01__minValue //----------------------------------------------------------------------- [Test] public static void Test_M02__maxValue() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_SOURCE_VALUE c_valueSource="+1.7976931348623157E+308"; const T_TARGET_VALUE c_valueTarget=T_TARGET_VALUE.MaxValue; System.Int64? testID=Helper__InsertRow(db,c_valueSource,c_valueTarget); var recs=db.testTable.Where(r => (T_TARGET_VALUE)(object)r.COL_SOURCE==r.COL_TARGET && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_valueSource, r.COL_SOURCE); Assert.AreEqual (c_valueTarget, r.COL_TARGET); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_SOURCE).T(", ").N("t",c_NameOf__COL_TARGET).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (CAST(").N("t",c_NameOf__COL_SOURCE).T(" AS "+c_NameOf__TARGET_SQL_TYPE+") = ").N("t",c_NameOf__COL_TARGET).T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_M02__maxValue //----------------------------------------------------------------------- [Test] public static void Test_M03() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_SOURCE_VALUE c_valueSource="000012345.7"; const T_TARGET_VALUE c_valueTarget=12345.7; System.Int64? testID=Helper__InsertRow(db,c_valueSource,c_valueTarget); var recs=db.testTable.Where(r => (T_TARGET_VALUE)(object)r.COL_SOURCE==r.COL_TARGET && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_valueSource, r.COL_SOURCE); Assert.AreEqual (c_valueTarget, r.COL_TARGET); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_SOURCE).T(", ").N("t",c_NameOf__COL_TARGET).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (CAST(").N("t",c_NameOf__COL_SOURCE).T(" AS "+c_NameOf__TARGET_SQL_TYPE+") = ").N("t",c_NameOf__COL_TARGET).T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_M03 //Helper methods -------------------------------------------------------- private static System.Int64 Helper__InsertRow(MyContext db, T_SOURCE_VALUE valueForColSource, T_TARGET_VALUE valueForColTarget) { var newRecord=new MyContext.TEST_RECORD(); newRecord.COL_SOURCE =valueForColSource; newRecord.COL_TARGET =valueForColTarget; db.testTable.Add(newRecord); db.SaveChanges(); db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_SOURCE).T(", ").N(c_NameOf__COL_TARGET).T(")").EOL() .T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL() .T("RETURNING ").N("TEST_ID").EOL() .T("INTO ").P("p2").T(";")); Assert.IsTrue (newRecord.TEST_ID.HasValue); Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value); return newRecord.TEST_ID.Value; }//Helper__InsertRow };//class TestSet__001__field //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D2.Query.CastAs.SET_001.String.Double
26.205742
192
0.570111
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D2/Query/CastAs/SET_001/String/Double/TestSet__001__field.cs
21,910
C#
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * 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 OpenSim Project 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 DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Xml; using log4net; using Nwc.XmlRpc; namespace OpenSim.Framework.Servers.HttpServer { public delegate XmlRpcResponse OSHttpXmlRpcProcessor(XmlRpcRequest request); public class OSHttpXmlRpcHandler: OSHttpHandler { private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// XmlRpcMethodMatch tries to reify (deserialize) an incoming /// XmlRpc request (and posts it to the "whiteboard") and /// checks whether the method name is one we are interested /// in. /// </summary> /// <returns>true if the handler is interested in the content; /// false otherwise</returns> protected bool XmlRpcMethodMatch(OSHttpRequest req) { XmlRpcRequest xmlRpcRequest = null; // check whether req is already reified // if not: reify (and post to whiteboard) try { if (req.Whiteboard.ContainsKey("xmlrequest")) { xmlRpcRequest = req.Whiteboard["xmlrequest"] as XmlRpcRequest; } else { StreamReader body = new StreamReader(req.InputStream); string requestBody = body.ReadToEnd(); xmlRpcRequest = (XmlRpcRequest)(new XmlRpcRequestDeserializer()).Deserialize(requestBody); req.Whiteboard["xmlrequest"] = xmlRpcRequest; } } catch (XmlException) { _log.ErrorFormat("[OSHttpXmlRpcHandler] failed to deserialize XmlRpcRequest from {0}", req.ToString()); return false; } // check against methodName if ((null != xmlRpcRequest) && !String.IsNullOrEmpty(xmlRpcRequest.MethodName) && xmlRpcRequest.MethodName == _methodName) { _log.DebugFormat("[OSHttpXmlRpcHandler] located handler {0} for {1}", _methodName, req.ToString()); return true; } return false; } // contains handler for processing XmlRpc Request private XmlRpcMethod _handler; // contains XmlRpc method name private string _methodName; /// <summary> /// Instantiate an XmlRpc handler. /// </summary> /// <param name="handler">XmlRpcMethod /// delegate</param> /// <param name="methodName">XmlRpc method name</param> /// <param name="path">XmlRpc path prefix (regular expression)</param> /// <param name="headers">Dictionary with header names and /// regular expressions to match content of headers</param> /// <param name="whitelist">IP whitelist of remote end points /// to accept (regular expression)</param> /// <remarks> /// Except for handler and methodName, all other parameters /// can be null, in which case they are not taken into account /// when the handler is being looked up. /// </remarks> public OSHttpXmlRpcHandler(XmlRpcMethod handler, string methodName, Regex path, Dictionary<string, Regex> headers, Regex whitelist) : base(new Regex(@"^POST$", RegexOptions.IgnoreCase | RegexOptions.Compiled), path, null, headers, new Regex(@"^(text|application)/xml", RegexOptions.IgnoreCase | RegexOptions.Compiled), whitelist) { _handler = handler; _methodName = methodName; } /// <summary> /// Instantiate an XmlRpc handler. /// </summary> /// <param name="handler">XmlRpcMethod /// delegate</param> /// <param name="methodName">XmlRpc method name</param> public OSHttpXmlRpcHandler(XmlRpcMethod handler, string methodName) : this(handler, methodName, null, null, null) { } /// <summary> /// Invoked by OSHttpRequestPump. /// </summary> public override OSHttpHandlerResult Process(OSHttpRequest request) { XmlRpcResponse xmlRpcResponse; string responseString; // check whether we are interested in this request if (!XmlRpcMethodMatch(request)) return OSHttpHandlerResult.Pass; OSHttpResponse resp = new OSHttpResponse(request); try { // reified XmlRpcRequest must still be on the whiteboard XmlRpcRequest xmlRpcRequest = request.Whiteboard["xmlrequest"] as XmlRpcRequest; xmlRpcResponse = _handler(xmlRpcRequest); responseString = XmlRpcResponseSerializer.Singleton.Serialize(xmlRpcResponse); resp.ContentType = "text/xml"; byte[] buffer = Encoding.UTF8.GetBytes(responseString); resp.SendChunked = false; resp.ContentLength = buffer.Length; resp.ContentEncoding = Encoding.UTF8; resp.Body.Write(buffer, 0, buffer.Length); resp.Body.Flush(); resp.Send(); } catch (Exception ex) { _log.WarnFormat("[OSHttpXmlRpcHandler]: Error: {0}", ex.Message); return OSHttpHandlerResult.Pass; } return OSHttpHandlerResult.Done; } } }
40.320442
119
0.620033
[ "BSD-3-Clause" ]
WhiteCoreSim/WhiteCore-Merger
OpenSim/Framework/Servers/HttpServer/OSHttpXmlRpcHandler.cs
7,298
C#
namespace SharpIpp.Model { public enum JobHoldUntil { Unsupported, /// <summary> /// 'no-hold': immediately, if there are not other reasons to hold the job /// </summary> NoHold, /// <summary> /// 'indefinite': - the job is held indefinitely, until a client performs a Release-Job (section 3.3.6) /// </summary> Indefinite, /// <summary> /// 'day-time': during the day /// </summary> DayTime, /// <summary> /// 'evening': evening /// </summary> Evening, /// <summary> /// 'night': night /// </summary> Night, /// <summary> /// 'weekend': weekend /// </summary> Weekend, /// <summary> /// 'second-shift': second-shift (after close of business) /// </summary> SecondShift, /// <summary> /// 'third-shift': third-shift (after midnight) /// </summary> ThirdShift } }
22.978723
116
0.45463
[ "MIT" ]
KittyDotNet/SharpIpp
SharpIpp/Model/JobHoldUntil.cs
1,082
C#
using System; using System.Collections.Generic; using System.Linq.Expressions; using ServiceStack.OrmLite; using Sod.Dba; using Sod.IoC; namespace Sod.Repositories { public class GenericRepository<T> : IRepository<T>, IDependency { public T FindById(int id) { using (var db = DbConnectionFactory.GetDbConnection()) { var entity = db.SingleById<T>(id); return entity; } } public IEnumerable<T> FindAll() { using (var db = DbConnectionFactory.GetDbConnection()) { var list = db.Select<T>(); return list; } } public IPagedList<T> FindPagedList(Expression<Func<T, bool>> predicate, int pageIndex = 0, int pageSize = 20) { using (var db = DbConnectionFactory.GetDbConnection()) { var entities = db.Select<T>(predicate); var totalCount = db.Count<T>(predicate); var list = new PagedList<T>(entities, pageIndex, pageSize, (int)totalCount); return list; } } public int Insert(T entity) { using (var db = DbConnectionFactory.GetDbConnection()) { return (int)db.Insert(entity); } } public bool Update(T entity) { using (var db = DbConnectionFactory.GetDbConnection()) { return db.Update(entity) > 0; } } public bool Delete(T entity) { using (var db = DbConnectionFactory.GetDbConnection()) { return db.Delete(entity) > 0; } } public bool Delete(Expression<Func<T, bool>> @where) { using (var db = DbConnectionFactory.GetDbConnection()) { return db.Delete(@where) > 0; } } public bool DeleteById(object id) { using (var db = DbConnectionFactory.GetDbConnection()) { return db.DeleteById<T>(id) > 0; } } public bool DeleteByIds(object[] ids) { using (var db = DbConnectionFactory.GetDbConnection()) { return db.DeleteByIds<T>(ids) > 0; } } } }
26.866667
117
0.495864
[ "MIT" ]
lampo1024/Sod
Sod.Repositories/GenericRepository.cs
2,420
C#
using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace Mntone.SvgForXaml.Primitives { public sealed class SvgPointCollection : IReadOnlyCollection<SvgPoint> { private readonly Collection<SvgPoint> _points; internal SvgPointCollection(string attributeValue) { var points = attributeValue.Split(new[] { ' ', '\n', '\r', '\t' }).Where(s => !string.IsNullOrWhiteSpace(s)).Select(p => SvgPoint.Parse(p)); this._points = new Collection<SvgPoint>(); foreach (var point in points) this._points.Add(point); } public int Count => this._points.Count; public IEnumerator<SvgPoint> GetEnumerator() => this._points.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable)this._points).GetEnumerator(); } }
33.833333
143
0.743842
[ "MIT" ]
mntone/SvgForXaml
Mntone.SvgForXaml/Mntone.SvgForXaml.Shared/Primitives/SvgPointCollection.cs
814
C#
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Security.Principal; using System.Web; using System.Web.SessionState; using MvcContrib.TestHelper.Fakes; namespace SpecsFor.Mvc.Helpers { public class FakeHttpContext : HttpContextBase { private readonly HttpCookieCollection _cookies; private readonly NameValueCollection _formParams; private IPrincipal _principal; private readonly NameValueCollection _queryStringParams; private readonly string _relativeUrl; private readonly string _method; private readonly SessionStateItemCollection _sessionItems; private HttpResponseBase _response; private HttpRequestBase _request; private readonly Dictionary<object, object> _items; public override HttpRequestBase Request { get { return this._request ?? (HttpRequestBase)new MvcContrib.TestHelper.Fakes.FakeHttpRequest(this._relativeUrl, this._method, this._formParams, this._queryStringParams, this._cookies); } } public override HttpResponseBase Response { get { return this._response ?? (HttpResponseBase)new FakeHttpResponse(); } } public override IPrincipal User { get { return this._principal; } set { this._principal = value; } } public override HttpSessionStateBase Session { get { return (HttpSessionStateBase)new FakeHttpSessionState(this._sessionItems); } } public override IDictionary Items { get { return (IDictionary)this._items; } } public override bool SkipAuthorization { get; set; } public FakeHttpContext(string relativeUrl, string method) : this(relativeUrl, method, (IPrincipal)null, (NameValueCollection)null, (NameValueCollection)null, (HttpCookieCollection)null, (SessionStateItemCollection)null) { } public FakeHttpContext(string relativeUrl) : this(relativeUrl, (IPrincipal)null, (NameValueCollection)null, (NameValueCollection)null, (HttpCookieCollection)null, (SessionStateItemCollection)null) { } public FakeHttpContext(string relativeUrl, IPrincipal principal, NameValueCollection formParams, NameValueCollection queryStringParams, HttpCookieCollection cookies, SessionStateItemCollection sessionItems) : this(relativeUrl, (string)null, principal, formParams, queryStringParams, cookies, sessionItems) { } public FakeHttpContext(string relativeUrl, string method, IPrincipal principal, NameValueCollection formParams, NameValueCollection queryStringParams, HttpCookieCollection cookies, SessionStateItemCollection sessionItems) { this._relativeUrl = relativeUrl; this._method = method; this._principal = principal; this._formParams = formParams; this._queryStringParams = queryStringParams; this._cookies = cookies; this._sessionItems = sessionItems; this._items = new Dictionary<object, object>(); } public static MvcContrib.TestHelper.Fakes.FakeHttpContext Root() { return new MvcContrib.TestHelper.Fakes.FakeHttpContext("~/"); } public void SetRequest(HttpRequestBase request) { this._request = request; } public void SetResponse(HttpResponseBase response) { this._response = response; } public override object GetService(Type serviceType) { return (object)null; } } }
29.042373
224
0.742048
[ "MIT" ]
milesibastos/SpecsFor
SpecsFor.Mvc/Helpers/FakeHttpContext.cs
3,429
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Vod.V20180717.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class PoliticalAsrReviewTemplateInfoForUpdate : AbstractModel { /// <summary> /// 语音鉴别涉及令人不适宜的信息的任务开关,可选值: /// <li>ON:开启语音鉴别涉及令人不适宜的信息的任务;</li> /// <li>OFF:关闭语音鉴别涉及令人不适宜的信息的任务。</li> /// </summary> [JsonProperty("Switch")] public string Switch{ get; set; } /// <summary> /// 判定涉嫌违规的分数阈值,当智能识别达到该分数以上,认为涉嫌违规。取值范围:0~100。 /// </summary> [JsonProperty("BlockConfidence")] public long? BlockConfidence{ get; set; } /// <summary> /// 判定需人工复核是否违规的分数阈值,当智能识别达到该分数以上,认为需人工复核。取值范围:0~100。 /// </summary> [JsonProperty("ReviewConfidence")] public long? ReviewConfidence{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "Switch", this.Switch); this.SetParamSimple(map, prefix + "BlockConfidence", this.BlockConfidence); this.SetParamSimple(map, prefix + "ReviewConfidence", this.ReviewConfidence); } } }
33.033333
89
0.642785
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Vod/V20180717/Models/PoliticalAsrReviewTemplateInfoForUpdate.cs
2,278
C#
using System.Web; using System.Web.Mvc; namespace DogAndPeople { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } } }
18.928571
80
0.656604
[ "MIT" ]
athena272/C-Net
Projetos/DogAndPeople/App_Start/FilterConfig.cs
267
C#
using System; using System.Linq; using System.Text; using System.Threading; using BinBridge.Ssh.Common; using System.Collections.Generic; using System.Globalization; using BinBridge.Ssh.Sftp.Responses; using BinBridge.Ssh.Sftp.Requests; namespace BinBridge.Ssh.Sftp { internal class SftpSession : SubsystemSession, ISftpSession { private const int MaximumSupportedVersion = 3; private const int MinimumSupportedVersion = 0; private readonly Dictionary<uint, SftpRequest> _requests = new Dictionary<uint, SftpRequest>(); //FIXME: obtain from SftpClient! private readonly List<byte> _data = new List<byte>(32 * 1024); private EventWaitHandle _sftpVersionConfirmed = new AutoResetEvent(false); private IDictionary<string, string> _supportedExtensions; /// <summary> /// Gets the remote working directory. /// </summary> /// <value> /// The remote working directory. /// </value> public string WorkingDirectory { get; private set; } /// <summary> /// Gets the SFTP protocol version. /// </summary> /// <value> /// The SFTP protocol version. /// </value> public uint ProtocolVersion { get; private set; } private long _requestId; /// <summary> /// Gets the next request id for sftp session. /// </summary> public uint NextRequestId { get { return (uint) Interlocked.Increment(ref _requestId); } } public SftpSession(ISession session, TimeSpan operationTimeout, Encoding encoding) : base(session, "sftp", operationTimeout, encoding) { } /// <summary> /// Changes the current working directory to the specified path. /// </summary> /// <param name="path">The new working directory.</param> public void ChangeDirectory(string path) { var fullPath = GetCanonicalPath(path); var handle = RequestOpenDir(fullPath); RequestClose(handle); WorkingDirectory = fullPath; } internal void SendMessage(SftpMessage sftpMessage) { var data = sftpMessage.GetBytes(); SendData(data); } /// <summary> /// Resolves a given path into an absolute path on the server. /// </summary> /// <param name="path">The path to resolve.</param> /// <returns> /// The absolute path. /// </returns> public string GetCanonicalPath(string path) { var fullPath = GetFullRemotePath(path); var canonizedPath = string.Empty; var realPathFiles = RequestRealPath(fullPath, true); if (realPathFiles != null) { canonizedPath = realPathFiles.First().Key; } if (!string.IsNullOrEmpty(canonizedPath)) return canonizedPath; // Check for special cases if (fullPath.EndsWith("/.", StringComparison.OrdinalIgnoreCase) || fullPath.EndsWith("/..", StringComparison.OrdinalIgnoreCase) || fullPath.Equals("/", StringComparison.OrdinalIgnoreCase) || fullPath.IndexOf('/') < 0) return fullPath; var pathParts = fullPath.Split('/'); var partialFullPath = string.Join("/", pathParts, 0, pathParts.Length - 1); if (string.IsNullOrEmpty(partialFullPath)) partialFullPath = "/"; realPathFiles = RequestRealPath(partialFullPath, true); if (realPathFiles != null) { canonizedPath = realPathFiles.First().Key; } if (string.IsNullOrEmpty(canonizedPath)) { return fullPath; } var slash = string.Empty; if (canonizedPath[canonizedPath.Length - 1] != '/') slash = "/"; return string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", canonizedPath, slash, pathParts[pathParts.Length - 1]); } internal string GetFullRemotePath(string path) { var fullPath = path; if (!string.IsNullOrEmpty(path) && path[0] != '/' && WorkingDirectory != null) { if (WorkingDirectory[WorkingDirectory.Length - 1] == '/') { fullPath = string.Format(CultureInfo.InvariantCulture, "{0}{1}", WorkingDirectory, path); } else { fullPath = string.Format(CultureInfo.InvariantCulture, "{0}/{1}", WorkingDirectory, path); } } return fullPath; } protected override void OnChannelOpen() { SendMessage(new SftpInitRequest(MaximumSupportedVersion)); WaitOnHandle(_sftpVersionConfirmed, OperationTimeout); if (ProtocolVersion > MaximumSupportedVersion || ProtocolVersion < MinimumSupportedVersion) { throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Server SFTP version {0} is not supported.", ProtocolVersion)); } // Resolve current directory WorkingDirectory = RequestRealPath(".").First().Key; } protected override void OnDataReceived(byte[] data) { const int packetLengthByteCount = 4; const int sftpMessageTypeByteCount = 1; const int minimumChannelDataLength = packetLengthByteCount + sftpMessageTypeByteCount; var offset = 0; var count = data.Length; // improve performance and reduce GC pressure by not buffering channel data if the received // chunk contains the complete packet data. // // for this, the buffer should be empty and the chunk should contain at least the packet length // and the type of the SFTP message if (_data.Count == 0) { while (count >= minimumChannelDataLength) { // extract packet length var packetDataLength = data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3]; var packetTotalLength = packetDataLength + packetLengthByteCount; // check if complete packet data (or more) is available if (count >= packetTotalLength) { // load and process SFTP message if (!TryLoadSftpMessage(data, offset + packetLengthByteCount, packetDataLength)) { return; } // remove processed bytes from the number of bytes to process as the channel // data we received may contain (part of) another message count -= packetTotalLength; // move offset beyond bytes we just processed offset += packetTotalLength; } else { // we don't have a complete message break; } } // check if there is channel data left to process or buffer if (count == 0) { return; } // check if we processed part of the channel data we received if (offset > 0) { // add (remaining) channel data to internal data holder var remainingChannelData = new byte[count]; Buffer.BlockCopy(data, offset, remainingChannelData, 0, count); _data.AddRange(remainingChannelData); } else { // add (remaining) channel data to internal data holder _data.AddRange(data); } // skip further processing as we'll need a new chunk to complete the message return; } // add (remaining) channel data to internal data holder _data.AddRange(data); while (_data.Count >= minimumChannelDataLength) { // extract packet length var packetDataLength = _data[0] << 24 | _data[1] << 16 | _data[2] << 8 | _data[3]; var packetTotalLength = packetDataLength + packetLengthByteCount; // check if complete packet data is available if (_data.Count < packetTotalLength) { // wait for complete message to arrive first break; } // create buffer to hold packet data var packetData = new byte[packetDataLength]; // copy packet data and bytes for length to array _data.CopyTo(packetLengthByteCount, packetData, 0, packetDataLength); // remove loaded data and bytes for length from _data holder if (_data.Count == packetTotalLength) { // the only buffered data is the data we're processing _data.Clear(); } else { // remove only the data we're processing _data.RemoveRange(0, packetTotalLength); } // load and process SFTP message if (!TryLoadSftpMessage(packetData, 0, packetDataLength)) { break; } } } private bool TryLoadSftpMessage(byte[] packetData, int offset, int count) { // Load SFTP Message and handle it var response = SftpMessage.Load(ProtocolVersion, packetData, offset, count, Encoding); try { var versionResponse = response as SftpVersionResponse; if (versionResponse != null) { ProtocolVersion = versionResponse.Version; _supportedExtensions = versionResponse.Extentions; _sftpVersionConfirmed.Set(); } else { HandleResponse(response as SftpResponse); } return true; } catch (Exception exp) { RaiseError(exp); return false; } } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { var sftpVersionConfirmed = _sftpVersionConfirmed; if (sftpVersionConfirmed != null) { _sftpVersionConfirmed = null; sftpVersionConfirmed.Dispose(); } } } private void SendRequest(SftpRequest request) { lock (_requests) { _requests.Add(request.RequestId, request); } SendMessage(request); } #region SFTP API functions /// <summary> /// Performs SSH_FXP_OPEN request /// </summary> /// <param name="path">The path.</param> /// <param name="flags">The flags.</param> /// <param name="nullOnError">if set to <c>true</c> returns <c>null</c> instead of throwing an exception.</param> /// <returns>File handle.</returns> public byte[] RequestOpen(string path, Flags flags, bool nullOnError = false) { byte[] handle = null; SshException exception = null; using (var wait = new AutoResetEvent(false)) { var request = new SftpOpenRequest(ProtocolVersion, NextRequestId, path, Encoding, flags, response => { handle = response.Handle; wait.Set(); }, response => { exception = GetSftpException(response); wait.Set(); }); SendRequest(request); WaitOnHandle(wait, OperationTimeout); } if (!nullOnError && exception != null) { throw exception; } return handle; } /// <summary> /// Performs SSH_FXP_CLOSE request. /// </summary> /// <param name="handle">The handle.</param> public void RequestClose(byte[] handle) { SshException exception = null; using (var wait = new AutoResetEvent(false)) { var request = new SftpCloseRequest(ProtocolVersion, NextRequestId, handle, response => { exception = GetSftpException(response); wait.Set(); }); SendRequest(request); WaitOnHandle(wait, OperationTimeout); } if (exception != null) { throw exception; } } /// <summary> /// Performs SSH_FXP_READ request. /// </summary> /// <param name="handle">The handle.</param> /// <param name="offset">The offset.</param> /// <param name="length">The length.</param> /// <returns>data array; null if EOF</returns> public byte[] RequestRead(byte[] handle, ulong offset, uint length) { SshException exception = null; byte[] data = null; using (var wait = new AutoResetEvent(false)) { var request = new SftpReadRequest(ProtocolVersion, NextRequestId, handle, offset, length, response => { data = response.Data; wait.Set(); }, response => { if (response.StatusCode != StatusCodes.Eof) { exception = GetSftpException(response); } data = Array<byte>.Empty; wait.Set(); }); SendRequest(request); WaitOnHandle(wait, OperationTimeout); } if (exception != null) { throw exception; } return data; } /// <summary> /// Performs SSH_FXP_WRITE request. /// </summary> /// <param name="handle">The handle.</param> /// <param name="serverOffset">The the zero-based offset (in bytes) relative to the beginning of the file that the write must start at.</param> /// <param name="data">The buffer holding the data to write.</param> /// <param name="offset">the zero-based offset in <paramref name="data" /> at which to begin taking bytes to write.</param> /// <param name="length">The length (in bytes) of the data to write.</param> /// <param name="wait">The wait event handle if needed.</param> /// <param name="writeCompleted">The callback to invoke when the write has completed.</param> public void RequestWrite(byte[] handle, ulong serverOffset, byte[] data, int offset, int length, AutoResetEvent wait, Action<SftpStatusResponse> writeCompleted = null) { SshException exception = null; var request = new SftpWriteRequest(ProtocolVersion, NextRequestId, handle, serverOffset, data, offset, length, response => { if (writeCompleted != null) { writeCompleted(response); } exception = GetSftpException(response); if (wait != null) wait.Set(); }); SendRequest(request); if (wait != null) WaitOnHandle(wait, OperationTimeout); if (exception != null) { throw exception; } } /// <summary> /// Performs SSH_FXP_LSTAT request. /// </summary> /// <param name="path">The path.</param> /// <returns> /// File attributes /// </returns> public SftpFileAttributes RequestLStat(string path) { SshException exception = null; SftpFileAttributes attributes = null; using (var wait = new AutoResetEvent(false)) { var request = new SftpLStatRequest(ProtocolVersion, NextRequestId, path, Encoding, response => { attributes = response.Attributes; wait.Set(); }, response => { exception = GetSftpException(response); wait.Set(); }); SendRequest(request); WaitOnHandle(wait, OperationTimeout); } if (exception != null) { throw exception; } return attributes; } /// <summary> /// Performs SSH_FXP_FSTAT request. /// </summary> /// <param name="handle">The handle.</param> /// <returns> /// File attributes /// </returns> public SftpFileAttributes RequestFStat(byte[] handle) { SshException exception = null; SftpFileAttributes attributes = null; using (var wait = new AutoResetEvent(false)) { var request = new SftpFStatRequest(ProtocolVersion, NextRequestId, handle, response => { attributes = response.Attributes; wait.Set(); }, response => { exception = GetSftpException(response); wait.Set(); }); SendRequest(request); WaitOnHandle(wait, OperationTimeout); } if (exception != null) { throw exception; } return attributes; } /// <summary> /// Performs SSH_FXP_SETSTAT request. /// </summary> /// <param name="path">The path.</param> /// <param name="attributes">The attributes.</param> public void RequestSetStat(string path, SftpFileAttributes attributes) { SshException exception = null; using (var wait = new AutoResetEvent(false)) { var request = new SftpSetStatRequest(ProtocolVersion, NextRequestId, path, Encoding, attributes, response => { exception = GetSftpException(response); wait.Set(); }); SendRequest(request); WaitOnHandle(wait, OperationTimeout); } if (exception != null) { throw exception; } } /// <summary> /// Performs SSH_FXP_FSETSTAT request. /// </summary> /// <param name="handle">The handle.</param> /// <param name="attributes">The attributes.</param> public void RequestFSetStat(byte[] handle, SftpFileAttributes attributes) { SshException exception = null; using (var wait = new AutoResetEvent(false)) { var request = new SftpFSetStatRequest(ProtocolVersion, NextRequestId, handle, attributes, response => { exception = GetSftpException(response); wait.Set(); }); SendRequest(request); WaitOnHandle(wait, OperationTimeout); } if (exception != null) { throw exception; } } /// <summary> /// Performs SSH_FXP_OPENDIR request /// </summary> /// <param name="path">The path.</param> /// <param name="nullOnError">if set to <c>true</c> returns null instead of throwing an exception.</param> /// <returns>File handle.</returns> public byte[] RequestOpenDir(string path, bool nullOnError = false) { SshException exception = null; byte[] handle = null; using (var wait = new AutoResetEvent(false)) { var request = new SftpOpenDirRequest(ProtocolVersion, NextRequestId, path, Encoding, response => { handle = response.Handle; wait.Set(); }, response => { exception = GetSftpException(response); wait.Set(); }); SendRequest(request); WaitOnHandle(wait, OperationTimeout); } if (!nullOnError && exception != null) { throw exception; } return handle; } /// <summary> /// Performs SSH_FXP_READDIR request /// </summary> /// <param name="handle">The handle.</param> /// <returns></returns> public KeyValuePair<string, SftpFileAttributes>[] RequestReadDir(byte[] handle) { SshException exception = null; KeyValuePair<string, SftpFileAttributes>[] result = null; using (var wait = new AutoResetEvent(false)) { var request = new SftpReadDirRequest(ProtocolVersion, NextRequestId, handle, response => { result = response.Files; wait.Set(); }, response => { if (response.StatusCode != StatusCodes.Eof) { exception = GetSftpException(response); } wait.Set(); }); SendRequest(request); WaitOnHandle(wait, OperationTimeout); } if (exception != null) { throw exception; } return result; } /// <summary> /// Performs SSH_FXP_REMOVE request. /// </summary> /// <param name="path">The path.</param> public void RequestRemove(string path) { SshException exception = null; using (var wait = new AutoResetEvent(false)) { var request = new SftpRemoveRequest(ProtocolVersion, NextRequestId, path, Encoding, response => { exception = GetSftpException(response); wait.Set(); }); SendRequest(request); WaitOnHandle(wait, OperationTimeout); } if (exception != null) { throw exception; } } /// <summary> /// Performs SSH_FXP_MKDIR request. /// </summary> /// <param name="path">The path.</param> public void RequestMkDir(string path) { SshException exception = null; using (var wait = new AutoResetEvent(false)) { var request = new SftpMkDirRequest(ProtocolVersion, NextRequestId, path, Encoding, response => { exception = GetSftpException(response); wait.Set(); }); SendRequest(request); WaitOnHandle(wait, OperationTimeout); } if (exception != null) { throw exception; } } /// <summary> /// Performs SSH_FXP_RMDIR request. /// </summary> /// <param name="path">The path.</param> public void RequestRmDir(string path) { SshException exception = null; using (var wait = new AutoResetEvent(false)) { var request = new SftpRmDirRequest(ProtocolVersion, NextRequestId, path, Encoding, response => { exception = GetSftpException(response); wait.Set(); }); SendRequest(request); WaitOnHandle(wait, OperationTimeout); } if (exception != null) { throw exception; } } /// <summary> /// Performs SSH_FXP_REALPATH request /// </summary> /// <param name="path">The path.</param> /// <param name="nullOnError">if set to <c>true</c> returns null instead of throwing an exception.</param> /// <returns></returns> internal KeyValuePair<string, SftpFileAttributes>[] RequestRealPath(string path, bool nullOnError = false) { SshException exception = null; KeyValuePair<string, SftpFileAttributes>[] result = null; using (var wait = new AutoResetEvent(false)) { var request = new SftpRealPathRequest(ProtocolVersion, NextRequestId, path, Encoding, response => { result = response.Files; wait.Set(); }, response => { exception = GetSftpException(response); wait.Set(); }); SendRequest(request); WaitOnHandle(wait, OperationTimeout); } if (!nullOnError && exception != null) { throw exception; } return result; } /// <summary> /// Performs SSH_FXP_STAT request. /// </summary> /// <param name="path">The path.</param> /// <param name="nullOnError">if set to <c>true</c> returns null instead of throwing an exception.</param> /// <returns> /// File attributes /// </returns> internal SftpFileAttributes RequestStat(string path, bool nullOnError = false) { SshException exception = null; SftpFileAttributes attributes = null; using (var wait = new AutoResetEvent(false)) { var request = new SftpStatRequest(ProtocolVersion, NextRequestId, path, Encoding, response => { attributes = response.Attributes; wait.Set(); }, response => { exception = GetSftpException(response); wait.Set(); }); SendRequest(request); WaitOnHandle(wait, OperationTimeout); } if (!nullOnError && exception != null) { throw exception; } return attributes; } /// <summary> /// Performs SSH_FXP_RENAME request. /// </summary> /// <param name="oldPath">The old path.</param> /// <param name="newPath">The new path.</param> public void RequestRename(string oldPath, string newPath) { if (ProtocolVersion < 2) { throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "SSH_FXP_RENAME operation is not supported in {0} version that server operates in.", ProtocolVersion)); } SshException exception = null; using (var wait = new AutoResetEvent(false)) { var request = new SftpRenameRequest(ProtocolVersion, NextRequestId, oldPath, newPath, Encoding, response => { exception = GetSftpException(response); wait.Set(); }); SendRequest(request); WaitOnHandle(wait, OperationTimeout); } if (exception != null) { throw exception; } } /// <summary> /// Performs SSH_FXP_READLINK request. /// </summary> /// <param name="path">The path.</param> /// <param name="nullOnError">if set to <c>true</c> returns null instead of throwing an exception.</param> /// <returns></returns> internal KeyValuePair<string, SftpFileAttributes>[] RequestReadLink(string path, bool nullOnError = false) { if (ProtocolVersion < 3) { throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "SSH_FXP_READLINK operation is not supported in {0} version that server operates in.", ProtocolVersion)); } SshException exception = null; KeyValuePair<string, SftpFileAttributes>[] result = null; using (var wait = new AutoResetEvent(false)) { var request = new SftpReadLinkRequest(ProtocolVersion, NextRequestId, path, Encoding, response => { result = response.Files; wait.Set(); }, response => { exception = GetSftpException(response); wait.Set(); }); SendRequest(request); WaitOnHandle(wait, OperationTimeout); } if (!nullOnError && exception != null) { throw exception; } return result; } /// <summary> /// Performs SSH_FXP_SYMLINK request. /// </summary> /// <param name="linkpath">The linkpath.</param> /// <param name="targetpath">The targetpath.</param> public void RequestSymLink(string linkpath, string targetpath) { if (ProtocolVersion < 3) { throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "SSH_FXP_SYMLINK operation is not supported in {0} version that server operates in.", ProtocolVersion)); } SshException exception = null; using (var wait = new AutoResetEvent(false)) { var request = new SftpSymLinkRequest(ProtocolVersion, NextRequestId, linkpath, targetpath, Encoding, response => { exception = GetSftpException(response); wait.Set(); }); SendRequest(request); WaitOnHandle(wait, OperationTimeout); } if (exception != null) { throw exception; } } #endregion #region SFTP Extended API functions /// <summary> /// Performs posix-rename@openssh.com extended request. /// </summary> /// <param name="oldPath">The old path.</param> /// <param name="newPath">The new path.</param> public void RequestPosixRename(string oldPath, string newPath) { if (ProtocolVersion < 3) { throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "SSH_FXP_EXTENDED operation is not supported in {0} version that server operates in.", ProtocolVersion)); } SshException exception = null; using (var wait = new AutoResetEvent(false)) { var request = new PosixRenameRequest(ProtocolVersion, NextRequestId, oldPath, newPath, Encoding, response => { exception = GetSftpException(response); wait.Set(); }); if (!_supportedExtensions.ContainsKey(request.Name)) throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Extension method {0} currently not supported by the server.", request.Name)); SendRequest(request); WaitOnHandle(wait, OperationTimeout); } if (exception != null) { throw exception; } } /// <summary> /// Performs statvfs@openssh.com extended request. /// </summary> /// <param name="path">The path.</param> /// <param name="nullOnError">if set to <c>true</c> [null on error].</param> /// <returns></returns> public SftpFileSytemInformation RequestStatVfs(string path, bool nullOnError = false) { if (ProtocolVersion < 3) { throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "SSH_FXP_EXTENDED operation is not supported in {0} version that server operates in.", ProtocolVersion)); } SshException exception = null; SftpFileSytemInformation information = null; using (var wait = new AutoResetEvent(false)) { var request = new StatVfsRequest(ProtocolVersion, NextRequestId, path, Encoding, response => { information = response.GetReply<StatVfsReplyInfo>().Information; wait.Set(); }, response => { exception = GetSftpException(response); wait.Set(); }); if (!_supportedExtensions.ContainsKey(request.Name)) throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Extension method {0} currently not supported by the server.", request.Name)); SendRequest(request); WaitOnHandle(wait, OperationTimeout); } if (!nullOnError && exception != null) { throw exception; } return information; } /// <summary> /// Performs fstatvfs@openssh.com extended request. /// </summary> /// <param name="handle">The file handle.</param> /// <param name="nullOnError">if set to <c>true</c> [null on error].</param> /// <returns></returns> /// <exception cref="NotSupportedException"></exception> internal SftpFileSytemInformation RequestFStatVfs(byte[] handle, bool nullOnError = false) { if (ProtocolVersion < 3) { throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "SSH_FXP_EXTENDED operation is not supported in {0} version that server operates in.", ProtocolVersion)); } SshException exception = null; SftpFileSytemInformation information = null; using (var wait = new AutoResetEvent(false)) { var request = new FStatVfsRequest(ProtocolVersion, NextRequestId, handle, response => { information = response.GetReply<StatVfsReplyInfo>().Information; wait.Set(); }, response => { exception = GetSftpException(response); wait.Set(); }); if (!_supportedExtensions.ContainsKey(request.Name)) throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Extension method {0} currently not supported by the server.", request.Name)); SendRequest(request); WaitOnHandle(wait, OperationTimeout); } if (!nullOnError && exception != null) { throw exception; } return information; } /// <summary> /// Performs hardlink@openssh.com extended request. /// </summary> /// <param name="oldPath">The old path.</param> /// <param name="newPath">The new path.</param> internal void HardLink(string oldPath, string newPath) { if (ProtocolVersion < 3) { throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "SSH_FXP_EXTENDED operation is not supported in {0} version that server operates in.", ProtocolVersion)); } SshException exception = null; using (var wait = new AutoResetEvent(false)) { var request = new HardLinkRequest(ProtocolVersion, NextRequestId, oldPath, newPath, response => { exception = GetSftpException(response); wait.Set(); }); if (!_supportedExtensions.ContainsKey(request.Name)) throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Extension method {0} currently not supported by the server.", request.Name)); SendRequest(request); WaitOnHandle(wait, OperationTimeout); } if (exception != null) { throw exception; } } #endregion /// <summary> /// Calculates the optimal size of the buffer to read data from the channel. /// </summary> /// <param name="bufferSize">The buffer size configured on the client.</param> /// <returns> /// The optimal size of the buffer to read data from the channel. /// </returns> public uint CalculateOptimalReadLength(uint bufferSize) { // a SSH_FXP_DATA message has 13 bytes of protocol fields: // bytes 1 to 4: packet length // byte 5: message type // bytes 6 to 9: response id // bytes 10 to 13: length of payload‏ // // most ssh servers limit the size of the payload of a SSH_MSG_CHANNEL_DATA // response to 16 KB; if we requested 16 KB of data, then the SSH_FXP_DATA // payload of the SSH_MSG_CHANNEL_DATA message would be too big (16 KB + 13 bytes), and // as a result, the ssh server would split this into two responses: // one containing 16384 bytes (13 bytes header, and 16371 bytes file data) // and one with the remaining 13 bytes of file data const uint lengthOfNonDataProtocolFields = 13u; var maximumPacketSize = Channel.LocalPacketSize; return Math.Min(bufferSize, maximumPacketSize) - lengthOfNonDataProtocolFields; } /// <summary> /// Calculates the optimal size of the buffer to write data on the channel. /// </summary> /// <param name="bufferSize">The buffer size configured on the client.</param> /// <param name="handle">The file handle.</param> /// <returns> /// The optimal size of the buffer to write data on the channel. /// </returns> /// <remarks> /// Currently, we do not take the remote window size into account. /// </remarks> public uint CalculateOptimalWriteLength(uint bufferSize, byte[] handle) { // 1-4: package length of SSH_FXP_WRITE message // 5: message type // 6-9: request id // 10-13: handle length // <handle> // 14-21: offset // 22-25: data length var lengthOfNonDataProtocolFields = 25u + (uint)handle.Length; var maximumPacketSize = Channel.RemotePacketSize; return Math.Min(bufferSize, maximumPacketSize) - lengthOfNonDataProtocolFields; } private static SshException GetSftpException(SftpStatusResponse response) { switch (response.StatusCode) { case StatusCodes.Ok: return null; case StatusCodes.PermissionDenied: return new SftpPermissionDeniedException(response.ErrorMessage); case StatusCodes.NoSuchFile: return new SftpPathNotFoundException(response.ErrorMessage); default: return new SshException(response.ErrorMessage); } } private void HandleResponse(SftpResponse response) { SftpRequest request; lock (_requests) { _requests.TryGetValue(response.ResponseId, out request); if (request != null) { _requests.Remove(response.ResponseId); } } if (request == null) throw new InvalidOperationException("Invalid response."); request.Complete(response); } } }
34.883965
195
0.489755
[ "MIT" ]
mazong1123/binbridge
BinBridge/src/BinBridge.Ssh/Sftp/SftpSession.cs
43,295
C#
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using FakeItEasy; using Squidex.Domain.Apps.Core; using Squidex.Domain.Apps.Core.Assets; using Squidex.Domain.Apps.Core.Contents; using Squidex.Domain.Apps.Core.Schemas; using Squidex.Domain.Apps.Entities.Assets; using Squidex.Domain.Apps.Entities.Contents.Queries.Steps; using Squidex.Domain.Apps.Entities.TestHelpers; using Squidex.Infrastructure; using Squidex.Infrastructure.Caching; using Squidex.Infrastructure.Json.Objects; using Xunit; namespace Squidex.Domain.Apps.Entities.Contents.Queries { public class ResolveAssetsTests { private readonly IAssetQueryService assetQuery = A.Fake<IAssetQueryService>(); private readonly IUrlGenerator urlGenerator = A.Fake<IUrlGenerator>(); private readonly IRequestCache requestCache = A.Fake<IRequestCache>(); private readonly NamedId<DomainId> appId = NamedId.Of(DomainId.NewGuid(), "my-app"); private readonly NamedId<DomainId> schemaId = NamedId.Of(DomainId.NewGuid(), "my-schema"); private readonly ProvideSchema schemaProvider; private readonly Context requestContext; private readonly ResolveAssets sut; public ResolveAssetsTests() { requestContext = new Context(Mocks.FrontendUser(), Mocks.App(appId, Language.DE)); var schemaDef = new Schema(schemaId.Name) .AddAssets(1, "asset1", Partitioning.Invariant, new AssetsFieldProperties { ResolveFirst = true, MinItems = 2, MaxItems = 3 }) .AddAssets(2, "asset2", Partitioning.Language, new AssetsFieldProperties { ResolveFirst = true, MinItems = 1, MaxItems = 1 }) .SetFieldsInLists("asset1", "asset2"); A.CallTo(() => urlGenerator.AssetContent(appId, A<string>._)) .ReturnsLazily(ctx => $"url/to/{ctx.GetArgument<string>(1)}"); schemaProvider = x => { if (x == schemaId.Id) { return Task.FromResult((Mocks.Schema(appId, schemaId, schemaDef), ResolvedComponents.Empty)); } else { throw new DomainObjectNotFoundException(x.ToString()); } }; sut = new ResolveAssets(urlGenerator, assetQuery, requestCache); } [Fact] public async Task Should_add_assets_id_and_versions_as_dependency() { var doc1 = CreateAsset(DomainId.NewGuid(), 3, AssetType.Unknown, "Document1.docx"); var doc2 = CreateAsset(DomainId.NewGuid(), 4, AssetType.Unknown, "Document2.docx"); var contents = new[] { CreateContent( new[] { doc1.Id }, new[] { doc1.Id }), CreateContent( new[] { doc2.Id }, new[] { doc2.Id }) }; A.CallTo(() => assetQuery.QueryAsync( A<Context>.That.Matches(x => x.ShouldSkipAssetEnrichment() && x.ShouldSkipTotal()), null, A<Q>.That.HasIds(doc1.Id, doc2.Id), A<CancellationToken>._)) .Returns(ResultList.CreateFrom(4, doc1, doc2)); await sut.EnrichAsync(requestContext, contents, schemaProvider, default); A.CallTo(() => requestCache.AddDependency(doc1.UniqueId, doc1.Version)) .MustHaveHappened(); A.CallTo(() => requestCache.AddDependency(doc2.UniqueId, doc2.Version)) .MustHaveHappened(); } [Fact] public async Task Should_enrich_with_asset_urls() { var img1 = CreateAsset(DomainId.NewGuid(), 1, AssetType.Image, "Image1.png"); var img2 = CreateAsset(DomainId.NewGuid(), 2, AssetType.Unknown, "Image2.png", "image/svg+xml"); var doc1 = CreateAsset(DomainId.NewGuid(), 3, AssetType.Unknown, "Document1.png"); var doc2 = CreateAsset(DomainId.NewGuid(), 4, AssetType.Unknown, "Document2.png", "image/svg+xml", 20_000); var contents = new[] { CreateContent( new[] { img1.Id }, new[] { img2.Id, img1.Id }), CreateContent( new[] { doc1.Id }, new[] { doc2.Id, doc1.Id }) }; A.CallTo(() => assetQuery.QueryAsync( A<Context>.That.Matches(x => x.ShouldSkipAssetEnrichment() && x.ShouldSkipTotal()), null, A<Q>.That.HasIds(doc1.Id, doc2.Id, img1.Id, img2.Id), A<CancellationToken>._)) .Returns(ResultList.CreateFrom(4, img1, img2, doc1, doc2)); await sut.EnrichAsync(requestContext, contents, schemaProvider, default); Assert.Equal( new ContentData() .AddField("asset1", new ContentFieldData() .AddLocalized("iv", JsonValue.Array($"url/to/{img1.Id}", img1.FileName))) .AddField("asset2", new ContentFieldData() .AddLocalized("en", JsonValue.Array($"url/to/{img2.Id}", img2.FileName))), contents[0].ReferenceData); Assert.Equal( new ContentData() .AddField("asset1", new ContentFieldData() .AddLocalized("iv", JsonValue.Array(doc1.FileName))) .AddField("asset2", new ContentFieldData() .AddLocalized("en", JsonValue.Array(doc2.FileName))), contents[1].ReferenceData); } [Fact] public async Task Should_not_enrich_references_if_not_api_user() { var contents = new[] { CreateContent(new[] { DomainId.NewGuid() }, Array.Empty<DomainId>()) }; var ctx = new Context(Mocks.ApiUser(), Mocks.App(appId)); await sut.EnrichAsync(ctx, contents, schemaProvider, default); Assert.Null(contents[0].ReferenceData); A.CallTo(() => assetQuery.QueryAsync(A<Context>._, null, A<Q>._, A<CancellationToken>._)) .MustNotHaveHappened(); } [Fact] public async Task Should_not_enrich_references_if_disabled() { var contents = new[] { CreateContent(new[] { DomainId.NewGuid() }, Array.Empty<DomainId>()) }; var ctx = new Context(Mocks.FrontendUser(), Mocks.App(appId)).Clone(b => b.WithoutContentEnrichment(true)); await sut.EnrichAsync(ctx, contents, schemaProvider, default); Assert.Null(contents[0].ReferenceData); A.CallTo(() => assetQuery.QueryAsync(A<Context>._, null, A<Q>._, A<CancellationToken>._)) .MustNotHaveHappened(); } [Fact] public async Task Should_not_invoke_query_service_if_no_assets_found() { var contents = new[] { CreateContent(Array.Empty<DomainId>(), Array.Empty<DomainId>()) }; await sut.EnrichAsync(requestContext, contents, schemaProvider, default); Assert.NotNull(contents[0].ReferenceData); A.CallTo(() => assetQuery.QueryAsync(A<Context>._, null, A<Q>._, A<CancellationToken>._)) .MustNotHaveHappened(); } [Fact] public async Task Should_only_query_first_assets() { var id1 = DomainId.NewGuid(); var id2 = DomainId.NewGuid(); var contents = new[] { CreateContent(new[] { id1, id2 }, Array.Empty<DomainId>()) }; await sut.EnrichAsync(requestContext, contents, schemaProvider, default); Assert.NotNull(contents[0].ReferenceData); A.CallTo(() => assetQuery.QueryAsync( A<Context>.That.Matches(x => x.ShouldSkipAssetEnrichment() && x.ShouldSkipTotal()), null, A<Q>.That.HasIds(id1), A<CancellationToken>._)) .MustHaveHappened(); } private ContentEntity CreateContent(DomainId[] assets1, DomainId[] assets2) { return new ContentEntity { Data = new ContentData() .AddField("asset1", new ContentFieldData() .AddLocalized("iv", JsonValue.Array(assets1.Select(x => x.ToString())))) .AddField("asset2", new ContentFieldData() .AddLocalized("en", JsonValue.Array(assets2.Select(x => x.ToString())))), SchemaId = schemaId }; } private IEnrichedAssetEntity CreateAsset(DomainId id, int version, AssetType type, string fileName, string? fileType = null, int fileSize = 100) { return new AssetEntity { AppId = appId, Id = id, Type = type, FileName = fileName, FileSize = fileSize, MimeType = fileType!, Version = version, }; } } }
39.58
188
0.527236
[ "MIT" ]
Appleseed/squidex
backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Queries/ResolveAssetsTests.cs
9,897
C#
using System; using System.Collections.Generic; using System.Threading; namespace UniRx { /// <summary> /// Represents a group of disposable resources that are disposed together. /// </summary> public abstract class StableCompositeDisposable : ICancelable { /// <summary> /// Creates a new group containing two disposable resources that are disposed together. /// </summary> /// <param name="disposable1">The first disposable resoruce to add to the group.</param> /// <param name="disposable2">The second disposable resoruce to add to the group.</param> /// <returns>Group of disposable resources that are disposed together.</returns> public static ICancelable Create(IDisposable disposable1, IDisposable disposable2) { if (disposable1 == null) throw new ArgumentNullException("disposable1"); if (disposable2 == null) throw new ArgumentNullException("disposable2"); return new Binary(disposable1, disposable2); } /// <summary> /// Creates a new group containing three disposable resources that are disposed together. /// </summary> /// <param name="disposable1">The first disposable resoruce to add to the group.</param> /// <param name="disposable2">The second disposable resoruce to add to the group.</param> /// <param name="disposable3">The third disposable resoruce to add to the group.</param> /// <returns>Group of disposable resources that are disposed together.</returns> public static ICancelable Create(IDisposable disposable1, IDisposable disposable2, IDisposable disposable3) { if (disposable1 == null) throw new ArgumentNullException("disposable1"); if (disposable2 == null) throw new ArgumentNullException("disposable2"); if (disposable3 == null) throw new ArgumentNullException("disposable3"); return new Trinary(disposable1, disposable2, disposable3); } /// <summary> /// Creates a new group containing four disposable resources that are disposed together. /// </summary> /// <param name="disposable1">The first disposable resoruce to add to the group.</param> /// <param name="disposable2">The second disposable resoruce to add to the group.</param> /// <param name="disposable3">The three disposable resoruce to add to the group.</param> /// <param name="disposable4">The four disposable resoruce to add to the group.</param> /// <returns>Group of disposable resources that are disposed together.</returns> public static ICancelable Create(IDisposable disposable1, IDisposable disposable2, IDisposable disposable3, IDisposable disposable4) { if (disposable1 == null) throw new ArgumentNullException("disposable1"); if (disposable2 == null) throw new ArgumentNullException("disposable2"); if (disposable3 == null) throw new ArgumentNullException("disposable3"); if (disposable4 == null) throw new ArgumentNullException("disposable4"); return new Quaternary(disposable1, disposable2, disposable3, disposable4); } /// <summary> /// Creates a new group of disposable resources that are disposed together. /// </summary> /// <param name="disposables">Disposable resources to add to the group.</param> /// <returns>Group of disposable resources that are disposed together.</returns> public static ICancelable Create(params IDisposable[] disposables) { if (disposables == null) throw new ArgumentNullException("disposables"); return new NAry(disposables); } /// <summary> /// Creates a new group of disposable resources that are disposed together. Array is not copied, it's unsafe but optimized. /// </summary> /// <param name="disposables">Disposable resources to add to the group.</param> /// <returns>Group of disposable resources that are disposed together.</returns> public static ICancelable CreateUnsafe(IDisposable[] disposables) { return new NAryUnsafe(disposables); } /// <summary> /// Creates a new group of disposable resources that are disposed together. /// </summary> /// <param name="disposables">Disposable resources to add to the group.</param> /// <returns>Group of disposable resources that are disposed together.</returns> public static ICancelable Create(IEnumerable<IDisposable> disposables) { if (disposables == null) throw new ArgumentNullException("disposables"); return new NAry(disposables); } /// <summary> /// Disposes all disposables in the group. /// </summary> public abstract void Dispose(); /// <summary> /// Gets a value that indicates whether the object is disposed. /// </summary> public abstract bool IsDisposed { get; } class Binary : StableCompositeDisposable { int disposedCallCount = -1; private volatile IDisposable _disposable1; private volatile IDisposable _disposable2; public Binary(IDisposable disposable1, IDisposable disposable2) { _disposable1 = disposable1; _disposable2 = disposable2; } public override bool IsDisposed { get { return disposedCallCount != -1; } } public override void Dispose() { if (Interlocked.Increment(ref disposedCallCount) == 0) { _disposable1.Dispose(); _disposable2.Dispose(); } } } class Trinary : StableCompositeDisposable { int disposedCallCount = -1; private volatile IDisposable _disposable1; private volatile IDisposable _disposable2; private volatile IDisposable _disposable3; public Trinary(IDisposable disposable1, IDisposable disposable2, IDisposable disposable3) { _disposable1 = disposable1; _disposable2 = disposable2; _disposable3 = disposable3; } public override bool IsDisposed { get { return disposedCallCount != -1; } } public override void Dispose() { if (Interlocked.Increment(ref disposedCallCount) == 0) { _disposable1.Dispose(); _disposable2.Dispose(); _disposable3.Dispose(); } } } class Quaternary : StableCompositeDisposable { int disposedCallCount = -1; private volatile IDisposable _disposable1; private volatile IDisposable _disposable2; private volatile IDisposable _disposable3; private volatile IDisposable _disposable4; public Quaternary(IDisposable disposable1, IDisposable disposable2, IDisposable disposable3, IDisposable disposable4) { _disposable1 = disposable1; _disposable2 = disposable2; _disposable3 = disposable3; _disposable4 = disposable4; } public override bool IsDisposed { get { return disposedCallCount != -1; } } public override void Dispose() { if (Interlocked.Increment(ref disposedCallCount) == 0) { _disposable1.Dispose(); _disposable2.Dispose(); _disposable3.Dispose(); _disposable4.Dispose(); } } } class NAry : StableCompositeDisposable { int disposedCallCount = -1; private volatile List<IDisposable> _disposables; public NAry(IDisposable[] disposables) : this((IEnumerable<IDisposable>)disposables) { } public NAry(IEnumerable<IDisposable> disposables) { _disposables = new List<IDisposable>(disposables); // // Doing this on the list to avoid duplicate enumeration of disposables. // if (_disposables.Contains(null)) throw new ArgumentException("Disposables can't contains null", "disposables"); } public override bool IsDisposed { get { return disposedCallCount != -1; } } public override void Dispose() { if (Interlocked.Increment(ref disposedCallCount) == 0) { foreach (var d in _disposables) { d.Dispose(); } } } } class NAryUnsafe : StableCompositeDisposable { int disposedCallCount = -1; private volatile IDisposable[] _disposables; public NAryUnsafe(IDisposable[] disposables) { _disposables = disposables; } public override bool IsDisposed { get { return disposedCallCount != -1; } } public override void Dispose() { if (Interlocked.Increment(ref disposedCallCount) == 0) { var len = _disposables.Length; for (int i = 0; i < len; i++) { _disposables[i].Dispose(); } } } } } }
38.227437
141
0.542827
[ "MIT" ]
317392507/QFramework
Assets/QFramework/Framework/0.Core/Plugins/UniRx/Disposables/StableCompositeDisposable.cs
10,591
C#
using System; using System.IO; namespace Amazon.JSII.Runtime.Services { internal interface INodeProcess : IDisposable { TextWriter StandardInput { get; } TextReader StandardOutput { get; } TextReader StandardError { get; } } }
19
49
0.665414
[ "Apache-2.0" ]
NGL321/jsii
packages/@jsii/dotnet-runtime/src/Amazon.JSII.Runtime/Services/INodeProcess.cs
268
C#
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using NSubstitute.ExceptionExtensions; using Shouldly; using Xunit; namespace AElf { public class TaskQueueTests : CoreAElfTestBase { private readonly ITaskQueueManager _taskQueueManager; public TaskQueueTests() { _taskQueueManager = GetRequiredService<ITaskQueueManager>(); } [Fact] public void Test_StartAsync() { var testQueue = _taskQueueManager.GetQueue("TestQueue"); testQueue.StartAsync().ShouldThrow<InvalidOperationException>(); testQueue.StopAsync(); Assert.Throws<InvalidOperationException>(() => testQueue.Enqueue(async () => { })); } [Fact] public async Task Test_Enqueue() { var result = 1; var testQueue = _taskQueueManager.GetQueue("TestQueue"); Parallel.For(0, 100, i => { testQueue.Enqueue(async () => { var value = result; result = value + 1; }); }); testQueue.Dispose(); result.ShouldBe(101); } [Fact] public async Task Test_Many_Enqueue() { var testData = new int[3]; var testQueueA = _taskQueueManager.GetQueue("TestQueueA"); var testQueueB = _taskQueueManager.GetQueue("TestQueueB"); var testQueueC = _taskQueueManager.GetQueue("TestQueueC"); Parallel.For(0, 100, i => { testQueueA.Enqueue(async () => { testData[0]++; }); testQueueB.Enqueue(async () => { testData[1]++; }); testQueueC.Enqueue(async () => { testData[2]++; }); }); testQueueA.Dispose(); testQueueB.Dispose(); testQueueC.Dispose(); testData[0].ShouldBe(100); testData[1].ShouldBe(100); testData[2].ShouldBe(100); } [Fact] public async Task Test_Dispose() { var result = 1; var testQueue = _taskQueueManager.GetQueue("TestQueue"); Parallel.For(0, 3, i => { testQueue.Enqueue(async () => { var value = result; await Task.Delay(100); result = value + 1; }); }); testQueue.Dispose(); result.ShouldBe(4); Assert.Throws<ObjectDisposedException>(() => testQueue.Enqueue(async () => { result++; })); } [Fact] public void Test_GetQueue() { var defaultQueueA = _taskQueueManager.GetQueue(); var defaultQueueB = _taskQueueManager.GetQueue(); defaultQueueA.ShouldBe(defaultQueueB); var testQueueA1 = _taskQueueManager.GetQueue("TestQueueA"); var testQueueA2 = _taskQueueManager.GetQueue("TestQueueA"); testQueueA1.ShouldBe(testQueueA2); testQueueA1.ShouldNotBe(defaultQueueA); var testQueueB1 = _taskQueueManager.GetQueue("TestQueueB"); var testQueueB2 = _taskQueueManager.GetQueue("TestQueueB"); testQueueB1.ShouldBe(testQueueB2); testQueueB1.ShouldNotBe(defaultQueueA); testQueueB1.ShouldNotBe(testQueueA1); } [Fact] public async Task Test_TaskQueue_StopAsync() { var testQueue = _taskQueueManager.GetQueue("TestQueue"); await testQueue.StopAsync(); var result = 1; Should.Throw<InvalidOperationException>(() => testQueue.Enqueue(async () => { var value = result; result = value + 1; }) ); } [Fact] public async Task Test_TaskQueueManager_Dispose() { _taskQueueManager.Dispose(); var testQueue = _taskQueueManager.GetQueue(); var result = 1; Should.Throw<ObjectDisposedException>(() => testQueue.Enqueue(async () => { var value = result; result = value + 1; }) ); } } }
29.684564
103
0.517748
[ "MIT" ]
quangdo3112/AElf
test/AElf.Core.Tests/TaskQueueTests.cs
4,425
C#
using PotatoReader.Structures; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PotatoReader.Providers { abstract class Source { public abstract Chapter LoadChapter(Book book, int chapterNumber, Action recheckCallback); public abstract void WaitForChapter(Book book, int chapterNumber); public abstract Task<Page> LoadPage(Page page); public abstract Task<Book> LoadBook(string path); } }
26.611111
92
0.797495
[ "MIT" ]
anonymousthing/PotatoReader
PotatoReader/Providers/Source.cs
481
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; namespace IdentityWithDapper.Mvc { 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.190476
70
0.584121
[ "MIT" ]
flaviogf/Cursos
balta/aspnet_core_identity_introduction/IdentityWithDapper/src/IdentityWithDapper.Mvc/Program.cs
529
C#
namespace EverscaleNet.Utils; /// <summary> /// EverOS static /// </summary> public static class EverOS { /// <summary> /// Endpoints static /// </summary> public static class Endpoints { /// <summary> /// Main network endpoints /// </summary> public static string[] Everscale => new[] { "https://eri01.main.everos.dev", "https://gra01.main.everos.dev", "https://gra02.main.everos.dev", "https://lim01.main.everos.dev", "https://rbx01.main.everos.dev" }; /// <summary> /// Dev network endpoints /// </summary> public static string[] Development => new[] { "https://eri01.net.everos.dev/", "https://rbx01.net.everos.dev/", "https://gra01.net.everos.dev/" }; /// <summary> /// Node SE network endpoints /// </summary> public static string[] NodeSE => new[] { "http://localhost", "http://127.0.0.1", "http://0.0.0.0" }; } }
22.243902
47
0.585526
[ "Apache-2.0" ]
everscale-actions/everscale-dotnet
src/EverscaleNet.Utils/EverOS.cs
912
C#
using System; namespace Rackspace { public static class TestData { public static string GenerateName() { return $"ci-test-{Guid.NewGuid()}"; } } }
15.153846
47
0.543147
[ "Apache-2.0" ]
rackspace/rackconnect.net
test/Rackspace.IntegrationTests/TestData.cs
199
C#
using Microsoft.Extensions.Logging; using Npgsql; using watchtower.Code.ExtensionMethods; using watchtower.Models.Census; namespace watchtower.Services.Db { public class VehicleDbStore : BaseStaticDbStore<PsVehicle> { public VehicleDbStore(ILoggerFactory loggerFactory, IDataReader<PsVehicle> reader, IDbHelper helper) : base("vehicle", loggerFactory, reader, helper) { } internal override void SetupUpsertCommand(NpgsqlCommand cmd, PsVehicle param) { cmd.CommandText = @" INSERT INTO vehicle ( id, name, description, type_id, cost_resource_id, image_set_id, image_id ) VALUES ( @ID, @Name, @Description, @TypeID, @CostResourceID, @ImageSetID, @ImageID ) ON CONFLICT (id) DO UPDATE SET name = @Name, description = @Description, type_id = @TypeID, cost_resource_id = @CostResourceID, image_set_id = @ImageSetID, image_id = @ImageID; "; cmd.AddParameter("ID", param.ID); cmd.AddParameter("Name", param.Name); cmd.AddParameter("Description", param.Description); cmd.AddParameter("TypeID", param.TypeID); cmd.AddParameter("CostResourceID", param.CostResourceID); cmd.AddParameter("ImageSetID", param.ImageSetID); cmd.AddParameter("ImageID", param.ImageID); } } }
38.292683
93
0.578344
[ "MIT" ]
Simacrus/honu
Services/Db/VehicleDbStore.cs
1,572
C#
// *********************************************************************** // Copyright (c) 2016 Charlie Poole, Rob Prouse // // 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.Reflection; using System.IO; using System.Diagnostics; namespace NUnit.Engine.Internal { public class ProvidedPathsAssemblyResolver { static ILogger log = InternalTrace.GetLogger(typeof(ProvidedPathsAssemblyResolver)); public ProvidedPathsAssemblyResolver() { _resolutionPaths = new List<string>(); } public void Install() { Debug.Assert(AppDomain.CurrentDomain.IsDefaultAppDomain()); AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolve; } public void AddPath(string dirPath) { if (!_resolutionPaths.Contains(dirPath)) { _resolutionPaths.Add(dirPath); log.Debug("Added path " + dirPath); } } public void AddPathFromFile(string filePath) { string dirPath = Path.GetDirectoryName(filePath); AddPath(dirPath); } public void RemovePath(string dirPath) { _resolutionPaths.Remove(dirPath); } public void RemovePathFromFile(string filePath) { string dirPath = Path.GetDirectoryName(filePath); RemovePath(dirPath); } Assembly AssemblyResolve(object sender, ResolveEventArgs args) { foreach (string path in _resolutionPaths) { string filename = new AssemblyName(args.Name).Name + ".dll"; string fullPath = Path.Combine(path, filename); try { if (File.Exists(fullPath)) { return Assembly.LoadFrom(fullPath); } } catch (Exception) { // Resolution at this path failed. Do not interrupt the process; try the next path. } } return null; } List<string> _resolutionPaths; } }
34.234694
103
0.592846
[ "MIT" ]
TimonPost/nunit-console
src/NUnitEngine/nunit.engine.core/Internal/ProvidedPathsAssemblyResolver.cs
3,355
C#
//@#$&+ // //The MIT X11 License // //Copyright (c) 2010 - 2016 Icucom Corporation // //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 NON-INFRINGEMENT. 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. //@#$&- // ReSharper disable once CheckNamespace namespace PlatformAgileFramework.Platform { /// <summary> /// <para> /// This class provides platform-specific information. There are certain constants /// that need to be loaded before an applcation can even start. Thus /// we create the platform-agility by swapping files. /// </para> /// <para> /// This is the MacintoshDesktop version. /// </para> /// </summary> public class MacPlatformInfo: IPlatformInfo { #region Fields and Autoproperties /// <summary> /// This represents the name of the current platform. /// </summary> public const string CURRENT_PLATFORM_NAME = "Mac"; /// <summary> /// This represents the name of the current platform binding assembly. /// </summary> public const string CURRENT_PLATFORM_ASSY = "ECMA"; /// <summary> /// This represents the default mapping for the c drive for /// the platform. This is legacy stuff for "porting" windows apps to /// mono. It's just fine - leave it alone. /// </summary> public const string C_DRIVE_MAPPING = "/tmp/monoapp/c_drive"; /// <summary> /// This represents the default mapping for the d drive for /// the platform. This is legacy stuff for "porting" windows apps to /// mono. It's just fine - leave it alone. /// </summary> public const string D_DRIVE_MAPPING = "/tmp/monoapp/d_drive"; /// <summary> /// This represents the executable extension for /// the platform. /// </summary> public const string EXECUTABLE_EXTENSION = ".exe"; /// <summary> /// This represents the dynamically linked library extension for /// the platform. /// </summary> public const string DLL_EXTENSION = ".dll"; /// <summary> /// This represents the "main" directory separator character for /// the platform. /// </summary> public const char MAIN_DIR_SEP_CHAR = '/'; /// <summary> /// This represents the "alternative" directory separator character for /// the platform. Our conversion stuff on unix accepts backslash. /// </summary> public const char ALT_DIR_SEP_CHAR = '\\'; #endregion // Fields and Autoproperties #region Implementation of IPlatformInfo /// <summary> /// Default for <see cref="IPlatformInfo"/>. /// </summary> public virtual string CurrentPlatformName { get { return CURRENT_PLATFORM_NAME; } } /// <summary> /// Default for <see cref="IPlatformInfo"/>. /// </summary> public virtual string CurrentPlatformAssyName { get { return CURRENT_PLATFORM_ASSY; } } /// <summary> /// Default for <see cref="IPlatformInfo"/>. /// </summary> public virtual string CDriveMapping { get { return C_DRIVE_MAPPING; } } /// <summary> /// Default for <see cref="IPlatformInfo"/>. /// </summary> public virtual string DDriveMapping { get { return D_DRIVE_MAPPING; } } /// <summary> /// Default for <see cref="IPlatformInfo"/>. /// </summary> public virtual string ExecutableExtension { get { return EXECUTABLE_EXTENSION; } } /// <summary> /// Default for <see cref="IPlatformInfo"/>. /// </summary> public virtual string DllExtension { get { return DLL_EXTENSION; } } /// <summary> /// Default for <see cref="IPlatformInfo"/>. /// </summary> public virtual char MainDirSepChar { get { return MAIN_DIR_SEP_CHAR; } } /// <summary> /// Default for <see cref="IPlatformInfo"/>. /// </summary> public virtual char AltDirSepChar { get { return ALT_DIR_SEP_CHAR; } } #endregion } }
30.468354
84
0.667221
[ "MIT" ]
Platform-Agile-Software/PAF-Community
PlatformAgileFrameworkCore/PlatformAgileFrameworkCoreContractsStandard/Platform/PlatformInfo/MacPlatformInfo.cs
4,814
C#
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.DependencyInjection; using Serilog; using System.Threading.Tasks; using Volo.Abp.AspNetCore.ExceptionHandling; using Volo.Abp.DependencyInjection; using Volo.Abp.ExceptionHandling; using Volo.Abp.Http; using Volo.Abp.Json; namespace Laison.Lapis.Shared.Host { /// <summary> /// 自定义异常过滤器 /// </summary> public class DakExceptionFilter : IAsyncExceptionFilter, ITransientDependency { private readonly IExceptionToErrorInfoConverter _errorInfoConverter; private readonly IHttpExceptionStatusCodeFinder _statusCodeFinder; private readonly IJsonSerializer _jsonSerializer; public DakExceptionFilter( IExceptionToErrorInfoConverter errorInfoConverter, IHttpExceptionStatusCodeFinder statusCodeFinder, IJsonSerializer jsonSerializer) { _errorInfoConverter = errorInfoConverter; _statusCodeFinder = statusCodeFinder; _jsonSerializer = jsonSerializer; } public async Task OnExceptionAsync(ExceptionContext context) { if (!ShouldHandleException(context)) { return; } await HandleAndWrapException(context); } protected virtual bool ShouldHandleException(ExceptionContext context) { //TODO: Create DontWrap attribute to control wrapping..? if (context.ActionDescriptor.IsControllerAction() && context.ActionDescriptor.HasObjectResult()) { return true; } if (context.HttpContext.Request.CanAccept(MimeTypes.Application.Json)) { return true; } if (context.HttpContext.Request.IsAjax()) { return true; } return false; } protected virtual async Task HandleAndWrapException(ExceptionContext context) { //TODO: Trigger an AbpExceptionHandled event or something like that. context.HttpContext.Response.Headers.Add(AbpHttpConsts.AbpErrorFormat, "true"); context.HttpContext.Response.StatusCode = (int)_statusCodeFinder.GetStatusCode(context.HttpContext, context.Exception); var remoteServiceErrorInfo = _errorInfoConverter.Convert(context.Exception, false); var response = new AjaxResponse(false) { Error = remoteServiceErrorInfo }; context.Result = new ObjectResult(response); Log.Error(context.Exception, ""); await context.HttpContext .RequestServices .GetRequiredService<IExceptionNotifier>() .NotifyAsync( new ExceptionNotificationContext(context.Exception) ); context.Exception = null; //Handled! } } }
32.197917
131
0.637334
[ "MIT" ]
zwcm2007/Lapis.Framework
Laison.Lapis.Shared/src/Laison.Lapis.Shared.Host/Filters/DakExceptionFilter.cs
3,109
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using GoPro.Hero.Browser.Media; namespace GoPro.Hero.Browser.Media { public static class TimeLapsedImageExtensions { public static async Task<Stream> ThumbnailAsync(this TimeLapsedImage image, int index) { var name = image.IndexName(index); return await image.ThumbnailAsync(name); } public static async Task<Stream> BigThumbnailAsync(this TimeLapsedImage image,int index) { var name = image.IndexName(index); return await image.BigThumbnailAsync(name); } public static async Task<Stream> BigThumbnailAsync(this TimeLapsedImage image) { return await image.BigThumbnailAsync(image.Name); } public static async Task<IMediaBrowser> DeleteAsync(this TimeLapsedImage image) { for (var i = image.Start; i <= image.End; i++) { var indexName = image.IndexName(i); await image.DeleteFile(indexName); } return image.Browser; } } }
29.463415
96
0.627483
[ "MIT" ]
r1pper/GoPro.Hero
src/GoPro.Hero.Extensions/Browser/Media/TimeLapsedImageExtensions.cs
1,210
C#
using Caliburn.Micro; using OrgPortal.Common; namespace OrgPortal.ViewModels { public class ViewModelBase : Screen { protected ViewModelBase(INavigation navigation) { this.navigation = navigation; } public void GoBack() { this.Navigation.GoBack(); } protected virtual void DeserializeParameter(string value) { } private readonly INavigation navigation; protected INavigation Navigation { get { return navigation; } } public bool CanGoBack { get { return navigation.CanGoBack; } } private bool isBusy; public bool IsBusy { get { return this.isBusy; } set { this.isBusy = value; NotifyOfPropertyChange(() => this.IsBusy); } } private string parameter; public string Parameter { get { return this.parameter; } set { this.parameter = value; NotifyOfPropertyChange(() => this.Parameter); if (value != null) { this.DeserializeParameter(value); } } } } }
17
59
0.621986
[ "MIT" ]
NatchEurope/OrgPortal
OrgPortal/ViewModels/ViewModelBase.cs
1,039
C#
/** * Copyright © 2017-2018 Anki Universal Team. * * 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 distributed with this work in the LICENSE.md file. You may * also obtain a copy of the License from * * 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 NLPJapaneseDictionary.Models; using NLPJapaneseDictionary.Core.DatabaseTable; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace NLPJapaneseDictionary.ViewModels { class OcrWordsViewModel { public int Index { get; private set; } public ObservableCollection<OcrWordsModel> Words { get; set; } public OcrWordsViewModel() { Words = new ObservableCollection<OcrWordsModel>(); } public OcrWordsViewModel(Jocr.TextBlock blocks, int index) { Index = index; List<OcrWordsModel> entriesModel = new List<OcrWordsModel>(); for (int i = 0; i < blocks.Text.Count; i++) entriesModel.Add(new OcrWordsModel(blocks.Text[i])); Words = new ObservableCollection<OcrWordsModel>(entriesModel); } public void AddNewList(Jocr.TextBlock blocks, int index) { Index = index; Words.Clear(); for (int i = 0; i < blocks.Text.Count; i++) Words.Add(new OcrWordsModel(blocks.Text[i])); } } }
33.416667
75
0.666833
[ "Apache-2.0" ]
AnkiUniversal/NLP-Japanese-Dictionary
NLPJapaneseDictionary/ViewModels/OcrWordsViewModel.cs
2,008
C#
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.HSSF.Record { using System; using System.Text; using System.Collections; using NPOI.Util; /** * Title: Write Protect Record * Description: Indicated that the sheet/workbook Is Write protected. * REFERENCE: PG 425 Microsoft Excel 97 Developer's Kit (ISBN: 1-57231-498-2) * @version 3.0-pre */ public class WriteProtectRecord : StandardRecord { public const short sid = 0x86; public WriteProtectRecord() { } /** * Constructs a WriteAccess record and Sets its fields appropriately. * @param in the RecordInputstream to Read the record from */ public WriteProtectRecord(RecordInputStream in1) { } public override String ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append("[WritePROTECT]\n"); buffer.Append("[/WritePROTECT]\n"); return buffer.ToString(); } public override void Serialize(ILittleEndianOutput out1) { } protected override int DataSize { get { return 0; } } public override short Sid { get { return sid; } } } }
29.721519
83
0.566865
[ "Apache-2.0" ]
sunshinele/npoi
main/HSSF/Record/WriteProtectRecord.cs
2,348
C#
using System; using System.Buffers; using System.Text; namespace SuperSocket.ProtoBase { public static class Extensions { public static string GetString(this ReadOnlySequence<byte> buffer, Encoding encoding) { if (buffer.IsSingleSegment) { return encoding.GetString(buffer.First.Span); } return string.Create((int)buffer.Length, buffer, (span, sequence) => { foreach (var segment in sequence) { var count = encoding.GetChars(segment.Span, span); span = span.Slice(count); } }); } } }
25.851852
93
0.528653
[ "Apache-2.0" ]
cnxy/SuperSocket
src/SuperSocket.ProtoBase/Extensions.cs
698
C#
namespace HostBox { /// <summary> /// Component loading configuration. /// </summary> public class ComponentConfig { /// <summary> /// Gets or sets path to domain binaries. /// </summary> public string Path { get; set; } /// <summary> /// Gets or sets path to shared libraries binaries. /// </summary> public string SharedLibraryPath { get; set; } } }
24.944444
59
0.532294
[ "MIT" ]
DenisKrasakovSDV/HostBox
Sources/HostBox/ComponentConfig.cs
451
C#
using System; using System.Collections.Generic; using NUnit.Framework; namespace AggregateSource { namespace EntityTests { [TestFixture] public class WithAnyInstance { [Test] public void ApplierCanNotBeNull() { Assert.Throws<ArgumentNullException>(() => new UseNullApplierEntity()); } [Test] public void PlayEventCanNotBeNull() { Assert.Throws<ArgumentNullException>(() => new PlayWithNullEventEntity()); } [Test] public void ApplyEventCanNotBeNull() { var sut = new ApplyNullEventEntity(); Assert.Throws<ArgumentNullException>(sut.ApplyNull); } [Test] public void RegisterHandlerCanNotBeNull() { Assert.Throws<ArgumentNullException>(() => new RegisterNullHandlerEntity()); } [Test] public void RegisterHandlerCanOnlyBeCalledOncePerEventType() { Assert.Throws<ArgumentException>(() => new RegisterSameEventHandlerTwiceEntity()); } } class UseNullApplierEntity : Entity { public UseNullApplierEntity() : base(null) {} } class PlayWithNullEventEntity : Entity { public PlayWithNullEventEntity() : base(_ => { }) { Play(null); } } class ApplyNullEventEntity : Entity { public ApplyNullEventEntity() : base(_ => { }) {} public void ApplyNull() { Apply(null); } } class RegisterNullHandlerEntity : Entity { public RegisterNullHandlerEntity() : base(_ => { }) { Register<object>(null); } } class RegisterSameEventHandlerTwiceEntity : Entity { public RegisterSameEventHandlerTwiceEntity() : base(_ => { }) { Register<object>(o => { }); Register<object>(o => { }); } } [TestFixture] public class WithInstanceWithHandlers { WithHandlersEntity _sut; Action<object> _applier; List<object> _appliedEvents; [SetUp] public void SetUp() { _appliedEvents = new List<object>(); _applier = _ => _appliedEvents.Add(_); _sut = new WithHandlersEntity(_applier); } [Test] public void PlayCallsHandlerOfEvent() { var expectedEvent = new object(); _sut.Play(expectedEvent); Assert.That(_sut.HandlerCallCount, Is.EqualTo(1)); Assert.That(_sut.PlayedEvents, Is.EquivalentTo(new[] {expectedEvent})); } [Test] public void ApplyEventCallsApplier() { var @event = new object(); _sut.DoApply(@event); Assert.That(_appliedEvents, Is.EquivalentTo(new[] {@event})); } } class WithHandlersEntity : Entity { public WithHandlersEntity(Action<object> applier) : base(applier) { PlayedEvents = new List<object>(); Register<object>(@event => { HandlerCallCount++; PlayedEvents.Add(@event); }); } public void DoApply(object @event) { Apply(@event); } public int HandlerCallCount { get; private set; } public List<object> PlayedEvents { get; private set; } } [TestFixture] public class WithInstanceWithoutHandlers { WithoutHandlersEntity _sut; Action<object> _applier; List<object> _appliedEvents; [SetUp] public void SetUp() { _appliedEvents = new List<object>(); _applier = _ => _appliedEvents.Add(_); _sut = new WithoutHandlersEntity(_applier); } [Test] public void PlayDoesNotThrow() { Assert.DoesNotThrow(() => _sut.Play(new object())); } [Test] public void ApplyEventDoesNotThrow() { var @event = new object(); _sut.DoApply(@event); Assert.That(_appliedEvents, Is.EquivalentTo(new[] {@event})); } } class WithoutHandlersEntity : Entity { public WithoutHandlersEntity(Action<object> applier) : base(applier) {} public void DoApply(object @event) { Apply(@event); } } } }
27.308108
98
0.481591
[ "BSD-3-Clause" ]
jen20/AggregateSource
src/AggregateSource.Tests/EntityTests.cs
5,054
C#
using System.ComponentModel; namespace OpenTracker.Models.Settings { /// <summary> /// This class contains GUI tracking settings data. /// </summary> public class TrackerSettings : ITrackerSettings { public event PropertyChangedEventHandler? PropertyChanged; private bool _displayAllLocations; public bool DisplayAllLocations { get => _displayAllLocations; set { if (_displayAllLocations != value) { _displayAllLocations = value; OnPropertyChanged(nameof(DisplayAllLocations)); } } } private bool _showItemCountsOnMap = true; public bool ShowItemCountsOnMap { get => _showItemCountsOnMap; set { if (_showItemCountsOnMap != value) { _showItemCountsOnMap = value; OnPropertyChanged(nameof(ShowItemCountsOnMap)); } } } /// <summary> /// Raises the PropertyChanged event for the specified property. /// </summary> /// <param name="propertyName"> /// A string representing the property name that changed. /// </param> private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
28.942308
86
0.544186
[ "MIT" ]
jimfasoline/OpenTracker
OpenTracker/Models/Settings/TrackerSettings.cs
1,507
C#
// ----------------------------------------------------------------------- // <copyright file="DataAuthCacheRefreshEventData.cs" company="OSharp开源团队"> // Copyright (c) 2014-2018 OSharp. All rights reserved. // </copyright> // <site>http://www.osharp.org</site> // <last-editor>郭明锋</last-editor> // <last-date>2018-08-12 1:47</last-date> // ----------------------------------------------------------------------- using System.Collections.Generic; using OSharp.EventBuses; using OSharp.Secutiry; namespace OSharp.Security.Events { /// <summary> /// 数据权限缓存刷新事件数据 /// </summary> public class DataAuthCacheRefreshEventData : EventDataBase { /// <summary> /// 获取或设置 要更新的数据权限缓存项集合 /// </summary> public IList<DataAuthCacheItem> SetItems { get; } = new List<DataAuthCacheItem>(); /// <summary> /// 获取或设置 要移除的数据权限缓存项信息 /// </summary> public IList<DataAuthCacheItem> RemoveItems { get; } = new List<DataAuthCacheItem>(); /// <summary> /// 是否有值 /// </summary> public bool HasData() { return SetItems.Count > 0 || RemoveItems.Count > 0; } } }
29.146341
93
0.524686
[ "Apache-2.0" ]
0xflotus/osharp
src/OSharp.Permissions/Security/Events/DataAuthCacheRefreshEventData.cs
1,315
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Models.Api20210809 { using Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Runtime.PowerShell; /// <summary>Error definition.</summary> [System.ComponentModel.TypeConverter(typeof(ErrorDefinitionTypeConverter))] public partial class ErrorDefinition { /// <summary> /// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the /// object before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); /// <summary> /// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); /// <summary> /// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); /// <summary> /// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); /// <summary> /// <c>OverrideToString</c> will be called if it is implemented. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="stringResult">/// instance serialized to a string, normally it is a Json</param> /// <param name="returnNow">/// set returnNow to true if you provide a customized OverrideToString function</param> partial void OverrideToString(ref string stringResult, ref bool returnNow); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Models.Api20210809.ErrorDefinition" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Models.Api20210809.IErrorDefinition" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Models.Api20210809.IErrorDefinition DeserializeFromDictionary(global::System.Collections.IDictionary content) { return new ErrorDefinition(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Models.Api20210809.ErrorDefinition" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Models.Api20210809.IErrorDefinition" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Models.Api20210809.IErrorDefinition DeserializeFromPSObject(global::System.Management.Automation.PSObject content) { return new ErrorDefinition(content); } /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Models.Api20210809.ErrorDefinition" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> internal ErrorDefinition(global::System.Collections.IDictionary content) { bool returnNow = false; BeforeDeserializeDictionary(content, ref returnNow); if (returnNow) { return; } // actually deserialize if (content.Contains("Code")) { ((Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Models.Api20210809.IErrorDefinitionInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Models.Api20210809.IErrorDefinitionInternal)this).Code, global::System.Convert.ToString); } if (content.Contains("Message")) { ((Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Models.Api20210809.IErrorDefinitionInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Models.Api20210809.IErrorDefinitionInternal)this).Message, global::System.Convert.ToString); } if (content.Contains("Detail")) { ((Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Models.Api20210809.IErrorDefinitionInternal)this).Detail = (Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Models.Api20210809.IErrorDefinition[]) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Models.Api20210809.IErrorDefinitionInternal)this).Detail, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Models.Api20210809.IErrorDefinition>(__y, Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Models.Api20210809.ErrorDefinitionTypeConverter.ConvertFrom)); } AfterDeserializeDictionary(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Models.Api20210809.ErrorDefinition" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> internal ErrorDefinition(global::System.Management.Automation.PSObject content) { bool returnNow = false; BeforeDeserializePSObject(content, ref returnNow); if (returnNow) { return; } // actually deserialize if (content.Contains("Code")) { ((Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Models.Api20210809.IErrorDefinitionInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Models.Api20210809.IErrorDefinitionInternal)this).Code, global::System.Convert.ToString); } if (content.Contains("Message")) { ((Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Models.Api20210809.IErrorDefinitionInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Models.Api20210809.IErrorDefinitionInternal)this).Message, global::System.Convert.ToString); } if (content.Contains("Detail")) { ((Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Models.Api20210809.IErrorDefinitionInternal)this).Detail = (Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Models.Api20210809.IErrorDefinition[]) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Models.Api20210809.IErrorDefinitionInternal)this).Detail, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Models.Api20210809.IErrorDefinition>(__y, Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Models.Api20210809.ErrorDefinitionTypeConverter.ConvertFrom)); } AfterDeserializePSObject(content); } /// <summary> /// Creates a new instance of <see cref="ErrorDefinition" />, deserializing the content from a json string. /// </summary> /// <param name="jsonText">a string containing a JSON serialized instance of this model.</param> /// <returns>an instance of the <see cref="className" /> model class.</returns> public static Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Models.Api20210809.IErrorDefinition FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Runtime.Json.JsonNode.Parse(jsonText)); /// <summary>Serializes this instance to a json string.</summary> /// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns> public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Runtime.SerializationMode.IncludeAll)?.ToString(); public override string ToString() { var returnNow = false; var result = global::System.String.Empty; OverrideToString(ref result, ref returnNow); if (returnNow) { return result; } return ToJsonString(); } } /// Error definition. [System.ComponentModel.TypeConverter(typeof(ErrorDefinitionTypeConverter))] public partial interface IErrorDefinition { } }
63.713483
589
0.683273
[ "MIT" ]
Agazoth/azure-powershell
src/BareMetal/generated/api/Models/Api20210809/ErrorDefinition.PowerShell.cs
11,164
C#
using System; using System.Runtime.InteropServices; using System.Windows.Interop; namespace TumblThree.Applications { public class ClipboardMonitor : IDisposable { private bool disposed = false; private readonly HwndSource hwndSource = new HwndSource(0, 0, 0, 0, 0, 0, 0, null, NativeMethods.HWND_MESSAGE); public ClipboardMonitor() { hwndSource.AddHook(WndProc); NativeMethods.AddClipboardFormatListener(hwndSource.Handle); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private static class NativeMethods { /// <summary> /// Sent when the contents of the clipboard have changed. /// </summary> public const int WM_CLIPBOARDUPDATE = 0x031D; /// <summary> /// To find message-only windows, specify HWND_MESSAGE in the hwndParent parameter of the FindWindowEx function. /// </summary> public static readonly IntPtr HWND_MESSAGE = new IntPtr(-3); /// <summary> /// Places the given window in the system-maintained clipboard format listener list. /// </summary> [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool AddClipboardFormatListener(IntPtr hwnd); /// <summary> /// Removes the given window from the system-maintained clipboard format listener list. /// </summary> [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool RemoveClipboardFormatListener(IntPtr hwnd); } protected virtual void Dispose(bool disposing) { if (disposed) return; if (disposing) { NativeMethods.RemoveClipboardFormatListener(hwndSource.Handle); hwndSource.RemoveHook(WndProc); hwndSource.Dispose(); } // Free any unmanaged objects here. // disposed = true; } private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { if (msg == NativeMethods.WM_CLIPBOARDUPDATE) OnClipboardContentChanged?.Invoke(this, EventArgs.Empty); return IntPtr.Zero; } ~ClipboardMonitor() => Dispose(false); /// <summary> /// Occurs when the clipboard content changes. /// </summary> public event EventHandler OnClipboardContentChanged; } }
32.870588
128
0.574445
[ "Apache-2.0", "MIT" ]
Grukz/TumblThree
src/TumblThree/TumblThree.Applications/ClipboardMonitor.cs
2,796
C#
using System; using System.Threading.Tasks; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Connector; namespace OctSolutions.bot.Dialogs { [Serializable] public class RootDialog : IDialog<object> { public Task StartAsync(IDialogContext context) { context.Wait(MessageReceivedAsync); return Task.CompletedTask; } private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result) { var activity = await result as Activity; // calculate something for us to return int length = (activity.Text ?? string.Empty).Length; // return our reply to the user await context.PostAsync($"You sent {activity.Text} which was {length} characters"); context.Wait(MessageReceivedAsync); } } }
28.16129
98
0.644903
[ "MIT" ]
coe-google-apps-support/oct-solutions-bot
OctSolutions.bot/Dialogs/RootDialog.cs
875
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.ApiManagement.V20170301.Outputs { /// <summary> /// Properties controlling TLS Certificate Validation. /// </summary> [OutputType] public sealed class BackendTlsPropertiesResponse { /// <summary> /// Flag indicating whether SSL certificate chain validation should be done when using self-signed certificates for this backend host. /// </summary> public readonly bool? ValidateCertificateChain; /// <summary> /// Flag indicating whether SSL certificate name validation should be done when using self-signed certificates for this backend host. /// </summary> public readonly bool? ValidateCertificateName; [OutputConstructor] private BackendTlsPropertiesResponse( bool? validateCertificateChain, bool? validateCertificateName) { ValidateCertificateChain = validateCertificateChain; ValidateCertificateName = validateCertificateName; } } }
34.358974
142
0.691791
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/ApiManagement/V20170301/Outputs/BackendTlsPropertiesResponse.cs
1,340
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using System.Reflection; namespace ColorsInImage { public partial class Form1 : Form { /*** Fields and Constants ***/ #region private const int MAXCOLORSTOLIST = 256; private int imgWidth = 0; private int imgHeight = 0; private ImageColorInformation imageColorInformation; private ListViewColumnSorter lvwColumnSorter; #endregion /*** Constructor & Initialization ***/ #region public Form1() { InitializeComponent(); imageColorInformation = null; lvwColumnSorter = new ListViewColumnSorter(); listView1.ListViewItemSorter = lvwColumnSorter; } #endregion /*** Event Handlers ***/ #region private void ColorInformation_DoneProcessing(object sender, EventArgs e) { UpdateStatus(imgHeight * imgWidth, imgHeight * imgWidth); UpdateImageInformation(); List<KeyValuePair<string, ImageColor>> myList = imageColorInformation.ColorsList.ToList(); myList.Sort((pair1, pair2) => pair2.Value.Count.CompareTo(pair1.Value.Count)); LoadListViewAsync(myList); } private void ColorInformation_RowProcessed(object sender, RowProcessedEventArgs e) { UpdateStatus(e.Row * imgWidth, e.TotalRows * imgWidth); } private void cmdAll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { foreach(ListViewItem lvi in listView1.Items) { lvi.Checked = true; } } private void cmdInverse_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { foreach (ListViewItem lvi in listView1.Items) { lvi.Checked = !lvi.Checked; } } private void cmdNone_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { foreach (ListViewItem lvi in listView1.Items) { lvi.Checked = false; } } private void cmdOpenImage_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog(this) == DialogResult.OK) { ResetControls(); Image img = Image.FromFile(openFileDialog1.FileName); imgWidth = img.Width; imgHeight = img.Height; pictureBox1.Image = img; imageColorInformation = new ImageColorInformation(); imageColorInformation.RowProcessed += ColorInformation_RowProcessed; imageColorInformation.DoneProcessing += ColorInformation_DoneProcessing; imageColorInformation.GetColorsListAsync(img); } } private void Form1_Load(object sender, EventArgs e) { LoadWebBrowserFromResourceFile(webBrowser1, "about"); openFileDialog1.Title = "Open Image"; LayoutControls(); UpdateStatus(0, 0); } private void listView1_ColumnClick(object sender, ColumnClickEventArgs e) { if (e.Column == lvwColumnSorter.SortColumn) { // Reverse the current sort direction for this column. if (lvwColumnSorter.Order == SortOrder.Ascending) { lvwColumnSorter.Order = SortOrder.Descending; } else { lvwColumnSorter.Order = SortOrder.Ascending; } } else { // Set the column number that is to be sorted; default to ascending. lvwColumnSorter.SortColumn = e.Column; lvwColumnSorter.Order = SortOrder.Ascending; } // Perform the sort with these new sort options. this.listView1.Sort(); } private void panel2_Resize(object sender, EventArgs e) { LayoutControls(); } #endregion /*** Private Methods ***/ #region private void LayoutControls() { Control panParent = cmdAll.Parent; int padSpace = 5; int nextTop = padSpace; int nextLeft = padSpace; cmdAll.Top = nextTop; cmdAll.Left = nextLeft; nextLeft = cmdAll.Left + cmdAll.Width + padSpace; if (nextLeft + cmdNone.Width > panParent.Width) { nextTop = nextTop + cmdAll.Height + padSpace; nextLeft = padSpace; } cmdNone.Top = nextTop; cmdNone.Left = nextLeft; nextLeft = cmdNone.Left + cmdNone.Width + padSpace; if (nextLeft + cmdInverse.Width > panParent.Width) { nextTop = nextTop + cmdInverse.Height + padSpace; nextLeft = padSpace; } cmdInverse.Top = nextTop; cmdInverse.Left = nextLeft; nextLeft = cmdInverse.Left + cmdInverse.Width + padSpace; panParent.Height = cmdInverse.Top + cmdInverse.Height + padSpace; } private void LoadHtmlColors() { LoadWebBrowserFromResourceFile(webBrowser1, "template"); string webText = webBrowser1.DocumentText; for (int i=0; i<6; i++) { string forecolor = ""; string backcolor = ""; string count = ""; if (listView1.CheckedItems.Count > i) { backcolor = listView1.CheckedItems[i].SubItems[0].Text; forecolor = ColorTranslator.ToHtml(listView1.CheckedItems[i].ForeColor); count = listView1.CheckedItems[i].SubItems[1].Text; } webText = webText.Replace(string.Format("<color{0} />", i), backcolor); webText = webText.Replace(string.Format("<colortext{0} />", i), forecolor); } webBrowser1.DocumentText = webText; SaveHtmlFile("Sample1.html", webText); } private async void LoadListViewAsync(List<KeyValuePair<string, ImageColor>> sortedList) { listView1.Columns.Clear(); listView1.Columns.Add("Color"); listView1.Columns.Add("Count"); await Task.Run(() => { int q = 0; for (int i = 0; i < sortedList.Count && i < MAXCOLORSTOLIST; i++) { ImageColor imgColor = sortedList[i].Value; ListViewItem newItem = new ListViewItem(new string[] { imgColor.HtmlColor, imgColor.Count.ToString() }, null, imgColor.TextColor, imgColor.ColorValue, null); newItem.Checked = i < 6; LoadListViewAddItem(newItem); } }); } private delegate void LoadListViewAddItemDelegate(ListViewItem newItem); private void LoadListViewAddItem(ListViewItem newItem) { if (this.InvokeRequired) { this.Invoke(new LoadListViewAddItemDelegate(LoadListViewAddItem), new object[] { newItem }); return; } listView1.Items.Add(newItem); } private void LoadWebBrowserFromResourceFile(WebBrowser webBrowser, string htmlFile) { Type myType = this.GetType(); Assembly assembly = Assembly.GetExecutingAssembly(); string resourceName = string.Format("{0}.html.{1}.html", myType.Namespace, htmlFile); Stream htmlFileStream = assembly.GetManifestResourceStream(resourceName); StreamReader reader = new StreamReader(htmlFileStream); string htmltext = reader.ReadToEnd(); webBrowser.Navigate("about:blank"); HtmlDocument doc = webBrowser.Document; doc.Write(htmltext); //webBrowser.DocumentText = htmltext; } private void ResetControls() { richTextBox1.Clear(); listView1.Items.Clear(); UpdateStatus(0, 0); pictureBox1.Image = null; LoadWebBrowserFromResourceFile(webBrowser1, "about"); } private void SaveHtmlFile(string filename, string htmlText, bool showInBrowser = true) { string htmlFileFullName = System.Reflection.Assembly.GetExecutingAssembly().Location; htmlFileFullName = Path.GetDirectoryName(htmlFileFullName); htmlFileFullName = Path.Combine(htmlFileFullName, filename); File.WriteAllText(htmlFileFullName, htmlText); if (showInBrowser) { System.Diagnostics.Process.Start(htmlFileFullName); } } private void UpdateImageInformation() { richTextBox1.Text = string.Format("Image Information\r\n" + "------------------------------------\r\n" + "Width: {0:#,##0}\r\n" + "Height: {1:#,##0}\r\n" + "Pixels: {2:#,##0}\r\n" + "Distinct Colors: {3:#,##0}", imgWidth, imgHeight, imgWidth * imgHeight, imageColorInformation.ColorsList.Count); } private delegate void UpdateStatusDelegate(int CurrentCount, int TotalCount); private void UpdateStatus(int CurrentCount, int TotalCount) { if (this.InvokeRequired) { this.Invoke(new UpdateStatusDelegate(UpdateStatus), new object[] { CurrentCount, TotalCount }); return; } // Handle special cases if(TotalCount == 0) { toolStripStatusLabel1.Text = "Open an image to start"; toolStripProgressBar2.Value = toolStripProgressBar2.Minimum; } else if(CurrentCount == TotalCount) { toolStripStatusLabel1.Text = "Done"; toolStripProgressBar2.Value = toolStripProgressBar2.Maximum; } else { toolStripStatusLabel1.Text = string.Format("{0:#,##0} of {1:#,##0} pixels", CurrentCount, TotalCount); toolStripProgressBar2.Value = toolStripProgressBar2.Minimum + (int)((toolStripProgressBar2.Maximum - toolStripProgressBar2.Minimum) * ((Double)CurrentCount / (Double)TotalCount)); } } #endregion private void button1_Click(object sender, EventArgs e) { LoadHtmlColors(); } } }
34.404255
196
0.541126
[ "MIT" ]
richteel/ColorsInImage
ColorsInImage/Form1.cs
11,321
C#
using System; using System.Xml.Serialization; namespace Aop.Api.Response { /// <summary> /// AlipayDataDataserviceDatabusSendResponse. /// </summary> public class AlipayDataDataserviceDatabusSendResponse : AopResponse { } }
19.153846
71
0.710843
[ "Apache-2.0" ]
Varorbc/alipay-sdk-net-all
AlipaySDKNet/Response/AlipayDataDataserviceDatabusSendResponse.cs
249
C#
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Text; using System.Runtime.InteropServices; namespace AinDecompiler { class ModifiedShiftJis2 : Encoding { private static UInt16[] MapUnicodeToBytes; private static char[] MapBytesToUnicode; private static GCHandle handle1, handle2; private static unsafe ushort* unicodeToBytes = null; private static unsafe char* bytesToUnicode = null; static ModifiedShiftJis2() { MapUnicodeToBytes = GetMapUnicodeToBytes(); MapBytesToUnicode = GetMapBytesToUnicode(); unsafe { handle1 = GCHandle.Alloc(MapUnicodeToBytes, GCHandleType.Pinned); unicodeToBytes = (ushort*)handle1.AddrOfPinnedObject(); handle2 = GCHandle.Alloc(MapBytesToUnicode, GCHandleType.Pinned); bytesToUnicode = (char*)handle2.AddrOfPinnedObject(); } } private static ushort[] GetMapUnicodeToBytes() { KeyValuePair<ushort[], char[]> pair = GetEncodingTables(); return pair.Key; } private static char[] GetMapBytesToUnicode() { KeyValuePair<ushort[], char[]> pair = GetEncodingTables(); return pair.Value; } static KeyValuePair<ushort[], char[]> _encodingTables; private static KeyValuePair<ushort[], char[]> GetEncodingTables() { if (_encodingTables.Key != null && _encodingTables.Value != null) { return _encodingTables; } char[] bytesToChar = new char[65536]; ushort[] charToBytes = new ushort[65536]; //first do Shift-JIS var shiftJis = Encoding.GetEncoding("shift_jis", EncoderFallback.ReplacementFallback, DecoderFallback.ReplacementFallback); byte[] bytes = new byte[2]; byte[] bytes2 = new byte[2]; char[] chars = new char[2]; for (int b1 = 0; b1 <= 0x7F; b1++) { for (int b2 = 0; b2 < 0x100; b2++) { int b = b1 + b2 * 0x100; bytesToChar[b] = (char)b1; charToBytes[b1] = (ushort)b1; } } for (int b1 = 0xA1; b1 <= 0xDF; b1++) { char c = (char)(b1 + 0xFF61 - 0xA1); for (int b2 = 0; b2 < 0x100; b2++) { int b = b1 + b2 * 0x100; bytesToChar[b] = c; charToBytes[c] = (ushort)b1; } } for (int b1 = 0x81; b1 < 0xFC; b1++) { if ( ((b1 >= 0x81 && b1 <= 0x9F) || (b1 >= 0xE0 && b1 <= 0xFC)) && !(b1 == 0x85 || b1 == 0x86 || b1 == 0xEB || b1 == 0xEC || (b1 >= 0xEF && b1 <= 0xF9)) ) { for (int b2 = 0x40; b2 <= 0xFC; b2++) { if (b2 != 0x7F) { ushort b = (ushort)(b1 + b2 * 0x100); bytes[0] = (byte)b1; bytes[1] = (byte)b2; shiftJis.GetChars(bytes, 0, 2, chars, 0); char c = chars[0]; if (c != '?') { bytesToChar[b] = c; charToBytes[c] = b; } } } } } //next do the extended characters for (int c = 0xA0; c < 0x500; c++) { int c2 = c - 0xA0; int b1 = c2 / 255 + 0xEF; int b2 = (c2 % 255) + 1; ushort b = (ushort)(b1 + b2 * 0x100); if (bytesToChar[b] == 0) { bytesToChar[b] = (char)c; } if (charToBytes[c] == 0) { charToBytes[c] = b; } } for (int c = 0x1E00; c < 0x2100; c++) { int c2 = c - 0x1E00 + (0x500 - 0xA0); int b1 = c2 / 255 + 0xEF; int b2 = (c2 % 255) + 1; ushort b = (ushort)(b1 + b2 * 0x100); if (bytesToChar[b] == 0) { bytesToChar[b] = (char)c; } if (charToBytes[c] == 0) { charToBytes[c] = b; } } for (int c = 0x2600; c < 0x2800; c++) { int c2 = c - 0x2600 + (0x500 - 0xA0 + 0x2100 - 0x1E00); int b1 = c2 / 255 + 0xEF; int b2 = (c2 % 255) + 1; ushort b = (ushort)(b1 + b2 * 0x100); if (bytesToChar[b] == 0) { bytesToChar[b] = (char)c; } if (charToBytes[c] == 0) { charToBytes[c] = b; } } _encodingTables = new KeyValuePair<ushort[], char[]>(charToBytes, bytesToChar); return _encodingTables; } public static ModifiedShiftJis2 GetEncoding() { return GetEncoding(EncoderFallback.ReplacementFallback, DecoderFallback.ReplacementFallback); } public static ModifiedShiftJis2 GetEncoding(EncoderFallback encoderFallback, DecoderFallback decoderFallback) { #if NET45 //In .NET framework 4.5, DecoderFallback and EncoderFallback properties can not be set return new ModifiedShiftJis2(encoderFallback, decoderFallback); #else var encoding = (ModifiedShiftJis2)(new ModifiedShiftJis2().Clone()); encoding.DecoderFallback = decoderFallback; encoding.EncoderFallback = encoderFallback; return encoding; #endif } private ModifiedShiftJis2() : base(932) { } #if NET45 private ModifiedShiftJis2(EncoderFallback encoderFallback, DecoderFallback decoderFallback) : base(932, encoderFallback, decoderFallback) { } #endif private EncoderFallbackBuffer encoderFallbackBuffer = null; private DecoderFallbackBuffer decoderFallbackBuffer = null; public override int GetByteCount(char[] chars, int index, int count) { if (count == 0) { return 0; } if (chars == null) { throw new ArgumentNullException("chars"); } if (index < 0 || index >= chars.Length) { throw new ArgumentOutOfRangeException("index"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (index + count > chars.Length) { throw new ArgumentOutOfRangeException("count"); } unsafe { fixed (char* c = chars) { return GetByteCount(c, count); } } } public unsafe override int GetByteCount(char* chars, int count) { int byteCount = 0; char* charLimit = chars + count; char* charPtr = chars; while (charPtr < charLimit) { char c = *charPtr; charPtr++; int value = unicodeToBytes[c]; if (!(value == 0 && c != 0)) { byteCount++; if (value >= 256) { byteCount++; } } else { int charIndex = (int)(charPtr - chars); byteCount += DoEncoderFallbackForByteCount(c, charIndex); } } return byteCount; } public override int GetByteCount(string s) { if (s == null) { throw new ArgumentNullException("s"); } if (s.Length == 0) { return 0; } unsafe { fixed (char* chars = s) { return GetByteCount(chars, s.Length); } } } unsafe private int DoEncoderFallbackForByteCount(char c, int charIndex) { int byteCount = 0; int value; if (encoderFallbackBuffer == null) { encoderFallbackBuffer = this.EncoderFallback.CreateFallbackBuffer(); } encoderFallbackBuffer.Fallback(c, charIndex); while (encoderFallbackBuffer.Remaining > 0) { c = encoderFallbackBuffer.GetNextChar(); if (c == 0) { break; } value = unicodeToBytes[c]; if (value != 0) { byteCount++; if (value >= 256) { byteCount++; } } else { //would output FFFF byteCount += 2; } } return byteCount; } public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (charCount == 0) { return 0; } if (chars == null) { throw new ArgumentNullException("chars"); } if (bytes == null) { throw new ArgumentNullException("bytes"); } if (charCount < 0) { throw new ArgumentOutOfRangeException("charCount"); } if (charIndex < 0 || charIndex >= chars.Length) { throw new ArgumentOutOfRangeException("charIndex"); } if (charIndex + charCount > chars.Length) { throw new ArgumentOutOfRangeException("charCount"); } if (byteIndex < 0 || byteIndex >= bytes.Length) { throw new ArgumentOutOfRangeException("byteIndex"); } int maxBytes = bytes.Length - byteIndex; unsafe { fixed (char* charsPtr = chars) { fixed (byte* bytesPtr = bytes) { return GetBytes(charsPtr + charIndex, charCount, bytesPtr + byteIndex, maxBytes); } } } } public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { char* charPtr = chars; char* limit = chars + charCount; byte* bytePtr = bytes; byte* byteLimit = bytes + byteCount; while (charPtr < limit && bytePtr < byteLimit) { char c = *charPtr; charPtr++; int value = unicodeToBytes[c]; if (!(value == 0 && c != 0)) { *bytePtr = (byte)(value & 0xFF); bytePtr++; if (value >= 256) { if (bytePtr < byteLimit) { *bytePtr = (byte)(value >> 8); bytePtr++; } else { throw new IndexOutOfRangeException("Not enough space in bytes to hold encoded characters"); } } } else { int charIndex = (int)(charPtr - chars); bytePtr = DoEncoderFallbackForGetBytes(bytePtr, byteLimit, c, charIndex); } } if (charPtr < limit) { throw new IndexOutOfRangeException("Not enough space in bytes to hold encoded characters"); } return (int)(bytePtr - bytes); } unsafe private byte* DoEncoderFallbackForGetBytes(byte* bytePtr, byte* byteLimit, char c, int charIndex) { //do the fallback stuff if (this.encoderFallbackBuffer != null) { this.encoderFallbackBuffer = this.EncoderFallback.CreateFallbackBuffer(); } encoderFallbackBuffer.Fallback(c, charIndex); while (encoderFallbackBuffer.Remaining > 0) { char c2 = encoderFallbackBuffer.GetNextChar(); if (c2 == 0) { break; } int value2 = unicodeToBytes[c2]; if (value2 > 0) { if (bytePtr < byteLimit) { *bytePtr = (byte)(value2 & 0xFF); bytePtr++; } else { throw new IndexOutOfRangeException("Not enough space in bytes to hold encoded characters"); } if (value2 > 256) { if (bytePtr < byteLimit) { *bytePtr = (byte)(value2 >> 8); bytePtr++; } else { throw new IndexOutOfRangeException("Not enough space in bytes to hold encoded characters"); } } } else { if (bytePtr + 1 < byteLimit) { *bytePtr = (byte)0xFF; bytePtr++; *bytePtr = (byte)0xFF; bytePtr++; } } } return bytePtr; } public override byte[] GetBytes(char[] chars, int index, int count) { if (count == 0) { return new byte[0]; } if (chars == null) { throw new ArgumentNullException("chars"); } if (count < 0) { throw new ArgumentOutOfRangeException("charCount"); } if (index < 0 || index >= chars.Length) { throw new ArgumentOutOfRangeException("charIndex"); } if (index + count > chars.Length) { throw new ArgumentOutOfRangeException("charCount"); } int byteCount = GetByteCount(chars, index, count); byte[] bytes = new byte[byteCount]; GetBytes(chars, index, count, bytes, 0); return bytes; } public override byte[] GetBytes(string s) { int byteCount = GetByteCount(s); byte[] bytes = new byte[byteCount]; unsafe { fixed (char* charPtr = s) { fixed (byte* bytePtr = bytes) { GetBytes(charPtr, s.Length, bytePtr, bytes.Length); return bytes; } } } } public override int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (charCount == 0) { return 0; } if (s == null) { throw new ArgumentNullException("chars"); } if (bytes == null) { throw new ArgumentNullException("bytes"); } if (charCount < 0) { throw new ArgumentOutOfRangeException("charCount"); } if (charIndex < 0 || charIndex >= s.Length) { throw new ArgumentOutOfRangeException("charIndex"); } if (charIndex + charCount > s.Length) { throw new ArgumentOutOfRangeException("charCount"); } if (byteIndex < 0 || byteIndex >= bytes.Length) { throw new ArgumentOutOfRangeException("byteIndex"); } unsafe { fixed (char* charPtr = s) { fixed (byte* bytePtr = bytes) { return GetBytes(charPtr, s.Length, bytePtr, bytes.Length); } } } } public override int GetCharCount(byte[] bytes, int index, int count) { if (count == 0) { return 0; } if (bytes == null) { throw new ArgumentNullException("chars"); } if (index < 0 || index >= bytes.Length) { throw new ArgumentOutOfRangeException("index"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } int last = index + count; if (last > bytes.Length) { throw new ArgumentOutOfRangeException("count"); } unsafe { fixed (byte* bytesPtr = bytes) { return GetCharCount(bytesPtr, count); } } } public override unsafe int GetCharCount(byte* bytes, int count) { byte* bytesLimit = bytes + count; byte* bytesPtr = bytes; int charCount = 0; while (bytesPtr + 1 < bytesLimit) { ushort* word = (ushort*)(bytesPtr); int value = *word; char c = bytesToUnicode[value]; if (!(c == 0 && (value & 0xFF) != 0)) { charCount++; int value2 = unicodeToBytes[c]; if (value2 < 256) { bytesPtr++; } else { bytesPtr += 2; } } else { charCount += DoDecoderFallbackForGetCharCount(value); bytesPtr++; } } if (bytesPtr == bytesLimit - 1) { int value = *bytesPtr; bytesPtr++; char c = bytesToUnicode[value]; if (!(c == 0 && value != 0)) { charCount++; } else { charCount += DoDecoderFallbackForGetCharCount(value); } } return charCount; } private int DoDecoderFallbackForGetCharCount(int value) { int charCount = 0; if (decoderFallbackBuffer == null) { decoderFallbackBuffer = this.DecoderFallback.CreateFallbackBuffer(); } decoderFallbackBuffer.Fallback(new byte[] { (byte)(value & 0xFF), (byte)(value >> 8) }, 0); while (decoderFallbackBuffer.Remaining > 0) { char c2 = decoderFallbackBuffer.GetNextChar(); if (c2 == 0) { break; } charCount++; } return charCount; } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { if (byteCount == 0) { return 0; } if (chars == null) { throw new ArgumentNullException("chars"); } if (bytes == null) { throw new ArgumentNullException("bytes"); } if (byteCount < 0) { throw new ArgumentOutOfRangeException("byteCount"); } if (byteIndex < 0 || byteIndex >= bytes.Length) { throw new ArgumentOutOfRangeException("byteIndex"); } if (byteIndex + byteCount > bytes.Length) { throw new ArgumentOutOfRangeException("byteCount"); } if (byteIndex < 0 || byteIndex >= bytes.Length) { throw new ArgumentOutOfRangeException("byteIndex"); } if (charIndex < 0 || charIndex >= chars.Length) { throw new ArgumentOutOfRangeException("charIndex"); } unsafe { fixed (byte* bytesPtr = bytes) { fixed (char* charsPtr = chars) { return GetChars(bytesPtr, byteCount, charsPtr, chars.Length - charIndex); } } } } public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { byte* byteLimit = bytes + byteCount; char* charLimit = chars + charCount; byte* bytesPtr = bytes; char* charsPtr = chars; while (bytesPtr - 1 < byteLimit && charsPtr < charLimit) { ushort* words = (ushort*)bytesPtr; int value = *words; char c = bytesToUnicode[value]; if (!(c == 0 && (value & 0xFF) != 0)) { *charsPtr = c; charsPtr++; int value2 = unicodeToBytes[c]; if (value2 < 256) { bytesPtr++; } else { bytesPtr += 2; } } else { charsPtr = DoDecoderFallbackForGetChars(charsPtr, charLimit, value); bytesPtr++; } } if (bytesPtr == byteLimit - 1 && charsPtr < charLimit) { int value = *bytesPtr; bytesPtr++; char c = bytesToUnicode[value]; if (!(c == 0 && (value & 0xFF) != 0)) { *charsPtr = c; charsPtr++; } else { charsPtr = DoDecoderFallbackForGetChars(charsPtr, charLimit, value); } } if (bytesPtr != byteLimit) { throw new IndexOutOfRangeException("Not enough space in characters for encoded bytes"); } return (int)(charsPtr - chars); } unsafe private char* DoDecoderFallbackForGetChars(char* charsPtr, char* charLimit, int value) { if (this.decoderFallbackBuffer == null) { this.decoderFallbackBuffer = this.DecoderFallback.CreateFallbackBuffer(); } this.decoderFallbackBuffer.Fallback(new byte[] { (byte)(value & 0xFF), (byte)(value >> 8) }, 0); while (this.decoderFallbackBuffer.Remaining > 0) { char c2 = this.decoderFallbackBuffer.GetNextChar(); if (c2 == 0) { break; } if (charsPtr < charLimit) { *charsPtr = c2; charsPtr++; } else { throw new IndexOutOfRangeException("Not enough space in characters for encoded bytes"); } } return charsPtr; } public override int GetMaxByteCount(int charCount) { return charCount * 2; } public override int GetMaxCharCount(int byteCount) { return byteCount; } public override string EncodingName { get { return "Modified Shift-JIS 2.0"; } } } }
33.093112
146
0.399537
[ "MIT" ]
UserUnknownFactor/AinDecompiler
AinDecompiler/ModifiedShiftJis2.cs
25,945
C#
#pragma warning disable SA1008 // Opening parenthesis must not be preceded by a space #pragma warning disable SA1009 // Closing parenthesis must not be followed by a space namespace KJU.Tests.AST { using System; using System.Collections.Generic; using System.Linq; using KJU.Core.AST; using KJU.Core.AST.BuiltinTypes; using KJU.Core.AST.TypeChecker; using KJU.Core.AST.Types; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Util; [TestClass] public class SolverTests { [TestMethod] public void TestSimple() { var typeVar = new TypeVariable(); var intVar = new IntType(); var clauses = new List<Clause> { new Clause { Alternatives = new List<List<(IHerbrandObject, IHerbrandObject)>> { new List<(IHerbrandObject, IHerbrandObject)> { (typeVar, intVar) } } } }; var solver = new Solver(clauses); var expectedSolution = new Dictionary<TypeVariable, IHerbrandObject> { { typeVar, intVar } }; CheckSolution(solver, expectedSolution); } [TestMethod] public void TestBacktrack() { var xTypeVar = new TypeVariable(); var yTypeVar = new TypeVariable(); var intVar = IntType.Instance; var boolVar = BoolType.Instance; var clauses = new List<Clause> { new Clause { Alternatives = new List<List<(IHerbrandObject, IHerbrandObject)>> { new List<(IHerbrandObject, IHerbrandObject)> { (xTypeVar, intVar) }, new List<(IHerbrandObject, IHerbrandObject)> { (xTypeVar, boolVar) } } }, new Clause { Alternatives = new List<List<(IHerbrandObject, IHerbrandObject)>> { new List<(IHerbrandObject, IHerbrandObject)> { (yTypeVar, intVar) }, new List<(IHerbrandObject, IHerbrandObject)> { (yTypeVar, boolVar) } } }, new Clause { Alternatives = new List<List<(IHerbrandObject, IHerbrandObject)>> { new List<(IHerbrandObject, IHerbrandObject)> { (xTypeVar, boolVar), (yTypeVar, intVar) } } } }; var solver = new Solver(clauses); var expectedSolution = new Dictionary<TypeVariable, IHerbrandObject> { { xTypeVar, boolVar }, { yTypeVar, intVar } }; CheckSolution(solver, expectedSolution); } [TestMethod] public void TestNoSolution() { var xTypeVar = new TypeVariable(); var yTypeVar = new TypeVariable(); var intVar = IntType.Instance; var boolVar = BoolType.Instance; var unitVar = UnitType.Instance; var clauses = new List<Clause> { new Clause { Alternatives = new List<List<(IHerbrandObject, IHerbrandObject)>> { new List<(IHerbrandObject, IHerbrandObject)> { (xTypeVar, intVar) }, new List<(IHerbrandObject, IHerbrandObject)> { (xTypeVar, boolVar) } } }, new Clause { Alternatives = new List<List<(IHerbrandObject, IHerbrandObject)>> { new List<(IHerbrandObject, IHerbrandObject)> { (yTypeVar, intVar) }, new List<(IHerbrandObject, IHerbrandObject)> { (yTypeVar, boolVar) } } }, new Clause { Alternatives = new List<List<(IHerbrandObject, IHerbrandObject)>> { new List<(IHerbrandObject, IHerbrandObject)> { (xTypeVar, unitVar), (yTypeVar, unitVar) } } } }; var solver = new Solver(clauses); CheckException(solver); } [TestMethod] public void TestMultipleSolutions() { var xTypeVar = new TypeVariable(); var yTypeVar = new TypeVariable(); var intVar = IntType.Instance; var boolVar = BoolType.Instance; var clauses = new List<Clause> { new Clause { Alternatives = new List<List<(IHerbrandObject, IHerbrandObject)>> { new List<(IHerbrandObject, IHerbrandObject)> { (xTypeVar, intVar) }, new List<(IHerbrandObject, IHerbrandObject)> { (xTypeVar, boolVar) } } }, new Clause { Alternatives = new List<List<(IHerbrandObject, IHerbrandObject)>> { new List<(IHerbrandObject, IHerbrandObject)> { (yTypeVar, intVar) }, new List<(IHerbrandObject, IHerbrandObject)> { (yTypeVar, boolVar) } } } }; var solver = new Solver(clauses); CheckException(solver); } [TestMethod] public void TestFuncWithArrays() { var xTypeVar = new TypeVariable(); var yTypeVar = new TypeVariable(); var zTypeVar = new TypeVariable(); var wTypeVar = new TypeVariable(); var wArrayVar = new ArrayType(wTypeVar); var zArrayVar = new ArrayType(wArrayVar); var intVar = IntType.Instance; var xFunVar = new FunType(new[] { yTypeVar, zTypeVar }, wArrayVar); var clauses = new List<Clause> { new Clause { Alternatives = new List<List<(IHerbrandObject, IHerbrandObject)>> { new List<(IHerbrandObject, IHerbrandObject)> { (xTypeVar, xFunVar) } } }, new Clause { Alternatives = new List<List<(IHerbrandObject, IHerbrandObject)>> { new List<(IHerbrandObject, IHerbrandObject)> { (yTypeVar, zArrayVar), (yTypeVar, intVar) }, new List<(IHerbrandObject, IHerbrandObject)> { (yTypeVar, zArrayVar), (zTypeVar, intVar) } } }, new Clause { Alternatives = new List<List<(IHerbrandObject, IHerbrandObject)>> { new List<(IHerbrandObject, IHerbrandObject)> { (wTypeVar, zTypeVar) } } } }; var solver = new Solver(clauses); var expectedSolution = new Dictionary<TypeVariable, IHerbrandObject> { { xTypeVar, xFunVar }, { yTypeVar, zArrayVar }, { zTypeVar, intVar }, { wTypeVar, intVar } }; CheckSolution(solver, expectedSolution); } private static void CheckException(Solver solver) { Assert.ThrowsException<TypeCheckerException>(() => solver.Solve()); } private static void CheckSolution(Solver solver, IDictionary<TypeVariable, IHerbrandObject> expectedOutput) { var solution = solver.Solve(); Assert.IsTrue(SameDictionaries(expectedOutput, solution.TypeVariableMapping)); } private static bool SameDictionaries( IDictionary<TypeVariable, IHerbrandObject> a, IDictionary<TypeVariable, IHerbrandObject> b) { return a.Count == b.Count && a.Keys.All(key => b.ContainsKey(key) && a[key] == b[key]); } } }
35.883817
115
0.471901
[ "BSD-3-Clause" ]
kamil0074/kju
src/KJU.Tests/AST/SolverTests.cs
8,648
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 kafka-2018-11-14.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Kafka.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Kafka.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for ZookeeperNodeInfo Object /// </summary> public class ZookeeperNodeInfoUnmarshaller : IUnmarshaller<ZookeeperNodeInfo, XmlUnmarshallerContext>, IUnmarshaller<ZookeeperNodeInfo, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> ZookeeperNodeInfo IUnmarshaller<ZookeeperNodeInfo, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public ZookeeperNodeInfo Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; ZookeeperNodeInfo unmarshalledObject = new ZookeeperNodeInfo(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("attachedENIId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.AttachedENIId = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("clientVpcIpAddress", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.ClientVpcIpAddress = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("endpoints", targetDepth)) { var unmarshaller = new ListUnmarshaller<string, StringUnmarshaller>(StringUnmarshaller.Instance); unmarshalledObject.Endpoints = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("zookeeperId", targetDepth)) { var unmarshaller = DoubleUnmarshaller.Instance; unmarshalledObject.ZookeeperId = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("zookeeperVersion", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.ZookeeperVersion = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static ZookeeperNodeInfoUnmarshaller _instance = new ZookeeperNodeInfoUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static ZookeeperNodeInfoUnmarshaller Instance { get { return _instance; } } } }
37.594828
164
0.614767
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/Kafka/Generated/Model/Internal/MarshallTransformations/ZookeeperNodeInfoUnmarshaller.cs
4,361
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/DirectML.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="DML_ELEMENT_WISE_ACOS_OPERATOR_DESC" /> struct.</summary> public static unsafe partial class DML_ELEMENT_WISE_ACOS_OPERATOR_DESCTests { /// <summary>Validates that the <see cref="DML_ELEMENT_WISE_ACOS_OPERATOR_DESC" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<DML_ELEMENT_WISE_ACOS_OPERATOR_DESC>(), Is.EqualTo(sizeof(DML_ELEMENT_WISE_ACOS_OPERATOR_DESC))); } /// <summary>Validates that the <see cref="DML_ELEMENT_WISE_ACOS_OPERATOR_DESC" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(DML_ELEMENT_WISE_ACOS_OPERATOR_DESC).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="DML_ELEMENT_WISE_ACOS_OPERATOR_DESC" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(DML_ELEMENT_WISE_ACOS_OPERATOR_DESC), Is.EqualTo(24)); } else { Assert.That(sizeof(DML_ELEMENT_WISE_ACOS_OPERATOR_DESC), Is.EqualTo(12)); } } } }
40.568182
148
0.67563
[ "MIT" ]
DaZombieKiller/terrafx.interop.windows
tests/Interop/Windows/um/DirectML/DML_ELEMENT_WISE_ACOS_OPERATOR_DESCTests.cs
1,787
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Linq; using TensorShader; using TensorShader.Operators.Connection3D; using TensorShaderCudaBackend.API; namespace TensorShaderTest.Operators.Connection3D { [TestClass] public class ImageToColumnTest { [TestMethod] public void ExecuteTest() { float max_err = 0; foreach (int batch in new int[] { 1, 2 }) { foreach (int channels in new int[] { 1, 2, 3, 4, 5, 10, 15, 20 }) { foreach ((int kwidth, int kheight, int kdepth) in new (int, int, int)[] { (1, 1, 1), (3, 3, 3), (5, 5, 5), (1, 3, 5), (3, 5, 1), (5, 1, 3) }) { foreach ((int inwidth, int inheight, int indepth) in new (int, int, int)[] { (13, 13, 13), (17, 17, 17), (19, 19, 19), (17, 19, 13), (13, 17, 19), (19, 13, 17) }) { int outwidth = inwidth - kwidth + 1, outheight = inheight - kheight + 1, outdepth = indepth - kdepth + 1; float[] xval = (new float[inwidth * inheight * indepth * channels * batch]).Select((_, idx) => idx * 1e-3f).ToArray(); Map3D x = new(channels, inwidth, inheight, indepth, batch, xval); Map3D y = Reference(x, kwidth, kheight, kdepth); OverflowCheckedTensor x_tensor = new(Shape.Map3D(channels, inwidth, inheight, indepth, batch), xval); OverflowCheckedTensor y_tensor = new(new Shape(ShapeType.Column, kwidth * kheight * kdepth, channels, outwidth, outheight, outdepth, batch)); ImageToColumn ope = new(inwidth, inheight, indepth, channels, kwidth, kheight, kdepth, batch); ope.Execute(x_tensor, y_tensor); float[] y_expect = y.ToArray(); float[] y_actual = y_tensor.State.Value; CollectionAssert.AreEqual(xval, x_tensor.State.Value); AssertError.Tolerance(y_expect, y_actual, 1e-7f, 1e-5f, ref max_err, $"mismatch value {channels},{kwidth},{kheight},{kdepth},{inwidth},{inheight},{indepth},{batch}"); Console.WriteLine($"pass: {channels},{kwidth},{kheight},{kdepth},{inwidth},{inheight},{indepth},{batch}"); } } } } Console.WriteLine($"maxerr:{max_err}"); } [TestMethod] public void SpeedTest() { int inwidth = 32, inheight = 32, indepth = 32, channels = 31, ksize = 3; int outwidth = inwidth - ksize + 1, outheight = inheight - ksize + 1, outdepth = indepth - ksize + 1; OverflowCheckedTensor x_tensor = new(Shape.Map3D(channels, inwidth, inheight, indepth)); OverflowCheckedTensor y_tensor = new(new Shape(ShapeType.Column, ksize * ksize * ksize, channels, outwidth, outheight, outdepth, 1)); ImageToColumn ope = new(inwidth, inheight, indepth, channels, ksize, ksize, ksize); Cuda.Profiler.Initialize("../../../../profiler.nvsetting", "../../nvprofiles/image_to_column_3d.nvvp"); Cuda.Profiler.Start(); ope.Execute(x_tensor, y_tensor); Cuda.Profiler.Stop(); } public static Map3D Reference(Map3D x, int kwidth, int kheight, int kdepth) { int channels = x.Channels, batch = x.Batch; int inw = x.Width, inh = x.Height, ind = x.Depth; int outw = inw - kwidth + 1, outh = inh - kheight + 1, outd = ind - kdepth + 1; Map3D y = new(kwidth * kheight * kdepth * channels, outw, outh, outd, batch); for (int k = 0, kx, ky, kz = 0; kz < kdepth; kz++) { for (ky = 0; ky < kheight; ky++) { for (kx = 0; kx < kwidth; k++, kx++) { for (int th = 0; th < batch; th++) { for (int ox, oy, oz = 0; oz < outd; oz++) { for (oy = 0; oy < outh; oy++) { for (ox = 0; ox < outw; ox++) { for (int ch = 0; ch < channels; ch++) { y[k + kwidth * kheight * kdepth * ch, ox, oy, oz, th] = x[ch, kx + ox, ky + oy, kz + oz, th]; } } } } } } } } return y; } } }
47.060606
194
0.490234
[ "MIT" ]
tk-yoshimura/TensorShader
TensorShaderTest/Operators/Connection3D/Transform/ImageToColumnTest.cs
4,659
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityStandardAssets.CrossPlatformInput; public class dialogueHolder1 : MonoBehaviour { public string dialogue; public string[] dialogueLines; private DialogueManager1 dMan; void Start() { dMan = FindObjectOfType<DialogueManager1>(); } void OnTriggerEnter2D(Collider2D other) { if(other.gameObject.name == "Character") { //if (CrossPlatformInputManager.GetButtonDown("Fire2")) //{ //} //dMan.ShowBox(dialogue); if (!dMan.dialogActive) { dMan.dialogLines = dialogueLines; dMan.currentLine = 0; dMan.ShowDialogue(); } } } }
25.727273
68
0.555948
[ "MIT" ]
MartinSarnes/TheEternalForest
Assets/Scripts/Dialogue/dialogueHolder1.cs
851
C#
using Gat.Base; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Gat.Define { /// <summary> /// Entity 資料集(指定型別) /// </summary> /// <typeparam name="T"></typeparam> [Obsolete] public class EntitySet<T> : EntitySet where T : EntityRow { /// <summary> /// 建構函式 /// </summary> /// <param name="entitySet"></param> public EntitySet(EntitySet entitySet, InstanceType instanceType) : base() { this.DataSetName = entitySet.DataSetName; this.OriginalEntitySet = entitySet; } /// <summary> /// 原始Entity資料集 /// </summary> private EntitySet OriginalEntitySet { get; } /// <summary> /// 資料表 /// </summary> public Dictionary<EntityTable<T>, EntityTable> EntityTables { get; } = new Dictionary<EntityTable<T>, EntityTable>(); /// <summary> /// /// </summary> /// <param name="tables"></param> private void ConvertGTables(InstanceType instanceType) { foreach (EntityTable table in this.OriginalEntitySet.Tables) this.EntityTables.Add(new EntityTable<T>(table, instanceType), table); } } /// <summary> /// Entity 資料集 /// </summary> public class EntitySet { /// <summary> /// 建構函式 /// </summary> public EntitySet() { } /// <summary> /// 建構函式 /// </summary> /// <param name="dataSetName">資料集名稱</param> public EntitySet(string dataSetName) : base() { this.DataSetName = dataSetName; } /// <summary> /// 建構函式 /// </summary> /// <param name="dataSet">資料集</param> public EntitySet(DataSet dataSet) { this.DataSetName = dataSet.DataSetName; foreach (DataTable table in dataSet.Tables) { this.Tables.Add(new EntityTable(table)); } } /// <summary> /// 資料集名稱 /// </summary> public string DataSetName { get; set; } /// <summary> /// 資料表集合 /// </summary> public EntityTableCollection Tables { get; } = new EntityTableCollection(); /// <summary> /// 物件描述 /// </summary> /// <returns></returns> public override string ToString() { return string.Format("Name:{0}, Count:{1}", this.DataSetName, this.Tables.Count); } } }
25.960784
125
0.518505
[ "Apache-2.0" ]
Sway0308/GHM-PY
Library/Gat.Define/Entity/EntitySet.cs
2,766
C#
using System; using System.Web.Http; using System.Web.Mvc; using ReferenceAPI.Areas.HelpPage.ModelDescriptions; using ReferenceAPI.Areas.HelpPage.Models; namespace ReferenceAPI.Areas.HelpPage.Controllers { /// <summary> /// The controller that will handle requests for the help page. /// </summary> public class HelpController : Controller { private const string ErrorViewName = "Error"; public HelpController() : this(GlobalConfiguration.Configuration) { } public HelpController(HttpConfiguration config) { Configuration = config; } public HttpConfiguration Configuration { get; private set; } public ActionResult Index() { ViewBag.DocumentationProvider = Configuration.Services.GetDocumentationProvider(); return View(Configuration.Services.GetApiExplorer().ApiDescriptions); } public ActionResult Api(string apiId) { if (!String.IsNullOrEmpty(apiId)) { HelpPageApiModel apiModel = Configuration.GetHelpPageApiModel(apiId); if (apiModel != null) { return View(apiModel); } } return View(ErrorViewName); } public ActionResult ResourceModel(string modelName) { if (!String.IsNullOrEmpty(modelName)) { ModelDescriptionGenerator modelDescriptionGenerator = Configuration.GetModelDescriptionGenerator(); ModelDescription modelDescription; if (modelDescriptionGenerator.GeneratedModels.TryGetValue(modelName, out modelDescription)) { return View(modelDescription); } } return View(ErrorViewName); } } }
30.079365
115
0.598417
[ "MIT" ]
brtbook/brt
microservices/Reference/ReferenceAPI/Areas/HelpPage/Controllers/HelpController.cs
1,895
C#
namespace OggVorbisEncoder.Setup.Templates.Stereo44.BookBlocks.Chapter0 { public class Page6_0 : IStaticCodeBook { public int Dimensions { get; } = 4; public byte[] LengthList { get; } = { 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7, 10, 9, 9, 10, 9, 9, 4, 6, 7, 10, 9, 9, 11, 9, 9, 7, 10, 10, 11, 11, 11, 12, 10, 11, 6, 9, 9, 11, 10, 11, 11, 10, 10, 6, 9, 9, 11, 10, 11, 11, 10, 10, 7, 11, 10, 12, 11, 11, 11, 11, 11, 7, 9, 9, 10, 10, 10, 11, 11, 10, 6, 9, 9, 11, 10, 10, 11, 10, 10 }; public CodeBookMapType MapType { get; } = CodeBookMapType.Implicit; public int QuantMin { get; } = -529137664; public int QuantDelta { get; } = 1618345984; public int Quant { get; } = 2; public int QuantSequenceP { get; } = 0; public int[] QuantList { get; } = { 1, 0, 2 }; } }
34.25
75
0.472367
[ "MIT" ]
cshung/.NET-Ogg-Vorbis-Encoder
OggVorbisEncoder/Setup/Templates/Stereo44/BookBlocks/Chapter0/Page6_0.cs
961
C#
using System; using System.Collections.Generic; using System.IO; namespace Trees_and_Graphs { class DFS_Traverse_Folders_and_Files { public static void Main(string[] args) { TraverseDirBFS(@"C:\Windows\assembly"); } private static void TraverseDirDFS(DirectoryInfo dir, string spaces) { Console.WriteLine(spaces + dir.FullName); FileInfo[] files = dir.GetFiles(); foreach (var file in files) { Console.WriteLine(spaces + " " + file.FullName); } DirectoryInfo[] children = dir.GetDirectories(); foreach (DirectoryInfo child in children) { TraverseDirDFS(child, spaces + " "); } } public static void TraverseDirBFS(string directoryPath) { TraverseDirDFS(new DirectoryInfo(directoryPath), string.Empty); } } }
25.972973
76
0.567118
[ "MIT" ]
superalex-dev/SoftUni
Svetlina/C#/Ds And Algo/Trees, BFS and DFS - Lab/DFS_Traverse_Folders_and_Files.cs
963
C#
using System; using System.Collections.Generic; using UnityEngine; namespace FairyGUI { /// <summary> /// /// </summary> public class CaptureCamera : MonoBehaviour { /// <summary> /// /// </summary> [System.NonSerialized] public Transform cachedTransform; /// <summary> /// /// </summary> [System.NonSerialized] public Camera cachedCamera; [System.NonSerialized] static CaptureCamera _main; [System.NonSerialized] static int _layer = -1; static int _hiddenLayer = -1; public const string Name = "Capture Camera"; public const string LayerName = "VUI"; public const string HiddenLayerName = "Hidden VUI"; void OnEnable() { cachedCamera = this.GetComponent<Camera>(); cachedTransform = this.gameObject.transform; if (this.gameObject.name == Name) _main = this; } /// <summary> /// /// </summary> public static void CheckMain() { if (_main != null && _main.cachedCamera != null) return; GameObject go = GameObject.Find(Name); if (go != null) { _main = go.GetComponent<CaptureCamera>(); return; } GameObject cameraObject = new GameObject(Name); Camera camera = cameraObject.AddComponent<Camera>(); camera.depth = 0; camera.cullingMask = 1 << layer; camera.clearFlags = CameraClearFlags.Depth; camera.orthographic = true; camera.orthographicSize = 5; camera.nearClipPlane = -30; camera.farClipPlane = 30; camera.enabled = false; #if UNITY_5_4_OR_NEWER camera.stereoTargetEye = StereoTargetEyeMask.None; #endif cameraObject.AddComponent<CaptureCamera>(); } /// <summary> /// /// </summary> public static int layer { get { if (_layer == -1) { _layer = LayerMask.NameToLayer(LayerName); if (_layer == -1) { _layer = 30; Debug.LogWarning("Please define two layers named '" + CaptureCamera.LayerName + "' and '" + CaptureCamera.HiddenLayerName + "'"); } } return _layer; } } /// <summary> /// /// </summary> public static int hiddenLayer { get { if (_hiddenLayer == -1) { _hiddenLayer = LayerMask.NameToLayer(HiddenLayerName); if (_hiddenLayer == -1) { Debug.LogWarning("Please define two layers named '" + CaptureCamera.LayerName + "' and '" + CaptureCamera.HiddenLayerName + "'"); _hiddenLayer = 31; } } return _hiddenLayer; } } /// <summary> /// /// </summary> /// <param name="width"></param> /// <param name="height"></param> /// <param name="stencilSupport"></param> /// <returns></returns> public static RenderTexture CreateRenderTexture(int width, int height, bool stencilSupport) { RenderTexture texture = new RenderTexture(width, height, stencilSupport ? 24 : 0, RenderTextureFormat.ARGB32); texture.antiAliasing = 1; texture.filterMode = FilterMode.Bilinear; texture.anisoLevel = 0; texture.useMipMap = false; texture.wrapMode = TextureWrapMode.Clamp; texture.hideFlags = DisplayOptions.hideFlags; return texture; } /// <summary> /// /// </summary> /// <param name="target"></param> /// <param name="texture"></param> /// <param name="offset"></param> public static void Capture(DisplayObject target, RenderTexture texture, Vector2 offset) { CheckMain(); Matrix4x4 matrix = target.cachedTransform.localToWorldMatrix; float unitsPerPixel = new Vector4(matrix.m00, matrix.m10, matrix.m20, matrix.m30).magnitude; Vector3 forward; forward.x = matrix.m02; forward.y = matrix.m12; forward.z = matrix.m22; Vector3 upwards; upwards.x = matrix.m01; upwards.y = matrix.m11; upwards.z = matrix.m21; float halfHeight = (float)texture.height / 2; Camera camera = _main.cachedCamera; camera.targetTexture = texture; camera.orthographicSize = halfHeight * unitsPerPixel; _main.cachedTransform.localPosition = target.cachedTransform.TransformPoint(halfHeight * camera.aspect - offset.x, -halfHeight + offset.y, 0); _main.cachedTransform.localRotation = Quaternion.LookRotation(forward, upwards); int oldLayer = 0; if (target.graphics != null) { oldLayer = target.graphics.gameObject.layer; target.graphics.gameObject.layer = CaptureCamera.layer; } if (target is Container) { oldLayer = ((Container)target).numChildren > 0 ? ((Container)target).GetChildAt(0).layer : CaptureCamera.hiddenLayer; ((Container)target).SetChildrenLayer(CaptureCamera.layer); } RenderTexture old = RenderTexture.active; RenderTexture.active = texture; GL.Clear(true, true, Color.clear); camera.Render(); RenderTexture.active = old; if (target.graphics != null) target.graphics.gameObject.layer = oldLayer; if (target is Container) ((Container)target).SetChildrenLayer(oldLayer); } } }
25.912371
146
0.640143
[ "MIT" ]
zhangjie0072/Learn_FairyGUI_Slua
Assets/_FairyGUI/Scripts/Core/CaptureCamera.cs
5,029
C#
// // Copyright (C) 2012-2014 DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using Cassandra.IntegrationTests.TestBase; using Cassandra.IntegrationTests.TestClusterManagement; using Cassandra.Tests; using NUnit.Framework; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Cassandra.IntegrationTests.Policies.Util; namespace Cassandra.IntegrationTests.Core { [TestFixture, Category("long")] public class StressTests : TestGlobals { [TestFixtureSetUp] public void TestFixtureSetUp() { Diagnostics.CassandraTraceSwitch.Level = TraceLevel.Info; //For different threads Trace.AutoFlush = true; } /// <summary> /// Insert and select records in parallel them using Session.Execute sync methods. /// </summary> [Test] public void Parallel_Insert_And_Select_Sync() { var testCluster = TestClusterManager.GetNonShareableTestCluster(3, 1, true, false); using (var cluster = Cluster.Builder() .WithRetryPolicy(AlwaysRetryRetryPolicy.Instance) .AddContactPoint(testCluster.InitialContactPoint) .Build()) { var session = cluster.Connect(); var uniqueKsName = "keyspace_" + Randomm.RandomAlphaNum(10); session.Execute(@"CREATE KEYSPACE " + uniqueKsName + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3};"); session.ChangeKeyspace(uniqueKsName); var tableName = "table_" + Guid.NewGuid().ToString("N").ToLower(); session.Execute(String.Format(TestUtils.CREATE_TABLE_TIME_SERIES, tableName)); var insertQuery = String.Format("INSERT INTO {0} (id, event_time, text_sample) VALUES (?, ?, ?)", tableName); var insertQueryPrepared = session.Prepare(insertQuery); var selectQuery = String.Format("SELECT * FROM {0} LIMIT 10000", tableName); const int rowsPerId = 1000; object insertQueryStatement = new SimpleStatement(insertQuery); if (CassandraVersion.Major < 2) { //Use prepared statements all the way as it is not possible to bind on a simple statement with C* 1.2 insertQueryStatement = session.Prepare(insertQuery); } var actionInsert = GetInsertAction(session, insertQueryStatement, ConsistencyLevel.Quorum, rowsPerId); var actionInsertPrepared = GetInsertAction(session, insertQueryPrepared, ConsistencyLevel.Quorum, rowsPerId); var actionSelect = GetSelectAction(session, selectQuery, ConsistencyLevel.Quorum, 10); //Execute insert sync to have some records actionInsert(); //Execute select sync to assert that everything is going OK actionSelect(); var actions = new List<Action>(); for (var i = 0; i < 10; i++) { //Add 10 actions to execute actions.AddRange(new[] {actionInsert, actionSelect, actionInsertPrepared}); actions.AddRange(new[] {actionSelect, actionInsert, actionInsertPrepared, actionInsert}); actions.AddRange(new[] {actionInsertPrepared, actionInsertPrepared, actionSelect}); } //Execute in parallel the 100 actions TestHelper.ParallelInvoke(actions.ToArray()); } } /// <summary> /// In parallel it inserts some records and selects them using Session.Execute sync methods. /// </summary> [Test] [TestCassandraVersion(2, 0)] public void Parallel_Insert_And_Select_Sync_With_Nodes_Failing() { var testCluster = TestClusterManager.GetNonShareableTestCluster(3, 1, true, false); using (var cluster = Cluster.Builder() .WithRetryPolicy(AlwaysRetryRetryPolicy.Instance) .AddContactPoint(testCluster.InitialContactPoint) .Build()) { var session = cluster.Connect(); var uniqueKsName = "keyspace_" + Randomm.RandomAlphaNum(10); session.Execute(@"CREATE KEYSPACE " + uniqueKsName + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3};"); session.ChangeKeyspace(uniqueKsName); var tableName = "table_" + Guid.NewGuid().ToString("N").ToLower(); session.Execute(String.Format(TestUtils.CREATE_TABLE_TIME_SERIES, tableName)); var insertQuery = String.Format("INSERT INTO {0} (id, event_time, text_sample) VALUES (?, ?, ?)", tableName); var insertQueryPrepared = session.Prepare(insertQuery); var selectQuery = String.Format("SELECT * FROM {0} LIMIT 10000", tableName); const int rowsPerId = 100; object insertQueryStatement = new SimpleStatement(insertQuery); if (CassandraVersion.Major < 2) { //Use prepared statements all the way as it is not possible to bind on a simple statement with C* 1.2 insertQueryStatement = session.Prepare(insertQuery); } var actionInsert = GetInsertAction(session, insertQueryStatement, ConsistencyLevel.Quorum, rowsPerId); var actionInsertPrepared = GetInsertAction(session, insertQueryPrepared, ConsistencyLevel.Quorum, rowsPerId); var actionSelect = GetSelectAction(session, selectQuery, ConsistencyLevel.Quorum, 10); //Execute insert sync to have some records actionInsert(); //Execute select sync to assert that everything is going OK actionSelect(); var actions = new List<Action>(); for (var i = 0; i < 10; i++) { //Add 10 actions to execute actions.AddRange(new[] { actionInsert, actionSelect, actionInsertPrepared }); actions.AddRange(new[] { actionSelect, actionInsert, actionInsertPrepared, actionInsert }); actions.AddRange(new[] { actionInsertPrepared, actionInsertPrepared, actionSelect }); } actions.Insert(8, () => { Thread.Sleep(300); testCluster.StopForce(2); }); TestHelper.ParallelInvoke(actions.ToArray()); } } /// <summary> /// Creates thousands of Session instances and checks memory consumption before and after Dispose and dereferencing /// </summary> [Test] public void Memory_Consumption_After_Cluster_Dispose() { var testCluster = TestClusterManager.GetTestCluster(2, DefaultMaxClusterCreateRetries, true, false); //Only warning as tracing through console slows it down. Diagnostics.CassandraTraceSwitch.Level = TraceLevel.Warning; var start = GC.GetTotalMemory(false); long diff = 0; Trace.TraceInformation("--Initial memory: {0}", start / 1024); Action multipleConnect = () => { var cluster = Cluster.Builder().AddContactPoint(testCluster.InitialContactPoint).Build(); for (var i = 0; i < 200; i++) { var session = cluster.Connect(); TestHelper.ParallelInvoke(() => session.Execute("select * from system.local"), 20); } Trace.TraceInformation("--Before disposing: {0}", GC.GetTotalMemory(false) / 1024); cluster.Dispose(); Trace.TraceInformation("--After disposing: {0}", GC.GetTotalMemory(false) / 1024); }; multipleConnect(); var handle = new AutoResetEvent(false); //Collect all generations GC.Collect(); //Wait 5 seconds for all the connections resources to be freed var timer = new Timer(s => { GC.Collect(); handle.Set(); diff = GC.GetTotalMemory(false) - start; Trace.TraceInformation("--End, diff memory: {0}", diff / 1024); }); timer.Change(5000, Timeout.Infinite); handle.WaitOne(); //the end memory usage can not be greater than double the start memory //If there is a memory leak, it should be an order of magnitude greater... Assert.Less(diff, start / 2); } public Action GetInsertAction(ISession session, object bindableStatement, ConsistencyLevel consistency, int rowsPerId) { Action action = () => { Trace.TraceInformation("Starting inserting from thread {0}", Thread.CurrentThread.ManagedThreadId); var id = Guid.NewGuid(); for (var i = 0; i < rowsPerId; i++) { var paramsArray = new object[] { id, DateTime.Now, DateTime.Now.ToString(System.Globalization.CultureInfo.InvariantCulture) }; IStatement statement; if (bindableStatement is SimpleStatement) { statement = new SimpleStatement(((SimpleStatement)bindableStatement).QueryString, paramsArray).SetConsistencyLevel(consistency); } else if (bindableStatement is PreparedStatement) { statement = ((PreparedStatement)bindableStatement).Bind(paramsArray).SetConsistencyLevel(consistency); } else { throw new Exception("Can not bind a statement of type " + bindableStatement.GetType().FullName); } session.Execute(statement); } Trace.TraceInformation("Finished inserting from thread {0}", Thread.CurrentThread.ManagedThreadId); }; return action; } public Action GetSelectAction(ISession session, string query, ConsistencyLevel consistency, int executeLength) { Action action = () => { for (var i = 0; i < executeLength; i++) { session.Execute(new SimpleStatement(query).SetPageSize(500).SetConsistencyLevel(consistency)); //Count will iterate through the result set and it will likely to page results //Assert.True(rs.Count() > 0); } }; return action; } } }
47.601626
152
0.579249
[ "Apache-2.0" ]
batwad/cassandra-csharp-driver
src/Cassandra.IntegrationTests/Core/StressTests.cs
11,710
C#
/* * freee API * * <h1 id=\"freee_api\">freee API</h1> <hr /> <h2 id=\"\">スタートガイド</h2> <p>1. セットアップ</p> <ol> <ul><li><a href=\"https://support.freee.co.jp/hc/ja/articles/202847230\" class=\"external-link\" rel=\"nofollow\">freeeアカウント(無料)</a>を<a href=\"https://secure.freee.co.jp/users/sign_up\" class=\"external-link\" rel=\"nofollow\">作成</a>します(すでにお持ちの場合は次へ)</li><li><a href=\"https://app.secure.freee.co.jp/developers/demo_companies/description\" class=\"external-link\" rel=\"nofollow\">開発者向け事業所・環境を作成</a>します</li><li><span><a href=\"https://app.secure.freee.co.jp/developers/applications\" class=\"external-link\" rel=\"nofollow\">前のステップで作成した事業所を選択してfreeeアプリを追加</a>します</span></li><li>Client IDをCopyしておきます</li> </ul> </ol> <p>2. 実際にAPIを叩いてみる(ブラウザからAPIのレスポンスを確認する)</p> <ol> <ul><li><span><span>以下のURLの●をclient_idに入れ替えて<a href=\"https://app.secure.freee.co.jp/developers/tutorials/3-%E3%82%A2%E3%82%AF%E3%82%BB%E3%82%B9%E3%83%88%E3%83%BC%E3%82%AF%E3%83%B3%E3%82%92%E5%8F%96%E5%BE%97%E3%81%99%E3%82%8B#%E8%AA%8D%E5%8F%AF%E3%82%B3%E3%83%BC%E3%83%89%E3%82%92%E5%8F%96%E5%BE%97%E3%81%99%E3%82%8B\" class=\"external-link\" rel=\"nofollow\">アクセストークンを取得</a>します</span></span><ul><li><span><span><pre><code>https://accounts.secure.freee.co.jp/public_api/authorize?client_id=●&amp;redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&amp;response_type=token</a></code></pre></span></span></li></ul></li><li><span><a href=\"https://developer.freee.co.jp/docs/accounting/reference#/%E9%80%A3%E7%B5%A1%E5%85%88\" class=\"external-link\" rel=\"nofollow\">APIリファレンス</a>で<code>Authorize</code>を押下します</span></li><li><span>アクセストークン<span><span>を入力して</span></span>&nbsp;もう一度<span><code>Authorize</code>を押下して<code>Close</code>を押下します</span></span></li><li>リファレンス内のCompanies(事業所)に移動し、<code>Try it out</code>を押下し、<code>Execute</code>を押下します</li><li>Response bodyを参照し、事業所ID(id属性)を活用して、Companies以外のエンドポイントでどのようなデータのやりとりできるのか確認します</li></ul> </ol> <p>3. 連携を実装する</p> <ol> <ul><li><a href=\"https://developer.freee.co.jp/tips\" class=\"external-link\" rel=\"nofollow\">API TIPS</a>を参考に、ユースケースごとの連携の概要を学びます。<span>例えば</span><span>&nbsp;</span><a href=\"https://developer.freee.co.jp/tips/how-to-cooperate-salesmanegement-system\" class=\"external-link\" rel=\"nofollow\">SFA、CRM、販売管理システムから会計freeeへの連携</a>や<a href=\"https://developer.freee.co.jp/tips/how-to-cooperate-excel-and-spreadsheet\" class=\"external-link\" rel=\"nofollow\">エクセルやgoogle spreadsheetからの連携</a>です</li><li>実利用向け事業所がすでにある場合は利用、ない場合は作成します(セットアップで作成したのは開発者向け環境のため活用不可)</li><li><a href=\"https://developer.freee.co.jp/docs/accounting/reference\" class=\"external-link\" rel=\"nofollow\">API documentation</a><span>&nbsp;を参照し、躓いた場合は</span><span>&nbsp;</span><a href=\"https://developer.freee.co.jp/community/forum/community\" class=\"external-link\" rel=\"nofollow\">Community</a><span>&nbsp;で質問してみましょう</span></li></ul> </ol> <p>アプリケーションの登録方法や認証方法、またはAPIの活用方法でご不明な点がある場合は<a href=\"https://support.freee.co.jp/hc/ja/sections/115000030743\">ヘルプセンター</a>もご確認ください</p> <hr /> <h2 id=\"_2\">仕様</h2> <h3 id=\"api\">APIエンドポイント</h3> <p>https://api.freee.co.jp/ (httpsのみ)</p> <h3 id=\"_3\">認証方式</h3> <p><a href=\"http://tools.ietf.org/html/rfc6749\">OAuth2</a>に対応</p> <ul> <li>Authorization Code Flow (Webアプリ向け)</li> <li>Implicit Flow (Mobileアプリ向け)</li> </ul> <h3 id=\"_4\">認証エンドポイント</h3> <p>https://accounts.secure.freee.co.jp/</p> <ul> <li>authorize : https://accounts.secure.freee.co.jp/public_api/authorize</li> <li>token : https://accounts.secure.freee.co.jp/public_api/token</li> </ul> <h3 id=\"_5\">アクセストークンのリフレッシュ</h3> <p>認証時に得たrefresh_token を使ってtoken の期限をリフレッシュして新規に発行することが出来ます。</p> <p>grant_type=refresh_token で https://accounts.secure.freee.co.jp/public_api/token にアクセスすればリフレッシュされます。</p> <p>e.g.)</p> <p>POST: https://accounts.secure.freee.co.jp/public_api/token</p> <p>params: grant_type=refresh_token&amp;client_id=UID&amp;client_secret=SECRET&amp;refresh_token=REFRESH_TOKEN</p> <p>詳細は<a href=\"https://github.com/applicake/doorkeeper/wiki/Enable-Refresh-Token-Credentials#flow\">refresh_token</a>を参照下さい。</p> <h3 id=\"_6\">アクセストークンの破棄</h3> <p>認証時に得たaccess_tokenまたはrefresh_tokenを使って、tokenを破棄することができます。 token=access_tokenまたはtoken=refresh_tokenでhttps://accounts.secure.freee.co.jp/public_api/revokeにアクセスすると破棄されます。token_type_hintでaccess_tokenまたはrefresh_tokenを陽に指定できます。</p> <p>e.g.)</p> <p>POST: https://accounts.secure.freee.co.jp/public_api/revoke</p> <p>params: token=ACCESS_TOKEN</p> <p>または</p> <p>params: token=REFRESH_TOKEN</p> <p>または</p> <p>params: token=ACCESS_TOKEN&amp;token_type_hint=access_token</p> <p>または</p> <p>params: token=REFRESH_TOKEN&amp;token_type_hint=refresh_token</p> <p>詳細は <a href=\"https://tools.ietf.org/html/rfc7009\">OAuth 2.0 Token revocation</a> をご参照ください。</p> <h3 id=\"_7\">データフォーマット</h3> <p>リクエスト、レスポンスともにJSON形式をサポート</p> <h3 id=\"_8\">共通レスポンスヘッダー</h3> <p>すべてのAPIのレスポンスには以下のHTTPヘッダーが含まれます。</p> <ul> <li> <p>X-Freee-Request-ID</p> <ul> <li>各リクエスト毎に発行されるID</li> </ul> </li> </ul> <h3 id=\"_9\">共通エラーレスポンス</h3> <ul> <li> <p>ステータスコードはレスポンス内のJSONに含まれる他、HTTPヘッダにも含まれる</p> </li> <li> <p>type</p> <ul> <li>status : HTTPステータスコードの説明</li> <li>validation : エラーの詳細の説明(開発者向け)</li> </ul> </li> </ul> <p>レスポンスの例</p> <pre><code> { &quot;status_code&quot; : 400, &quot;errors&quot; : [ { &quot;type&quot; : &quot;status&quot;, &quot;messages&quot; : [&quot;不正なリクエストです。&quot;] }, { &quot;type&quot; : &quot;validation&quot;, &quot;messages&quot; : [&quot;Date は不正な日付フォーマットです。入力例:2013-01-01&quot;] } ] }</code></pre> <hr /> <h2 id=\"_10\">連絡先</h2> <p>ご不明点、ご要望等は <a href=\"https://support.freee.co.jp/hc/ja/requests/new\">freee サポートデスクへのお問い合わせフォーム</a> からご連絡ください。</p> <hr />&copy; Since 2013 freee K.K. * * The version of the OpenAPI document: v1.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using OpenAPIDateConverter = Freee.Accounting.Client.OpenAPIDateConverter; namespace Freee.Accounting.Models { /// <summary> /// SelectablesIndexResponseAccountItems /// </summary> [DataContract] public partial class SelectablesIndexResponseAccountItems : IEquatable<SelectablesIndexResponseAccountItems> { /// <summary> /// Initializes a new instance of the <see cref="SelectablesIndexResponseAccountItems" /> class. /// </summary> [JsonConstructorAttribute] protected SelectablesIndexResponseAccountItems() { } /// <summary> /// Initializes a new instance of the <see cref="SelectablesIndexResponseAccountItems" /> class. /// </summary> /// <param name="id">勘定科目ID (required).</param> /// <param name="name">勘定科目.</param> /// <param name="desc">勘定科目の説明.</param> /// <param name="help">勘定科目の説明(詳細).</param> /// <param name="shortcut">ショートカット.</param> /// <param name="defaultTax">defaultTax.</param> public SelectablesIndexResponseAccountItems(int id = default(int), string name = default(string), string desc = default(string), string help = default(string), string shortcut = default(string), SelectablesIndexResponseDefaultTax defaultTax = default(SelectablesIndexResponseDefaultTax)) { this.Id = id; this.Name = name; this.Desc = desc; this.Help = help; this.Shortcut = shortcut; this.DefaultTax = defaultTax; } /// <summary> /// 勘定科目ID /// </summary> /// <value>勘定科目ID</value> [DataMember(Name="id", EmitDefaultValue=false)] public int Id { get; set; } /// <summary> /// 勘定科目 /// </summary> /// <value>勘定科目</value> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// 勘定科目の説明 /// </summary> /// <value>勘定科目の説明</value> [DataMember(Name="desc", EmitDefaultValue=false)] public string Desc { get; set; } /// <summary> /// 勘定科目の説明(詳細) /// </summary> /// <value>勘定科目の説明(詳細)</value> [DataMember(Name="help", EmitDefaultValue=false)] public string Help { get; set; } /// <summary> /// ショートカット /// </summary> /// <value>ショートカット</value> [DataMember(Name="shortcut", EmitDefaultValue=false)] public string Shortcut { get; set; } /// <summary> /// Gets or Sets DefaultTax /// </summary> [DataMember(Name="default_tax", EmitDefaultValue=false)] public SelectablesIndexResponseDefaultTax DefaultTax { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class SelectablesIndexResponseAccountItems {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Desc: ").Append(Desc).Append("\n"); sb.Append(" Help: ").Append(Help).Append("\n"); sb.Append(" Shortcut: ").Append(Shortcut).Append("\n"); sb.Append(" DefaultTax: ").Append(DefaultTax).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as SelectablesIndexResponseAccountItems); } /// <summary> /// Returns true if SelectablesIndexResponseAccountItems instances are equal /// </summary> /// <param name="input">Instance of SelectablesIndexResponseAccountItems to be compared</param> /// <returns>Boolean</returns> public bool Equals(SelectablesIndexResponseAccountItems input) { if (input == null) return false; return ( this.Id == input.Id || this.Id.Equals(input.Id) ) && ( this.Name == input.Name || (this.Name != null && this.Name.Equals(input.Name)) ) && ( this.Desc == input.Desc || (this.Desc != null && this.Desc.Equals(input.Desc)) ) && ( this.Help == input.Help || (this.Help != null && this.Help.Equals(input.Help)) ) && ( this.Shortcut == input.Shortcut || (this.Shortcut != null && this.Shortcut.Equals(input.Shortcut)) ) && ( this.DefaultTax == input.DefaultTax || (this.DefaultTax != null && this.DefaultTax.Equals(input.DefaultTax)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; hashCode = hashCode * 59 + this.Id.GetHashCode(); if (this.Name != null) hashCode = hashCode * 59 + this.Name.GetHashCode(); if (this.Desc != null) hashCode = hashCode * 59 + this.Desc.GetHashCode(); if (this.Help != null) hashCode = hashCode * 59 + this.Help.GetHashCode(); if (this.Shortcut != null) hashCode = hashCode * 59 + this.Shortcut.GetHashCode(); if (this.DefaultTax != null) hashCode = hashCode * 59 + this.DefaultTax.GetHashCode(); return hashCode; } } } }
63.294118
5,736
0.607807
[ "MIT" ]
s-taira/freee-accounting-sdk-csharp
src/Freee.Accounting/Models/SelectablesIndexResponseAccountItems.cs
14,926
C#
using System; using System.Reflection; using System.Text; namespace ByValue { internal static class TypeExtensions { public static string GetFriendlyName(this Type type) { return GetFriendlyNameInner(type, t => t.Name); } public static string GetFriendlyFullName(this Type type) { return GetFriendlyNameInner(type, t => t.FullName); } private static string GetFriendlyNameInner(Type type, Func<Type, string> nameSelector) { // GetTypeInfo() not need for net461 if (type.GetTypeInfo().IsGenericType) { // always use Name for generics, it is probably collection type var genericName = type.Name; var iBacktick = genericName.IndexOf('`'); if (iBacktick > 0) { genericName = genericName.Remove(iBacktick); } var builder = new StringBuilder(); builder.Append(genericName); builder.Append("<"); var typeArguments = type.GetTypeInfo().GenericTypeArguments; for (var i = 0; i < typeArguments.Length; ++i) { var typeArgumentName = GetFriendlyNameInner(typeArguments[i], nameSelector); builder.Append(i == 0 ? typeArgumentName : "," + typeArgumentName); } builder.Append(">"); return builder.ToString(); } return nameSelector(type); } } }
32.08
96
0.534913
[ "MIT" ]
sm-g/ByValue
src/ByValue/Helpers/TypeExtensions.cs
1,606
C#
using System.Linq; using NUnit.Framework; using System; using System.Data; using unQuery.SqlTypes; namespace unQuery.Tests.SqlTypes { public class SqlCharTests : TestFixture { [Test] public void GetTypeHandler() { Assert.IsInstanceOf<SqlTypeHandler>(SqlChar.GetTypeHandler()); } [Test] public void CreateParamFromValue() { Assert.Throws<TypeCannotBeUsedAsAClrTypeException>(() => SqlChar.GetTypeHandler().CreateParamFromValue("Test", null)); } [Test] public void CreateMetaData() { Assert.Throws<TypeCannotBeUsedAsAClrTypeException>(() => SqlChar.GetTypeHandler().CreateMetaData("Test")); SqlTypeHandler col = new SqlChar("Test", null, ParameterDirection.Input); Assert.Throws<TypePropertiesMustBeSetExplicitlyException>(() => col.CreateMetaData("Test")); col = new SqlChar("Test", 10, ParameterDirection.Input); var meta = col.CreateMetaData("Test"); Assert.AreEqual(SqlDbType.Char, meta.SqlDbType); Assert.AreEqual(10, meta.MaxLength); Assert.AreEqual("Test", meta.Name); } [Test] public void GetParameter() { TestHelper.AssertSqlParameter((new SqlChar("Test", 10, ParameterDirection.Input)).GetParameter(), SqlDbType.Char, "Test", size: 10); TestHelper.AssertSqlParameter((new SqlChar(null, 10, ParameterDirection.Input)).GetParameter(), SqlDbType.Char, DBNull.Value, size: 10); TestHelper.AssertSqlParameter((new SqlChar("Test", null, ParameterDirection.Input)).GetParameter(), SqlDbType.Char, "Test", size: 4); TestHelper.AssertSqlParameter((new SqlChar(null, null, ParameterDirection.Input)).GetParameter(), SqlDbType.Char, DBNull.Value, size: 0); } [Test] public void GetRawValue() { SqlType type = new SqlChar("Test", 10, ParameterDirection.Input); Assert.AreEqual("Test", type.GetRawValue()); type = new SqlChar(null, 10, ParameterDirection.Input); Assert.Null(type.GetRawValue()); } [Test] public void Factory() { Assert.IsInstanceOf<SqlChar>(Col.Char("Test", 10)); Assert.IsInstanceOf<SqlChar>(Col.Char("Test")); } [Test] public void Structured() { var rows = DB.GetRows("SELECT * FROM @Input", new { Input = Col.Structured("ListOfChars", new[] { new { A = Col.Char("Test", 10) }, new { A = Col.Char(null, 10) } }) }); Assert.AreEqual(2, rows.Count); Assert.AreEqual(typeof(string), rows[0].A.GetType()); Assert.AreEqual("Test ", rows[0].A); Assert.AreEqual(null, rows[1].A); } [Test] public void StructuredDynamicYielder() { var result = new StructuredDynamicYielder(new[] { new { A = Col.Char("Test", 10), B = Col.Char(null, 10) }}).First(); Assert.AreEqual(2, result.FieldCount); Assert.AreEqual(typeof(string), result.GetValue(0).GetType()); Assert.AreEqual("Test", result.GetValue(0)); Assert.AreEqual(DBNull.Value, result.GetValue(1)); } [Test] public void TypeMaps() { Assert.IsInstanceOf<SqlTypeHandler>(unQueryDB.ClrTypeHandlers[typeof(SqlChar)]); Assert.IsInstanceOf<SqlTypeHandler>(unQueryDB.SqlDbTypeHandlers[SqlDbType.Char]); } } }
31.465347
141
0.676211
[ "MIT" ]
JTOne123/unQuery
src/unQuery.Tests/SqlTypes/SqlCharTests.cs
3,180
C#
using System.Collections.Generic; using Microsoft.ApplicationInsights; using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Mvc; namespace Helpdesk.Mvc.Controllers { [Route("error")] public class ErrorController : Controller { private readonly TelemetryClient _telemetryClient; public ErrorController(TelemetryClient telemetryClient) { _telemetryClient = telemetryClient; } [Route("500")] public IActionResult AppError() { var exceptionHandlerPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>(); _telemetryClient.TrackException(exceptionHandlerPathFeature.Error); _telemetryClient.TrackEvent("Error.ServerError", new Dictionary<string, string> { ["originalPath"] = exceptionHandlerPathFeature.Path, ["error"] = exceptionHandlerPathFeature.Error.Message }); return View(); } [Route("404")] public IActionResult PageNotFound() { string originalPath = "unknown"; if (HttpContext.Items.ContainsKey("originalPath")) { originalPath = HttpContext.Items["originalPath"] as string; } _telemetryClient.TrackEvent("Error.PageNotFound", new Dictionary<string, string> { ["originalPath"] = originalPath }); return View(); } } }
32.717391
103
0.614618
[ "MIT" ]
MagnusIIIBR/DotnetDesk-Rebirth
src/Helpdesk.Mvc/Controllers/ErrorController.cs
1,507
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Net; using System.Threading; using System.Threading.Tasks; using Azure.Core; using Azure.Core.Pipeline; using Azure.Data.Tables.Models; using Azure.Data.Tables.Queryable; using Azure.Data.Tables.Sas; namespace Azure.Data.Tables { /// <summary> /// The <see cref="TableClient"/> allows you to interact with Azure Storage /// Tables. /// </summary> public class TableClient { private readonly string _table; private readonly OdataMetadataFormat _format; private readonly ClientDiagnostics _diagnostics; private readonly TableRestClient _tableOperations; private readonly string _version; private readonly bool _isPremiumEndpoint; /// <summary> /// Initializes a new instance of the <see cref="TableClient"/>. /// </summary> /// <param name="tableName">The name of the table with which this client instance will interact.</param> /// <param name="endpoint"> /// A <see cref="Uri"/> referencing the table service account. /// This is likely to be similar to "https://{account_name}.table.core.windows.net/" or "https://{account_name}.table.cosmos.azure.com/". /// </param> /// <param name="options"> /// Optional client options that define the transport pipeline policies for authentication, retries, etc., that are applied to every request. /// </param> /// <exception cref="ArgumentException"><paramref name="endpoint"/> is not https.</exception> public TableClient(string tableName, Uri endpoint, TableClientOptions options = null) : this(tableName, endpoint, default(TableSharedKeyPipelinePolicy), options) { Argument.AssertNotNull(tableName, nameof(tableName)); if (endpoint.Scheme != "https") { throw new ArgumentException("Cannot use TokenCredential without HTTPS.", nameof(endpoint)); } } /// <summary> /// Initializes a new instance of the <see cref="TableClient"/>. /// </summary> /// <param name="tableName">The name of the table with which this client instance will interact.</param> /// <param name="endpoint"> /// A <see cref="Uri"/> referencing the table service account. /// This is likely to be similar to "https://{account_name}.table.core.windows.net/" or "https://{account_name}.table.cosmos.azure.com/". /// </param> /// <param name="credential">The shared key credential used to sign requests.</param> /// <exception cref="ArgumentNullException"><paramref name="tableName"/> or <paramref name="credential"/> is null.</exception> public TableClient(string tableName, Uri endpoint, TableSharedKeyCredential credential) : this(tableName, endpoint, new TableSharedKeyPipelinePolicy(credential), null) { Argument.AssertNotNull(tableName, nameof(tableName)); Argument.AssertNotNull(credential, nameof(credential)); } /// <summary> /// Initializes a new instance of the <see cref="TableClient"/>. /// </summary> /// <param name="tableName">The name of the table with which this client instance will interact.</param> /// <param name="endpoint"> /// A <see cref="Uri"/> referencing the table service account. /// This is likely to be similar to "https://{account_name}.table.core.windows.net/" or "https://{account_name}.table.cosmos.azure.com/". /// </param> /// <param name="credential">The shared key credential used to sign requests.</param> /// <param name="options"> /// Optional client options that define the transport pipeline policies for authentication, retries, etc., that are applied to every request. /// </param> /// <exception cref="ArgumentNullException"><paramref name="tableName"/> or <paramref name="credential"/> is null.</exception> public TableClient(string tableName, Uri endpoint, TableSharedKeyCredential credential, TableClientOptions options = null) : this(tableName, endpoint, new TableSharedKeyPipelinePolicy(credential), options) { Argument.AssertNotNull(tableName, nameof(tableName)); Argument.AssertNotNull(credential, nameof(credential)); } internal TableClient(string tableName, Uri endpoint, TableSharedKeyPipelinePolicy policy, TableClientOptions options) { Argument.AssertNotNull(tableName, nameof(tableName)); Argument.AssertNotNull(endpoint, nameof(endpoint)); options ??= new TableClientOptions(); HttpPipeline pipeline = HttpPipelineBuilder.Build(options, policy); _diagnostics = new ClientDiagnostics(options); _tableOperations = new TableRestClient(_diagnostics, pipeline, endpoint.ToString()); _version = options.VersionString; _table = tableName; _format = OdataMetadataFormat.ApplicationJsonOdataFullmetadata; _isPremiumEndpoint = TableServiceClient.IsPremiumEndpoint(endpoint); ; } internal TableClient(string table, TableRestClient tableOperations, string version, ClientDiagnostics diagnostics, bool isPremiumEndpoint) { _tableOperations = tableOperations; _version = version; _table = table; _format = OdataMetadataFormat.ApplicationJsonOdataFullmetadata; _diagnostics = diagnostics; _isPremiumEndpoint = isPremiumEndpoint; } /// <summary> /// Initializes a new instance of the <see cref="TableClient"/> /// class for mocking. /// </summary> protected TableClient() { } /// <summary> /// Gets a <see cref="TableSasBuilder"/> instance scoped to the current table. /// </summary> /// <param name="permissions"><see cref="TableSasPermissions"/> containing the allowed permissions.</param> /// <param name="expiresOn">The time at which the shared access signature becomes invalid.</param> /// <returns>An instance of <see cref="TableSasBuilder"/>.</returns> public virtual TableSasBuilder GetSasBuilder(TableSasPermissions permissions, DateTimeOffset expiresOn) { return new TableSasBuilder(_table, permissions, expiresOn) { Version = _version }; } /// <summary> /// Gets a <see cref="TableSasBuilder"/> instance scoped to the current table. /// </summary> /// <param name="rawPermissions">The permissions associated with the shared access signature. This string should contain one or more of the following permission characters in this order: "racwdl".</param> /// <param name="expiresOn">The time at which the shared access signature becomes invalid.</param> /// <returns>An instance of <see cref="TableSasBuilder"/>.</returns> public virtual TableSasBuilder GetSasBuilder(string rawPermissions, DateTimeOffset expiresOn) { return new TableSasBuilder(_table, rawPermissions, expiresOn) { Version = _version }; } /// <summary> /// Creates the current table. /// </summary> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <returns>A <see cref="Response{TableItem}"/> containing properties of the table.</returns> public virtual Response<TableItem> Create(CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(Create)}"); scope.Start(); try { var response = _tableOperations.Create(new TableProperties() { TableName = _table }, null, queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken); return Response.FromValue(response.Value as TableItem, response.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Creates the current table. /// </summary> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <returns>A <see cref="Response{TableItem}"/> containing properties of the table.</returns> public virtual async Task<Response<TableItem>> CreateAsync(CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(Create)}"); scope.Start(); try { var response = await _tableOperations.CreateAsync(new TableProperties() { TableName = _table }, null, queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken).ConfigureAwait(false); return Response.FromValue(response.Value as TableItem, response.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Creates the current table. /// </summary> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <returns>If the table does not already exist, a <see cref="Response{TableItem}"/>. If the table already exists, <c>null</c>.</returns> public virtual Response<TableItem> CreateIfNotExists(CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(CreateIfNotExists)}"); scope.Start(); try { var response = _tableOperations.Create(new TableProperties() { TableName = _table }, null, queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken); return Response.FromValue(response.Value as TableItem, response.GetRawResponse()); } catch (RequestFailedException ex) when (ex.Status == (int)HttpStatusCode.Conflict) { return default; } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Creates the current table. /// </summary> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <returns>If the table does not already exist, a <see cref="Response{TableItem}"/>. If the table already exists, <c>null</c>.</returns> public virtual async Task<Response<TableItem>> CreateIfNotExistsAsync(CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(CreateIfNotExists)}"); scope.Start(); try { var response = await _tableOperations.CreateAsync(new TableProperties() { TableName = _table }, null, queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken).ConfigureAwait(false); return Response.FromValue(response.Value as TableItem, response.GetRawResponse()); } catch (RequestFailedException ex) when (ex.Status == (int)HttpStatusCode.Conflict) { return default; } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Deletes the current table. /// </summary> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns></returns> public virtual Response Delete(CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(Delete)}"); scope.Start(); try { return _tableOperations.Delete(table: _table, null, cancellationToken: cancellationToken); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Deletes the current table. /// </summary> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns></returns> public virtual async Task<Response> DeleteAsync(CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(Delete)}"); scope.Start(); try { return await _tableOperations.DeleteAsync(table: _table, null, cancellationToken: cancellationToken).ConfigureAwait(false); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Adds a Table Entity into the Table. /// </summary> /// <param name="entity">The entity to add.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <returns>The added Table entity.</returns> /// <exception cref="RequestFailedException">Exception thrown if entity already exists.</exception> public virtual async Task<Response<T>> AddEntityAsync<T>(T entity, CancellationToken cancellationToken = default) where T : class, ITableEntity, new() { Argument.AssertNotNull(entity, nameof(entity)); Argument.AssertNotNull(entity?.PartitionKey, nameof(entity.PartitionKey)); Argument.AssertNotNull(entity?.RowKey, nameof(entity.RowKey)); using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(AddEntity)}"); scope.Start(); try { var response = await _tableOperations.InsertEntityAsync(_table, tableEntityProperties: entity.ToOdataAnnotatedDictionary(), queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken).ConfigureAwait(false); var result = ((Dictionary<string, object>)response.Value).ToTableEntity<T>(); return Response.FromValue(result, response.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Adds a Table Entity into the Table. /// </summary> /// <param name="entity">The entity to add.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns>The added Table entity.</returns> /// <exception cref="RequestFailedException">Exception thrown if entity already exists.</exception> public virtual Response<T> AddEntity<T>(T entity, CancellationToken cancellationToken = default) where T : class, ITableEntity, new() { Argument.AssertNotNull(entity, nameof(entity)); Argument.AssertNotNull(entity?.PartitionKey, nameof(entity.PartitionKey)); Argument.AssertNotNull(entity?.RowKey, nameof(entity.RowKey)); using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(AddEntity)}"); scope.Start(); try { var response = _tableOperations.InsertEntity(_table, tableEntityProperties: entity.ToOdataAnnotatedDictionary(), queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken); var result = ((Dictionary<string, object>)response.Value).ToTableEntity<T>(); return Response.FromValue(result, response.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Gets the specified table entity. /// </summary> /// <param name="partitionKey">The partitionKey that identifies the table entity.</param> /// <param name="rowKey">The rowKey that identifies the table entity.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns>The <see cref="Response"/> indicating the result of the operation.</returns> /// <exception cref="RequestFailedException">Exception thrown if the entity doesn't exist.</exception> /// <exception cref="ArgumentNullException"><paramref name="partitionKey"/> or <paramref name="rowKey"/> is null.</exception> public virtual Response<T> GetEntity<T>(string partitionKey, string rowKey, CancellationToken cancellationToken = default) where T : class, ITableEntity, new() { Argument.AssertNotNull("message", nameof(partitionKey)); Argument.AssertNotNull("message", nameof(rowKey)); using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(GetEntity)}"); scope.Start(); try { var response = _tableOperations.QueryEntitiesWithPartitionAndRowKey( _table, partitionKey, rowKey, queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken); var result = ((Dictionary<string, object>)response.Value).ToTableEntity<T>(); return Response.FromValue(result, response.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Gets the specified table entity. /// </summary> /// <param name="partitionKey">The partitionKey that identifies the table entity.</param> /// <param name="rowKey">The rowKey that identifies the table entity.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns>The <see cref="Response"/> indicating the result of the operation.</returns> /// <exception cref="RequestFailedException">Exception thrown if the entity doesn't exist.</exception> /// <exception cref="ArgumentNullException"><paramref name="partitionKey"/> or <paramref name="rowKey"/> is null.</exception> public virtual async Task<Response<T>> GetEntityAsync<T>(string partitionKey, string rowKey, CancellationToken cancellationToken = default) where T : class, ITableEntity, new() { Argument.AssertNotNull("message", nameof(partitionKey)); Argument.AssertNotNull("message", nameof(rowKey)); using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(GetEntity)}"); scope.Start(); try { var response = await _tableOperations.QueryEntitiesWithPartitionAndRowKeyAsync( _table, partitionKey, rowKey, queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken).ConfigureAwait(false); var result = ((Dictionary<string, object>)response.Value).ToTableEntity<T>(); return Response.FromValue(result, response.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Replaces the specified table entity, if it exists. Creates the entity if it does not exist. /// </summary> /// <param name="entity">The entity to upsert.</param> /// <param name="mode">An enum that determines which upsert operation to perform.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <returns>The <see cref="Response"/> indicating the result of the operation.</returns> public virtual async Task<Response> UpsertEntityAsync<T>(T entity, TableUpdateMode mode = TableUpdateMode.Merge, CancellationToken cancellationToken = default) where T : class, ITableEntity, new() { Argument.AssertNotNull(entity, nameof(entity)); Argument.AssertNotNull(entity?.PartitionKey, nameof(entity.PartitionKey)); Argument.AssertNotNull(entity?.RowKey, nameof(entity.RowKey)); using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(UpsertEntity)}"); scope.Start(); try { if (mode == TableUpdateMode.Replace) { return await _tableOperations.UpdateEntityAsync(_table, entity.PartitionKey, entity.RowKey, tableEntityProperties: entity.ToOdataAnnotatedDictionary(), queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken).ConfigureAwait(false); } else if (mode == TableUpdateMode.Merge) { return await _tableOperations.MergeEntityAsync(_table, entity.PartitionKey, entity.RowKey, tableEntityProperties: entity.ToOdataAnnotatedDictionary(), queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken).ConfigureAwait(false); } else { throw new ArgumentException($"Unexpected value for {nameof(mode)}: {mode}"); } } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Replaces the specified table entity, if it exists. Creates the entity if it does not exist. /// </summary> /// <param name="entity">The entity to upsert.</param> /// <param name="mode">An enum that determines which upsert operation to perform.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <returns>The <see cref="Response"/> indicating the result of the operation.</returns> public virtual Response UpsertEntity<T>(T entity, TableUpdateMode mode = TableUpdateMode.Merge, CancellationToken cancellationToken = default) where T : class, ITableEntity, new() { Argument.AssertNotNull(entity, nameof(entity)); Argument.AssertNotNull(entity?.PartitionKey, nameof(entity.PartitionKey)); Argument.AssertNotNull(entity?.RowKey, nameof(entity.RowKey)); using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(UpsertEntity)}"); scope.Start(); try { if (mode == TableUpdateMode.Replace) { return _tableOperations.UpdateEntity(_table, entity.PartitionKey, entity.RowKey, tableEntityProperties: entity.ToOdataAnnotatedDictionary(), queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken); } else if (mode == TableUpdateMode.Merge) { return _tableOperations.MergeEntity(_table, entity.PartitionKey, entity.RowKey, tableEntityProperties: entity.ToOdataAnnotatedDictionary(), queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken); } else { throw new ArgumentException($"Unexpected value for {nameof(mode)}: {mode}"); } } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Replaces the specified table entity, if it exists. /// </summary> /// <param name="entity">The entity to update.</param> /// <param name="ifMatch">The If-Match value to be used for optimistic concurrency.</param> /// <param name="mode">An enum that determines which upsert operation to perform.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <returns>The <see cref="Response"/> indicating the result of the operation.</returns> public virtual async Task<Response> UpdateEntityAsync<T>(T entity, string ifMatch, TableUpdateMode mode = TableUpdateMode.Merge, CancellationToken cancellationToken = default) where T : class, ITableEntity, new() { Argument.AssertNotNull(entity, nameof(entity)); Argument.AssertNotNull(entity?.PartitionKey, nameof(entity.PartitionKey)); Argument.AssertNotNull(entity?.RowKey, nameof(entity.RowKey)); Argument.AssertNotNullOrWhiteSpace(ifMatch, nameof(ifMatch)); using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(UpdateEntity)}"); scope.Start(); try { if (mode == TableUpdateMode.Replace) { return await _tableOperations.UpdateEntityAsync(_table, entity.PartitionKey, entity.RowKey, tableEntityProperties: entity.ToOdataAnnotatedDictionary(), ifMatch: ifMatch, queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken).ConfigureAwait(false); } else if (mode == TableUpdateMode.Merge) { return await _tableOperations.MergeEntityAsync(_table, entity.PartitionKey, entity.RowKey, tableEntityProperties: entity.ToOdataAnnotatedDictionary(), ifMatch: ifMatch, queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken).ConfigureAwait(false); } else { throw new ArgumentException($"Unexpected value for {nameof(mode)}: {mode}"); } } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Replaces the specified table entity, if it exists. /// </summary> /// <param name="entity">The entity to update.</param> /// <param name="ifMatch">The If-Match value to be used for optimistic concurrency.</param> /// <param name="mode">An enum that determines which upsert operation to perform.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <returns>The <see cref="Response"/> indicating the result of the operation.</returns> public virtual Response UpdateEntity<T>(T entity, string ifMatch, TableUpdateMode mode = TableUpdateMode.Merge, CancellationToken cancellationToken = default) where T : class, ITableEntity, new() { Argument.AssertNotNull(entity, nameof(entity)); Argument.AssertNotNull(entity?.PartitionKey, nameof(entity.PartitionKey)); Argument.AssertNotNull(entity?.RowKey, nameof(entity.RowKey)); Argument.AssertNotNullOrWhiteSpace(ifMatch, nameof(ifMatch)); using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(UpdateEntity)}"); scope.Start(); try { if (mode == TableUpdateMode.Replace) { return _tableOperations.UpdateEntity(_table, entity.PartitionKey, entity.RowKey, tableEntityProperties: entity.ToOdataAnnotatedDictionary(), ifMatch: ifMatch, queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken); } else if (mode == TableUpdateMode.Merge) { return _tableOperations.MergeEntity(_table, entity.PartitionKey, entity.RowKey, tableEntityProperties: entity.ToOdataAnnotatedDictionary(), ifMatch: ifMatch, queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken); } else { throw new ArgumentException($"Unexpected value for {nameof(mode)}: {mode}"); } } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Queries entities in the table. /// </summary> /// <param name="filter">Returns only entities that satisfy the specified filter.</param> /// <param name="maxPerPage">The maximum number of entities that will be returned per page.</param> /// <param name="select">Selects which set of entity properties to return in the result set.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual AsyncPageable<T> QueryAsync<T>(Expression<Func<T, bool>> filter, int? maxPerPage = null, IEnumerable<string> select = null, CancellationToken cancellationToken = default) where T : class, ITableEntity, new() { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(Query)}"); scope.Start(); try { return QueryAsync<T>(Bind(filter), maxPerPage, select, cancellationToken); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Queries entities in the table. /// </summary> /// <param name="filter">Returns only entities that satisfy the specified filter.</param> /// <param name="maxPerPage">The maximum number of entities that will be returned per page.</param> /// <param name="select">Selects which set of entity properties to return in the result set.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual Pageable<T> Query<T>(Expression<Func<T, bool>> filter, int? maxPerPage = null, IEnumerable<string> select = null, CancellationToken cancellationToken = default) where T : class, ITableEntity, new() { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(Query)}"); scope.Start(); try { return Query<T>(Bind(filter), maxPerPage, select, cancellationToken); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Queries entities in the table. /// </summary> /// <param name="filter">Returns only entities that satisfy the specified filter.</param> /// <param name="maxPerPage">The maximum number of entities that will be returned per page.</param> /// <param name="select">Selects which set of entity properties to return in the result set.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns></returns> public virtual AsyncPageable<T> QueryAsync<T>(string filter = null, int? maxPerPage = null, IEnumerable<string> select = null, CancellationToken cancellationToken = default) where T : class, ITableEntity, new() { string selectArg = select == null ? null : string.Join(",", select); using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(Query)}"); scope.Start(); try { return PageableHelpers.CreateAsyncEnumerable(async _ => { var response = await _tableOperations.QueryEntitiesAsync( _table, queryOptions: new QueryOptions() { Format = _format, Top = maxPerPage, Filter = filter, Select = selectArg }, cancellationToken: cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value.ToTableEntityList<T>(), CreateContinuationTokenFromHeaders(response.Headers), response.GetRawResponse()); }, async (continuationToken, _) => { var (NextPartitionKey, NextRowKey) = ParseContinuationToken(continuationToken); var response = await _tableOperations.QueryEntitiesAsync( _table, queryOptions: new QueryOptions() { Format = _format, Top = maxPerPage, Filter = filter, Select = selectArg }, nextPartitionKey: NextPartitionKey, nextRowKey: NextRowKey, cancellationToken: cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value.ToTableEntityList<T>(), CreateContinuationTokenFromHeaders(response.Headers), response.GetRawResponse()); }); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Queries entities in the table. /// </summary> /// <param name="filter">Returns only entities that satisfy the specified filter.</param> /// <param name="maxPerPage">The maximum number of entities that will be returned per page.</param> /// <param name="select">Selects which set of entity properties to return in the result set.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> public virtual Pageable<T> Query<T>(string filter = null, int? maxPerPage = null, IEnumerable<string> select = null, CancellationToken cancellationToken = default) where T : class, ITableEntity, new() { string selectArg = select == null ? null : string.Join(",", select); return PageableHelpers.CreateEnumerable((int? _) => { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(Query)}"); scope.Start(); try { var response = _tableOperations.QueryEntities(_table, queryOptions: new QueryOptions() { Format = _format, Top = maxPerPage, Filter = filter, Select = selectArg }, cancellationToken: cancellationToken); return Page.FromValues( response.Value.Value.ToTableEntityList<T>(), CreateContinuationTokenFromHeaders(response.Headers), response.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } }, (continuationToken, _) => { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(Query)}"); scope.Start(); try { var (NextPartitionKey, NextRowKey) = ParseContinuationToken(continuationToken); var response = _tableOperations.QueryEntities( _table, queryOptions: new QueryOptions() { Format = _format, Top = maxPerPage, Filter = filter, Select = selectArg }, nextPartitionKey: NextPartitionKey, nextRowKey: NextRowKey, cancellationToken: cancellationToken); return Page.FromValues(response.Value.Value.ToTableEntityList<T>(), CreateContinuationTokenFromHeaders(response.Headers), response.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } }); } /// <summary> /// Deletes the specified table entity. /// </summary> /// <param name="partitionKey">The partitionKey that identifies the table entity.</param> /// <param name="rowKey">The rowKey that identifies the table entity.</param> /// <param name="ifMatch">The If-Match value to be used for optimistic concurrency.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <returns>The <see cref="Response"/> indicating the result of the operation.</returns> public virtual async Task<Response> DeleteEntityAsync(string partitionKey, string rowKey, string ifMatch = "*", CancellationToken cancellationToken = default) { Argument.AssertNotNull(partitionKey, nameof(partitionKey)); Argument.AssertNotNull(rowKey, nameof(rowKey)); using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(DeleteEntity)}"); scope.Start(); try { return await _tableOperations.DeleteEntityAsync(_table, partitionKey, rowKey, ifMatch: ifMatch, queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken).ConfigureAwait(false); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Deletes the specified table entity. /// </summary> /// <param name="partitionKey">The partitionKey that identifies the table entity.</param> /// <param name="rowKey">The rowKey that identifies the table entity.</param> /// <param name="ifMatch">The If-Match value to be used for optimistic concurrency. The default is to delete unconditionally.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <returns>The <see cref="Response"/> indicating the result of the operation.</returns> public virtual Response DeleteEntity(string partitionKey, string rowKey, string ifMatch = "*", CancellationToken cancellationToken = default) { Argument.AssertNotNull(partitionKey, nameof(partitionKey)); Argument.AssertNotNull(rowKey, nameof(rowKey)); using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(DeleteEntity)}"); scope.Start(); try { return _tableOperations.DeleteEntity(_table, partitionKey, rowKey, ifMatch: ifMatch, queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> Retrieves details about any stored access policies specified on the table that may be used with Shared Access Signatures. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual async Task<Response<IReadOnlyList<SignedIdentifier>>> GetAccessPolicyAsync(CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(GetAccessPolicy)}"); scope.Start(); try { var response = await _tableOperations.GetAccessPolicyAsync(_table, cancellationToken: cancellationToken).ConfigureAwait(false); return Response.FromValue(response.Value, response.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> Retrieves details about any stored access policies specified on the table that may be used with Shared Access Signatures. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual Response<IReadOnlyList<SignedIdentifier>> GetAccessPolicy(CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(GetAccessPolicy)}"); scope.Start(); try { var response = _tableOperations.GetAccessPolicy(_table, cancellationToken: cancellationToken); return Response.FromValue(response.Value, response.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> sets stored access policies for the table that may be used with Shared Access Signatures. </summary> /// <param name="tableAcl"> the access policies for the table. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual async Task<Response> SetAccessPolicyAsync(IEnumerable<SignedIdentifier> tableAcl, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(SetAccessPolicy)}"); scope.Start(); try { return await _tableOperations.SetAccessPolicyAsync(_table, tableAcl: tableAcl, cancellationToken: cancellationToken).ConfigureAwait(false); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> sets stored access policies for the table that may be used with Shared Access Signatures. </summary> /// <param name="tableAcl"> the access policies for the table. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual Response SetAccessPolicy(IEnumerable<SignedIdentifier> tableAcl, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(SetAccessPolicy)}"); scope.Start(); try { return _tableOperations.SetAccessPolicy(_table, tableAcl: tableAcl, cancellationToken: cancellationToken); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Creates an Odata filter query string from the provided expression. /// </summary> /// <typeparam name="T">The type of the entity being queried. Typically this will be derrived from <see cref="ITableEntity"/> or <see cref="Dictionary{String, Object}"/>.</typeparam> /// <param name="filter">A filter expresssion.</param> /// <returns>The string representation of the filter expression.</returns> public static string CreateQueryFilter<T>(Expression<Func<T, bool>> filter) => Bind(filter); internal static string Bind(Expression expression) { Argument.AssertNotNull(expression, nameof(expression)); Dictionary<Expression, Expression> normalizerRewrites = new Dictionary<Expression, Expression>(ReferenceEqualityComparer<Expression>.Instance); // Evaluate any local valid expressions ( lambdas etc) Expression partialEvaluatedExpression = Evaluator.PartialEval(expression); // Normalize expression, replace String Comparisons etc. Expression normalizedExpression = ExpressionNormalizer.Normalize(partialEvaluatedExpression, normalizerRewrites); // Parse the Bound expression into an OData filter. ExpressionParser parser = new ExpressionParser(); parser.Translate(normalizedExpression); // Return the FilterString. return parser.FilterString == "true" ? null : parser.FilterString; } private static string CreateContinuationTokenFromHeaders(TableQueryEntitiesHeaders headers) { if (headers.XMsContinuationNextPartitionKey == null && headers.XMsContinuationNextRowKey == null) { return null; } else { return $"{headers.XMsContinuationNextPartitionKey} {headers.XMsContinuationNextRowKey}"; } } private static (string NextPartitionKey, string NextRowKey) ParseContinuationToken(string continuationToken) { // There were no headers passed and the continuation token contains just the space delimiter if (continuationToken?.Length <= 1) { return (null, null); } var tokens = continuationToken.Split(' '); return (tokens[0], tokens.Length > 1 ? tokens[1] : null); } } }
52.581856
233
0.602943
[ "MIT" ]
m-nash/azure-sdk-for-net
sdk/tables/Azure.Data.Tables/src/TableClient.cs
50,426
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Network.V20190801.Inputs { /// <summary> /// Minimum and maximum number of scale units to deploy. /// </summary> public sealed class ExpressRouteGatewayPropertiesBoundsArgs : Pulumi.ResourceArgs { /// <summary> /// Maximum number of scale units deployed for ExpressRoute gateway. /// </summary> [Input("max")] public Input<int>? Max { get; set; } /// <summary> /// Minimum number of scale units deployed for ExpressRoute gateway. /// </summary> [Input("min")] public Input<int>? Min { get; set; } public ExpressRouteGatewayPropertiesBoundsArgs() { } } }
28.971429
85
0.641026
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Network/V20190801/Inputs/ExpressRouteGatewayPropertiesBoundsArgs.cs
1,014
C#
using Volo.Abp; namespace AbpFileUploadToAzureStorage.EntityFrameworkCore { public abstract class AbpFileUploadToAzureStorageEntityFrameworkCoreTestBase : AbpFileUploadToAzureStorageTestBase<AbpFileUploadToAzureStorageEntityFrameworkCoreTestModule> { } }
27.1
177
0.852399
[ "MIT" ]
bartvanhoey/AbpFileUploadToAzureStorage
test/AbpFileUploadToAzureStorage.EntityFrameworkCore.Tests/EntityFrameworkCore/AbpFileUploadToAzureStorageEntityFrameworkCoreTestBase.cs
273
C#
/* * Swagger Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; namespace IO.Swagger.Client { public class ReadOnlyDictionary<T, K> : IDictionary<T, K> { private IDictionary<T, K> _dictionaryImplementation; public IEnumerator<KeyValuePair<T, K>> GetEnumerator() { return _dictionaryImplementation.GetEnumerator(); } public ReadOnlyDictionary() { _dictionaryImplementation = new Dictionary<T, K>(); } public ReadOnlyDictionary(IDictionary<T, K> dictionaryImplementation) { if (dictionaryImplementation == null) throw new ArgumentNullException("dictionaryImplementation"); _dictionaryImplementation = dictionaryImplementation; } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable) _dictionaryImplementation).GetEnumerator(); } public void Add(KeyValuePair<T, K> item) { throw new ReadonlyOperationException("This instance is readonly."); } public void Clear() { throw new ReadonlyOperationException("This instance is readonly."); } public bool Contains(KeyValuePair<T, K> item) { return _dictionaryImplementation.Contains(item); } public void CopyTo(KeyValuePair<T, K>[] array, int arrayIndex) { _dictionaryImplementation.CopyTo(array, arrayIndex); } public bool Remove(KeyValuePair<T, K> item) { throw new ReadonlyOperationException("This instance is readonly."); } public int Count { get { return _dictionaryImplementation.Count; } } public bool IsReadOnly { get { return true; } } public void Add(T key, K value) { throw new ReadonlyOperationException("This instance is readonly."); } public bool ContainsKey(T key) { return _dictionaryImplementation.ContainsKey(key); } public bool Remove(T key) { throw new ReadonlyOperationException("This instance is readonly."); } public bool TryGetValue(T key, out K value) { return _dictionaryImplementation.TryGetValue(key, out value); } public K this[T key] { get { return _dictionaryImplementation[key]; } set { throw new ReadonlyOperationException("This instance is readonly."); } } public ICollection<T> Keys { get { return _dictionaryImplementation.Keys; } } public ICollection<K> Values { get { return _dictionaryImplementation.Values; } } } [Serializable] public class ReadonlyOperationException : Exception { // // For guidelines regarding the creation of new exception types, see // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconerrorraisinghandlingguidelines.asp // and // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp07192001.asp // public ReadonlyOperationException() { } public ReadonlyOperationException(string message) : base(message) { } public ReadonlyOperationException(string message, Exception inner) : base(message, inner) { } protected ReadonlyOperationException( SerializationInfo info, StreamingContext context) : base(info, context) { } } }
28.171233
159
0.603452
[ "Apache-2.0" ]
Cadcorp/swagger-codegen
samples/client/petstore/csharp/SwaggerClientNet40/src/IO.Swagger/Client/ReadOnlyDictionary.cs
4,113
C#
using System; using System.Drawing; using Emgu.CV.Structure; namespace Sudoku.Recognition.Extensions { /// <summary> /// Provides the extensions methods for point array <see cref="PointF"/>[]. /// </summary> /// <seealso cref="PointF"/> public static class PointArrayEx { /// <summary> /// Get true if contour is rectangle with angles within <c>[lowAngle, upAngle]</c> degree. /// The default case is <c>[75, 105]</c> given by <paramref name="lowerAngle"/> and /// <paramref name="upperAngle"/>. /// </summary> /// <param name="contour">The contour.</param> /// <param name="lowerAngle">The lower angle. The default value is <c>75</c>.</param> /// <param name="upperAngle">The upper angle. The default value is <c>105</c>.</param> /// <param name="ratio">The ratio. The default value is <c>.35</c>.</param> /// <returns>A <see cref="bool"/> value.</returns> public static bool IsRectangle(this PointF[] contour, int lowerAngle = 75, int upperAngle = 105, double ratio = .35) { if (contour.Length > 4) { return false; } var sides = new LineSegment2DF[] { new(contour[0], contour[1]), new(contour[1], contour[3]), new(contour[2], contour[3]), new(contour[0], contour[2]) }; // Check angles between common sides. for (int j = 0; j < 4; j++) { double angle = Math.Abs(sides[(j + 1) % sides.Length].GetExteriorAngleDegree(sides[j])); if (angle < lowerAngle || angle > upperAngle) { return false; } } // Check ratio between all sides, it can't be more than allowed. for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (sides[i].Length / sides[j].Length < ratio || sides[i].Length / sides[j].Length > 1 + ratio) { return false; } } } return true; } } }
28.359375
118
0.604959
[ "MIT" ]
micexu/Sudoku
src/Sudoku.Recognition/Extensions/PointArrayEx.cs
1,817
C#
using APICore.Data; using Microsoft.EntityFrameworkCore; namespace APICore.Test.Unit.SettingServiceTests.Providers { public class SqliteSettingServiceTests : SettingServiceTests { public SqliteSettingServiceTests() : base(new DbContextOptionsBuilder<CoreDbContext>() .UseSqlite("Filename=Test.db") .Options) { } } }
30.133333
94
0.575221
[ "MIT" ]
samir1604/wep-api-aad
APICore/APICore.Test/Unit/SettingServiceTests/Providers/SqliteSettingServiceTests.cs
454
C#
using System.Collections.Generic; using UnityEngine; public class PauseGame : MonoBehaviour { public List<GameObject> objectsToHideOnPause; public List<GameObject> objectsToRevealOnPause; public void Pause() { Time.timeScale = 0f; foreach (GameObject obj in objectsToHideOnPause) { obj.SetActive(false); } foreach (GameObject obj in objectsToRevealOnPause) { obj.SetActive(true); } } public void Unpause() { Time.timeScale = 1f; foreach (GameObject obj in objectsToHideOnPause) { obj.SetActive(true); } foreach (GameObject obj in objectsToRevealOnPause) { obj.SetActive(false); } } }
20.102564
58
0.586735
[ "MIT" ]
DeusIntra/Snowball-Fight
Assets/Scripts/UI/Gameplay UI/PauseGame.cs
786
C#
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // namespace Microsoft.VisualStudio.Text.Editor { using System; /// <summary> /// Gets an <see cref="ISmartIndent"/> object for a given <see cref="ITextView"/>. /// Component exporters must supply at least one content type attribute to specify the applicable content types. /// </summary> /// <remarks> /// This is a MEF component part, and should be exported with the following attributes: /// [Export(NameSource=typeof(ISmartIndentProvider))] /// [ContentType("some content type")] /// </remarks> public interface ISmartIndentProvider { /// <summary> /// Creates an <see cref="ISmartIndent"/> object for the given <see cref="ITextView"/>. /// </summary> /// <param name="textView"> /// The <see cref="ITextView"/> on which the <see cref="ISmartIndent"/> will navigate. /// </param> /// <returns> /// A valid <see cref="ISmartIndent"/>. This value will never be <c>null</c>. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="textView"/> is <c>null</c>.</exception> ISmartIndent CreateSmartIndent(ITextView textView); } }
40.939394
116
0.636566
[ "MIT" ]
AmadeusW/vs-editor-api
src/Editor/Text/Def/TextUI/Editor/ISmartIndentProvider.cs
1,351
C#
/************************************************************************************ Filename : ONSPPropagationSerializationManager.cs Content : Functionality for serializing Oculus Audio geometry Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved. Licensed under the Oculus SDK Version 3.5 (the "License"); you may not use the Oculus SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at https://developer.oculus.com/licenses/sdk-3.5/ Unless required by applicable law or agreed to in writing, the Oculus SDK 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 UnityEditor; using UnityEditor.Build; using UnityEngine; using UnityEditor.SceneManagement; using UnityEngine.SceneManagement; using System.Collections.Generic; public enum PlayModeState { Stopped, Playing, Paused } class ONSPPropagationSerializationManager { <<<<<<< HEAD private static PlayModeState _currentState = PlayModeState.Stopped; ======= >>>>>>> master static ONSPPropagationSerializationManager() { EditorSceneManager.sceneSaving += OnSceneSaving; } public int callbackOrder { get { return 0; } } public void OnPreprocessBuild(BuildTarget target, string path) { Debug.Log("ONSPPropagationSerializationManager.OnPreprocessBuild for target " + target + " at path " + path); } [MenuItem("Oculus/Spatializer/Build audio geometry for current scene")] public static void BuildAudioGeometryForCurrentScene() { BuildAudioGeometryForScene(EditorSceneManager.GetActiveScene()); } [MenuItem("Oculus/Spatializer/Rebuild audio geometry all scenes")] public static void RebuildAudioGeometryForAllScenes() { Debug.Log("Rebuilding geometry for all scenes"); System.IO.Directory.Delete(ONSPPropagationGeometry.GeometryAssetPath, true); for (int i = 0; i < EditorSceneManager.sceneCount; ++i) { BuildAudioGeometryForScene(EditorSceneManager.GetSceneAt(i)); } } public static void OnSceneSaving(Scene scene, string path) { BuildAudioGeometryForScene(scene); } private static void BuildAudioGeometryForScene(Scene scene) { Debug.Log("Building audio geometry for scene " + scene.name); List<GameObject> rootObjects = new List<GameObject>(); scene.GetRootGameObjects(rootObjects); HashSet<string> fileNames = new HashSet<string>(); foreach (GameObject go in rootObjects) { var geometryComponents = go.GetComponentsInChildren<ONSPPropagationGeometry>(); foreach (ONSPPropagationGeometry geo in geometryComponents) { if (geo.fileEnabled) { if (!geo.WriteFile()) { Debug.LogError("Failed writing geometry for " + geo.gameObject.name); } else { if (!fileNames.Add(geo.filePathRelative)) { Debug.LogWarning("Duplicate file name detected: " + geo.filePathRelative); } } } } } Debug.Log("Successfully built " + fileNames.Count + " geometry objects"); } }
35.018349
117
0.631648
[ "MIT" ]
gafr4910/VR-Tower-Defense
Assets/Donwloads/Oculus/Spatializer/editor/ONSPPropagationSerializationManager.cs
3,817
C#
using System; namespace R5T.Bulgaria.Base.Construction { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } }
16.153846
47
0.519048
[ "MIT" ]
MinexAutomation/R5T.Bulgaria.Base
source/R5T.Bulgaria.Base.Construction/Code/Program.cs
212
C#
using System; namespace WhiteSparrow.Shared.Logging { [AttributeUsage(AttributeTargets.Class)] public class LogChannelAttribute : Attribute { } }
16.777778
45
0.788079
[ "MIT" ]
JakubSlaby/Chirp
WhiteSparrow/Logging/Chirp/Runtime/Channels/LogChannelAttribute.cs
153
C#
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace Altinn.Common.EFormidlingClient.Models { /// <summary> /// Initializes a new instance of the <see cref="Conversation"/> class. /// </summary> [ExcludeFromCodeCoverage] public class Conversation { /// <summary> /// Gets or sets the ID. Integer. The numeric message status ID. /// </summary> public int Id { get; set; } /// <summary> /// Gets or sets the ConversationId. The conversationId - typically an UUID. /// </summary> public string ConversationId { get; set; } /// <summary> /// Gets or sets the MessageId. The messageId - typically an UUID. /// </summary> public string MessageId { get; set; } /// <summary> /// Gets or sets the SenderIdentifier. Descriptor with information to identify the sender. Requires a 0192: prefix for all norwegian organizations. /// </summary> public string SenderIdentifier { get; set; } /// <summary> /// Gets or sets the ReceiverIdentifier. Descriptor with information to identify the receiver. Requires a 0192: prefix for all norwegian organizations. Prefix is not required for individuals. /// </summary> public string ReceiverIdentifier { get; set; } /// <summary> /// Gets or sets the ProcessIdentifier. The process identifier used by the message. /// </summary> public string ProcessIdentifier { get; set; } /// <summary> /// Gets or sets the MessageReference. The message reference /// </summary> public string MessageReference { get; set; } /// <summary> /// Gets or sets the MessageTitle. The message title /// </summary> public string MessageTitle { get; set; } /// <summary> /// Gets or sets the ServiceCode. Altinn service code /// </summary> public string ServiceCode { get; set; } /// <summary> /// Gets or sets the ServiceEditionCode. Altinn service edition code. /// </summary> public string ServiceEditionCode { get; set; } /// <summary> /// Gets or sets the LastUpdate. Date and time of status. /// </summary> public DateTime LastUpdate { get; set; } /// <summary> /// Gets or sets the Finished. f the conversation has a finished state or not. /// </summary> public bool Finished { get; set; } /// <summary> /// Gets or sets the Expiry. Expiry timestamp /// </summary> public DateTime Expiry { get; set; } /// <summary> /// Gets or sets the Direction. The direction. Can be one of: OUTGOING, INCOMING /// </summary> public string Direction { get; set; } /// <summary> /// Gets or sets the ServiceIdentifier. The service identifier. Can be one of: DPO, DPV, DPI, DPF, DPFIO, DPE, UNKNOWN /// </summary> public string ServiceIdentifier { get; set; } /// <summary> /// Gets or sets the MessageStatuses. An array of message statuses. /// </summary> public List<MessageStatus> MessageStatuses { get; set; } } /// <summary> /// Initializes a new instance of the <see cref="MessageStatus"/> class. /// </summary> public class MessageStatus { /// <summary> /// Gets or sets the Id. Integer. The numeric message status ID. /// </summary> public int Id { get; set; } /// <summary> /// Gets or sets the LastUpdate. Date and time of status. /// </summary> public DateTime LastUpdate { get; set; } /// <summary> /// Gets or sets the Status. The message status. Can be one of: OPPRETTET, SENDT, MOTTATT, LEVERT, LEST, FEIL, ANNET, INNKOMMENDE_MOTTATT, INNKOMMENDE_LEVERT, LEVETID_UTLOPT. /// More details can be found here: https://docs.digdir.no/eformidling_selfhelp_traffic_flow.html /// </summary> public string Status { get; set; } /// <summary> /// Gets or sets the Description /// </summary> public string Description { get; set; } } }
35.702479
200
0.588194
[ "BSD-3-Clause" ]
Altinn/altinn-studio
src/Altinn.Common/Altinn.EFormidlingClient/Altinn.EFormidlingClient/Models/Conversation.cs
4,320
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("nav_demo_app")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("nav_demo_app")] [assembly: AssemblyCopyright("Copyright © Navitar, Inc. 2015,2016")] [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("8c78dfe6-191e-4b8f-901e-c011519cdbf9")] // 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.8.0.0")] [assembly: AssemblyFileVersion("1.8.0.0")]
38.243243
84
0.745583
[ "Apache-2.0" ]
TotteKarlsson/atapi
thirdparty/navitar/nav_demo_app/Properties/AssemblyInfo.cs
1,418
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 03.11.2021. using NUnit.Framework; using structure_lib=lcpi.lib.structure; using xEFCore=Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb; namespace EFCore_LcpiOleDb_Tests.General.Unit.ErrorServices.Check{ //////////////////////////////////////////////////////////////////////////////// //class TestsFor__Arg_IsNullOrNotEmpty public static class TestsFor__Arg_IsNullOrNotEmpty { [Test] public static void Test_01__ok__null() { xEFCore.Check.Arg_IsNullOrNotEmpty (xEFCore.ErrSourceID.common, "x1", "x2", null); }//Test_01__ok__null //----------------------------------------------------------------------- [Test] public static void Test_02__ok__not_empty() { xEFCore.Check.Arg_IsNullOrNotEmpty (xEFCore.ErrSourceID.common, "x1", "x2", " "); }//Test_02__ok__not_empty //----------------------------------------------------------------------- [Test] public static void Test_03__err__Empty() { try { xEFCore.Check.Arg_IsNullOrNotEmpty (xEFCore.ErrSourceID.common, "x1", "x2", ""); } catch(structure_lib.exceptions.t_argument_exception e) { CheckErrors.PrintException_OK(e); CheckErrors.CheckException__ArgumentIsEmpty (e, CheckErrors.c_src__EFCoreDataProvider__common, "x1", "x2"); return; }//catch TestServices.ThrowWeWaitError(); }//Test_03__err__Empty };//class TestsFor__Arg_IsNullOrNotEmpty //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Unit.ErrorServices.Check
25.985294
81
0.559706
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Unit/ErrorServices/Check/TestsFor__Arg_IsNullOrNotEmpty.cs
1,769
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 NRZMyk.Services.Data; namespace NRZMyk.Services.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("20200804050114_ClinicalBreakpoints_Initial")] partial class ClinicalBreakpoints_Initial { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.4") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("NRZMyk.Services.Data.Entities.ClinicalBreakpoint", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("AntifungalAgent") .HasColumnType("int"); b.Property<string>("AntifungalAgentDetails") .IsRequired() .HasColumnType("nvarchar(450)"); b.Property<float?>("MicBreakpointResistent") .HasColumnType("real"); b.Property<float?>("MicBreakpointSusceptible") .HasColumnType("real"); b.Property<int>("Species") .HasColumnType("int"); b.Property<int>("Standard") .HasColumnType("int"); b.Property<DateTime>("ValidFrom") .HasColumnType("datetime2"); b.Property<string>("Version") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("Standard", "Version", "AntifungalAgentDetails") .IsUnique(); b.ToTable("ClinicalBreakpoints"); }); modelBuilder.Entity("NRZMyk.Services.Data.Entities.SentinelEntry", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("AgeGroup") .HasColumnType("int"); b.Property<string>("IdentifiedSpecies") .HasColumnType("nvarchar(max)"); b.Property<int>("Material") .HasColumnType("int"); b.Property<string>("Remark") .HasColumnType("nvarchar(max)"); b.Property<int>("ResidentialTreatment") .HasColumnType("int"); b.Property<DateTime?>("SamplingDate") .HasColumnType("datetime2"); b.Property<string>("SenderLaboratoryNumber") .HasColumnType("nvarchar(max)"); b.Property<int>("SpeciesTestingMethod") .HasColumnType("int"); b.HasKey("Id"); b.ToTable("SentinelEntries"); }); #pragma warning restore 612, 618 } } }
36.855769
125
0.527002
[ "MIT" ]
markusrt/NRZMyk
NRZMyk.Services/Data/Migrations/20200804050114_ClinicalBreakpoints_Initial.Designer.cs
3,835
C#
using UnityEngine; using UnityEditor; using Beans.Unity.Editor; namespace DeformEditor { public class DeformSettingsWindow : EditorWindow { private static class Content { public static GUIContent SolidHandleColor = new GUIContent (text: "Solid Color"); public static GUIContent LightHandleColor = new GUIContent (text: "Light Color"); public static GUIContent DottedLineSize = new GUIContent (text: "Dotted Line Size"); public static GUIContent ScreenspaceSliderHandleCapSize= new GUIContent (text: "Handle Size"); public static GUIContent ScreenspaceAngleHandleSize = new GUIContent (text: "Angle Handle Size"); public static GUIContent ModelsReadableByDefault = new GUIContent (text: "Models Readable By Default", tooltip: "When true, any newly imported models will be marked as readable."); } private SerializedObject serializedAsset; [MenuItem ("Window/Deform/Settings", priority = 10000)] [MenuItem ("Tools/Deform/Settings", priority = 10000)] public static void ShowWindow () { GetWindow<DeformSettingsWindow> ("Deform Settings", true); } private void OnEnable () { serializedAsset = new SerializedObject (DeformEditorSettings.SettingsAsset); Undo.undoRedoPerformed += Repaint; } private void OnDisable () { serializedAsset.Dispose (); Undo.undoRedoPerformed -= Repaint; } private void OnGUI () { var sceneExpandedProperty = serializedAsset.FindProperty (nameof(DeformEditorSettingsAsset.dottedLineSize)); if (sceneExpandedProperty.isExpanded = EditorGUILayoutx.FoldoutHeader ("Scene", sceneExpandedProperty.isExpanded)) { using (var check = new EditorGUI.ChangeCheckScope ()) { var solidColor = EditorGUILayout.ColorField (Content.SolidHandleColor, DeformEditorSettings.SolidHandleColor); if (check.changed) { Undo.RecordObject (DeformEditorSettings.SettingsAsset, "Changed Solid Color Settings"); DeformEditorSettings.SolidHandleColor = solidColor; } } using (var check = new EditorGUI.ChangeCheckScope ()) { var lightColor = EditorGUILayout.ColorField (Content.LightHandleColor, DeformEditorSettings.LightHandleColor); if (check.changed) { Undo.RecordObject (DeformEditorSettings.SettingsAsset, "Changed Light Color Settings"); DeformEditorSettings.LightHandleColor = lightColor; } } using (var check = new EditorGUI.ChangeCheckScope ()) { var dottedLineSize = EditorGUILayout.FloatField (Content.DottedLineSize, DeformEditorSettings.DottedLineSize); if (check.changed) { Undo.RecordObject (DeformEditorSettings.SettingsAsset, "Changed Dotted Line Size Settings"); DeformEditorSettings.DottedLineSize = dottedLineSize; } } using (var check = new EditorGUI.ChangeCheckScope ()) { var handleSize = EditorGUILayout.FloatField (Content.ScreenspaceSliderHandleCapSize, DeformEditorSettings.ScreenspaceSliderHandleCapSize); if (check.changed) { Undo.RecordObject (DeformEditorSettings.SettingsAsset, "Changed Handle Size Settings"); DeformEditorSettings.ScreenspaceSliderHandleCapSize = handleSize; } } using (var check = new EditorGUI.ChangeCheckScope ()) { var angleHandleSize = EditorGUILayout.FloatField (Content.ScreenspaceAngleHandleSize, DeformEditorSettings.ScreenspaceAngleHandleSize); if (check.changed) { Undo.RecordObject (DeformEditorSettings.SettingsAsset, "Changed Angle Handle Size Settings"); DeformEditorSettings.ScreenspaceAngleHandleSize = angleHandleSize; } } } var importerExpandedProperty = serializedAsset.FindProperty (nameof(DeformEditorSettingsAsset.modelsReadableByDefault)); if (importerExpandedProperty.isExpanded = EditorGUILayoutx.FoldoutHeader("Importer", importerExpandedProperty.isExpanded)) { using (var check = new EditorGUI.ChangeCheckScope ()) { var modelsReadableByDefault = EditorGUILayout.Toggle(Content.ModelsReadableByDefault, DeformEditorSettings.ModelsReadableByDefault); if (check.changed) { Undo.RecordObject (DeformEditorSettings.SettingsAsset, "Changed Models Readable By Default"); DeformEditorSettings.ModelsReadableByDefault = modelsReadableByDefault; } } } } } }
40.093458
183
0.74965
[ "MIT" ]
sabresaurus/Deform
Code/Editor/DeformSettingsWindow.cs
4,292
C#
using System; using System.Globalization; using System.Threading; using Microsoft.VisualStudio.TestTools.UnitTesting; using FluentAssertions; namespace Noesis.Javascript.Tests { [TestClass] public class ExceptionTests { private JavascriptContext _context; [TestInitialize] public void SetUp() { _context = new JavascriptContext(); Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US"); } [TestCleanup] public void TearDown() { _context.Dispose(); } class ClassWithIndexer { public string this[int index] { get { return ""; } set { } } } [TestMethod] public void HandleInvalidArgumentsInIndexerCall() { _context.SetParameter("obj", new ClassWithIndexer()); Action action = () => _context.Run("obj[1] = 123 /* passing int when expecting string */"); action.ShouldThrowExactly<JavascriptException>().WithMessage("Object of type 'System.Int32' cannot be converted to type 'System.String'."); } class ClassWithMethods { public void Method(ClassWithMethods a) {} public void MethodThatThrows() { throw new Exception("Test C# exception"); } } [TestMethod] public void HandleInvalidArgumentsInMethodCall() { _context.SetParameter("obj", new ClassWithMethods()); Action action = () => _context.Run("obj.Method('hello') /* passing string when expecting int */"); action.ShouldThrowExactly<JavascriptException>().WithMessage("Argument mismatch for method \"Method\"."); } [TestMethod] public void HandleExceptionWhenInvokingMethodOnManagedObject() { _context.SetParameter("obj", new ClassWithMethods()); Action action = () => _context.Run("obj.MethodThatThrows()"); action.ShouldThrowExactly<JavascriptException>().WithMessage("Test C# exception"); } [TestMethod] public void StackOverflow() { Action action = () => _context.Run("function f() { f(); }; f();"); action.ShouldThrowExactly<JavascriptException>().WithMessage("RangeError: Maximum call stack size exceeded"); } [TestMethod] public void ArgumentChecking() { Action action = () => _context.Run(null); action.ShouldThrowExactly<ArgumentNullException>(); } } }
31.107143
151
0.590126
[ "BSD-2-Clause" ]
Ablu/Javascript.Net
Tests/Noesis.Javascript.Tests/ExceptionTests.cs
2,615
C#
using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Refit; using RefitConsul; using RefitSample.RpcServices; namespace RefitSample.Controllers { [ApiController] [Route("[controller]")] public class HomeController : ControllerBase { private readonly IAuthApi _authApi; private readonly string _token = Helper.GetToken().Result; /// <summary> /// RefitConsul测试 /// </summary> /// <param name="authApi">IAuthApi服务</param> public HomeController(IAuthApi authApi) { _authApi = authApi; } [HttpGet] public async Task<dynamic> GetAsync() { //不需要验证的服务 //var result1 = await _authApi.GetUsers(); //需要验证,token采用参数传递 //var result2 = await _authApi.GetCurrentUserInfo($"Bearer {_token}"); //需要验证,token在ConsulDiscoveryDelegatingHandler获取。 var result3 = await _authApi.GetCurrentUserInfo(); return result3; } } }
25.604651
82
0.61762
[ "MIT" ]
AlphaYu/RefitConsul
src/Sample/Controllers/HomeController.cs
1,165
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 System.ComponentModel; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Common.Core; using Microsoft.Common.Core.Security; using Microsoft.Common.Core.Services; using Microsoft.Common.Core.Shell; using Microsoft.Common.Core.Threading; using Microsoft.R.Components.OS; namespace Microsoft.R.Components.Security { public class WindowsSecurityService : ISecurityService { private readonly IServiceContainer _services; public WindowsSecurityService(IServiceContainer services) { _services = services; } public Task<Credentials> GetUserCredentialsAsync(string authority, string workspaceName, CancellationToken cancellationToken) { var (username, password) = ReadUserCredentials(authority); return username != null ? Task.FromResult(Credentials.Create(username, password)) : PromptForWindowsCredentialsAsync(authority, workspaceName, cancellationToken); } public bool ValidateX509Certificate(X509Certificate certificate, string message) { var certificate2 = certificate as X509Certificate2; Debug.Assert(certificate2 != null); if (certificate2.Verify()) { return true; } // Use native message box here since Win32 can show it from any thread. // Parent window must be NULL since otherwise the call hangs since VS // is in modal state due to the progress dialog. Note that native message // box appearance is a bit different from VS dialogs and matches OS theme // rather than VS fonts and colors. var platform = _services.GetService<IPlatformServices>(); if (Win32MessageBox.Show(platform.ApplicationWindowHandle, message, Win32MessageBox.Flags.YesNo | Win32MessageBox.Flags.IconWarning) == Win32MessageBox.Result.Yes) { return true; } return false; } public void DeleteCredentials(string authority) { if (!NativeMethods.CredDelete(authority, NativeMethods.CRED_TYPE.GENERIC, 0)) { var err = Marshal.GetLastWin32Error(); if (err != NativeMethods.ERROR_NOT_FOUND) { throw new Win32Exception(err); } } } public bool DeleteUserCredentials(string authority) => NativeMethods.CredDelete(authority, NativeMethods.CRED_TYPE.GENERIC, 0); public (string username, SecureString password) ReadUserCredentials(string authority) { using (var ch = CredentialHandle.ReadFromCredentialManager(authority)) { if (ch == null) { return (null, null); } var credData = ch.GetCredentialData(); return (credData.UserName, SecurityUtilities.SecureStringFromNativeBuffer(credData.CredentialBlob)); } } public void SaveUserCredentials(string authority, string userName, SecureString password, bool save) { var creds = default(NativeMethods.CredentialData); try { creds.TargetName = authority; // We have to save the credentials even if user selected NOT to save. Otherwise, user will be asked to enter // credentials for every REPL/intellisense/package/Connection test request. This can provide the best user experience. // We can limit how long the information is saved, in the case whee user selected not to save the credential persistence // is limited to the current log on session. The credentials will not be available if the use logs off and back on. creds.Persist = save ? NativeMethods.CRED_PERSIST.CRED_PERSIST_ENTERPRISE : NativeMethods.CRED_PERSIST.CRED_PERSIST_SESSION; creds.Type = NativeMethods.CRED_TYPE.GENERIC; creds.UserName = userName; creds.CredentialBlob = Marshal.SecureStringToCoTaskMemUnicode(password); creds.CredentialBlobSize = (uint)((password.Length + 1) * sizeof(char)); // unicode password + unicode null if (!NativeMethods.CredWrite(ref creds, 0)) { var error = Marshal.GetLastWin32Error(); throw new Win32Exception(error, Resources.Error_CredWriteFailed); } } finally { if (creds.CredentialBlob != IntPtr.Zero) { Marshal.ZeroFreeCoTaskMemUnicode(creds.CredentialBlob); } } } private async Task<Credentials> PromptForWindowsCredentialsAsync(string authority, string workspaceName, CancellationToken cancellationToken) { await _services.MainThread().SwitchToAsync(cancellationToken); var credui = new NativeMethods.CREDUI_INFO { cbSize = Marshal.SizeOf(typeof(NativeMethods.CREDUI_INFO)), hwndParent = _services.GetService<IPlatformServices>().ApplicationWindowHandle, pszCaptionText = Resources.Info_ConnectingTo.FormatInvariant(workspaceName) }; uint authPkg = 0; var credStorage = IntPtr.Zero; var save = true; var flags = NativeMethods.CredUIWinFlags.CREDUIWIN_CHECKBOX; // For password, use native memory so it can be securely freed. var passwordStorage = CreatePasswordBuffer(); var inCredSize = 1024; var inCredBuffer = Marshal.AllocCoTaskMem(inCredSize); try { if (!NativeMethods.CredPackAuthenticationBuffer(0, WindowsIdentity.GetCurrent().Name, "", inCredBuffer, ref inCredSize)) { var error = Marshal.GetLastWin32Error(); throw new Win32Exception(error); } var err = NativeMethods.CredUIPromptForWindowsCredentials(ref credui, 0, ref authPkg, inCredBuffer, (uint)inCredSize, out credStorage, out var credSize, ref save, flags); if (err != 0) { throw new OperationCanceledException(); } var userNameBuilder = new StringBuilder(NativeMethods.CRED_MAX_USERNAME_LENGTH); var userNameLen = NativeMethods.CRED_MAX_USERNAME_LENGTH; var domainBuilder = new StringBuilder(NativeMethods.CRED_MAX_USERNAME_LENGTH); var domainLen = NativeMethods.CRED_MAX_USERNAME_LENGTH; var passLen = NativeMethods.CREDUI_MAX_PASSWORD_LENGTH; if (!NativeMethods.CredUnPackAuthenticationBuffer(NativeMethods.CRED_PACK_PROTECTED_CREDENTIALS, credStorage, credSize, userNameBuilder, ref userNameLen, domainBuilder, ref domainLen, passwordStorage, ref passLen)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } var userName = userNameBuilder.ToString(); var password = SecurityUtilities.SecureStringFromNativeBuffer(passwordStorage); SaveUserCredentials(authority, userName, password, save); return Credentials.Create(userName, password); } finally { if (inCredBuffer != IntPtr.Zero) { Marshal.FreeCoTaskMem(inCredBuffer); } if (credStorage != IntPtr.Zero) { Marshal.ZeroFreeCoTaskMemUnicode(credStorage); } if (passwordStorage != IntPtr.Zero) { Marshal.ZeroFreeCoTaskMemUnicode(passwordStorage); } } } private static IntPtr CreatePasswordBuffer() => Marshal.AllocCoTaskMem(NativeMethods.CREDUI_MAX_PASSWORD_LENGTH); } }
49.648485
232
0.645508
[ "MIT" ]
Bhaskers-Blu-Org2/RTVS
src/Windows/R/Components/Impl/Security/WindowsSecurityService.cs
8,194
C#
/*** Copyright (C) 2018-2020. dc-koromo. All Rights Reserved. Author: Koromo Copy Developer ***/ using Newtonsoft.Json; using System; using System.IO; namespace Koromo_Copy.Component.Hitomi { public class HitomiJsonModel { [JsonProperty] public string Id; [JsonProperty] public string Title; [JsonProperty] public string[] Artists; [JsonProperty] public string[] Groups; [JsonProperty] public string[] Series; [JsonProperty] public string[] Characters; [JsonProperty] public string Types; [JsonProperty] public int Pages; [JsonProperty] public string[] Tags; } public class HitomiJson { string path; HitomiJsonModel model; public HitomiJson(string path) { this.path = Path.Combine(path, "Info.json"); if (File.Exists(this.path)) model = JsonConvert.DeserializeObject<HitomiJsonModel>(File.ReadAllText(this.path)); if (model == null) model = new HitomiJsonModel(); } public void Save() { try { string json = JsonConvert.SerializeObject(model, Formatting.Indented); using (var fs = new StreamWriter(new FileStream(path, FileMode.Create, FileAccess.Write))) { fs.Write(json); } } catch (Exception e) { Monitor.Instance.Push("[Hitomi Json] Skip save json. Fail " + e.Message); } } public void SetModelFromArticle(HitomiArticle article) { model.Id = article.Magic; model.Title = article.Title; model.Artists = article.Artists; model.Series = article.Series; model.Characters = article.Characters; model.Groups = article.Groups; model.Types = article.Type; model.Pages = article.ImagesLink.Count; model.Tags = article.Tags; } public ref HitomiJsonModel GetModel() { return ref model; } } }
26.333333
124
0.546564
[ "MIT" ]
dc-koromo/downloader-windows
Koromo Copy/Component/Hitomi/HitomiJson.cs
2,214
C#
using System; using System.Linq; using AgentNetworkManagement.Business.Contracts; using AgentNetworkManager.Domain; using AgentNetworkManager.Domain.DbViews; using AgentNetworkManager.Domain.Models; using Echenim.Nine.Misc.Functionals.ErrorsAndFailures; using Echenim.Nine.Util.UniqueReferenceGenerator.Processs; namespace AgentNetworkManagement.Business.Repositories { internal class MemberInformation:IMember { private readonly ApplicationDbContext _ctx; public MemberInformation(ApplicationDbContext context) { _ctx = context; } /// <summary> /// get memeber information /// </summary> /// <param name="predicate">lambda expression</param> /// <returns>return collection of member </returns> //public IEnumerable<Member> Get(Func<Member, bool> predicate = null) => predicate == null // ? _ctx.Members.OrderBy(s => s.Name) // : _ctx.Members.Where(predicate); /// <summary> /// get single member object /// </summary> /// <param name="predicate"></param> /// <returns>return member object</returns> public Member Find(Func<Member, bool> predicate) => _ctx.Members .FirstOrDefault(predicate); //public Notification Add(UserPositionHeldInOrganogramm entity) //{ // var notification = new Notification(); // try // { // _ctx.UserPositionHeld.Add(entity); // _ctx.SaveChanges(); // notification.Message = "role was created successful"; // notification.Success = false; // } // catch // { // notification.Message = "fail to create role"; // notification.Success = false; // } // return notification; //} public Notification Add(UserPositionHeldInOrganogramm entity) { var notification = new Notification(); using (var trns = _ctx.Database.BeginTransaction()) { try { var checkOfUserHasWorkSpace = _ctx.UserPositionHeld.SingleOrDefault(s => s.UserId.Equals(entity.UserId)); if (checkOfUserHasWorkSpace != null ) { var userspace = new UserPositionHeldInOrganogramm { UserId = checkOfUserHasWorkSpace.UserId, OrggrammId = checkOfUserHasWorkSpace.OrggrammId }; var delete = _ctx.Database.ExecuteSqlCommand("Delete FROM UserPositionHeldInOrganogramms where UserId = {0}", new object[] { userspace.UserId }); //_ctx.Entry(userspace).State = EntityState.Deleted; //_ctx.SaveChanges(); _ctx.UserPositionHeld.Add(entity); _ctx.SaveChanges(); } else { _ctx.UserPositionHeld.Add(entity); _ctx.SaveChanges(); } trns.Commit(); notification.Id = Guid.NewGuid().ToString(); notification.Message = "role was created successful"; notification.Success = true; } catch (Exception ex) { trns.Rollback(); notification.Id = Guid.NewGuid().ToString(); notification.Message = "fail to create role"; notification.Success = false; } } return notification; } public Notification AddMemberToAgentNetwork(AssignUsersToTheirAgentNetwork entity) { var notification = new Notification(); try { entity.Id = new ReferenceGenerator().GenerateId(); _ctx.UsersToTheirAgentNetworks.Add(entity); _ctx.SaveChanges(); notification.Id = Guid.NewGuid().ToString(); notification.Message = "role was created successful"; notification.Success = true; } catch { notification.Id = Guid.NewGuid().ToString(); notification.Message = "fail to create role"; notification.Success = false; } return notification; } public IQueryable<Member> GetMembers() => from u in _ctx.Members select u; public IQueryable<Member> Get(Func<Member, bool> predicate = null) => predicate == null ? _ctx.Members.OrderBy(s => s.Name) : _ctx.Members.Where(predicate).AsQueryable(); } }
35.514286
170
0.524336
[ "MIT" ]
echenim/AgentBanking
AgentNetworkManagement.Business/Repositories/MemberInformation.cs
4,974
C#
#if ASYNC using System; using System.Collections.Generic; using System.Data; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; namespace ServiceStack.OrmLite { public static class OrmLiteWriteExpressionsApiAsync { /// <summary> /// Use an SqlExpression to select which fields to update and construct the where expression, E.g: /// /// var q = db.From&gt;Person&lt;()); /// db.UpdateOnly(new Person { FirstName = "JJ" }, q.Update(p => p.FirstName).Where(x => x.FirstName == "Jimi")); /// UPDATE "Person" SET "FirstName" = 'JJ' WHERE ("FirstName" = 'Jimi') /// /// What's not in the update expression doesn't get updated. No where expression updates all rows. E.g: /// /// db.UpdateOnly(new Person { FirstName = "JJ", LastName = "Hendo" }, ev.Update(p => p.FirstName)); /// UPDATE "Person" SET "FirstName" = 'JJ' /// </summary> public static Task<int> UpdateOnlyAsync<T>(this IDbConnection dbConn, T model, SqlExpression<T> onlyFields, Action<IDbCommand> commandFilter = null, CancellationToken token = default(CancellationToken)) { return dbConn.Exec(dbCmd => dbCmd.UpdateOnlyAsync(model, onlyFields, commandFilter, token)); } /// <summary> /// Update record, updating only fields specified in updateOnly that matches the where condition (if any), E.g: /// /// db.UpdateOnlyAsync(() => new Person { FirstName = "JJ" }, where: p => p.LastName == "Hendrix"); /// UPDATE "Person" SET "FirstName" = 'JJ' WHERE ("LastName" = 'Hendrix') /// /// db.UpdateOnlyAsync(() => new Person { FirstName = "JJ" }); /// UPDATE "Person" SET "FirstName" = 'JJ' /// </summary> public static Task<int> UpdateOnlyAsync<T>(this IDbConnection dbConn, Expression<Func<T>> updateFields, Expression<Func<T, bool>> where = null, Action<IDbCommand> commandFilter = null, CancellationToken token = default(CancellationToken)) { return dbConn.Exec(dbCmd => dbCmd.UpdateOnlyAsync(updateFields, dbCmd.GetDialectProvider().SqlExpression<T>().Where(where), commandFilter, token)); } /// <summary> /// Update record, updating only fields specified in updateOnly that matches the where condition (if any), E.g: /// /// db.UpdateOnlyAsync(() => new Person { FirstName = "JJ" }, db.From&lt;Person&gt;().Where(p => p.LastName == "Hendrix")); /// UPDATE "Person" SET "FirstName" = 'JJ' WHERE ("LastName" = 'Hendrix') /// </summary> public static Task<int> UpdateOnlyAsync<T>(this IDbConnection dbConn, Expression<Func<T>> updateFields, SqlExpression<T> q, Action<IDbCommand> commandFilter = null, CancellationToken token = default(CancellationToken)) { return dbConn.Exec(dbCmd => dbCmd.UpdateOnlyAsync(updateFields, q, commandFilter, token)); } /// <summary> /// Update record, updating only fields specified in updateOnly that matches the where condition (if any), E.g: /// /// var q = db.From&gt;Person&lt;().Where(p => p.LastName == "Hendrix"); /// db.UpdateOnlyAsync(() => new Person { FirstName = "JJ" }, q.WhereExpression, q.Params); /// UPDATE "Person" SET "FirstName" = 'JJ' WHERE ("LastName" = 'Hendrix') /// </summary> public static Task<int> UpdateOnlyAsync<T>(this IDbConnection dbConn, Expression<Func<T>> updateFields, string whereExpression, IEnumerable<IDbDataParameter> sqlParams, Action<IDbCommand> commandFilter = null, CancellationToken token = default(CancellationToken)) { return dbConn.Exec(dbCmd => dbCmd.UpdateOnlyAsync(updateFields, whereExpression, sqlParams, commandFilter, token)); } /// <summary> /// Update record, updating only fields specified in updateOnly that matches the where condition (if any), E.g: /// /// db.UpdateOnly(new Person { FirstName = "JJ" }, p => p.FirstName, p => p.LastName == "Hendrix"); /// UPDATE "Person" SET "FirstName" = 'JJ' WHERE ("LastName" = 'Hendrix') /// /// db.UpdateOnly(new Person { FirstName = "JJ" }, p => p.FirstName); /// UPDATE "Person" SET "FirstName" = 'JJ' /// </summary> public static Task<int> UpdateOnlyAsync<T>(this IDbConnection dbConn, T obj, Expression<Func<T, object>> onlyFields = null, Expression<Func<T, bool>> where = null, Action<IDbCommand> commandFilter = null, CancellationToken token = default(CancellationToken)) { return dbConn.Exec(dbCmd => dbCmd.UpdateOnlyAsync(obj, onlyFields, where, commandFilter, token)); } /// <summary> /// Update record, updating only fields specified in updateOnly that matches the where condition (if any), E.g: /// Numeric fields generates an increment sql which is useful to increment counters, etc... /// avoiding concurrency conflicts /// /// db.UpdateAddAsync(() => new Person { Age = 5 }, where: p => p.LastName == "Hendrix"); /// UPDATE "Person" SET "Age" = "Age" + 5 WHERE ("LastName" = 'Hendrix') /// /// db.UpdateAddAsync(() => new Person { Age = 5 }); /// UPDATE "Person" SET "Age" = "Age" + 5 /// </summary> public static Task<int> UpdateAddAsync<T>(this IDbConnection dbConn, Expression<Func<T>> updateFields, Expression<Func<T, bool>> where = null, Action<IDbCommand> commandFilter = null, CancellationToken token = default(CancellationToken)) { return dbConn.Exec(dbCmd => dbCmd.UpdateAddAsync(updateFields, dbCmd.GetDialectProvider().SqlExpression<T>().Where(where), commandFilter, token)); } /// <summary> /// Update record, updating only fields specified in updateOnly that matches the where condition (if any), E.g: /// /// db.UpdateOnly(new Person { FirstName = "JJ" }, new[]{ "FirstName" }, p => p.LastName == "Hendrix"); /// UPDATE "Person" SET "FirstName" = 'JJ' WHERE ("LastName" = 'Hendrix') /// </summary> public static Task<int> UpdateOnlyAsync<T>(this IDbConnection dbConn, T obj, string[] onlyFields, Expression<Func<T, bool>> where = null, Action<IDbCommand> commandFilter = null, CancellationToken token = default(CancellationToken)) { return dbConn.Exec(dbCmd => dbCmd.UpdateOnlyAsync(obj, onlyFields, where, commandFilter, token)); } /// <summary> /// Update record, updating only fields specified in updateOnly that matches the where condition (if any), E.g: /// Numeric fields generates an increment sql which is useful to increment counters, etc... /// avoiding concurrency conflicts /// /// db.UpdateAddAsync(() => new Person { Age = 5 }, db.From&lt;Person&gt;().Where(p => p.LastName == "Hendrix")); /// UPDATE "Person" SET "Age" = "Age" + 5 WHERE ("LastName" = 'Hendrix') /// </summary> public static Task<int> UpdateAddAsync<T>(this IDbConnection dbConn, Expression<Func<T>> updateFields, SqlExpression<T> q, Action<IDbCommand> commandFilter = null, CancellationToken token = default(CancellationToken)) { return dbConn.Exec(dbCmd => dbCmd.UpdateAddAsync(updateFields, q, commandFilter, token)); } /// <summary> /// Updates all values from Object Dictionary matching the where condition. E.g /// /// db.UpdateOnlyAsync&lt;Person&gt;(new Dictionary&lt;string,object&lt; { {"FirstName", "JJ"} }, where:p => p.FirstName == "Jimi"); /// UPDATE "Person" SET "FirstName" = 'JJ' WHERE ("FirstName" = 'Jimi') /// </summary> public static Task<int> UpdateOnlyAsync<T>(this IDbConnection dbConn, Dictionary<string, object> updateFields, Expression<Func<T, bool>> where, Action<IDbCommand> commandFilter = null, CancellationToken token = default(CancellationToken)) { return dbConn.Exec(dbCmd => dbCmd.UpdateOnlyAsync(updateFields, where, commandFilter, token)); } /// <summary> /// Updates all non-default values set on item matching the where condition (if any). E.g /// /// db.UpdateNonDefaults(new Person { FirstName = "JJ" }, p => p.FirstName == "Jimi"); /// UPDATE "Person" SET "FirstName" = 'JJ' WHERE ("FirstName" = 'Jimi') /// </summary> public static Task<int> UpdateNonDefaultsAsync<T>(this IDbConnection dbConn, T item, Expression<Func<T, bool>> obj, CancellationToken token = default(CancellationToken)) { return dbConn.Exec(dbCmd => dbCmd.UpdateNonDefaultsAsync(item, obj, token)); } /// <summary> /// Updates all values set on item matching the where condition (if any). E.g /// /// db.Update(new Person { Id = 1, FirstName = "JJ" }, p => p.LastName == "Hendrix"); /// UPDATE "Person" SET "Id" = 1,"FirstName" = 'JJ',"LastName" = NULL,"Age" = 0 WHERE ("LastName" = 'Hendrix') /// </summary> public static Task<int> UpdateAsync<T>(this IDbConnection dbConn, T item, Expression<Func<T, bool>> where, Action<IDbCommand> commandFilter = null, CancellationToken token = default(CancellationToken)) { return dbConn.Exec(dbCmd => dbCmd.UpdateAsync(item, where, commandFilter, token)); } /// <summary> /// Updates all matching fields populated on anonymousType that matches where condition (if any). E.g: /// /// db.Update&lt;Person&gt;(new { FirstName = "JJ" }, p => p.LastName == "Hendrix"); /// UPDATE "Person" SET "FirstName" = 'JJ' WHERE ("LastName" = 'Hendrix') /// </summary> public static Task<int> UpdateAsync<T>(this IDbConnection dbConn, object updateOnly, Expression<Func<T, bool>> where = null, Action<IDbCommand> commandFilter = null, CancellationToken token = default(CancellationToken)) { return dbConn.Exec(dbCmd => dbCmd.UpdateAsync(updateOnly, where, commandFilter, token)); } /// <summary> /// Using an SqlExpression to only Insert the fields specified, e.g: /// /// db.InsertOnlyAsync(new Person { FirstName = "Amy" }, p => p.FirstName)); /// INSERT INTO "Person" ("FirstName") VALUES ('Amy'); /// /// db.InsertOnlyAsync(new Person { Id =1 , FirstName="Amy" }, p => new { p.Id, p.FirstName })); /// INSERT INTO "Person" ("Id", "FirstName") VALUES (1, 'Amy'); /// </summary> public static Task InsertOnlyAsync<T>(this IDbConnection dbConn, T obj, Expression<Func<T, object>> onlyFields, CancellationToken token = default(CancellationToken)) { return dbConn.Exec(dbCmd => dbCmd.InsertOnlyAsync(obj, onlyFields.GetFieldNames(), token)); } /// <summary> /// Using an SqlExpression to only Insert the fields specified, e.g: /// /// db.InsertOnly(new Person { FirstName = "Amy" }, new[]{ "FirstName" })); /// INSERT INTO "Person" ("FirstName") VALUES ('Amy'); /// </summary> public static Task InsertOnlyAsync<T>(this IDbConnection dbConn, T obj, string[] onlyFields, CancellationToken token = default(CancellationToken)) { return dbConn.Exec(dbCmd => dbCmd.InsertOnlyAsync(obj, onlyFields, token)); } /// <summary> /// Using an SqlExpression to only Insert the fields specified, e.g: /// /// db.InsertOnlyAsync(() => new Person { FirstName = "Amy" })); /// INSERT INTO "Person" ("FirstName") VALUES (@FirstName); /// </summary> public static Task<int> InsertOnlyAsync<T>(this IDbConnection dbConn, Expression<Func<T>> insertFields, CancellationToken token = default(CancellationToken)) { return dbConn.Exec(dbCmd => dbCmd.InsertOnlyAsync(insertFields, token)); } /// <summary> /// Delete the rows that matches the where expression, e.g: /// /// db.Delete&lt;Person&gt;(p => p.Age == 27); /// DELETE FROM "Person" WHERE ("Age" = 27) /// </summary> public static Task<int> DeleteAsync<T>(this IDbConnection dbConn, Expression<Func<T, bool>> where, CancellationToken token = default(CancellationToken)) { return dbConn.Exec(dbCmd => dbCmd.DeleteAsync(where, token)); } /// <summary> /// Delete the rows that matches the where expression, e.g: /// /// var q = db.From&gt;Person&lt;()); /// db.Delete&lt;Person&gt;(q.Where(p => p.Age == 27)); /// DELETE FROM "Person" WHERE ("Age" = 27) /// </summary> public static Task<int> DeleteAsync<T>(this IDbConnection dbConn, SqlExpression<T> where, CancellationToken token = default(CancellationToken)) { return dbConn.Exec(dbCmd => dbCmd.DeleteAsync(where, token)); } } } #endif
51.722222
178
0.579162
[ "Apache-2.0" ]
AlbertoP57/YAFNET
yafsrc/ServiceStack/ServiceStack.OrmLite/OrmLiteWriteExpressionsApiAsync.cs
13,698
C#
#if UNITY_EDITOR && UNITY_IOS namespace Shopify.Unity.Editor.BuildPipeline { using UnityEngine; using UnityEditor; using UnityEditor.iOS.Xcode; using System.IO; using System; public class iOSTestPostProcessor { /// <summary> /// Perform post processing on the build to only run Shopify Tests /// </summary> public static void ProcessForTests(string buildPath) { var project = new ExtendedPBXProject(buildPath); SetBuildProperties(project); SetCorrectTestsTarget(project); project.RemoveFileFromBuild(project.TestTargetGuid, project.FindFileGuidByProjectPath("Unity-iPhone Tests/Unity_iPhone_Tests.m")); iOSPostProcessor.SetSwiftInterfaceHeader(project); project.Save(); } /// Sets the correct build properties to run private static void SetBuildProperties(ExtendedPBXProject project) { iOSPostProcessor.SetBuildProperties(project); project.SetBuildProperty(project.GetAllTargetGuids(), ExtendedPBXProject.SwiftVersionKey, "4.0"); project.SetBuildProperty(project.TestTargetGuid, ExtendedPBXProject.SwiftBridgingHeaderKey, "Libraries/Shopify/Plugins/iOS/Shopify/Unity-iPhone-Tests-Bridging-Header.h"); project.SetBuildProperty(project.TestTargetGuid, ExtendedPBXProject.RunpathSearchKey, "@loader_path/Frameworks"); project.SetBuildProperty(project.TestTargetGuid, ExtendedPBXProject.ProjectModuleNameKey, "$(PRODUCT_NAME:c99extidentifier)Tests"); project.SetBuildPropertyForConfig(project.GetDebugConfig(project.UnityTargetGuid), ExtendedPBXProject.EnableTestabilityKey, "YES"); project.SetBuildPropertyForConfig(project.GetDebugConfig(project.UnityTargetGuid), ExtendedPBXProject.SwiftOptimizationLevelKey, "-Onone"); } /// Sets the correct target for Shopify Tests private static void SetCorrectTestsTarget(ExtendedPBXProject project) { string testPath = Path.Combine(project.BuildPath, "Libraries/Shopify/Plugins/iOS/Shopify/BuyTests/"); var testDirectory = new DirectoryInfo(testPath); try { project.SetFilesInDirectoryToTestTarget(testDirectory); } catch (Exception e) { Debug.Log(e.Message); } } } } #endif
49.625
182
0.70445
[ "MIT" ]
isabella232/unity-buy-sdk
Assets/Editor/BuildPipeline/iOSTestPostProcessor.cs
2,382
C#