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
#pragma warning disable 1591 using System; using System.Collections.Generic; using System.Text; namespace Braintree { public class WebhookTestingGateway : IWebhookTestingGateway { private readonly BraintreeService service; protected internal WebhookTestingGateway(BraintreeGateway gateway) { gateway.Configuration.AssertHasAccessTokenOrKeys(); service = new BraintreeService(gateway.Configuration); } public virtual Dictionary<string, string> SampleNotification(WebhookKind kind, string id, string sourceMerchantId = null) { var response = new Dictionary<string, string>(); string payload = BuildPayload(kind, id, sourceMerchantId); response["bt_payload"] = payload; response["bt_signature"] = BuildSignature(payload); return response; } private string BuildPayload(WebhookKind kind, string id, string sourceMerchantId) { var currentTime = DateTime.Now.ToUniversalTime().ToString("u"); var sourceMerchantIdXml = ""; if (sourceMerchantId != null) { sourceMerchantIdXml = string.Format("<source-merchant-id>{0}</source-merchant-id>", sourceMerchantId); } var payload = string.Format("<notification><timestamp type=\"datetime\">{0}</timestamp><kind>{1}</kind>{2}<subject>{3}</subject></notification>", currentTime, kind, sourceMerchantIdXml, SubjectSampleXml(kind, id)); return Convert.ToBase64String(Encoding.GetEncoding(0).GetBytes(payload)) + '\n'; } private string BuildSignature(string payload) { return string.Format("{0}|{1}", service.PublicKey, new Sha1Hasher().HmacHash(service.PrivateKey, payload).Trim().ToLower()); } private string SubjectSampleXml(WebhookKind kind, string id) { if (kind == WebhookKind.SUB_MERCHANT_ACCOUNT_APPROVED) { return MerchantAccountApprovedSampleXml(id); } else if (kind == WebhookKind.SUB_MERCHANT_ACCOUNT_DECLINED) { return MerchantAccountDeclinedSampleXml(id); } else if (kind == WebhookKind.TRANSACTION_DISBURSED) { return TransactionDisbursedSampleXml(id); } else if (kind == WebhookKind.TRANSACTION_SETTLED) { return TransactionSettledSampleXml(id); } else if (kind == WebhookKind.TRANSACTION_SETTLEMENT_DECLINED) { return TransactionSettlementDeclinedSampleXml(id); } else if (kind == WebhookKind.DISBURSEMENT_EXCEPTION) { return DisbursementExceptionSampleXml(id); } else if (kind == WebhookKind.DISBURSEMENT) { return DisbursementSampleXml(id); } else if (kind == WebhookKind.PARTNER_MERCHANT_CONNECTED) { return PartnerMerchantConnectedSampleXml(id); } else if (kind == WebhookKind.PARTNER_MERCHANT_DISCONNECTED) { return PartnerMerchantDisconnectedSampleXml(id); } else if (kind == WebhookKind.CONNECTED_MERCHANT_STATUS_TRANSITIONED) { return ConnectedMerchantStatusTransitionedSampleXml(id); } else if (kind == WebhookKind.CONNECTED_MERCHANT_PAYPAL_STATUS_CHANGED) { return ConnectedMerchantPayPalStatusChangedSampleXml(id); } else if (kind == WebhookKind.PARTNER_MERCHANT_DECLINED) { return PartnerMerchantDeclinedSampleXml(id); } else if (kind == WebhookKind.OAUTH_ACCESS_REVOKED) { return OAuthAccessRevokedSampleXml(id); } else if (kind == WebhookKind.DISPUTE_OPENED) { return DisputeOpenedSampleXml(id); } else if (kind == WebhookKind.DISPUTE_LOST) { return DisputeLostSampleXml(id); } else if (kind == WebhookKind.DISPUTE_WON) { return DisputeWonSampleXml(id); } else if (kind == WebhookKind.SUBSCRIPTION_CHARGED_SUCCESSFULLY) { return SubscriptionChargedSuccessfullySampleXml(id); } else if (kind == WebhookKind.SUBSCRIPTION_CHARGED_UNSUCCESSFULLY) { return SubscriptionChargedUnsuccessfullySampleXml(id); } else if (kind == WebhookKind.CHECK) { return CheckSampleXml(); } else if (kind == WebhookKind.ACCOUNT_UPDATER_DAILY_REPORT) { return AccountUpdaterDailyReportSampleXml(id); // NEXT_MAJOR_VERSION Remove this class as legacy Ideal has been removed/disabled in the Braintree Gateway // DEPRECATED If you're looking to accept iDEAL as a payment method contact accounts@braintreepayments.com for a solution. } else if (kind == WebhookKind.IDEAL_PAYMENT_COMPLETE) { return IdealPaymentCompleteSampleXml(id); // NEXT_MAJOR_VERSION Remove this class as legacy Ideal has been removed/disabled in the Braintree Gateway // DEPRECATED If you're looking to accept iDEAL as a payment method contact accounts@braintreepayments.com for a solution. } else if (kind == WebhookKind.IDEAL_PAYMENT_FAILED) { return IdealPaymentFailedSampleXml(id); } else if (kind == WebhookKind.GRANTED_PAYMENT_INSTRUMENT_UPDATE) { // NEXT_MAJOR_VERSION remove GRANTED_PAYMENT_INSTRUMENT_UPDATE branch return GrantedPaymentInstrumentUpdateSampleXml(); } else if (kind == WebhookKind.GRANTOR_UPDATED_GRANTED_PAYMENT_METHOD) { return GrantedPaymentInstrumentUpdateSampleXml(); } else if (kind == WebhookKind.RECIPIENT_UPDATED_GRANTED_PAYMENT_METHOD) { return GrantedPaymentInstrumentUpdateSampleXml(); } else if (kind == WebhookKind.PAYMENT_METHOD_REVOKED_BY_CUSTOMER) { return PaymentMethodRevokedByCustomerSampleXml(id); } else if (kind == WebhookKind.LOCAL_PAYMENT_COMPLETED) { return LocalPaymentCompletedSampleXml(); } else { return SubscriptionXml(id); } } private static readonly string TYPE_DATE = "type=\"date\""; private static readonly string TYPE_DATE_TIME = "type=\"datetime\""; private static readonly string TYPE_ARRAY = "type=\"array\""; private static readonly string TYPE_SYMBOL = "type=\"symbol\""; private static readonly string NIL_TRUE = "nil=\"true\""; private static readonly string TYPE_BOOLEAN = "type=\"boolean\""; private string MerchantAccountDeclinedSampleXml(string id) { return Node("api-error-response", Node("message", "Applicant declined due to OFAC."), NodeAttr("errors", TYPE_ARRAY, Node("merchant-account", NodeAttr("errors", TYPE_ARRAY, Node("error", Node("code", "82621"), Node("message", "Applicant declined due to OFAC."), NodeAttr("attribute", TYPE_SYMBOL, "base") ) ) ) ), Node("merchant-account", Node("id", id), Node("status", "suspended"), Node("master-merchant-account", Node("id", "master_ma_for_" + id), Node("status", "suspended") ) ) ); } private string TransactionDisbursedSampleXml(string id) { return Node("transaction", Node("id", id), Node("amount", "100.00"), Node("disbursement-details", NodeAttr("disbursement-date", TYPE_DATE, "2013-07-09") ), Node("billing"), Node("credit-card"), Node("customer"), Node("descriptor"), Node("shipping"), Node("subscription") ); } private string TransactionSettledSampleXml(string id) { return Node("transaction", Node("id", id), Node("status", "settled"), Node("type", "sale"), Node("currency-iso-code", "USD"), Node("amount", "100.00"), Node("us-bank-account", Node("routing-number", "123456789"), Node("last-4", "1234"), Node("account-type", "checking"), Node("account-holder-name", "Dan Schulman")), Node("disbursement-details"), Node("billing"), Node("credit-card"), Node("customer"), Node("descriptor"), Node("shipping"), Node("subscription") ); } private string TransactionSettlementDeclinedSampleXml(string id) { return Node("transaction", Node("id", id), Node("status", "settlement_declined"), Node("type", "sale"), Node("currency-iso-code", "USD"), Node("amount", "100.00"), Node("us-bank-account", Node("routing-number", "123456789"), Node("last-4", "1234"), Node("account-type", "checking"), Node("account-holder-name", "Dan Schulman")), Node("disbursement-details"), Node("billing"), Node("credit-card"), Node("customer"), Node("descriptor"), Node("shipping"), Node("subscription") ); } private string DisbursementExceptionSampleXml(string id) { return Node("disbursement", Node("id", id), Node("amount", "100.00"), Node("exception-message", "bank_rejected"), NodeAttr("disbursement-date", TYPE_DATE, "2014-02-10"), Node("follow-up-action", "update_funding_information"), NodeAttr("success", TYPE_BOOLEAN, "false"), NodeAttr("retry", TYPE_BOOLEAN, "false"), Node("merchant-account", Node("id", "merchant_account_id"), Node("master-merchant-account", Node("id", "master_ma"), Node("status", "active") ), Node("status", "active") ), NodeAttr("transaction-ids", TYPE_ARRAY, Node("item", "asdf"), Node("item", "qwer") ) ); } private string DisbursementSampleXml(string id) { return Node("disbursement", Node("id", id), Node("amount", "100.00"), NodeAttr("exception-message", NIL_TRUE, ""), NodeAttr("disbursement-date", TYPE_DATE, "2014-02-10"), NodeAttr("follow-up-action", NIL_TRUE, ""), NodeAttr("success", TYPE_BOOLEAN, "true"), NodeAttr("retry", TYPE_BOOLEAN, "false"), Node("merchant-account", Node("id", "merchant_account_id"), Node("master-merchant-account", Node("id", "master_ma"), Node("status", "active") ), Node("status", "active") ), NodeAttr("transaction-ids", TYPE_ARRAY, Node("item", "asdf"), Node("item", "qwer") ) ); } private string DisputeOpenedSampleXml(string id) { return Node("dispute", Node("id", id), Node("amount", "250.00"), Node("amount-disputed", "250.00"), Node("amount-won", "245.00"), NodeAttr("received-date", TYPE_DATE, "2014-03-21"), NodeAttr("reply-by-date", TYPE_DATE, "2014-03-21"), Node("currency-iso-code", "USD"), Node("kind", "chargeback"), Node("status", "open"), Node("reason", "fraud"), Node("transaction", Node("id", id), Node("amount", "250.00") ), NodeAttr("date-opened", TYPE_DATE, "2014-03-21") ); } private string DisputeLostSampleXml(string id) { return Node("dispute", Node("id", id), Node("amount", "250.00"), Node("amount-disputed", "250.00"), Node("amount-won", "245.00"), NodeAttr("received-date", TYPE_DATE, "2014-03-21"), NodeAttr("reply-by-date", TYPE_DATE, "2014-03-21"), Node("currency-iso-code", "USD"), Node("kind", "chargeback"), Node("status", "lost"), Node("reason", "fraud"), Node("transaction", Node("id", id), Node("amount", "250.00") ), NodeAttr("date-opened", TYPE_DATE, "2014-03-21") ); } private string DisputeWonSampleXml(string id) { return Node("dispute", Node("id", id), Node("amount", "250.00"), Node("amount-disputed", "250.00"), Node("amount-won", "245.00"), NodeAttr("received-date", TYPE_DATE, "2014-03-21"), NodeAttr("reply-by-date", TYPE_DATE, "2014-03-21"), Node("currency-iso-code", "USD"), Node("kind", "chargeback"), Node("status", "won"), Node("reason", "fraud"), Node("transaction", Node("id", id), Node("amount", "250.00") ), NodeAttr("date-opened", TYPE_DATE, "2014-03-21"), NodeAttr("date-won", TYPE_DATE, "2014-03-22") ); } private string SubscriptionXml(string id) { return Node("subscription", Node("id", id), NodeAttr("transactions", TYPE_ARRAY), NodeAttr("add_ons", TYPE_ARRAY), NodeAttr("discounts", TYPE_ARRAY) ); } private string SubscriptionChargedSuccessfullySampleXml(string id) { return Node("subscription", Node("id", id), Node("transactions", Node("transaction", Node("id", id), Node("amount", "49.99"), Node("status", "submitted_for_settlement"), Node("disbursement-details", NodeAttr("disbursement-date", TYPE_DATE, "2013-07-09") ), Node("billing"), Node("credit-card"), Node("customer"), Node("descriptor"), Node("shipping"), Node("subscription") ) ), NodeAttr("add_ons", TYPE_ARRAY), NodeAttr("discounts", TYPE_ARRAY) ); } private string SubscriptionChargedUnsuccessfullySampleXml(string id) { return Node("subscription", Node("id", id), Node("transactions", Node("transaction", Node("id", id), Node("amount", "49.99"), Node("status", "failed"), Node("disbursement-details"), Node("billing"), Node("credit-card"), Node("customer"), Node("descriptor"), Node("shipping"), Node("subscription") ) ), NodeAttr("add_ons", TYPE_ARRAY), NodeAttr("discounts", TYPE_ARRAY) ); } private string CheckSampleXml() { return NodeAttr("check", TYPE_BOOLEAN, "true"); } private string MerchantAccountApprovedSampleXml(string id) { return Node("merchant-account", Node("id", id), Node("master-merchant-account", Node("id", "master_ma_for_" + id), Node("status", "active") ), Node("status", "active") ); } private string PartnerMerchantConnectedSampleXml(string id) { return Node("partner-merchant", Node("partner-merchant-id", "abc123"), Node("merchant-public-id", "public_id"), Node("public-key", "public_key"), Node("private-key", "private_key"), Node("client-side-encryption-key", "cse_key") ); } private string PartnerMerchantDisconnectedSampleXml(string id) { return Node("partner-merchant", Node("partner-merchant-id", "abc123") ); } private string ConnectedMerchantStatusTransitionedSampleXml(string id) { return Node("connected-merchant-status-transitioned", Node("oauth-application-client-id", "oauth_application_client_id"), Node("merchant-public-id", id), Node("status", "new_status") ); } private string ConnectedMerchantPayPalStatusChangedSampleXml(string id) { return Node("connected-merchant-paypal-status-changed", Node("oauth-application-client-id", "oauth_application_client_id"), Node("merchant-public-id", id), Node("action", "link") ); } private string PartnerMerchantDeclinedSampleXml(string id) { return Node("partner-merchant", Node("partner-merchant-id", "abc123") ); } private string OAuthAccessRevokedSampleXml(string id) { return Node("oauth-application-revocation", Node("merchant-id", id), Node("oauth-application-client-id", "oauth_application_client_id") ); } private string AccountUpdaterDailyReportSampleXml(string id) { return Node("account-updater-daily-report", NodeAttr("report-date", TYPE_DATE, "2016-01-14"), Node("report-url", "link-to-csv-report") ); } // NEXT_MAJOR_VERSION Remove this class as legacy Ideal has been removed/disabled in the Braintree Gateway private string IdealPaymentCompleteSampleXml(string id) { return Node("ideal-payment", Node("id", id), Node("status", "COMPLETE"), Node("issuer", "ABCISSUER"), Node("order-id", "ORDERABC"), Node("currency", "EUR"), Node("amount", "10.00"), Node("created-at", "2016-11-29T23:27:34.547Z"), Node("approval-url", "https://example.com"), Node("ideal-transaction-id", "1234567890") ); } // NEXT_MAJOR_VERSION Remove this class as legacy Ideal has been removed/disabled in the Braintree Gateway private string IdealPaymentFailedSampleXml(string id) { return Node("ideal-payment", Node("id", id), Node("status", "FAILED"), Node("issuer", "ABCISSUER"), Node("order-id", "ORDERABC"), Node("currency", "EUR"), Node("amount", "10.00"), Node("created-at", "2016-11-29T23:27:34.547Z"), Node("approval-url", "https://example.com"), Node("ideal-transaction-id", "1234567890") ); } private string GrantedPaymentInstrumentUpdateSampleXml() { return Node("granted-payment-instrument-update", Node("grant-owner-merchant-id", "vczo7jqrpwrsi2px"), Node("grant-recipient-merchant-id", "cf0i8wgarszuy6hc"), Node("payment-method-nonce", Node("nonce", "ee257d98-de40-47e8-96b3-a6954ea7a9a4"), Node("consumed", TYPE_BOOLEAN, "false"), Node("locked", TYPE_BOOLEAN, "false") ), Node("token", "abc123z"), Node("updated-fields", TYPE_ARRAY, Node("item", "expiration-month"), Node("item", "expiration-year") ) ); } private static string PaymentMethodRevokedByCustomerSampleXml(string id) { return Node("paypal-account", Node("billing-agreement-id", "a-billing-agreement-id"), NodeAttr("created-at", TYPE_DATE_TIME, "2019-01-01T12:00:00Z"), Node("customer-id", "a-customer-id"), NodeAttr("default", TYPE_BOOLEAN, "true"), Node("email", "name@email.com"), Node("global-id", "cGF5bWVudG1ldGhvZF9jaDZieXNz"), Node("image-url", "https://assets.braintreegateway.com/payment_method_logo/paypal.png?environment=test"), Node("token", id), NodeAttr("updated-at", TYPE_DATE_TIME, "2019-01-02T12:00:00Z"), Node("is-channel-initiated", NIL_TRUE, ""), Node("payer-id", "a-payer-id"), Node("payer-info", NIL_TRUE, ""), Node("limited-use-order-id", NIL_TRUE, ""), NodeAttr("revoked-at", TYPE_DATE_TIME, "2019-01-02T12:00:00Z") ); } private static string LocalPaymentCompletedSampleXml() { return Node("local-payment", Node("payment-id", "a-payment-id"), Node("payer-id", "a-payer-id"), Node("payment-method-nonce", "ee257d98-de40-47e8-96b3-a6954ea7a9a4"), Node("transaction", Node("id", "1"), Node("status", "authorizing"), Node("amount", "10.00"), Node("order-id", "order1234") ) ); } private static string Node(string name, params string[] contents) { return NodeAttr(name, null, contents); } private static string NodeAttr(string name, string attributes, params string[] contents) { StringBuilder buffer = new StringBuilder(); buffer.Append('<').Append(name); if (attributes != null) { buffer.Append(" ").Append(attributes); } buffer.Append('>'); foreach (string content in contents) { buffer.Append(content); } buffer.Append("</").Append(name).Append('>'); return buffer.ToString(); } } }
45.231193
226
0.489879
[ "MIT" ]
Ethernodes-org/braintree_dotnet
src/Braintree/WebhookTestingGateway.cs
24,651
C#
using System; using System.Collections.Generic; using System.Text; namespace UltimateOrb.Buffers { public struct MemorySpanRecord { public MemoryReferenceRecord Reference; public object? Manager { get => Reference.Manager; set => Reference.Manager = value; } public IntPtr ByteOffset { get => Reference.ByteOffset; set => Reference.ByteOffset = value; } public int Count; } }
17.535714
48
0.596741
[ "MIT" ]
LEI-Hongfaan/UltimateOrb.Core.v2
UltimateOrb.Core/Buffers/MemorySpanRecord.cs
493
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Collections.Generic; using Azure.Core; namespace Azure.ResourceManager.KeyVault.Models { /// <summary> Parameters for patching a secret. </summary> public partial class SecretUpdateOptions { /// <summary> Initializes a new instance of SecretUpdateOptions. </summary> public SecretUpdateOptions() { Tags = new ChangeTrackingDictionary<string, string>(); } /// <summary> The tags that will be assigned to the secret. </summary> public IDictionary<string, string> Tags { get; } /// <summary> Properties of the secret. </summary> public SecretPatchProperties Properties { get; set; } } }
29.607143
83
0.670688
[ "MIT" ]
AntonioVT/azure-sdk-for-net
sdk/keyvault/Azure.ResourceManager.KeyVault/src/Generated/Models/SecretUpdateOptions.cs
829
C#
using Amazon.JSII.Runtime.Deputy; #pragma warning disable CS0672,CS0809,CS1591 namespace AlibabaCloud.SDK.ROS.CDK.Polardb { /// <summary>Properties for defining a `ALIYUN::POLARDB::DBNodes`.</summary> [JsiiInterface(nativeType: typeof(IRosDBNodesProps), fullyQualifiedName: "@alicloud/ros-cdk-polardb.RosDBNodesProps")] public interface IRosDBNodesProps { /// <remarks> /// <strong>Property</strong>: amount: Number of nodes to be added to cluster. /// </remarks> [JsiiProperty(name: "amount", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}")] object Amount { get; } /// <remarks> /// <strong>Property</strong>: dbClusterId: The ID of the ApsaraDB for POLARDB cluster to be added nodes to. /// </remarks> [JsiiProperty(name: "dbClusterId", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}")] object DbClusterId { get; } /// <summary>Properties for defining a `ALIYUN::POLARDB::DBNodes`.</summary> [JsiiTypeProxy(nativeType: typeof(IRosDBNodesProps), fullyQualifiedName: "@alicloud/ros-cdk-polardb.RosDBNodesProps")] internal sealed class _Proxy : DeputyBase, AlibabaCloud.SDK.ROS.CDK.Polardb.IRosDBNodesProps { private _Proxy(ByRefValue reference): base(reference) { } /// <remarks> /// <strong>Property</strong>: amount: Number of nodes to be added to cluster. /// </remarks> [JsiiProperty(name: "amount", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}")] public object Amount { get => GetInstanceProperty<object>()!; } /// <remarks> /// <strong>Property</strong>: dbClusterId: The ID of the ApsaraDB for POLARDB cluster to be added nodes to. /// </remarks> [JsiiProperty(name: "dbClusterId", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}")] public object DbClusterId { get => GetInstanceProperty<object>()!; } } } }
42.438596
162
0.575444
[ "Apache-2.0" ]
aliyun/Resource-Orchestration-Service-Cloud-Development-K
multiple-languages/dotnet/AlibabaCloud.SDK.ROS.CDK.Polardb/AlibabaCloud/SDK/ROS/CDK/Polardb/IRosDBNodesProps.cs
2,419
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using EventStore.Common.Log; using EventStore.Core.Messages; using EventStore.Core.Messaging; using EventStore.Core.Tests.Helpers; using EventStore.Core.Tests.ClientAPI.Helpers; using EventStore.Core.Services; using EventStore.Core.Services.UserManagement; using EventStore.ClientAPI; using NUnit.Framework; using ILogger = EventStore.Common.Log.ILogger; using System.Threading.Tasks; namespace EventStore.Core.Tests.Services.Storage.Scavenge { [TestFixture] public class when_running_scavenge_from_storage_scavenger : SpecificationWithDirectoryPerTestFixture { private static readonly ILogger Log = LogManager.GetLoggerFor<when_running_scavenge_from_storage_scavenger>(); private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(60); private MiniNode _node; private List<ResolvedEvent> _result; public override void TestFixtureSetUp() { base.TestFixtureSetUp(); _node = new MiniNode(PathName, skipInitializeStandardUsersCheck: false); _node.Start(); var scavengeMessage = new ClientMessage.ScavengeDatabase(new NoopEnvelope(), Guid.NewGuid(), SystemAccount.Principal, 0, 1); _node.Node.MainQueue.Publish(scavengeMessage); When(); } [TearDown] public void TearDown() { _node.Shutdown(); } public void When() { using (var conn = TestConnection.Create(_node.TcpEndPoint, TcpType.Normal, DefaultData.AdminCredentials)) { conn.ConnectAsync().Wait(); var countdown = new CountdownEvent(2); _result = new List<ResolvedEvent>(); conn.SubscribeToStreamFrom(SystemStreams.ScavengesStream, null, CatchUpSubscriptionSettings.Default, (x, y) => { _result.Add(y); countdown.Signal(); return Task.CompletedTask; }, _ => Log.Info("Processing events started."), (x, y, z) => { Log.Info("Subscription dropped: {0}, {1}.", y, z); } ); if (!countdown.Wait(Timeout)) { Assert.Fail("Timeout expired while waiting for events."); } } } [Test] public void should_create_scavenge_started_event_on_index_stream() { var scavengeStartedEvent = _result.FirstOrDefault(x => x.Event.EventType == SystemEventTypes.ScavengeStarted); Assert.IsNotNull(scavengeStartedEvent); } [Test] public void should_create_scavenge_completed_event_on_index_stream() { var scavengeCompletedEvent = _result.FirstOrDefault(x => x.Event.EventType == SystemEventTypes.ScavengeCompleted); Assert.IsNotNull(scavengeCompletedEvent); } [Test] public void should_link_started_and_completed_events_to_the_same_stream() { var scavengeStartedEvent = _result.FirstOrDefault(x => x.Event.EventType == SystemEventTypes.ScavengeStarted); var scavengeCompletedEvent = _result.FirstOrDefault(x => x.Event.EventType == SystemEventTypes.ScavengeCompleted); Assert.AreEqual(scavengeStartedEvent.Event.EventStreamId, scavengeCompletedEvent.Event.EventStreamId); } } }
33.58427
112
0.757444
[ "Apache-2.0", "CC0-1.0" ]
JasonKStevens/EventStoreRx
src/EventStore.Core.Tests/Services/Storage/Scavenge/when_running_a_scavenge_from_storage_scavenger.cs
2,989
C#
// *** WARNING: this file was generated by pulumigen. *** // *** 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.Kubernetes.Types.Outputs.Core.V1 { [OutputType] public sealed class VsphereVirtualDiskVolumeSource { /// <summary> /// Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. /// </summary> public readonly string FsType; /// <summary> /// Storage Policy Based Management (SPBM) profile ID associated with the StoragePolicyName. /// </summary> public readonly string StoragePolicyID; /// <summary> /// Storage Policy Based Management (SPBM) profile name. /// </summary> public readonly string StoragePolicyName; /// <summary> /// Path that identifies vSphere volume vmdk /// </summary> public readonly string VolumePath; [OutputConstructor] private VsphereVirtualDiskVolumeSource( string fsType, string storagePolicyID, string storagePolicyName, string volumePath) { FsType = fsType; StoragePolicyID = storagePolicyID; StoragePolicyName = storagePolicyName; VolumePath = volumePath; } } }
31.56
179
0.63308
[ "Apache-2.0" ]
Teshel/pulumi-kubernetes
sdk/dotnet/Core/V1/Outputs/VsphereVirtualDiskVolumeSource.cs
1,578
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DynamicProgramming { public class Fibonacci { public long[] FibonacciNumbers(int n) { long[] fibo = new long[n + 1]; fibo[0] = 0; fibo[1] = 1; for (int i = 2; i < n + 1; i++) fibo[i] = fibo[i - 1] + fibo[i - 2]; return fibo; } } }
21.409091
52
0.509554
[ "MIT" ]
lizhen325/MIT-Data-Structures-And-Algorithms
MIT/DynamicProgramming/DynamicProgramming/Fibonacci.cs
473
C#
namespace MegaBuild { #region Using Directives using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Windows.Forms; using Menees; using Menees.Windows.Forms; #endregion internal sealed partial class SoundStepCtrl : StepEditorControl { #region Private Data Members private SoundStep step; #endregion #region Constructors public SoundStepCtrl() { this.InitializeComponent(); // Get all the SystemSound enum values, but order by name instead of binary value. var items = ((SystemSound[])Enum.GetValues(typeof(SystemSound))).OrderBy(s => s.ToString()).Select(s => (object)s).ToArray(); this.cbSystemSound.Items.AddRange(items); } #endregion #region Public Properties public override string DisplayName => "Sound"; public SoundStep Step { set { if (this.step != value) { this.step = value; this.rbSystemSound.Checked = false; this.rbWavFile.Checked = false; this.rbBeep.Checked = false; switch (this.step.Style) { case SoundStyle.SystemSound: this.rbSystemSound.Checked = true; break; case SoundStyle.WavFile: this.rbWavFile.Checked = true; break; case SoundStyle.Beep: this.rbBeep.Checked = true; break; } this.cbSystemSound.SelectedItem = this.step.SystemSound; this.edtWavFile.Text = this.step.WavFile; this.edtFrequency.Value = this.step.Frequency; this.edtDuration.Value = this.step.Duration; this.UpdateControlStates(); } } } #endregion #region Public Methods public override bool OnOk() { bool result = false; if (this.rbWavFile.Checked && string.IsNullOrEmpty(this.edtWavFile.Text.Trim())) { WindowsUtility.ShowError(this, "You must specify a .wav filename."); } else { if (this.rbSystemSound.Checked) { this.step.Style = SoundStyle.SystemSound; } else if (this.rbWavFile.Checked) { this.step.Style = SoundStyle.WavFile; } else { this.step.Style = SoundStyle.Beep; } this.step.SystemSound = (SystemSound)this.cbSystemSound.SelectedItem; this.step.WavFile = this.edtWavFile.Text.Trim(); this.step.Frequency = (int)this.edtFrequency.Value; this.step.Duration = (int)this.edtDuration.Value; result = true; } return result; } #endregion #region Private Methods private void WavFile_Click(object sender, EventArgs e) { this.OpenDlg.FileName = Manager.ExpandVariables(this.edtWavFile.Text); if (this.OpenDlg.ShowDialog(this) == DialogResult.OK) { this.edtWavFile.Text = Manager.CollapseVariables(this.OpenDlg.FileName); } } private void RadioButton_CheckedChanged(object sender, EventArgs e) { this.UpdateControlStates(); } private void UpdateControlStates() { this.cbSystemSound.Enabled = this.rbSystemSound.Checked; this.edtWavFile.Enabled = this.rbWavFile.Checked; this.btnWavFile.Enabled = this.rbWavFile.Checked; this.edtFrequency.Enabled = this.rbBeep.Checked; this.edtDuration.Enabled = this.rbBeep.Checked; } #endregion } }
21.682432
128
0.686818
[ "MIT" ]
menees/MegaBuild
src/MegaBuildSdk/Controls/SoundStepCtrl.cs
3,209
C#
#if UNITY_2017_2_OR_NEWER //----------------------------------------------------------------------- // <copyright file="VectorIntDrawer.cs" company="Sirenix IVS"> // Copyright (c) Sirenix IVS. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace Sirenix.OdinInspector.Editor.Drawers { using Utilities.Editor; using UnityEditor; using UnityEngine; /// <summary> /// Vector2Int proprety drawer. /// </summary> public sealed class Vector2IntDrawer : OdinValueDrawer<Vector2Int>, IDefinesGenericMenuItems { /// <summary> /// Draws the property. /// </summary> protected override void DrawPropertyLayout(GUIContent label) { Rect labelRect; var contentRect = SirenixEditorGUI.BeginHorizontalPropertyLayout(label, out labelRect); { EditorGUI.BeginChangeCheck(); var val = SirenixEditorFields.VectorPrefixSlideRect(labelRect, (Vector2)this.ValueEntry.SmartValue); if (EditorGUI.EndChangeCheck()) { this.ValueEntry.SmartValue = new Vector2Int((int)val.x, (int)val.y); } var showLabels = SirenixEditorFields.ResponsiveVectorComponentFields && contentRect.width >= 185; GUIHelper.PushLabelWidth(SirenixEditorFields.SingleLetterStructLabelWidth); this.ValueEntry.Property.Children[0].Draw(showLabels ? GUIHelper.TempContent("X") : null); this.ValueEntry.Property.Children[1].Draw(showLabels ? GUIHelper.TempContent("Y") : null); GUIHelper.PopLabelWidth(); } SirenixEditorGUI.EndHorizontalPropertyLayout(); } /// <summary> /// Populates the generic menu for the property. /// </summary> public void PopulateGenericMenu(InspectorProperty property, GenericMenu genericMenu) { var value = (Vector2Int)property.ValueEntry.WeakSmartValue; if (genericMenu.GetItemCount() > 0) { genericMenu.AddSeparator(""); } genericMenu.AddItem(new GUIContent("Zero", "Set the vector to (0, 0)"), value == Vector2Int.zero, () => SetVector(property, Vector2Int.zero)); genericMenu.AddItem(new GUIContent("One", "Set the vector to (1, 1)"), value == Vector2Int.one, () => SetVector(property, Vector2Int.one)); genericMenu.AddSeparator(""); genericMenu.AddItem(new GUIContent("Right", "Set the vector to (1, 0)"), value == Vector2Int.right, () => SetVector(property, Vector2Int.right)); genericMenu.AddItem(new GUIContent("Left", "Set the vector to (-1, 0)"), value == Vector2Int.left, () => SetVector(property, Vector2Int.left)); genericMenu.AddItem(new GUIContent("Up", "Set the vector to (0, 1)"), value == Vector2Int.up, () => SetVector(property, Vector2Int.up)); genericMenu.AddItem(new GUIContent("Down", "Set the vector to (0, -1)"), value == Vector2Int.down, () => SetVector(property, Vector2Int.down)); } private void SetVector(InspectorProperty property, Vector2Int value) { property.Tree.DelayActionUntilRepaint(() => { for (var i = 0; i < property.ValueEntry.ValueCount; i++) { property.ValueEntry.WeakValues[i] = value; } }); } } /// <summary> /// Vector3Int property drawer. /// </summary> public sealed class Vector3IntDrawer : OdinValueDrawer<Vector3Int>, IDefinesGenericMenuItems { /// <summary> /// Draws the property. /// </summary> protected override void DrawPropertyLayout(GUIContent label) { Rect labelRect; var contentRect = SirenixEditorGUI.BeginHorizontalPropertyLayout(label, out labelRect); { EditorGUI.BeginChangeCheck(); var val = SirenixEditorFields.VectorPrefixSlideRect(labelRect, (Vector3)this.ValueEntry.SmartValue); if (EditorGUI.EndChangeCheck()) { this.ValueEntry.SmartValue = new Vector3Int((int)val.x, (int)val.y, (int)val.z); } var showLabels = SirenixEditorFields.ResponsiveVectorComponentFields && contentRect.width >= 185; GUIHelper.PushLabelWidth(SirenixEditorFields.SingleLetterStructLabelWidth); this.ValueEntry.Property.Children[0].Draw(showLabels ? GUIHelper.TempContent("X") : null); this.ValueEntry.Property.Children[1].Draw(showLabels ? GUIHelper.TempContent("Y") : null); this.ValueEntry.Property.Children[2].Draw(showLabels ? GUIHelper.TempContent("Z") : null); GUIHelper.PopLabelWidth(); } SirenixEditorGUI.EndHorizontalPropertyLayout(); } /// <summary> /// Populates the generic menu for the property. /// </summary> public void PopulateGenericMenu(InspectorProperty property, GenericMenu genericMenu) { var value = (Vector3Int)property.ValueEntry.WeakSmartValue; if (genericMenu.GetItemCount() > 0) { genericMenu.AddSeparator(""); } genericMenu.AddItem(new GUIContent("Zero", "Set the vector to (0, 0, 0)"), value == Vector3Int.zero, () => SetVector(property, Vector3Int.zero)); genericMenu.AddItem(new GUIContent("One", "Set the vector to (1, 1, 1)"), value == Vector3Int.one, () => SetVector(property, Vector3Int.one)); genericMenu.AddSeparator(""); genericMenu.AddItem(new GUIContent("Right", "Set the vector to (1, 0, 0)"), value == Vector3Int.right, () => SetVector(property, Vector3Int.right)); genericMenu.AddItem(new GUIContent("Left", "Set the vector to (-1, 0, 0)"), value == Vector3Int.left, () => SetVector(property, Vector3Int.left)); genericMenu.AddItem(new GUIContent("Up", "Set the vector to (0, 1, 0)"), value == Vector3Int.up, () => SetVector(property, Vector3Int.up)); genericMenu.AddItem(new GUIContent("Down", "Set the vector to (0, -1, 0)"), value == Vector3Int.down, () => SetVector(property, Vector3Int.down)); genericMenu.AddItem(new GUIContent("Forward", "Set the vector property to (0, 0, 1)"), value == new Vector3Int(0, 0, 1), () => SetVector(property, new Vector3Int(0, 0, 1))); genericMenu.AddItem(new GUIContent("Back", "Set the vector property to (0, 0, -1)"), value == new Vector3Int(0, 0, -1), () => SetVector(property, new Vector3Int(0, 0, -1))); } private void SetVector(InspectorProperty property, Vector3Int value) { property.Tree.DelayActionUntilRepaint(() => { property.ValueEntry.WeakSmartValue = value; }); } } } #endif
49.921986
185
0.596676
[ "MIT" ]
alexandrejanin/TrafficJam
Assets/Plugins/Sirenix/Odin Inspector/Scripts/Editor/VectorIntDrawers.cs
7,041
C#
using System; using System.ComponentModel; namespace SkiaSharp { public unsafe class GRContext : SKObject, ISKReferenceCounted { [Preserve] internal GRContext (IntPtr h, bool owns) : base (h, owns) { } protected override void Dispose (bool disposing) => base.Dispose (disposing); // Create public static GRContext Create (GRBackend backend) => backend switch { GRBackend.Metal => throw new NotSupportedException (), GRBackend.OpenGL => CreateGl (), GRBackend.Vulkan => throw new NotSupportedException (), _ => throw new ArgumentOutOfRangeException (nameof (backend)), }; public static GRContext Create (GRBackend backend, GRGlInterface backendContext) => backend switch { GRBackend.Metal => throw new NotSupportedException (), GRBackend.OpenGL => CreateGl (backendContext), GRBackend.Vulkan => throw new NotSupportedException (), _ => throw new ArgumentOutOfRangeException (nameof (backend)), }; [EditorBrowsable (EditorBrowsableState.Never)] [Obsolete ("Use Create(GRBackend, GRGlInterface) instead.")] public static GRContext Create (GRBackend backend, IntPtr backendContext) => backend switch { GRBackend.Metal => throw new NotSupportedException (), GRBackend.OpenGL => GetObject<GRContext> (SkiaApi.gr_context_make_gl (backendContext)), GRBackend.Vulkan => throw new NotSupportedException (), _ => throw new ArgumentOutOfRangeException (nameof (backend)), }; // CreateGl public static GRContext CreateGl () => CreateGl (null); public static GRContext CreateGl (GRGlInterface backendContext) => GetObject<GRContext> (SkiaApi.gr_context_make_gl (backendContext == null ? IntPtr.Zero : backendContext.Handle)); // public GRBackend Backend => SkiaApi.gr_context_get_backend (Handle); public void AbandonContext (bool releaseResources = false) { if (releaseResources) SkiaApi.gr_context_release_resources_and_abandon_context (Handle); else SkiaApi.gr_context_abandon_context (Handle); } public void GetResourceCacheLimits (out int maxResources, out long maxResourceBytes) { IntPtr maxResBytes; fixed (int* maxRes = &maxResources) { SkiaApi.gr_context_get_resource_cache_limits (Handle, maxRes, &maxResBytes); } maxResourceBytes = (long)maxResBytes; } public void SetResourceCacheLimits (int maxResources, long maxResourceBytes) => SkiaApi.gr_context_set_resource_cache_limits (Handle, maxResources, (IntPtr)maxResourceBytes); public void GetResourceCacheUsage (out int maxResources, out long maxResourceBytes) { IntPtr maxResBytes; fixed (int* maxRes = &maxResources) { SkiaApi.gr_context_get_resource_cache_usage (Handle, maxRes, &maxResBytes); } maxResourceBytes = (long)maxResBytes; } public void ResetContext (GRGlBackendState state) => ResetContext ((uint)state); public void ResetContext (GRBackendState state = GRBackendState.All) => ResetContext ((uint)state); public void ResetContext (uint state) => SkiaApi.gr_context_reset_context (Handle, state); public void Flush () => SkiaApi.gr_context_flush (Handle); public int GetMaxSurfaceSampleCount (SKColorType colorType) => SkiaApi.gr_context_get_max_surface_sample_count_for_color_type (Handle, colorType); [EditorBrowsable (EditorBrowsableState.Never)] [Obsolete] public int GetRecommendedSampleCount (GRPixelConfig config, float dpi) => 0; } }
31.633028
116
0.742749
[ "MIT" ]
silvrwolfboy/SkiaSharp
binding/Binding/GRContext.cs
3,450
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class UmShop : EventObject { public override void Trigger() { CloseTrigger(); var umbera = Umbera.Get(); umbera.transform.SetParent(Player.Me.transform); umbera.transform.localPosition = Vector3.zero; umbera.transform.localEulerAngles = Vector3.zero; } }
24.6875
57
0.688608
[ "MIT" ]
pineapplle/HomeTemptation
HomeTemptation/Assets/_script/Event/UmShop.cs
397
C#
using System; namespace Microsoft.Marketplace.SaasKit.Client.DataAccess.Entities { public partial class OfferAttributes { public int Id { get; set; } public string ParameterId { get; set; } public string DisplayName { get; set; } public string Description { get; set; } public int? ValueTypeId { get; set; } public bool FromList { get; set; } public string ValuesList { get; set; } public int? Max { get; set; } public int? Min { get; set; } public string Type { get; set; } public int? DisplaySequence { get; set; } public bool Isactive { get; set; } public DateTime? CreateDate { get; set; } public int? UserId { get; set; } public Guid OfferId { get; set; } public bool? IsDelete { get; set; } public bool? IsRequired { get; set; } } }
34.192308
66
0.587177
[ "MIT" ]
Azure/Commercial-Marketplace-SaaS-Accelerator
src/SaaS.SDK.Client.DataAccess/Entities/OfferAttributes.cs
891
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="OrSpecification.cs" company="MCode"> // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Epic.Common.Query { using System; using System.Linq; using System.Linq.Expressions; /// <summary> /// Class OrSpecification. /// </summary> /// <typeparam name="T">The type of the specification.</typeparam> /// <seealso cref="Query.Specification{T}" /> public class OrSpecification<T> : Specification<T> { /// <summary> /// The left. /// </summary> private readonly Specification<T> left; /// <summary> /// The right. /// </summary> private readonly Specification<T> right; /// <summary> /// Initializes a new instance of the <see cref="OrSpecification{T}"/> class. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> public OrSpecification(Specification<T> left, Specification<T> right) { this.left = left; this.right = right; } /// <summary> /// Gets the spec. /// </summary> /// <value>The spec.</value> public override Expression<Func<T, bool>> Spec => Expression.Lambda<Func<T, bool>>( Expression.OrElse(this.left.Spec, this.right.Spec), this.left.Spec.Parameters.Single()); } }
38.59322
119
0.551603
[ "MIT" ]
RoyGI/Interview
csharp/src/common/Epic.Common/Query/OrSpecification.cs
2,277
C#
using System.IO; using System; using Serilog; using System.Reflection; using Newtonsoft.Json; using System.Collections.Generic; namespace FasterQuant.StrategyLogger { public class LoggerFactory { private readonly LogConfiguration _logConfig; private readonly string _logPath; private readonly string _identifierPlaceHolder; private readonly List<string> _indentifierValues; private readonly string _searchStringTemplate; private readonly RollingInterval _rollingInterval; public LoggerFactory(StrategyMode strategyMode, string logConfigFileName, RollingInterval rollingInterval) { var config = ReadConfig(GetConfigPath(), logConfigFileName); this._logConfig = JsonConvert.DeserializeObject<LogConfiguration>(config); this._logPath = GetLogPath(strategyMode, this._logConfig); this._rollingInterval = rollingInterval; } public LoggerFactory(StrategyMode strategyMode, LogConfiguration logConfig, RollingInterval rollingInterval) { this._logConfig = logConfig; this._logPath = GetLogPath(strategyMode, logConfig); this._rollingInterval = rollingInterval; } public LoggerFactory(StrategyMode strategyMode, string logConfigFileName, RollingInterval rollingInterval, string identifierPlaceHolder, string searchStringTemplate, List<string> indentifierValues) { var config = ReadConfig(GetConfigPath(), logConfigFileName); this._logConfig = JsonConvert.DeserializeObject<LogConfiguration>(config); this._logPath = GetLogPath(strategyMode, this._logConfig); this._rollingInterval = rollingInterval; this._identifierPlaceHolder = identifierPlaceHolder; this._searchStringTemplate = searchStringTemplate; this._indentifierValues = indentifierValues; } public LoggerFactory(StrategyMode strategyMode, LogConfiguration logConfig, RollingInterval rollingInterval, string identifierPlaceHolder, string searchStringTemplate, List<string> indentifierValues) { this._logConfig = logConfig; this._logPath = GetLogPath(strategyMode, logConfig); this._rollingInterval = rollingInterval; this._identifierPlaceHolder = identifierPlaceHolder; this._searchStringTemplate = searchStringTemplate; this._indentifierValues = indentifierValues; } public ILogger GetLogger() { if (string.IsNullOrEmpty(this._identifierPlaceHolder)) { return GetLoggerWithASingleFileSync(); } return GetLoggerWithMultipleFilesSync(); } private ILogger GetLoggerWithASingleFileSync() { return new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.File(this._logPath, rollingInterval: this._rollingInterval) .CreateLogger(); } private ILogger GetLoggerWithMultipleFilesSync() { var lc = new LoggerConfiguration(); foreach (var v in this._indentifierValues) { var searchString = this._searchStringTemplate.Replace(this._identifierPlaceHolder, v); var path = this._logPath.Replace(this._identifierPlaceHolder, v); lc.WriteTo.Logger(x => { x.WriteTo.File(path, rollingInterval: this._rollingInterval); x.Filter.ByIncludingOnly(e => e.RenderMessage().Contains(searchString)); }); } return lc.MinimumLevel.Debug() .CreateLogger(); } private string GetLogPath(StrategyMode strategyMode, LogConfiguration logConfig) { var logFile = strategyMode == StrategyMode.Live ? logConfig.LiveTradingLogFile :logConfig.BacktestLogFile; return Path.Combine(logConfig.Path, logFile); } private string GetConfigPath() { var ass = Assembly.GetExecutingAssembly(); return new Uri(ass.CodeBase).LocalPath.ToLower().Replace((Assembly.GetExecutingAssembly().GetName().Name).ToLower() + ".dll", ""); } private string ReadConfig(string path, string logConfigFileName) { var config = ""; var s = ""; var fullPath = Path.Combine(path, logConfigFileName); if (!File.Exists(fullPath)) { throw new Exception("The following path does not exist: " + fullPath + ". Please make sure " + logConfigFileName + " is deployed with " + Assembly.GetExecutingAssembly().GetName() + "."); } using (StreamReader sr = File.OpenText(fullPath)) { while ((s = sr.ReadLine()) != null) { config += s; } } return config; } } }
38.748092
207
0.629827
[ "MIT" ]
fasterquant/StrategyLogger
Source/FasterQuant.StrategyLogger/LoggerFactory.cs
5,078
C#
using System.Collections.Generic; namespace MistrzowieWynajmu.Models.Interfaces { public interface IPropertyRepository { List<Property> GetAllProperties(); Property GetProperty(int propertyId); int AddProperty(Property property, Address address, Owner owner); int UpdateProperty(Property property); void DeleteProperty(Property property, Address address, Owner owner); } }
30.5
77
0.725995
[ "MIT" ]
KropkaTest/mistrzowiewynajmu
MistrzowieWynajmu/MistrzowieWynajmu/Models/Interfaces/IPropertyRepository.cs
429
C#
using IntelligentMemoryScavenger.Logger; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IntelligentMemoryScavenger { public class MemoryScavenger { private ILogger _logger; public MemoryScavenger(ILogger logger) { _logger = logger; } public void CleanMemory() { _logger.Log("Service is recall at " + DateTime.Now); try { var tempFolderPath = Path.GetTempPath(); var tempFileFolders = Directory.EnumerateDirectories(tempFolderPath); var tempFiles = Directory.EnumerateFiles(tempFolderPath); foreach (var tempFileFolder in tempFileFolders) { try { _logger.Log($"Deleting temp file folder: {tempFileFolder}"); Directory.Delete(tempFileFolder, true); _logger.Log($"Service is able to scavenge temp folder at: {tempFileFolder}"); } catch (Exception e1) { _logger.Log($"Service is unable to scavenge temp folder at: {tempFileFolder} and exception thrown is: {e1.Message}"); } } foreach (var tempFile in tempFiles) { try { _logger.Log($"Deleting temp file: {tempFile}"); File.Delete(tempFile); _logger.Log($"Service is able to scavenge temp file: {tempFile}"); } catch (Exception e2) { _logger.Log($"Service is unable to scavenge temp folder at: {tempFile} and exception thrown is: {e2.Message}"); } } _logger.Log($"Service is able to scavenge temp folder at " + DateTime.Now); } catch (Exception exception) { _logger.Log($"Service is unable to delete files because of exception : { exception.Message }"); } } } }
37.15873
142
0.491243
[ "Apache-2.0" ]
yogakce/TempMemoryCleaner
MemoryScavenger.cs
2,343
C#
using System; using System.Collections.Generic; using System.Text; namespace XSel { public class BrowserSize { public static BrowserSize Parse(string format) { if (string.IsNullOrWhiteSpace(format)) throw new ArgumentNullException("format"); var invariantFormat = format.ToLowerInvariant(); if (invariantFormat.Contains("max")) { return new BrowserSizeMaximized(); } else { var sizeAbsAsString = invariantFormat.Split('x'); if (sizeAbsAsString.Length != 2) throw new InvalidOperationException("BrowserSize must be in format '1024x648'."); int x = int.Parse(sizeAbsAsString[0]); int y = int.Parse(sizeAbsAsString[1]); return new BrowserSize { X = x, Y = y }; } } public int X { get; set; } = 1920; public int Y { get; set; } = 1080; public System.Drawing.Size ToSize() { return new System.Drawing.Size(X, Y); } } public class BrowserSizeMaximized : BrowserSize { } }
26.021739
101
0.539683
[ "MIT" ]
wulfland/XSel
src/XSel/BrowserSize.cs
1,199
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // non-local exits in a catch handler nested in another catch handler using System; namespace hello { class Class1 { private static TestUtil.TestLog testLog; static Class1() { // Create test writer object to hold expected output System.IO.StringWriter expectedOut = new System.IO.StringWriter(); // Write expected output to string writer object expectedOut.WriteLine("in Try"); expectedOut.WriteLine("in Try"); expectedOut.WriteLine("in Try"); expectedOut.WriteLine("L5"); expectedOut.WriteLine("in Catch"); expectedOut.WriteLine("in Try"); expectedOut.WriteLine("in Catch"); expectedOut.WriteLine("L4"); expectedOut.WriteLine("in Try"); expectedOut.WriteLine("in Catch"); expectedOut.WriteLine("L4"); expectedOut.WriteLine("L5"); expectedOut.WriteLine("in Catch"); expectedOut.WriteLine("in Finally"); expectedOut.WriteLine("in Finally"); // Create and initialize test log object testLog = new TestUtil.TestLog(expectedOut); } static int i; static public void inTry() { Console.WriteLine("in Try"); i++; if (i > 3) throw new Exception(); } static public void inCatch() { Console.WriteLine("in Catch"); } static public void inFinally() { Console.WriteLine("in Finally"); } static public int Main(string[] args) { //Start recording testLog.StartRecording(); i = 0; L1: if (i > 0) goto L3; try { inTry(); try { inTry(); L2: try { // catch Exception inTry(); throw new Exception(); } catch (Exception e) { L5: Console.WriteLine("L5"); inCatch(); if (i == 5) goto L1; try { // catch System inTry(); } catch (Exception e1) { inCatch(); if (i == 0) goto L1; if (i == 1) goto L2; L4: Console.WriteLine("L4"); if (i == 5) goto L5; try { inTry(); } catch (Exception e2) { inCatch(); if (i == 0) goto L3; if (i == 1) goto L2; if (i > 1) goto L4; Console.WriteLine("Unreached\n"); try { for (int ii = 0; ii < 10; ii++) { try { Console.WriteLine(args[ii]); } finally { Console.WriteLine("Unreached finally\n"); } } } catch { Console.WriteLine("Unreached catch\n"); switch (i) { case 0: goto L1; case 3: goto L2; case 4: goto L4; default: break; } goto L5; } } } } } finally { inFinally(); } } finally { inFinally(); } L3: // stop recoding testLog.StopRecording(); return testLog.VerifyOutput(); } // Main } // class } // namespace
32.588608
101
0.322198
[ "MIT" ]
corefan/coreclr
tests/src/JIT/Methodical/eh/nested/general/cascadedcatch.cs
5,149
C#
using System.Reflection; 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("BeatSaberDiscordPresence")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BeatSaberDiscordPresence")] [assembly: AssemblyCopyright("Copyright © Slaynash 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0A3B23AC-9395-49EF-BD55-57BAC10947AE")] // 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("2.2.1.0")] [assembly: AssemblyFileVersion("2.2.1.0")]
39.685714
84
0.74802
[ "MIT" ]
Slaynash/BeatSaberDiscordPresence
BeatSaberDiscordPresence/Properties/AssemblyInfo.cs
1,392
C#
using System; using System.Collections.Generic; using ErikEJ.SqlCeScripting; using System.Data; using System.Linq; namespace ErikEJ.SqlCeToolbox.Helpers { internal class DescriptionHelper { private const string TableName = "__ExtendedProperties"; private const string CreateScript = @"CREATE TABLE __ExtendedProperties ( [Id] [int] NOT NULL IDENTITY, [Type] [int] NOT NULL DEFAULT 0, [ParentName] nvarchar(128) NULL, [ObjectName] nvarchar(128) NULL, [Value] nvarchar(4000) NOT NULL ); GO CREATE INDEX [__ExtendedProperties_ObjectName_ParentName] ON [__ExtendedProperties] ([ObjectName], [ParentName]); GO "; private const string InsertScript = @"INSERT INTO [__ExtendedProperties] ([Type] ,[ParentName] ,[ObjectName] ,[Value]) VALUES (0 ,{0} ,{1} ,'{2}'); GO "; private const string UpdateScript = @"UPDATE [__ExtendedProperties] SET [Value] = '{0}' WHERE {1}; GO "; private const string SelectScript = @"SELECT [ObjectName], [ParentName], [Value] FROM [__ExtendedProperties]; GO "; private void AddDescription(string description, string parentName, string objectName, DatabaseInfo databaseInfo) { if (string.IsNullOrWhiteSpace(description)) return; using (IRepository repo = Helpers.RepositoryHelper.CreateRepository(databaseInfo)) { CreateExtPropsTable(repo); string sql = string.Format(InsertScript, (parentName == null ? "NULL" : "'" + parentName + "'"), (objectName == null ? "NULL" : "'" + objectName + "'"), description.Replace("'", "''")); repo.ExecuteSql(sql); } } private void UpdateDescription(string description, string parentName, string objectName, DatabaseInfo databaseInfo) { if (string.IsNullOrWhiteSpace(description)) return; description = description.Replace("'", "''"); using (IRepository repo = Helpers.RepositoryHelper.CreateRepository(databaseInfo)) { string where = (objectName == null ? "[ObjectName] IS NULL AND " : "[ObjectName] = '" + objectName + "' AND"); where += (parentName == null ? "[ParentName] IS NULL AND [Type] = 0" : "[ParentName] = '" + parentName + "' AND [Type] = 0"); repo.ExecuteSql(string.Format(UpdateScript, description, where)); } } public void SaveDescription(DatabaseInfo databaseInfo,List<DbDescription> cache, string description, string parentName, string objectName) { DbDescription desc = null; if (cache != null) desc = cache.Where(c => c.Object == objectName && c.Parent == parentName).SingleOrDefault(); if (desc != null) { UpdateDescription(description, parentName, objectName, databaseInfo); } else { AddDescription(description, parentName, objectName, databaseInfo); } GetDescriptions(databaseInfo); } public List<DbDescription> GetDescriptions(DatabaseInfo databaseInfo) { var list = new List<DbDescription>(); using (IRepository repo = Helpers.RepositoryHelper.CreateRepository(databaseInfo)) { var tlist = repo.GetAllTableNames(); if (tlist.Contains(TableName)) { var ds = repo.ExecuteSql(SelectScript); if (ds.Tables.Count > 0) { foreach (DataRow row in ds.Tables[0].Rows) { var dbDesc = new DbDescription(); dbDesc.Object = row[0] == DBNull.Value ? null : row[0].ToString(); dbDesc.Parent = row[1] == DBNull.Value ? null : row[1].ToString(); dbDesc.Description = row[2] == DBNull.Value ? null : row[2].ToString(); list.Add(dbDesc); } } } } return list; } private static void CreateExtPropsTable(IRepository repo) { var list = repo.GetAllTableNames(); if (!list.Contains(TableName)) repo.ExecuteSql(CreateScript); } } }
33.208633
146
0.544194
[ "Apache-2.0" ]
BekoSan/SqlCeToolbox
src/GUI/SqlCe35Toolbox/Helpers/DescriptionHelper.cs
4,618
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Graphics.OpenGL.Vertices; using osuTK.Graphics.ES30; using osu.Framework.Statistics; using osu.Framework.Development; namespace osu.Framework.Graphics.OpenGL.Buffers { public abstract class VertexBuffer<T> : IDisposable where T : struct, IEquatable<T>, IVertex { protected static readonly int STRIDE = VertexUtils<T>.STRIDE; public readonly T[] Vertices; private readonly BufferUsageHint usage; private bool isInitialised; private int vboId; protected VertexBuffer(int amountVertices, BufferUsageHint usage) { this.usage = usage; Vertices = new T[amountVertices]; } /// <summary> /// Initialises this <see cref="VertexBuffer{T}"/>. Guaranteed to be run on the draw thread. /// </summary> protected virtual void Initialise() { ThreadSafety.EnsureDrawThread(); GL.GenBuffers(1, out vboId); if (GLWrapper.BindBuffer(BufferTarget.ArrayBuffer, vboId)) VertexUtils<T>.Bind(); GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(Vertices.Length * STRIDE), IntPtr.Zero, usage); } ~VertexBuffer() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected bool IsDisposed; protected virtual void Dispose(bool disposing) { if (IsDisposed) return; if (isInitialised) { Unbind(); GLWrapper.DeleteBuffer(vboId); } IsDisposed = true; } public virtual void Bind(bool forRendering) { if (IsDisposed) throw new ObjectDisposedException(ToString(), "Can not bind disposed vertex buffers."); if (!isInitialised) { Initialise(); isInitialised = true; } if (GLWrapper.BindBuffer(BufferTarget.ArrayBuffer, vboId)) VertexUtils<T>.Bind(); } public virtual void Unbind() { } protected virtual int ToElements(int vertices) { return vertices; } protected virtual int ToElementIndex(int vertexIndex) { return vertexIndex; } protected abstract PrimitiveType Type { get; } public void Draw() { DrawRange(0, Vertices.Length); } public void DrawRange(int startIndex, int endIndex) { Bind(true); int amountVertices = endIndex - startIndex; GL.DrawElements(Type, ToElements(amountVertices), DrawElementsType.UnsignedShort, (IntPtr)(ToElementIndex(startIndex) * sizeof(ushort))); Unbind(); } public void Update() { UpdateRange(0, Vertices.Length); } public void UpdateRange(int startIndex, int endIndex) { Bind(false); int amountVertices = endIndex - startIndex; GL.BufferSubData(BufferTarget.ArrayBuffer, (IntPtr)(startIndex * STRIDE), (IntPtr)(amountVertices * STRIDE), ref Vertices[startIndex]); Unbind(); FrameStatistics.Add(StatisticsCounterType.VerticesUpl, amountVertices); } } }
27.474453
150
0.549947
[ "MIT" ]
GurovRoman/osu-framework
osu.Framework/Graphics/OpenGL/Buffers/VertexBuffer.cs
3,630
C#
using System; using System.Collections.Generic; using System.IdentityModel.Tokens; using System.Linq; using System.Security.Claims; using System.Web; using System.Web.Security; namespace SimpleInjectorWeb { public class ClaimsTransformer : ClaimsAuthenticationManager { //public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal principal) //{ //} public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal) { if (!incomingPrincipal.Identity.IsAuthenticated) { return base.Authenticate(resourceName, incomingPrincipal); } var newPrincipal = CreateApplicationPrincipal(incomingPrincipal.Identity.Name); EstablishSession(newPrincipal); return newPrincipal; } private void EstablishSession(ClaimsPrincipal newPrincipal) { var sessionToken = new SessionSecurityToken(newPrincipal, TimeSpan.FromHours(10)); //FederatedAuthentication.SessionAuthenticationModule.WriteSessionCookie(); } private ClaimsPrincipal CreateApplicationPrincipal(string userName) { var claims = new List<Claim>(); if (userName == "richard") { claims.Add(new Claim(ClaimTypes.Name, userName)); claims.Add(new Claim(ClaimTypes.GivenName, "Richard")); Roles.GetRolesForUser(userName).ToList().ForEach(role => claims.Add(new Claim(ClaimTypes.Role, role))); } else { claims.Add(new Claim(ClaimTypes.Name, userName)); claims.Add(new Claim(ClaimTypes.GivenName, userName)); } return new ClaimsPrincipal(new ClaimsIdentity(claims, "Custom")); } } }
33.589286
119
0.639553
[ "MIT" ]
cloudstrifebro/mySamples
SimpleInjectorSample/SimpleInjectorConsole/SimpleInjectorWeb/ClaimsTransformer.cs
1,883
C#
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace ZXing.Client.Result { /// <author>jbreiden@google.com (Jeff Breidenbach)</author> public sealed class ISBNParsedResult : ParsedResult { internal ISBNParsedResult(String isbn) : base(ParsedResultType.ISBN) { ISBN = isbn; displayResultValue = isbn; } public String ISBN { get; private set; } } }
29.30303
74
0.707342
[ "Apache-2.0" ]
DigitalPlatform/dp2
zxing_lib/client/result/ISBNParsedResult.cs
967
C#
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalRis { /// <summary> /// Strongly-typed collection for the PnCredito class. /// </summary> [Serializable] public partial class PnCreditoCollection : ActiveList<PnCredito, PnCreditoCollection> { public PnCreditoCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>PnCreditoCollection</returns> public PnCreditoCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { PnCredito o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the PN_credito table. /// </summary> [Serializable] public partial class PnCredito : ActiveRecord<PnCredito>, IActiveRecord { #region .ctors and Default Settings public PnCredito() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public PnCredito(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public PnCredito(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public PnCredito(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("PN_credito", TableType.Table, DataService.GetInstance("RisProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdCredito = new TableSchema.TableColumn(schema); colvarIdCredito.ColumnName = "id_credito"; colvarIdCredito.DataType = DbType.Int32; colvarIdCredito.MaxLength = 0; colvarIdCredito.AutoIncrement = true; colvarIdCredito.IsNullable = false; colvarIdCredito.IsPrimaryKey = true; colvarIdCredito.IsForeignKey = false; colvarIdCredito.IsReadOnly = false; colvarIdCredito.DefaultSetting = @""; colvarIdCredito.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdCredito); TableSchema.TableColumn colvarCantidad = new TableSchema.TableColumn(schema); colvarCantidad.ColumnName = "cantidad"; colvarCantidad.DataType = DbType.Decimal; colvarCantidad.MaxLength = 0; colvarCantidad.AutoIncrement = false; colvarCantidad.IsNullable = true; colvarCantidad.IsPrimaryKey = false; colvarCantidad.IsForeignKey = false; colvarCantidad.IsReadOnly = false; colvarCantidad.DefaultSetting = @""; colvarCantidad.ForeignKeyTableName = ""; schema.Columns.Add(colvarCantidad); TableSchema.TableColumn colvarIdFactura = new TableSchema.TableColumn(schema); colvarIdFactura.ColumnName = "id_factura"; colvarIdFactura.DataType = DbType.Int32; colvarIdFactura.MaxLength = 0; colvarIdFactura.AutoIncrement = false; colvarIdFactura.IsNullable = false; colvarIdFactura.IsPrimaryKey = false; colvarIdFactura.IsForeignKey = false; colvarIdFactura.IsReadOnly = false; colvarIdFactura.DefaultSetting = @""; colvarIdFactura.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdFactura); TableSchema.TableColumn colvarIdNomenclador = new TableSchema.TableColumn(schema); colvarIdNomenclador.ColumnName = "id_nomenclador"; colvarIdNomenclador.DataType = DbType.Int32; colvarIdNomenclador.MaxLength = 0; colvarIdNomenclador.AutoIncrement = false; colvarIdNomenclador.IsNullable = false; colvarIdNomenclador.IsPrimaryKey = false; colvarIdNomenclador.IsForeignKey = false; colvarIdNomenclador.IsReadOnly = false; colvarIdNomenclador.DefaultSetting = @""; colvarIdNomenclador.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdNomenclador); TableSchema.TableColumn colvarIdMotivoD = new TableSchema.TableColumn(schema); colvarIdMotivoD.ColumnName = "id_motivo_d"; colvarIdMotivoD.DataType = DbType.Int32; colvarIdMotivoD.MaxLength = 0; colvarIdMotivoD.AutoIncrement = false; colvarIdMotivoD.IsNullable = false; colvarIdMotivoD.IsPrimaryKey = false; colvarIdMotivoD.IsForeignKey = false; colvarIdMotivoD.IsReadOnly = false; colvarIdMotivoD.DefaultSetting = @""; colvarIdMotivoD.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdMotivoD); TableSchema.TableColumn colvarMonto = new TableSchema.TableColumn(schema); colvarMonto.ColumnName = "monto"; colvarMonto.DataType = DbType.Decimal; colvarMonto.MaxLength = 0; colvarMonto.AutoIncrement = false; colvarMonto.IsNullable = true; colvarMonto.IsPrimaryKey = false; colvarMonto.IsForeignKey = false; colvarMonto.IsReadOnly = false; colvarMonto.DefaultSetting = @""; colvarMonto.ForeignKeyTableName = ""; schema.Columns.Add(colvarMonto); TableSchema.TableColumn colvarCodigoCred = new TableSchema.TableColumn(schema); colvarCodigoCred.ColumnName = "codigo_cred"; colvarCodigoCred.DataType = DbType.AnsiString; colvarCodigoCred.MaxLength = -1; colvarCodigoCred.AutoIncrement = false; colvarCodigoCred.IsNullable = true; colvarCodigoCred.IsPrimaryKey = false; colvarCodigoCred.IsForeignKey = false; colvarCodigoCred.IsReadOnly = false; colvarCodigoCred.DefaultSetting = @""; colvarCodigoCred.ForeignKeyTableName = ""; schema.Columns.Add(colvarCodigoCred); TableSchema.TableColumn colvarObservacionesCred = new TableSchema.TableColumn(schema); colvarObservacionesCred.ColumnName = "observaciones_cred"; colvarObservacionesCred.DataType = DbType.AnsiString; colvarObservacionesCred.MaxLength = -1; colvarObservacionesCred.AutoIncrement = false; colvarObservacionesCred.IsNullable = true; colvarObservacionesCred.IsPrimaryKey = false; colvarObservacionesCred.IsForeignKey = false; colvarObservacionesCred.IsReadOnly = false; colvarObservacionesCred.DefaultSetting = @""; colvarObservacionesCred.ForeignKeyTableName = ""; schema.Columns.Add(colvarObservacionesCred); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["RisProvider"].AddSchema("PN_credito",schema); } } #endregion #region Props [XmlAttribute("IdCredito")] [Bindable(true)] public int IdCredito { get { return GetColumnValue<int>(Columns.IdCredito); } set { SetColumnValue(Columns.IdCredito, value); } } [XmlAttribute("Cantidad")] [Bindable(true)] public decimal? Cantidad { get { return GetColumnValue<decimal?>(Columns.Cantidad); } set { SetColumnValue(Columns.Cantidad, value); } } [XmlAttribute("IdFactura")] [Bindable(true)] public int IdFactura { get { return GetColumnValue<int>(Columns.IdFactura); } set { SetColumnValue(Columns.IdFactura, value); } } [XmlAttribute("IdNomenclador")] [Bindable(true)] public int IdNomenclador { get { return GetColumnValue<int>(Columns.IdNomenclador); } set { SetColumnValue(Columns.IdNomenclador, value); } } [XmlAttribute("IdMotivoD")] [Bindable(true)] public int IdMotivoD { get { return GetColumnValue<int>(Columns.IdMotivoD); } set { SetColumnValue(Columns.IdMotivoD, value); } } [XmlAttribute("Monto")] [Bindable(true)] public decimal? Monto { get { return GetColumnValue<decimal?>(Columns.Monto); } set { SetColumnValue(Columns.Monto, value); } } [XmlAttribute("CodigoCred")] [Bindable(true)] public string CodigoCred { get { return GetColumnValue<string>(Columns.CodigoCred); } set { SetColumnValue(Columns.CodigoCred, value); } } [XmlAttribute("ObservacionesCred")] [Bindable(true)] public string ObservacionesCred { get { return GetColumnValue<string>(Columns.ObservacionesCred); } set { SetColumnValue(Columns.ObservacionesCred, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(decimal? varCantidad,int varIdFactura,int varIdNomenclador,int varIdMotivoD,decimal? varMonto,string varCodigoCred,string varObservacionesCred) { PnCredito item = new PnCredito(); item.Cantidad = varCantidad; item.IdFactura = varIdFactura; item.IdNomenclador = varIdNomenclador; item.IdMotivoD = varIdMotivoD; item.Monto = varMonto; item.CodigoCred = varCodigoCred; item.ObservacionesCred = varObservacionesCred; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdCredito,decimal? varCantidad,int varIdFactura,int varIdNomenclador,int varIdMotivoD,decimal? varMonto,string varCodigoCred,string varObservacionesCred) { PnCredito item = new PnCredito(); item.IdCredito = varIdCredito; item.Cantidad = varCantidad; item.IdFactura = varIdFactura; item.IdNomenclador = varIdNomenclador; item.IdMotivoD = varIdMotivoD; item.Monto = varMonto; item.CodigoCred = varCodigoCred; item.ObservacionesCred = varObservacionesCred; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdCreditoColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn CantidadColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn IdFacturaColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn IdNomencladorColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn IdMotivoDColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn MontoColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn CodigoCredColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn ObservacionesCredColumn { get { return Schema.Columns[7]; } } #endregion #region Columns Struct public struct Columns { public static string IdCredito = @"id_credito"; public static string Cantidad = @"cantidad"; public static string IdFactura = @"id_factura"; public static string IdNomenclador = @"id_nomenclador"; public static string IdMotivoD = @"id_motivo_d"; public static string Monto = @"monto"; public static string CodigoCred = @"codigo_cred"; public static string ObservacionesCred = @"observaciones_cred"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
29.036403
188
0.653909
[ "MIT" ]
saludnqn/prosane
RIS_Publico/RIS_Publico/generated/PnCredito.cs
13,560
C#
using System; using System.Collections.Generic; namespace Wellcome.Dds.AssetDomain.Workflow { public class WorkflowCallStats { public int TotalJobs { get; set; } public int FinishedJobs { get; set; } public float FinishedPercent { get; set; } public decimal WordCount { get; set; } public List<WorkflowJob> RecentlyTaken { get; set; } public List<WorkflowJob> TakenAndUnfinished { get; set; } public DateTime EstimatedCompletion { get; set; } public int RecentSampleHours { get; set; } public int Errors { get; set; } } }
33.666667
65
0.651815
[ "MIT" ]
wellcomecollection/iiif-builder
src/Wellcome.Dds/Wellcome.Dds.AssetDomain/Workflow/WorkflowCallStats.cs
606
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WallpaperChanger.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WallpaperChanger.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
38.739726
182
0.60785
[ "Apache-2.0" ]
masaaki-yoshida-dev/myoshidan.WallpaperChanger.Activities
WallpaperChanger/WallpaperChanger/WallpaperChanger/Properties/Resources.Designer.cs
2,830
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; 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.Sas; namespace Azure.Data.Tables { public class TableServiceClient { private readonly ClientDiagnostics _diagnostics; private readonly TableRestClient _tableOperations; private readonly ServiceRestClient _serviceOperations; private readonly ServiceRestClient _secondaryServiceOperations; private readonly OdataMetadataFormat _format = OdataMetadataFormat.ApplicationJsonOdataMinimalmetadata; private readonly string _version; internal readonly bool _isPremiumEndpoint; /// <summary> /// Initializes a new instance of the <see cref="TableServiceClient"/>. /// </summary> /// <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> public TableServiceClient(Uri endpoint) : this(endpoint, options: null) { } /// <summary> /// Initializes a new instance of the <see cref="TableServiceClient"/>. /// </summary> /// <param name="connectionString"> /// A connection string includes the authentication information /// required for your application to access data in an Azure Storage /// account at runtime. /// /// For more information, /// <see href="https://docs.microsoft.com/azure/storage/common/storage-configure-connection-string"> /// Configure Azure Storage connection strings</see>. /// </param> public TableServiceClient(string connectionString) : this(connectionString, options: null) { } /// <summary> /// Initializes a new instance of the <see cref="TableServiceClient"/>. /// </summary> /// <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> public TableServiceClient(Uri endpoint, TableClientOptions options = null) : this(endpoint, default(TableSharedKeyPipelinePolicy), options) { if (endpoint.Scheme != "https") { throw new ArgumentException("Cannot use TokenCredential without HTTPS.", nameof(endpoint)); } } /// <summary> /// Initializes a new instance of the <see cref="TableServiceClient"/>. /// </summary> /// <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> public TableServiceClient(Uri endpoint, TableSharedKeyCredential credential) : this(endpoint, new TableSharedKeyPipelinePolicy(credential), null) { Argument.AssertNotNull(credential, nameof(credential)); } /// <summary> /// Initializes a new instance of the <see cref="TableServiceClient"/>. /// </summary> /// <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> public TableServiceClient(Uri endpoint, TableSharedKeyCredential credential, TableClientOptions options = null) : this(endpoint, new TableSharedKeyPipelinePolicy(credential), options) { Argument.AssertNotNull(credential, nameof(credential)); } /// <summary> /// Initializes a new instance of the <see cref="TableServiceClient"/>. /// </summary> /// <param name="connectionString"> /// A connection string includes the authentication information /// required for your application to access data in an Azure Storage /// account at runtime. /// /// For more information, /// <see href="https://docs.microsoft.com/azure/storage/common/storage-configure-connection-string"> /// Configure Azure Storage connection strings</see>. /// </param> /// <param name="options"> /// Optional client options that define the transport pipeline policies for authentication, retries, etc., that are applied to every request. /// </param> public TableServiceClient(string connectionString, TableClientOptions options = null) { Argument.AssertNotNull(connectionString, nameof(connectionString)); TableConnectionString connString = TableConnectionString.Parse(connectionString); options ??= new TableClientOptions(); var endpointString = connString.TableStorageUri.PrimaryUri.ToString(); var secondaryEndpoint = connString.TableStorageUri.PrimaryUri?.ToString() ?? endpointString.Insert(endpointString.IndexOf('.'), "-secondary"); TableSharedKeyPipelinePolicy policy = connString.Credentials switch { TableSharedKeyCredential credential => new TableSharedKeyPipelinePolicy(credential), _ => default }; HttpPipeline pipeline = HttpPipelineBuilder.Build(options, policy); _diagnostics = new ClientDiagnostics(options); _tableOperations = new TableRestClient(_diagnostics, pipeline, endpointString); _serviceOperations = new ServiceRestClient(_diagnostics, pipeline, endpointString); _secondaryServiceOperations = new ServiceRestClient(_diagnostics, pipeline, secondaryEndpoint); _version = options.VersionString; _isPremiumEndpoint = IsPremiumEndpoint(connString.TableStorageUri.PrimaryUri); } internal TableServiceClient(Uri endpoint, TableSharedKeyPipelinePolicy policy, TableClientOptions options) { Argument.AssertNotNull(endpoint, nameof(endpoint)); options ??= new TableClientOptions(); var endpointString = endpoint.ToString(); var secondaryEndpoint = endpointString.Insert(endpointString.IndexOf('.'), "-secondary"); HttpPipeline pipeline = HttpPipelineBuilder.Build(options, policy); _diagnostics = new ClientDiagnostics(options); _tableOperations = new TableRestClient(_diagnostics, pipeline, endpointString); _serviceOperations = new ServiceRestClient(_diagnostics, pipeline, endpointString); _secondaryServiceOperations = new ServiceRestClient(_diagnostics, pipeline, secondaryEndpoint); _version = options.VersionString; _isPremiumEndpoint = IsPremiumEndpoint(endpoint); } /// <summary> /// Initializes a new instance of the <see cref="TableServiceClient"/> /// class for mocking. /// </summary> internal TableServiceClient(TableRestClient internalClient) { _tableOperations = internalClient; } /// <summary> /// Initializes a new instance of the <see cref="TableServiceClient"/> /// class for mocking. /// </summary> protected TableServiceClient() { } /// <summary> /// Gets a <see cref="TableSasBuilder"/> instance scoped to the current account. /// </summary> /// <param name="permissions"><see cref="TableAccountSasPermissions"/> containing the allowed permissions.</param> /// <param name="resourceTypes"><see cref="TableAccountSasResourceTypes"/> containing the accessible resource types.</param> /// <param name="expiresOn">The time at which the shared access signature becomes invalid.</param> /// <returns>An instance of <see cref="TableAccountSasBuilder"/>.</returns> public virtual TableAccountSasBuilder GetSasBuilder(TableAccountSasPermissions permissions, TableAccountSasResourceTypes resourceTypes, DateTimeOffset expiresOn) { return new TableAccountSasBuilder(permissions, resourceTypes, expiresOn) { Version = _version }; } /// <summary> /// Gets a <see cref="TableAccountSasBuilder"/> 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="resourceTypes"><see cref="TableAccountSasResourceTypes"/> containing the accessible resource types.</param> /// <param name="expiresOn">The time at which the shared access signature becomes invalid.</param> /// <returns>An instance of <see cref="TableAccountSasBuilder"/>.</returns> public virtual TableAccountSasBuilder GetSasBuilder(string rawPermissions, TableAccountSasResourceTypes resourceTypes, DateTimeOffset expiresOn) { return new TableAccountSasBuilder(rawPermissions, resourceTypes, expiresOn) { Version = _version }; } public virtual TableClient GetTableClient(string tableName) { Argument.AssertNotNull(tableName, nameof(tableName)); return new TableClient(tableName, _tableOperations, _version, _diagnostics, _isPremiumEndpoint); } /// <summary> /// Gets a list of tables from the storage account. /// </summary> /// <param name="filter">Returns only tables that satisfy the specified filter.</param> /// <param name="maxPerPage">The maximum number of tables that will be returned per page.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns></returns> public virtual AsyncPageable<TableItem> GetTablesAsync(string filter = null, int? maxPerPage = null, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(GetTables)}"); scope.Start(); try { return PageableHelpers.CreateAsyncEnumerable(async _ => { var response = await _tableOperations.QueryAsync( null, null, new QueryOptions() { Filter = filter, Select = null, Top = maxPerPage, Format = _format }, cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value, response.Headers.XMsContinuationNextTableName, response.GetRawResponse()); }, async (nextLink, _) => { var response = await _tableOperations.QueryAsync( null, nextTableName: nextLink, new QueryOptions() { Filter = filter, Select = null, Top = maxPerPage, Format = _format }, cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value, response.Headers.XMsContinuationNextTableName, response.GetRawResponse()); }); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Gets a list of tables from the storage account. /// </summary> /// <param name="filter">Returns only tables or entities that satisfy the specified filter.</param> /// <param name="maxPerPage">The maximum number of tables that will be returned per page.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns></returns> public virtual Pageable<TableItem> GetTables(string filter = null, int? maxPerPage = null, CancellationToken cancellationToken = default) { return PageableHelpers.CreateEnumerable(_ => { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(GetTables)}"); scope.Start(); try { var response = _tableOperations.Query( null, null, new QueryOptions() { Filter = filter, Select = null, Top = maxPerPage, Format = _format }, cancellationToken); return Page.FromValues(response.Value.Value, response.Headers.XMsContinuationNextTableName, response.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } }, (nextLink, _) => { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(GetTables)}"); scope.Start(); try { var response = _tableOperations.Query( null, nextTableName: nextLink, new QueryOptions() { Filter = filter, Select = null, Top = maxPerPage, Format = _format }, cancellationToken); return Page.FromValues(response.Value.Value, response.Headers.XMsContinuationNextTableName, response.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } }); } /// <summary> /// Creates a table in the storage account. /// </summary> /// <param name="tableName">The table name to create.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns>A <see cref="Response{TableItem}"/> containing properties of the table.</returns> public virtual Response<TableItem> CreateTable(string tableName, CancellationToken cancellationToken = default) { Argument.AssertNotNull(tableName, nameof(tableName)); using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(CreateTable)}"); scope.Start(); try { var response = _tableOperations.Create(new TableProperties() { TableName = tableName }, 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 a table in the storage account. /// </summary> /// <param name="tableName">The table name to create.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns>A <see cref="Response{TableItem}"/> containing properties of the table.</returns> public virtual async Task<Response<TableItem>> CreateTableAsync(string tableName, CancellationToken cancellationToken = default) { Argument.AssertNotNull(tableName, nameof(tableName)); using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(CreateTable)}"); scope.Start(); try { var response = await _tableOperations.CreateAsync(new TableProperties() { TableName = tableName }, 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 a table in the storage account. /// </summary> /// <param name="tableName">The table name to create.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <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> CreateTableIfNotExists(string tableName, CancellationToken cancellationToken = default) { Argument.AssertNotNull(tableName, nameof(tableName)); using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(CreateTableIfNotExists)}"); scope.Start(); try { var response = _tableOperations.Create(new TableProperties() { TableName = tableName }, 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 a table in the storage account. /// </summary> /// <param name="tableName">The table name to create.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <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>> CreateTableIfNotExistsAsync(string tableName, CancellationToken cancellationToken = default) { Argument.AssertNotNull(tableName, nameof(tableName)); using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(CreateTableIfNotExists)}"); scope.Start(); try { var response = await _tableOperations.CreateAsync(new TableProperties() { TableName = tableName }, 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 a table in the storage account. /// </summary> /// <param name="tableName">The table name to create.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns></returns> public virtual Response DeleteTable(string tableName, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(DeleteTable)}"); scope.Start(); try { return _tableOperations.Delete(tableName, null, cancellationToken: cancellationToken); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Deletes a table in the storage account. /// </summary> /// <param name="tableName">The table name to create.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns></returns> public virtual async Task<Response> DeleteTableAsync(string tableName, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(DeleteTable)}"); scope.Start(); try { return await _tableOperations.DeleteAsync(tableName, null, cancellationToken: cancellationToken).ConfigureAwait(false); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> Sets properties for an account's Table service endpoint, including properties for Analytics and CORS (Cross-Origin Resource Sharing) rules. </summary> /// <param name="properties"> The Table Service properties. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response SetProperties(TableServiceProperties properties, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(SetProperties)}"); scope.Start(); try { return _serviceOperations.SetProperties(properties, cancellationToken: cancellationToken); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> Sets properties for an account's Table service endpoint, including properties for Analytics and CORS (Cross-Origin Resource Sharing) rules. </summary> /// <param name="properties"> The Table Service properties. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<Response> SetPropertiesAsync(TableServiceProperties properties, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(SetProperties)}"); scope.Start(); try { return await _serviceOperations.SetPropertiesAsync(properties, cancellationToken: cancellationToken).ConfigureAwait(false); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> Gets the properties of an account's Table service, including properties for Analytics and CORS (Cross-Origin Resource Sharing) rules. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response<TableServiceProperties> GetProperties(CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(GetProperties)}"); scope.Start(); try { var response = _serviceOperations.GetProperties(cancellationToken: cancellationToken); return Response.FromValue(response.Value, response.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> Gets the properties of an account's Table service, including properties for Analytics and CORS (Cross-Origin Resource Sharing) rules. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<Response<TableServiceProperties>> GetPropertiesAsync(CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(GetProperties)}"); scope.Start(); try { var response = await _serviceOperations.GetPropertiesAsync(cancellationToken: cancellationToken).ConfigureAwait(false); return Response.FromValue(response.Value, response.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> Retrieves statistics related to replication for the Table service. It is only available on the secondary location endpoint when read-access geo-redundant replication is enabled for the account. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<Response<TableServiceStatistics>> GetStatisticsAsync(CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(GetStatistics)}"); scope.Start(); try { var response = await _secondaryServiceOperations.GetStatisticsAsync(cancellationToken: cancellationToken).ConfigureAwait(false); return Response.FromValue(response.Value, response.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> Retrieves statistics related to replication for the Table service. It is only available on the secondary location endpoint when read-access geo-redundant replication is enabled for the account. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response<TableServiceStatistics> GetStatistics(CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableServiceClient)}.{nameof(GetStatistics)}"); scope.Start(); try { var response = _secondaryServiceOperations.GetStatistics(cancellationToken: cancellationToken); return Response.FromValue(response.Value, response.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } internal static bool IsPremiumEndpoint(Uri endpoint) { string absoluteUri = endpoint.OriginalString.ToLowerInvariant(); return (endpoint.Host.Equals("localhost", StringComparison.OrdinalIgnoreCase) && endpoint.Port != 10002) || absoluteUri.Contains(TableConstants.CosmosTableDomain) || absoluteUri.Contains(TableConstants.LegacyCosmosTableDomain); } } }
50.90942
234
0.62113
[ "MIT" ]
Aishwarya-C-S/azure-sdk-for-net
sdk/tables/Azure.Data.Tables/src/TableServiceClient.cs
28,102
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AdTool.Core { public enum LoginType { Default, GOV } }
14.5
33
0.704433
[ "Apache-2.0" ]
NaverCloudPlatform/ActiveDirectoryTool
AdTool.Core/DataModel/LoginType.cs
205
C#
// License text here using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using ZigBeeNet.DAO; using ZigBeeNet.ZCL.Protocol; using ZigBeeNet.ZCL.Field; using ZigBeeNet.ZCL.Clusters.Commissioning; /** *Commissioningcluster implementation (Cluster ID 0x0015). * * Code is auto-generated. Modifications may be overwritten! */ /* Autogenerated: 14.02.2019 - 18:41 */ namespace ZigBeeNet.ZCL.Clusters { public class ZclCommissioningCluster : ZclCluster { /** * The ZigBee Cluster Library Cluster ID */ public static ushort CLUSTER_ID = 0x0015; /** * The ZigBee Cluster Library Cluster Name */ public static string CLUSTER_NAME = "Commissioning"; // Attribute initialisation protected override Dictionary<ushort, ZclAttribute> InitializeAttributes() { Dictionary<ushort, ZclAttribute> attributeMap = new Dictionary<ushort, ZclAttribute>(0); return attributeMap; } /** * Default constructor to create a Commissioning cluster. * * @param zigbeeEndpoint the {@link ZigBeeEndpoint} */ public ZclCommissioningCluster(ZigBeeEndpoint zigbeeEndpoint) : base(zigbeeEndpoint, CLUSTER_ID, CLUSTER_NAME) { } /** * The Restart Device Command * * @param option {@link byte} Option * @param delay {@link byte} Delay * @param jitter {@link byte} Jitter * @return the Task<CommandResult> command result Task */ public Task<CommandResult> RestartDeviceCommand(byte option, byte delay, byte jitter) { RestartDeviceCommand command = new RestartDeviceCommand(); // Set the fields command.Option = option; command.Delay = delay; command.Jitter = jitter; return Send(command); } /** * The Save Startup Parameters Command * * @param option {@link byte} Option * @param index {@link byte} Index * @return the Task<CommandResult> command result Task */ public Task<CommandResult> SaveStartupParametersCommand(byte option, byte index) { SaveStartupParametersCommand command = new SaveStartupParametersCommand(); // Set the fields command.Option = option; command.Index = index; return Send(command); } /** * The Restore Startup Parameters Command * * @param option {@link byte} Option * @param index {@link byte} Index * @return the Task<CommandResult> command result Task */ public Task<CommandResult> RestoreStartupParametersCommand(byte option, byte index) { RestoreStartupParametersCommand command = new RestoreStartupParametersCommand(); // Set the fields command.Option = option; command.Index = index; return Send(command); } /** * The Reset Startup Parameters Command * * @param option {@link byte} Option * @param index {@link byte} Index * @return the Task<CommandResult> command result Task */ public Task<CommandResult> ResetStartupParametersCommand(byte option, byte index) { ResetStartupParametersCommand command = new ResetStartupParametersCommand(); // Set the fields command.Option = option; command.Index = index; return Send(command); } /** * The Restart Device Response Response * * @param status {@link byte} Status * @return the Task<CommandResult> command result Task */ public Task<CommandResult> RestartDeviceResponseResponse(byte status) { RestartDeviceResponseResponse command = new RestartDeviceResponseResponse(); // Set the fields command.Status = status; return Send(command); } /** * The Save Startup Parameters Response * * @param status {@link byte} Status * @return the Task<CommandResult> command result Task */ public Task<CommandResult> SaveStartupParametersResponse(byte status) { SaveStartupParametersResponse command = new SaveStartupParametersResponse(); // Set the fields command.Status = status; return Send(command); } /** * The Restore Startup Parameters Response * * @param status {@link byte} Status * @return the Task<CommandResult> command result Task */ public Task<CommandResult> RestoreStartupParametersResponse(byte status) { RestoreStartupParametersResponse command = new RestoreStartupParametersResponse(); // Set the fields command.Status = status; return Send(command); } /** * The Reset Startup Parameters Response * * @param status {@link byte} Status * @return the Task<CommandResult> command result Task */ public Task<CommandResult> ResetStartupParametersResponse(byte status) { ResetStartupParametersResponse command = new ResetStartupParametersResponse(); // Set the fields command.Status = status; return Send(command); } public override ZclCommand GetCommandFromId(int commandId) { switch (commandId) { case 0: // RESTART_DEVICE_COMMAND return new RestartDeviceCommand(); case 1: // SAVE_STARTUP_PARAMETERS_COMMAND return new SaveStartupParametersCommand(); case 2: // RESTORE_STARTUP_PARAMETERS_COMMAND return new RestoreStartupParametersCommand(); case 3: // RESET_STARTUP_PARAMETERS_COMMAND return new ResetStartupParametersCommand(); default: return null; } } public ZclCommand getResponseFromId(int commandId) { switch (commandId) { case 0: // RESTART_DEVICE_RESPONSE_RESPONSE return new RestartDeviceResponseResponse(); case 1: // SAVE_STARTUP_PARAMETERS_RESPONSE return new SaveStartupParametersResponse(); case 2: // RESTORE_STARTUP_PARAMETERS_RESPONSE return new RestoreStartupParametersResponse(); case 3: // RESET_STARTUP_PARAMETERS_RESPONSE return new ResetStartupParametersResponse(); default: return null; } } } }
30.312775
99
0.606598
[ "MIT" ]
lehn85/ZigbeeNet
src/ZigBeeNet/ZCL/Clusters/ZclCommissioningCluster.cs
6,883
C#
using LETS.Models; using Orchard.ContentManagement; using Orchard.ContentManagement.Handlers; using Orchard.Data; using Orchard.Localization; namespace LETS.Handlers { public class LETSSettingsPartHandler: ContentHandler { public Localizer T { get; set; } public LETSSettingsPartHandler(IRepository<LETSSettingsPartRecord> repository) { T = NullLocalizer.Instance; Filters.Add(new ActivatingFilter<LETSSettingsPart>("Site")); Filters.Add(StorageFilter.For(repository)); } protected override void GetItemMetadata(GetContentItemMetadataContext context) { if (context.ContentItem.ContentType != "Site") return; base.GetItemMetadata(context); context.Metadata.EditorGroupInfo.Add(new GroupInfo(T("LETS"))); } } }
32
86
0.671296
[ "BSD-3-Clause" ]
planetClaire/Orchard-LETS
src/Orchard.Web/Modules/LETS/Handlers/LETSSettingsPartHandler.cs
866
C#
#region Apache License Version 2.0 /*---------------------------------------------------------------- Copyright 2018 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md ----------------------------------------------------------------*/ #endregion Apache License Version 2.0 /*---------------------------------------------------------------- Copyright (C) 2018 Senparc 文件名:GroupMessageAPI.cs 文件功能描述:高级群发接口 创建标识:Senparc - 20150211 修改标识:Senparc - 20150303 修改描述:整理接口 修改标识:Senparc - 20150312 修改描述:开放代理请求超时时间 修改标识:Senparc - 20160718 修改描述:增加其接口的异步方法 修改标识:Senparc - 20170402 修改描述:v14.3.140 1、添加BaseGroupMessageDataByGroupId.send_ignore_reprint属性 2、优化代码 修改标识:Senparc - 20170707 修改描述:v14.5.1 完善异步方法async/await 修改标识:Senparc - 2017224 修改描述:v14.8.12 完成群发接口添加clientmsgid属性 修改标识:Senparc - 20180319 修改描述:v14.10.8 GroupMessageApi.SendGroupMessageByFilter() 方法修复判断错误 修改标识:Senparc - 20180507 修改描述:v14.12.4 删除群发接口 GroupMessageApi.DeleteSendMessage() 添加article_idx参数 修改标识:Senparc - 20180928 修改描述:增加GetSendSpeed,SetSendSpeed ----------------------------------------------------------------*/ /* API地址:http://mp.weixin.qq.com/wiki/15/5380a4e6f02f2ffdc7981a8ed7a40753.html */ using System; using System.Threading.Tasks; using Senparc.Weixin.Entities; using Senparc.CO2NET.Extensions; using Senparc.Weixin.MP.AdvancedAPIs.GroupMessage; using Senparc.Weixin.MP.CommonAPIs; using Senparc.Weixin.HttpUtility; using Senparc.NeuChar; namespace Senparc.Weixin.MP.AdvancedAPIs { /// <summary> /// 高级群发接口 /// </summary> public static class GroupMessageApi { //官方文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1481187827_i0l21 #region 同步方法 #region 根据分组或标签群发 /// <summary> /// 根据分组或标签进行群发【订阅号与服务号认证后均可用】 /// /// 请注意: /// 1、该接口暂时仅提供给已微信认证的服务号 /// 2、虽然开发者使用高级群发接口的每日调用限制为100次,但是用户每月只能接收4条,请小心测试 /// 3、无论在公众平台网站上,还是使用接口群发,用户每月只能接收4条群发消息,多于4条的群发将对该用户发送失败。 /// 4、群发视频时需要先调用GetVideoMediaIdResult接口获取专用的MediaId然后进行群发 /// /// </summary> /// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param> /// <param name="groupId">群发到的分组的group_id,参见用户管理中用户分组接口,若is_to_all值为true,可不填写group_id;如果groupId和tagId同时填写,优先使用groupId;groupId和tagId最多只能使用一个</param> /// <param name="tagId">群发到的标签的tag_id,若is_to_all值为true,可不填写tag_id;如果groupId和tagId同时填写,优先使用groupId;groupId和tagId最多只能使用一个</param> /// <param name="value">群发媒体文件时传入mediaId,群发文本消息时传入content,群发卡券时传入cardId</param> /// <param name="type"></param> /// <param name="isToAll">用于设定是否向全部用户发送,值为true或false,选择true该消息群发给所有用户,选择false可根据group_id发送给指定群组的用户</param> /// <param name="sendIgnoreReprint">待群发的文章被判定为转载时,是否继续群发</param> /// <param name="clientmsgid">开发者侧群发msgid,长度限制64字节,如不填,则后台默认以群发范围和群发内容的摘要值做为clientmsgid</param> /// <param name="timeOut">代理请求超时时间(毫秒)</param> /// <returns></returns> [ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "GroupMessageApi.SendGroupMessageByFilter", true)] private static SendResult SendGroupMessageByFilter(string accessTokenOrAppId, string groupId, string tagId, string value, GroupMessageType type, bool isToAll = false, bool sendIgnoreReprint = false, string clientmsgid = null, int timeOut = Config.TIME_OUT) { return ApiHandlerWapper.TryCommonApi(accessToken => { string urlFormat = Config.ApiMpHost + "/cgi-bin/message/mass/sendall?access_token={0}"; BaseGroupMessageDataByFilter baseData = null; BaseGroupMessageByFilter filter = null; if (!groupId.IsNullOrEmpty()) { filter = new GroupMessageByGroupId() { group_id = groupId, is_to_all = isToAll, }; } else { filter = new GroupMessageByTagId() { tag_id = tagId, is_to_all = isToAll, }; } switch (type) { case GroupMessageType.image: baseData = new GroupMessageByFilter_ImageData() { filter = filter, image = new GroupMessageByGroupId_MediaId() { media_id = value }, msgtype = "image" }; break; case GroupMessageType.voice: baseData = new GroupMessageByFilter_VoiceData() { filter = filter, voice = new GroupMessageByGroupId_MediaId() { media_id = value }, msgtype = "voice" }; break; case GroupMessageType.mpnews: baseData = new GroupMessageByFilter_MpNewsData() { filter = filter, mpnews = new GroupMessageByGroupId_MediaId() { media_id = value }, msgtype = "mpnews" }; break; case GroupMessageType.video: baseData = new GroupMessageByFilter_MpVideoData() { filter = filter, mpvideo = new GroupMessageByGroupId_MediaId() { media_id = value }, msgtype = "mpvideo" }; break; case GroupMessageType.wxcard: baseData = new GroupMessageByFilter_WxCardData() { filter = filter, wxcard = new GroupMessageByGroupId_WxCard() { card_id = value }, msgtype = "wxcard" }; break; case GroupMessageType.text: baseData = new GroupMessageByFilter_TextData() { filter = filter, text = new GroupMessageByGroupId_Content() { content = value }, msgtype = "text" }; break; default: throw new Exception("参数错误。"); //break; } baseData.send_ignore_reprint = sendIgnoreReprint ? 0 : 1;//待群发的文章被判定为转载时,是否继续群发 baseData.clientmsgid = clientmsgid; return CommonJsonSend.Send<SendResult>(accessToken, urlFormat, baseData, timeOut: timeOut); }, accessTokenOrAppId); } /// <summary> /// 根据[分组]进行群发【订阅号与服务号认证后均可用】 /// /// 请注意: /// 1、该接口暂时仅提供给已微信认证的服务号 /// 2、虽然开发者使用高级群发接口的每日调用限制为100次,但是用户每月只能接收4条,请小心测试 /// 3、无论在公众平台网站上,还是使用接口群发,用户每月只能接收4条群发消息,多于4条的群发将对该用户发送失败。 /// 4、群发视频时需要先调用GetVideoMediaIdResult接口获取专用的MediaId然后进行群发 /// /// </summary> /// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param> /// <param name="groupId">群发到的分组的group_id,参见用户管理中用户分组接口,若is_to_all值为true,可不填写group_id;如果groupId和tagId同时填写,优先使用groupId;groupId和tagId最多只能使用一个</param> /// <param name="value">群发媒体文件时传入mediaId,群发文本消息时传入content,群发卡券时传入cardId</param> /// <param name="type"></param> /// <param name="isToAll">用于设定是否向全部用户发送,值为true或false,选择true该消息群发给所有用户,选择false可根据group_id发送给指定群组的用户</param> /// <param name="sendIgnoreReprint">待群发的文章被判定为转载时,是否继续群发</param> /// <param name="clientmsgid">开发者侧群发msgid,长度限制64字节,如不填,则后台默认以群发范围和群发内容的摘要值做为clientmsgid</param> /// <param name="timeOut">代理请求超时时间(毫秒)</param> /// <returns></returns> [ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "GroupMessageApi.SendGroupMessageByGroupId", true)] public static SendResult SendGroupMessageByGroupId(string accessTokenOrAppId, string groupId, string value, GroupMessageType type, bool isToAll = false, bool sendIgnoreReprint = false, string clientmsgid = null, int timeOut = Config.TIME_OUT) { return SendGroupMessageByFilter(accessTokenOrAppId, groupId, null, value, type, isToAll, sendIgnoreReprint, clientmsgid, timeOut); } /// <summary> /// 根据[标签]进行群发【订阅号与服务号认证后均可用】 /// /// 请注意: /// 1、该接口暂时仅提供给已微信认证的服务号 /// 2、虽然开发者使用高级群发接口的每日调用限制为100次,但是用户每月只能接收4条,请小心测试 /// 3、无论在公众平台网站上,还是使用接口群发,用户每月只能接收4条群发消息,多于4条的群发将对该用户发送失败。 /// 4、群发视频时需要先调用GetVideoMediaIdResult接口获取专用的MediaId然后进行群发 /// /// </summary> /// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param> /// <param name="tagId">群发到的标签的tag_id,若is_to_all值为true,可不填写tag_id</param> /// <param name="value">群发媒体文件时传入mediaId,群发文本消息时传入content,群发卡券时传入cardId</param> /// <param name="type"></param> /// <param name="isToAll">用于设定是否向全部用户发送,值为true或false,选择true该消息群发给所有用户,选择false可根据group_id发送给指定群组的用户</param> /// <param name="sendIgnoreReprint">待群发的文章被判定为转载时,是否继续群发</param> /// <param name="clientmsgid">开发者侧群发msgid,长度限制64字节,如不填,则后台默认以群发范围和群发内容的摘要值做为clientmsgid</param> /// <param name="timeOut">代理请求超时时间(毫秒)</param> /// <returns></returns> [ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "GroupMessageApi.SendGroupMessageByTagId", true)] public static SendResult SendGroupMessageByTagId(string accessTokenOrAppId, string tagId, string value, GroupMessageType type, bool isToAll = false, bool sendIgnoreReprint = false, string clientmsgid = null, int timeOut = Config.TIME_OUT) { return SendGroupMessageByFilter(accessTokenOrAppId, null, tagId, value, type, isToAll, sendIgnoreReprint, clientmsgid, timeOut); } #endregion /// <summary> /// 根据OpenId进行群发【订阅号不可用,服务号认证后可用】 /// </summary> /// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param> /// <param name="value">群发媒体文件时传入mediaId,群发文本消息时传入content,群发卡券时传入cardId</param> /// <param name="type"></param> /// <param name="openIds">openId字符串数组</param> /// <param name="clientmsgid">开发者侧群发msgid,长度限制64字节,如不填,则后台默认以群发范围和群发内容的摘要值做为clientmsgid</param> /// <param name="timeOut">代理请求超时时间(毫秒)</param> /// <returns></returns> [ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "GroupMessageApi.SendGroupMessageByOpenId", true)] public static SendResult SendGroupMessageByOpenId(string accessTokenOrAppId, GroupMessageType type, string value, string clientmsgid = null, int timeOut = Config.TIME_OUT, params string[] openIds) { return ApiHandlerWapper.TryCommonApi(accessToken => { string urlFormat = Config.ApiMpHost + "/cgi-bin/message/mass/send?access_token={0}"; BaseGroupMessageDataByOpenId baseData = null; switch (type) { case GroupMessageType.image: baseData = new GroupMessageByOpenId_ImageData() { touser = openIds, image = new GroupMessageByOpenId_MediaId() { media_id = value }, msgtype = "image" }; break; case GroupMessageType.voice: baseData = new GroupMessageByOpenId_VoiceData() { touser = openIds, voice = new GroupMessageByOpenId_MediaId() { media_id = value }, msgtype = "voice" }; break; case GroupMessageType.mpnews: baseData = new GroupMessageByOpenId_MpNewsData() { touser = openIds, mpnews = new GroupMessageByOpenId_MediaId() { media_id = value }, msgtype = "mpnews" }; break; case GroupMessageType.wxcard: baseData = new GroupMessageByOpenId_WxCardData() { touser = openIds, wxcard = new GroupMessageByOpenId_WxCard() { card_id = value }, msgtype = "wxcard" }; break; case GroupMessageType.video: throw new Exception("发送视频信息请使用SendVideoGroupMessageByOpenId方法。"); break; case GroupMessageType.text: baseData = new GroupMessageByOpenId_TextData() { touser = openIds, text = new GroupMessageByOpenId_Content() { content = value }, msgtype = "text" }; break; default: throw new Exception("参数错误。"); break; } baseData.clientmsgid = clientmsgid; return CommonJsonSend.Send<SendResult>(accessToken, urlFormat, baseData, timeOut: timeOut); }, accessTokenOrAppId); } /// <summary> /// 根据OpenID列表群发视频消息【订阅号不可用,服务号认证后可用】 /// 注意:群发视频时需要先调用GetVideoMediaIdResult接口获取专用的MediaId然后进行群发 /// </summary> /// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param> /// <param name="title"></param> /// <param name="mediaId"></param> /// <param name="clientmsgid">开发者侧群发msgid,长度限制64字节,如不填,则后台默认以群发范围和群发内容的摘要值做为clientmsgid</param> /// <param name="openIds">openId字符串数组</param> /// <param name="description"></param> /// <param name="timeOut">代理请求超时时间(毫秒)</param> /// <returns></returns> [ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "GroupMessageApi.SendVideoGroupMessageByOpenId", true)] public static SendResult SendVideoGroupMessageByOpenId(string accessTokenOrAppId, string title, string description, string mediaId, string clientmsgid = null, int timeOut = Config.TIME_OUT, params string[] openIds) { return ApiHandlerWapper.TryCommonApi(accessToken => { string urlFormat = Config.ApiMpHost + "/cgi-bin/message/mass/send?access_token={0}"; BaseGroupMessageDataByOpenId baseData = new GroupMessageByOpenId_MpVideoData() { touser = openIds, video = new GroupMessageByOpenId_Video() { title = title, description = description, media_id = mediaId }, msgtype = "mpvideo" }; baseData.clientmsgid = clientmsgid; return CommonJsonSend.Send<SendResult>(accessToken, urlFormat, baseData, timeOut: timeOut); }, accessTokenOrAppId); } /// <summary> /// 删除群发消息 /// </summary> /// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param> /// <param name="msgId">发送出去的消息ID</param> /// <param name="articleIdx">(非必填)要删除的文章在图文消息中的位置,第一篇编号为1,该字段不填或填0会删除全部文章</param> /// <param name="timeOut">代理请求超时时间(毫秒)</param> /// <returns></returns> [ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "GroupMessageApi.DeleteSendMessage", true)] public static WxJsonResult DeleteSendMessage(string accessTokenOrAppId, string msgId, int? articleIdx, int timeOut = Config.TIME_OUT) { return ApiHandlerWapper.TryCommonApi(accessToken => { //官方API地址为https://api.weixin.qq.com//cgi-bin/message/mass/delete?access_token={0},应该是多了一个/ string urlFormat = Config.ApiMpHost + "/cgi-bin/message/mass/delete?access_token={0}"; var data = new { msg_id = msgId, article_idx = articleIdx }; return CommonJsonSend.Send<WxJsonResult>(accessToken, urlFormat, data, timeOut: timeOut); }, accessTokenOrAppId); } /// <summary> /// 预览接口【订阅号与服务号认证后均可用】 /// 注意:openId与wxName两者任选其一,同时传入以wxName优先 /// </summary> /// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param> /// <param name="value">群发媒体消息时为media_id,群发文本信息为content</param> /// <param name="type"></param> /// <param name="openId">接收消息用户对应该公众号的openid</param> /// <param name="wxName">接收消息用户的微信号</param> /// <param name="timeOut">代理请求超时时间(毫秒)</param> /// <returns></returns> [ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "GroupMessageApi.SendGroupMessagePreview", true)] public static SendResult SendGroupMessagePreview(string accessTokenOrAppId, GroupMessageType type, string value, string openId, string wxName = null, int timeOut = Config.TIME_OUT) { return ApiHandlerWapper.TryCommonApi(accessToken => { string urlFormat = Config.ApiMpHost + "/cgi-bin/message/mass/preview?access_token={0}"; BaseGroupMessageDataPreview baseData = null; switch (type) { case GroupMessageType.image: baseData = new GroupMessagePreview_ImageData() { touser = openId, towxname = wxName, image = new GroupMessagePreview_MediaId() { media_id = value }, msgtype = "image" }; break; case GroupMessageType.voice: baseData = new GroupMessagePreview_VoiceData() { touser = openId, towxname = wxName, voice = new GroupMessagePreview_MediaId() { media_id = value }, msgtype = "voice" }; break; case GroupMessageType.mpnews: baseData = new GroupMessagePreview_MpNewsData() { touser = openId, towxname = wxName, mpnews = new GroupMessagePreview_MediaId() { media_id = value }, msgtype = "mpnews" }; break; case GroupMessageType.video: baseData = new GroupMessagePreview_MpVideoData() { touser = openId, towxname = wxName, mpvideo = new GroupMessagePreview_MediaId() { media_id = value }, msgtype = "mpvideo" }; break; case GroupMessageType.text: baseData = new GroupMessagePreview_TextData() { touser = openId, towxname = wxName, text = new GroupMessagePreview_Content() { content = value }, msgtype = "text" }; break; case GroupMessageType.wxcard: throw new Exception("发送卡券息请使用WxCardGroupMessagePreview方法。"); default: throw new Exception("参数错误。"); } return CommonJsonSend.Send<SendResult>(accessToken, urlFormat, baseData, timeOut: timeOut); }, accessTokenOrAppId); } /// <summary> /// 预览卡券接口 /// </summary> /// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param> /// <param name="cardId"></param> /// <param name="code"></param> /// <param name="openId"></param> /// <param name="wxName"></param> /// <param name="timestamp"></param> /// <param name="signature"></param> /// <param name="timeOut"></param> /// <returns></returns> [ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "GroupMessageApi.WxCardGroupMessagePreview", true)] public static SendResult WxCardGroupMessagePreview(string accessTokenOrAppId, string cardId, string code, string openId, string wxName, string timestamp, string signature, int timeOut = Config.TIME_OUT) { return ApiHandlerWapper.TryCommonApi(accessToken => { string urlFormat = Config.ApiMpHost + "/cgi-bin/message/mass/preview?access_token={0}"; BaseGroupMessageDataPreview baseData = new GroupMessagePreview_WxCardData() { touser = openId, towxname = wxName, wxcard = new GroupMessagePreview_WxCard() { card_id = cardId, card_ext = string.Format("\"code\":\"{0}\",\"openid\":\"{1}\",\"timestamp\":\"{2}\",\"signature\":\"{3}\"", code, openId, timestamp, signature) }, msgtype = "wxcard" }; return CommonJsonSend.Send<SendResult>(accessToken, urlFormat, baseData, timeOut: timeOut); }, accessTokenOrAppId); } /// <summary> /// 查询群发消息发送状态【订阅号与服务号认证后均可用】 /// </summary> /// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param> /// <param name="msgId">群发消息后返回的消息id</param> /// <param name="timeOut">代理请求超时时间(毫秒)</param> /// <returns></returns> [ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "GroupMessageApi.GetGroupMessageResult", true)] public static GetSendResult GetGroupMessageResult(string accessTokenOrAppId, string msgId, int timeOut = Config.TIME_OUT) { return ApiHandlerWapper.TryCommonApi(accessToken => { string urlFormat = Config.ApiMpHost + "/cgi-bin/message/mass/get?access_token={0}"; var data = new { msg_id = msgId }; return CommonJsonSend.Send<GetSendResult>(accessToken, urlFormat, data, timeOut: timeOut); }, accessTokenOrAppId); } /// <summary> /// 获取视频群发用的MediaId /// </summary> /// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param> /// <param name="mediaId"></param> /// <param name="title"></param> /// <param name="description"></param> /// <param name="timeOut"></param> /// <returns></returns> [ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "GroupMessageApi.GetVideoMediaIdResult", true)] public static VideoMediaIdResult GetVideoMediaIdResult(string accessTokenOrAppId, string mediaId, string title, string description, int timeOut = Config.TIME_OUT) { return ApiHandlerWapper.TryCommonApi(accessToken => { string url = string.Format("https://file.api.weixin.qq.com/cgi-bin/media/uploadvideo?access_token={0}", accessToken.AsUrlData()); var data = new { media_id = mediaId, title = title, description = description }; return CommonJsonSend.Send<VideoMediaIdResult>(null, url, data, CommonJsonSendType.POST, timeOut, true); }, accessTokenOrAppId); } /// <summary> /// 获取群发速度 /// </summary> /// <param name="accessTokenOrAppId"></param> /// <param name="timeOut"></param> /// <returns></returns> [ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "GroupMessageApi.GetSendSpeed", true)] public static GetSpeedResult GetSendSpeed(string accessTokenOrAppId, int timeOut = Config.TIME_OUT) { return ApiHandlerWapper.TryCommonApi(accessToken => { string urlFormat = Config.ApiMpHost + "/cgi-bin/message/mass/speed/get?access_token={0}"; return CommonJsonSend.Send<GetSpeedResult>(null, urlFormat, null, CommonJsonSendType.POST, timeOut, true); }, accessTokenOrAppId); } /// <summary> /// 设置群发速度 /// </summary> /// <param name="accessTokenOrAppId"></param> /// <param name="speed">群发速度的级别</param> /// <param name="timeOut"></param> /// <returns></returns> [ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "GroupMessageApi.SetSendSpeed", true)] public static WxJsonResult SetSendSpeed(string accessTokenOrAppId, int speed, int timeOut = Config.TIME_OUT) { return ApiHandlerWapper.TryCommonApi(accessToken => { string urlFormat = Config.ApiMpHost + "/cgi-bin/message/mass/speed/set?access_token={0}"; var data = new { speed = speed }; return CommonJsonSend.Send<WxJsonResult>(null, urlFormat, data, CommonJsonSendType.POST, timeOut, true); }, accessTokenOrAppId); } #endregion #if !NET35 && !NET40 #region 异步方法 #region 根据分组或标签群发 /// <summary> /// 【异步方法】根据分组进行群发【订阅号与服务号认证后均可用】 /// /// 请注意: /// 1、该接口暂时仅提供给已微信认证的服务号 /// 2、虽然开发者使用高级群发接口的每日调用限制为100次,但是用户每月只能接收4条,请小心测试 /// 3、无论在公众平台网站上,还是使用接口群发,用户每月只能接收4条群发消息,多于4条的群发将对该用户发送失败。 /// 4、群发视频时需要先调用GetVideoMediaIdResult接口获取专用的MediaId然后进行群发 /// /// </summary> /// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param> /// <param name="groupId">群发到的分组的group_id,参见用户管理中用户分组接口,若is_to_all值为true,可不填写group_id;如果groupId和tagId同时填写,优先使用groupId;groupId和tagId最多只能使用一个</param> /// <param name="tagId">群发到的标签的tag_id,若is_to_all值为true,可不填写tag_id;如果groupId和tagId同时填写,优先使用groupId;groupId和tagId最多只能使用一个</param> /// <param name="value">群发媒体文件时传入mediaId,群发文本消息时传入content,群发卡券时传入cardId</param> /// <param name="type"></param> /// <param name="isToAll">用于设定是否向全部用户发送,值为true或false,选择true该消息群发给所有用户,选择false可根据group_id发送给指定群组的用户</param> /// <param name="sendIgnoreReprint">待群发的文章被判定为转载时,是否继续群发</param> /// <param name="clientmsgid">开发者侧群发msgid,长度限制64字节,如不填,则后台默认以群发范围和群发内容的摘要值做为clientmsgid</param> /// <param name="timeOut">代理请求超时时间(毫秒)</param> /// <returns></returns> [ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "GroupMessageApi.SendGroupMessageByFilterAsync", true)] private static async Task<SendResult> SendGroupMessageByFilterAsync(string accessTokenOrAppId, string groupId, string tagId, string value, GroupMessageType type, bool isToAll = false, bool sendIgnoreReprint = false, string clientmsgid = null, int timeOut = Config.TIME_OUT) { return await ApiHandlerWapper.TryCommonApiAsync(async accessToken => { string urlFormat = Config.ApiMpHost + "/cgi-bin/message/mass/sendall?access_token={0}"; BaseGroupMessageDataByFilter baseData = null; BaseGroupMessageByFilter filter = null; if (!groupId.IsNullOrEmpty()) { filter = new GroupMessageByGroupId() { group_id = groupId, is_to_all = isToAll, }; } else { filter = new GroupMessageByTagId() { tag_id = tagId, is_to_all = isToAll, }; } switch (type) { case GroupMessageType.image: baseData = new GroupMessageByFilter_ImageData() { filter = filter, image = new GroupMessageByGroupId_MediaId() { media_id = value }, msgtype = "image" }; break; case GroupMessageType.voice: baseData = new GroupMessageByFilter_VoiceData() { filter = filter, voice = new GroupMessageByGroupId_MediaId() { media_id = value }, msgtype = "voice" }; break; case GroupMessageType.mpnews: baseData = new GroupMessageByFilter_MpNewsData() { filter = filter, mpnews = new GroupMessageByGroupId_MediaId() { media_id = value }, msgtype = "mpnews" }; break; case GroupMessageType.video: baseData = new GroupMessageByFilter_MpVideoData() { filter = filter, mpvideo = new GroupMessageByGroupId_MediaId() { media_id = value }, msgtype = "mpvideo" }; break; case GroupMessageType.wxcard: baseData = new GroupMessageByFilter_WxCardData() { filter = filter, wxcard = new GroupMessageByGroupId_WxCard() { card_id = value }, msgtype = "wxcard" }; break; case GroupMessageType.text: baseData = new GroupMessageByFilter_TextData() { filter = filter, text = new GroupMessageByGroupId_Content() { content = value }, msgtype = "text" }; break; default: throw new Exception("参数错误。"); //break; } baseData.send_ignore_reprint = sendIgnoreReprint ? 0 : 1;//待群发的文章被判定为转载时,是否继续群发 baseData.clientmsgid = clientmsgid; return await Senparc.Weixin.CommonAPIs.CommonJsonSend.SendAsync<SendResult>(accessToken, urlFormat, baseData, timeOut: timeOut); }, accessTokenOrAppId); } /// <summary> /// 【异步方法】根据[分组]进行群发【订阅号与服务号认证后均可用】 /// /// 请注意: /// 1、该接口暂时仅提供给已微信认证的服务号 /// 2、虽然开发者使用高级群发接口的每日调用限制为100次,但是用户每月只能接收4条,请小心测试 /// 3、无论在公众平台网站上,还是使用接口群发,用户每月只能接收4条群发消息,多于4条的群发将对该用户发送失败。 /// 4、群发视频时需要先调用GetVideoMediaIdResult接口获取专用的MediaId然后进行群发 /// /// </summary> /// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param> /// <param name="groupId">群发到的分组的group_id,参见用户管理中用户分组接口,若is_to_all值为true,可不填写group_id;如果groupId和tagId同时填写,优先使用groupId;groupId和tagId最多只能使用一个</param> /// <param name="value">群发媒体文件时传入mediaId,群发文本消息时传入content,群发卡券时传入cardId</param> /// <param name="type"></param> /// <param name="isToAll">用于设定是否向全部用户发送,值为true或false,选择true该消息群发给所有用户,选择false可根据group_id发送给指定群组的用户</param> /// <param name="sendIgnoreReprint">待群发的文章被判定为转载时,是否继续群发</param> /// <param name="clientmsgid">开发者侧群发msgid,长度限制64字节,如不填,则后台默认以群发范围和群发内容的摘要值做为clientmsgid</param> /// <param name="timeOut">代理请求超时时间(毫秒)</param> /// <returns></returns> [ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "GroupMessageApi.SendGroupMessageByGroupIdAsync", true)] public static async Task<SendResult> SendGroupMessageByGroupIdAsync(string accessTokenOrAppId, string groupId, string value, GroupMessageType type, bool isToAll = false, bool sendIgnoreReprint = false, string clientmsgid = null, int timeOut = Config.TIME_OUT) { return await SendGroupMessageByFilterAsync(accessTokenOrAppId, groupId, null, value, type, isToAll, sendIgnoreReprint, clientmsgid, timeOut); } /// <summary> /// 【异步方法】根据[标签]进行群发【订阅号与服务号认证后均可用】 /// /// 请注意: /// 1、该接口暂时仅提供给已微信认证的服务号 /// 2、虽然开发者使用高级群发接口的每日调用限制为100次,但是用户每月只能接收4条,请小心测试 /// 3、无论在公众平台网站上,还是使用接口群发,用户每月只能接收4条群发消息,多于4条的群发将对该用户发送失败。 /// 4、群发视频时需要先调用GetVideoMediaIdResult接口获取专用的MediaId然后进行群发 /// /// </summary> /// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param> /// <param name="tagId">群发到的标签的tag_id,若is_to_all值为true,可不填写tag_id</param> /// <param name="value">群发媒体文件时传入mediaId,群发文本消息时传入content,群发卡券时传入cardId</param> /// <param name="type"></param> /// <param name="isToAll">用于设定是否向全部用户发送,值为true或false,选择true该消息群发给所有用户,选择false可根据group_id发送给指定群组的用户</param> /// <param name="sendIgnoreReprint">待群发的文章被判定为转载时,是否继续群发</param> /// <param name="clientmsgid">开发者侧群发msgid,长度限制64字节,如不填,则后台默认以群发范围和群发内容的摘要值做为clientmsgid</param> /// <param name="timeOut">代理请求超时时间(毫秒)</param> /// <returns></returns> [ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "GroupMessageApi.SendGroupMessageByTagIdAsync", true)] public static async Task<SendResult> SendGroupMessageByTagIdAsync(string accessTokenOrAppId, string tagId, string value, GroupMessageType type, bool isToAll = false, bool sendIgnoreReprint = false, string clientmsgid = null, int timeOut = Config.TIME_OUT) { return await SendGroupMessageByFilterAsync(accessTokenOrAppId, null, tagId, value, type, isToAll, sendIgnoreReprint, clientmsgid, timeOut); } #endregion /// <summary> /// 【异步方法】根据OpenId进行群发【订阅号不可用,服务号认证后可用】 /// </summary> /// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param> /// <param name="value">群发媒体文件时传入mediaId,群发文本消息时传入content,群发卡券时传入cardId</param> /// <param name="type"></param> /// <param name="openIds">openId字符串数组</param> /// <param name="clientmsgid">开发者侧群发msgid,长度限制64字节,如不填,则后台默认以群发范围和群发内容的摘要值做为clientmsgid</param> /// <param name="timeOut">代理请求超时时间(毫秒)</param> /// <returns></returns> [ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "GroupMessageApi.SendGroupMessageByOpenIdAsync", true)] public static async Task<SendResult> SendGroupMessageByOpenIdAsync(string accessTokenOrAppId, GroupMessageType type, string value, string clientmsgid = null, int timeOut = Config.TIME_OUT, params string[] openIds) { return await ApiHandlerWapper.TryCommonApiAsync(async accessToken => { string urlFormat = Config.ApiMpHost + "/cgi-bin/message/mass/send?access_token={0}"; BaseGroupMessageDataByOpenId baseData = null; switch (type) { case GroupMessageType.image: baseData = new GroupMessageByOpenId_ImageData() { touser = openIds, image = new GroupMessageByOpenId_MediaId() { media_id = value }, msgtype = "image" }; break; case GroupMessageType.voice: baseData = new GroupMessageByOpenId_VoiceData() { touser = openIds, voice = new GroupMessageByOpenId_MediaId() { media_id = value }, msgtype = "voice" }; break; case GroupMessageType.mpnews: baseData = new GroupMessageByOpenId_MpNewsData() { touser = openIds, mpnews = new GroupMessageByOpenId_MediaId() { media_id = value }, msgtype = "mpnews" }; break; case GroupMessageType.wxcard: baseData = new GroupMessageByOpenId_WxCardData() { touser = openIds, wxcard = new GroupMessageByOpenId_WxCard() { card_id = value }, msgtype = "wxcard" }; break; case GroupMessageType.video: throw new Exception("发送视频信息请使用SendVideoGroupMessageByOpenId方法。"); //break; case GroupMessageType.text: baseData = new GroupMessageByOpenId_TextData() { touser = openIds, text = new GroupMessageByOpenId_Content() { content = value }, msgtype = "text" }; break; default: throw new Exception("参数错误。"); //break; } baseData.clientmsgid = clientmsgid; return await Senparc.Weixin.CommonAPIs.CommonJsonSend.SendAsync<SendResult>(accessToken, urlFormat, baseData, timeOut: timeOut); }, accessTokenOrAppId); } /// <summary> /// 【异步方法】根据OpenID列表群发视频消息【订阅号不可用,服务号认证后可用】 /// 注意:群发视频时需要先调用GetVideoMediaIdResult接口获取专用的MediaId然后进行群发 /// </summary> /// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param> /// <param name="title"></param> /// <param name="mediaId"></param> /// <param name="clientmsgid">开发者侧群发msgid,长度限制64字节,如不填,则后台默认以群发范围和群发内容的摘要值做为clientmsgid</param> /// <param name="openIds">openId字符串数组</param> /// <param name="description"></param> /// <param name="timeOut">代理请求超时时间(毫秒)</param> /// <returns></returns> [ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "GroupMessageApi.SendVideoGroupMessageByOpenIdAsync", true)] public static async Task<SendResult> SendVideoGroupMessageByOpenIdAsync(string accessTokenOrAppId, string title, string description, string mediaId, string clientmsgid = null, int timeOut = Config.TIME_OUT, params string[] openIds) { return await ApiHandlerWapper.TryCommonApiAsync(async accessToken => { string urlFormat = Config.ApiMpHost + "/cgi-bin/message/mass/send?access_token={0}"; BaseGroupMessageDataByOpenId baseData = new GroupMessageByOpenId_MpVideoData() { touser = openIds, video = new GroupMessageByOpenId_Video() { title = title, description = description, media_id = mediaId }, msgtype = "mpvideo" }; baseData.clientmsgid = clientmsgid; return await Senparc.Weixin.CommonAPIs.CommonJsonSend.SendAsync<SendResult>(accessToken, urlFormat, baseData, timeOut: timeOut); }, accessTokenOrAppId); } /// <summary> /// 【异步方法】删除群发消息 /// </summary> /// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param> /// <param name="msgId">发送出去的消息ID</param> /// <param name="articleIdx">(非必填)要删除的文章在图文消息中的位置,第一篇编号为1,该字段不填或填0会删除全部文章</param> /// <param name="timeOut">代理请求超时时间(毫秒)</param> /// <returns></returns> [ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "GroupMessageApi.DeleteSendMessageAsync", true)] public static async Task<WxJsonResult> DeleteSendMessageAsync(string accessTokenOrAppId, string msgId, int? articleIdx, int timeOut = Config.TIME_OUT) { return await ApiHandlerWapper.TryCommonApiAsync(async accessToken => { //官方API地址为https://api.weixin.qq.com//cgi-bin/message/mass/delete?access_token={0},应该是多了一个/ string urlFormat = Config.ApiMpHost + "/cgi-bin/message/mass/delete?access_token={0}"; var data = new { msg_id = msgId, article_idx = articleIdx }; return await Senparc.Weixin.CommonAPIs.CommonJsonSend.SendAsync<WxJsonResult>(accessToken, urlFormat, data, timeOut: timeOut); }, accessTokenOrAppId); } /// <summary> /// 【异步方法】预览接口【订阅号与服务号认证后均可用】 /// 注意:openId与wxName两者任选其一,同时传入以wxName优先 /// </summary> /// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param> /// <param name="value">群发媒体消息时为media_id,群发文本信息为content</param> /// <param name="type"></param> /// <param name="openId">接收消息用户对应该公众号的openid</param> /// <param name="wxName">接收消息用户的微信号</param> /// <param name="timeOut">代理请求超时时间(毫秒)</param> /// <returns></returns> [ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "GroupMessageApi.SendGroupMessagePreviewAsync", true)] public static async Task<SendResult> SendGroupMessagePreviewAsync(string accessTokenOrAppId, GroupMessageType type, string value, string openId, string wxName = null, int timeOut = Config.TIME_OUT) { return await ApiHandlerWapper.TryCommonApiAsync(async accessToken => { string urlFormat = Config.ApiMpHost + "/cgi-bin/message/mass/preview?access_token={0}"; BaseGroupMessageDataPreview baseData = null; switch (type) { case GroupMessageType.image: baseData = new GroupMessagePreview_ImageData() { touser = openId, towxname = wxName, image = new GroupMessagePreview_MediaId() { media_id = value }, msgtype = "image" }; break; case GroupMessageType.voice: baseData = new GroupMessagePreview_VoiceData() { touser = openId, towxname = wxName, voice = new GroupMessagePreview_MediaId() { media_id = value }, msgtype = "voice" }; break; case GroupMessageType.mpnews: baseData = new GroupMessagePreview_MpNewsData() { touser = openId, towxname = wxName, mpnews = new GroupMessagePreview_MediaId() { media_id = value }, msgtype = "mpnews" }; break; case GroupMessageType.video: baseData = new GroupMessagePreview_MpVideoData() { touser = openId, towxname = wxName, mpvideo = new GroupMessagePreview_MediaId() { media_id = value }, msgtype = "mpvideo" }; break; case GroupMessageType.text: baseData = new GroupMessagePreview_TextData() { touser = openId, towxname = wxName, text = new GroupMessagePreview_Content() { content = value }, msgtype = "text" }; break; case GroupMessageType.wxcard: throw new Exception("发送卡券息请使用WxCardGroupMessagePreview方法。"); default: throw new Exception("参数错误。"); } return await Senparc.Weixin.CommonAPIs.CommonJsonSend.SendAsync<SendResult>(accessToken, urlFormat, baseData, timeOut: timeOut); }, accessTokenOrAppId); } /// <summary> /// 【异步方法】预览卡券接口 /// </summary> /// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param> /// <param name="cardId"></param> /// <param name="code"></param> /// <param name="openId"></param> /// <param name="wxName"></param> /// <param name="timestamp"></param> /// <param name="signature"></param> /// <param name="timeOut"></param> /// <returns></returns> [ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "GroupMessageApi.WxCardGroupMessagePreviewAsync", true)] public static async Task<SendResult> WxCardGroupMessagePreviewAsync(string accessTokenOrAppId, string cardId, string code, string openId, string wxName, string timestamp, string signature, int timeOut = Config.TIME_OUT) { return await ApiHandlerWapper.TryCommonApiAsync(async accessToken => { string urlFormat = Config.ApiMpHost + "/cgi-bin/message/mass/preview?access_token={0}"; BaseGroupMessageDataPreview baseData = new GroupMessagePreview_WxCardData() { touser = openId, towxname = wxName, wxcard = new GroupMessagePreview_WxCard() { card_id = cardId, card_ext = string.Format("\"code\":\"{0}\",\"openid\":\"{1}\",\"timestamp\":\"{2}\",\"signature\":\"{3}\"", code, openId, timestamp, signature) }, msgtype = "wxcard" }; return await Senparc.Weixin.CommonAPIs.CommonJsonSend.SendAsync<SendResult>(accessToken, urlFormat, baseData, timeOut: timeOut); }, accessTokenOrAppId); } /// <summary> /// 【异步方法】查询群发消息发送状态【订阅号与服务号认证后均可用】 /// </summary> /// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param> /// <param name="msgId">群发消息后返回的消息id</param> /// <param name="timeOut">代理请求超时时间(毫秒)</param> /// <returns></returns> [ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "GroupMessageApi.GetGroupMessageResultAsync", true)] public static async Task<GetSendResult> GetGroupMessageResultAsync(string accessTokenOrAppId, string msgId, int timeOut = Config.TIME_OUT) { return await ApiHandlerWapper.TryCommonApiAsync(async accessToken => { string urlFormat = Config.ApiMpHost + "/cgi-bin/message/mass/get?access_token={0}"; var data = new { msg_id = msgId }; return await Senparc.Weixin.CommonAPIs.CommonJsonSend.SendAsync<GetSendResult>(accessToken, urlFormat, data, timeOut: timeOut); }, accessTokenOrAppId); } /// <summary> /// 【异步方法】获取视频群发用的MediaId /// </summary> /// <param name="accessTokenOrAppId">AccessToken或AppId(推荐使用AppId,需要先注册)</param> /// <param name="mediaId"></param> /// <param name="title"></param> /// <param name="description"></param> /// <param name="timeOut"></param> /// <returns></returns> [ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "GroupMessageApi.GetVideoMediaIdResultAsync", true)] public static async Task<VideoMediaIdResult> GetVideoMediaIdResultAsync(string accessTokenOrAppId, string mediaId, string title, string description, int timeOut = Config.TIME_OUT) { return await ApiHandlerWapper.TryCommonApiAsync(async accessToken => { string url = string.Format("https://file.api.weixin.qq.com/cgi-bin/media/uploadvideo?access_token={0}", accessToken.AsUrlData()); var data = new { media_id = mediaId, title = title, description = description }; return await Senparc.Weixin.CommonAPIs.CommonJsonSend.SendAsync<VideoMediaIdResult>(null, url, data, CommonJsonSendType.POST, timeOut, true); }, accessTokenOrAppId); } /// <summary> /// 【异步方法】获取群发速度 /// </summary> /// <param name="accessTokenOrAppId"></param> /// <param name="timeOut"></param> /// <returns></returns> [ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "GroupMessageApi.GetSendSpeedAsync", true)] public static async Task<GetSpeedResult> GetSendSpeedAsync(string accessTokenOrAppId, int timeOut = Config.TIME_OUT) { return await ApiHandlerWapper.TryCommonApiAsync(async accessToken => { string urlFormat = Config.ApiMpHost + "/cgi-bin/message/mass/speed/get?access_token={0}"; return await Weixin.CommonAPIs.CommonJsonSend.SendAsync<GetSpeedResult>(null, urlFormat, null, CommonJsonSendType.POST, timeOut, true); }, accessTokenOrAppId); } /// <summary> /// 【异步方法】设置群发速度 /// </summary> /// <param name="accessTokenOrAppId"></param> /// <param name="speed">群发速度的级别</param> /// <param name="timeOut"></param> /// <returns></returns> [ApiBind(NeuChar.PlatformType.WeChat_OfficialAccount, "GroupMessageApi.SetSendSpeedAsync", true)] public static async Task<WxJsonResult> SetSendSpeedAsync(string accessTokenOrAppId, int speed, int timeOut = Config.TIME_OUT) { return await ApiHandlerWapper.TryCommonApiAsync(async accessToken => { string urlFormat = Config.ApiMpHost + "/cgi-bin/message/mass/speed/set?access_token={0}"; var data = new { speed = speed }; return await Weixin.CommonAPIs.CommonJsonSend.SendAsync<WxJsonResult>(null, urlFormat, data, CommonJsonSendType.POST, timeOut, true); }, accessTokenOrAppId); } #endregion #endif } }
45.402948
281
0.52281
[ "Apache-2.0" ]
CAH-FlyChen/WeiXinMPSDK
src/Senparc.Weixin.MP/Senparc.Weixin.MP/AdvancedAPIs/GroupMessage/GroupMessageApi.cs
62,921
C#
using System; using System.Collections.Generic; using Gaze.Utilities; namespace Gaze.MVVM.ReadOnly { public interface IReactiveQueue<T> : IReactiveProperty<Queue<T>> { int Count { get; } T Peek(); void SafeBindOnEnqueueAction(IDestroyable destroyable, Action<T> action); void SafeBindOnDequeueAction(IDestroyable destroyable, Action<T> action); void SafeBindOnClearAction(IDestroyable destroyable, Action action); } }
29.4375
81
0.717622
[ "MIT" ]
RenanDresch/GazePackages
src/Gaze/Assets/UPM/GazeMVVM/Runtime/ReadOnly/ReactiveProperties/IReactiveQueue.cs
471
C#
using System; namespace Simple.Scheduler { /// <summary> /// Represents the recurring working item task. /// Recurring task schedules self for the repeating execution, based on the specified parameters. /// Recalculation of next time period is done in local time. /// </summary> /// <seealso cref="RecurringWorkingItem" /> internal class LocalTimeRecurringWorkingItem : RecurringWorkingItem { /// <summary> /// Initializes a new instance of the <see cref="LocalTimeRecurringWorkingItem"/> class. /// </summary> /// <param name="action">The action.</param> /// <param name="name">The task name.</param> /// <param name="startAt">The start at.</param> /// <param name="startAfter">The start after.</param> /// <param name="repeatFor">The repeat for.</param> /// <param name="repeatPeriod">The repeat period.</param> /// <param name="repeatUntil">The repeat until.</param> /// <param name="recurring">if set to <c>true</c> [recurring].</param> public LocalTimeRecurringWorkingItem( Action action, string name, DateTime startAt, TimeSpan startAfter, TimeSpan repeatFor, TimeSpan repeatPeriod, DateTime repeatUntil, bool recurring) : base( action, name, Time.ToUniversalTime(startAt), startAfter, repeatFor, repeatPeriod, Time.ToUniversalTime(repeatUntil), recurring) { } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override string ToString() { return $"{Name} (RL)"; } /// <summary> /// Calculates the next execution time. /// </summary> /// <param name="repeatPeriod">The repeat period.</param> /// <returns> /// A time of the next execution /// </returns> protected override DateTime CalculateNextExecutionTime(TimeSpan repeatPeriod) { var previousExec = Time.ToLocalTime(ExecutionTime); var next = previousExec + repeatPeriod; return Time.ToUniversalTime(next); } } }
36.873239
110
0.551184
[ "MIT" ]
georgemcz/SimpleScheduler
Scheduling/Internals/LocalTimeRecurringWorkingItem.cs
2,618
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.Migrate.Inputs { /// <summary> /// Gets or sets the tags. /// </summary> public sealed class MigrateProjectTagsArgs : Pulumi.ResourceArgs { [Input("additionalProperties")] public Input<string>? AdditionalProperties { get; set; } public MigrateProjectTagsArgs() { } } }
25.5
81
0.675716
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Migrate/Inputs/MigrateProjectTagsArgs.cs
663
C#
/* * Copyright 2020 Sage Intacct, 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 * * or in the "LICENSE" file accompanying this file. This file is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System.Collections.Generic; using System.IO; using System.Text; using System.Xml; using Intacct.SDK.Functions.DataDeliveryService; using Intacct.SDK.Functions; using Intacct.SDK.Tests.Xml; using Intacct.SDK.Xml; using Xunit; namespace Intacct.SDK.Tests.Functions.DataDeliveryService { public class DdsObjectListTest : XmlObjectTestHelper { [Fact] public void GetXmlTest() { string expected = @"<?xml version=""1.0"" encoding=""utf-8""?> <function controlid=""unittest""> <getDdsObjects /> </function>"; DdsObjectList record = new DdsObjectList("unittest"); this.CompareXml(expected, record); } } }
29.857143
80
0.69697
[ "Apache-2.0" ]
Intacct/intacct-sdk-net
Intacct.SDK.Tests/Functions/DataDeliveryService/DdsObjectListTest.cs
1,256
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace Shortcut.Demo.WPF { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { } }
18.388889
42
0.703927
[ "MIT" ]
AlexArchive/Shortcut
Demos/Shortcut.Demo.WPF/App.xaml.cs
333
C#
using System; using Vector2 = DeusaldSharp.Vector2; using System.Runtime.CompilerServices; namespace Box2DSharp.Common { /// Rotation internal struct Rotation { /// Sine and cosine public float Sin; public float Cos; public Rotation(float sin, float cos) { Sin = sin; Cos = cos; } /// Initialize from an angle in radians public Rotation(float angle) { // TODO_ERIN optimize Sin = (float) Math.Sin(angle); Cos = (float) Math.Cos(angle); } /// Set using an angle in radians. [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Set(float angle) { // TODO_ERIN optimize Sin = (float) Math.Sin(angle); Cos = (float) Math.Cos(angle); } /// Set to the identity rotation [MethodImpl(MethodImplOptions.AggressiveInlining)] public void SetIdentity() { Sin = 0.0f; Cos = 1.0f; } /// Get the angle in radians public float Angle => (float) Math.Atan2(Sin, Cos); /// Get the x-axis public Vector2 GetXAxis() { return new Vector2(Cos, Sin); } /// Get the u-axis public Vector2 GetYAxis() { return new Vector2(-Sin, Cos); } } }
24.442623
60
0.496311
[ "MIT" ]
Deusald/DeusaldPhysics2D
DeusaldPhysics2D/Box2dCSharp/Common/Rotation.cs
1,431
C#
using Fixatic.Services.Types; using Fixatic.Types; namespace Fixatic.Services { /// <summary> /// Interface - CustomProperty service /// </summary> public interface ICustomPropertiesService { /// <summary> /// Creates the or update CustomProperty. /// </summary> /// <param name="entry">The entry.</param> /// <returns></returns> Task<ServiceResponse<int>> CreateOrUpdateAsync(CustomProperty entry); /// <summary> /// Gets all CustomProperties. /// </summary> /// <returns></returns> Task<ServiceResponse<List<CustomProperty>>> GetAllAsync(); /// <summary> /// Gets CustomProperty the by ticket. /// </summary> /// <param name="ticketId">The ticket identifier.</param> /// <returns></returns> Task<ServiceResponse<List<FullProperty>>> GetByTicketAsync(int ticketId); /// <summary> /// Deletes the CustomProperty. /// </summary> /// <param name="id">The identifier.</param> /// <returns></returns> Task<ServiceResponse<bool>> DeleteAsync(int id); } }
25.820513
75
0.670308
[ "MIT" ]
Fjarik/Fixatic
src/Fixatic/Services/Fixatic.Services/ICustomPropertiesService.cs
1,009
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Reinforced.Tecture.Commands; using Reinforced.Tecture.Testing.Checks; using Reinforced.Tecture.Testing.Checks.ParameterDescription; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace Reinforced.Tecture.Testing.Validation { partial class CSharpUnitTestGenerator { private IEnumerable<ExpressionSyntax> ProduceArguments(CommandBase command, CheckDescription desc) { var args = desc.GetCheckParameters(command); foreach (var o in args) { if (o is CommandExtractCheckParameter cecp) { yield return ExtractFromCommand(command, cecp); } if (o is AssertionCheckParameter acp) { yield return MakeAssertions(command, acp); } } } private ExpressionSyntax ExtractFromCommand(CommandBase command, CommandExtractCheckParameter cecp) { var value = cecp.Extractor.DynamicInvoke(command); ExpressionSyntax result; if (cecp.Type.IsInlineable()) { EnsureUsing(cecp.Type); result = TypeInitConstructor.Construct(cecp.Type, value); } else { throw new Exception($"{cecp.Type} is not inlineable into tests"); } return result; } private ExpressionSyntax MakeAssertions(CommandBase command, AssertionCheckParameter cecp) { var value = cecp.Extractor.DynamicInvoke(command); var statements = new Stack<StatementSyntax>(); const string varName = "x"; statements.Push(ReturnStatement(LiteralExpression(SyntaxKind.TrueLiteralExpression))); if (value == null) { statements.Push(IfReturnFalse(IdentifierName(varName), LiteralExpression(SyntaxKind.NullLiteralExpression))); } else { var tp = value.GetType(); if (tp.IsInlineable()) { var v = TypeInitConstructor.Construct(tp, value); statements.Push(IfReturnFalse(IdentifierName(varName), v)); } else { var assertProps = cecp.PropertiesToAssert; if (assertProps == null || assertProps.Length == 0) assertProps = tp.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty); var props = assertProps .Where(x => x.PropertyType.IsInlineable()); foreach (var propertyInfo in props) { var access = MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName(varName), IdentifierName(propertyInfo.Name)); var propValue = propertyInfo.GetValue(value); var inlinedValue = TypeInitConstructor.Construct(propertyInfo.PropertyType, propValue); statements.Push(IfReturnFalse(access, inlinedValue)); } } } var blk = Block(List(statements)); var lambda = SimpleLambdaExpression(Parameter(Identifier(varName)), blk); return lambda; } private StatementSyntax IfReturnFalse(ExpressionSyntax left, ExpressionSyntax right) { return IfStatement( BinaryExpression( SyntaxKind.NotEqualsExpression, left, right), ReturnStatement( LiteralExpression( SyntaxKind.FalseLiteralExpression)).WithoutTrivia().WithAdditionalAnnotations(Annotations.IfStatement)); } } }
37.026549
128
0.570268
[ "MIT" ]
ForNeVeR/Reinforced.Tecture
Testing/Reinforced.Tecture.Testing/Validation/Interpolator.Arguments.cs
4,186
C#
using Microsoft.Azure.WebJobs.Host.Bindings; using System.Reflection; using System.Threading.Tasks; namespace FuncInjector { /// <summary> /// The factory for InjectBinding. /// </summary> public class InjectBindingProvider : IBindingProvider { private readonly RegisterServicesTrigger config; public InjectBindingProvider(RegisterServicesTrigger configuration) => config = configuration; public Task<IBinding> TryCreateAsync(BindingProviderContext context) { var parameter = context.Parameter; var attribute = parameter.GetCustomAttribute<InjectAttribute>(false); IBinding binding = new InjectBinding(context.Parameter, config, attribute.RegisterServicesFunctionName); return Task.FromResult(binding); } } }
33
116
0.707879
[ "MIT" ]
MV10/Azure.Functions.Dependency.Injection
FuncInjector/Injection/InjectBindingProvider.cs
827
C#
// <copyright file="IFtpUser.cs" company="Fubar Development Junker"> // Copyright (c) Fubar Development Junker. All rights reserved. // </copyright> using System; namespace FubarDev.FtpServer.AccountManagement { /// <summary> /// A basic FTP user interface. /// </summary> [Obsolete("Use ClaimsPrincipal")] public interface IFtpUser { /// <summary> /// Gets the name of the user. /// </summary> string Name { get; } /// <summary> /// Returns <c>true</c> when the user is in the given group. /// </summary> /// <param name="groupName">The name of the group.</param> /// <returns><c>true</c> when the user is in the queries <paramref name="groupName"/>.</returns> bool IsInGroup(string groupName); /// <summary> /// Gets authority id. /// </summary> string AuthorityId { get; } } }
28
104
0.577922
[ "MIT" ]
alexandrius007/FtpServer
src/FubarDev.FtpServer.Abstractions/AccountManagement/IFtpUser.cs
924
C#
//************************************************************************************************ // Copyright © 2021 Steven M Cohn. All rights reserved. //************************************************************************************************ namespace River.OneMoreAddIn.Models { using System.Xml.Linq; /// <summary> /// Represents a Meta element /// </summary> /// <remarks> /// To delete a one:Meta element, you must also delete its parent container's objectID /// </remarks> internal class Meta : XElement { /// <summary> /// Instantiates a new meta with the given content and predefined namespace /// </summary> /// <remarks> /// PageNamespace.Value must be set prior to using this constructor /// </remarks> public Meta(string name, string content) : this(PageNamespace.Value, name, content) { } /// <summary> /// Initializes a new meta with the given content and namespace /// </summary> /// <param name="ns">A namespace</param> public Meta(XNamespace ns, string name, string content) : base(ns + "Meta") { Add(new XAttribute("name", name)); Add(new XAttribute("content", content)); } /// <summary> /// Gets the name of this meta element /// </summary> public string MetaName => Attribute("name").Value; /// <summary> /// Gets the value of this meta element. /// Note this may return encoded content; if so, use DecodeContent instead /// </summary> public string Content => Attribute("content").Value; /// <summary> /// Sets the value of this meta element /// </summary> /// <param name="content"></param> public XElement SetContent(string content) { SetAttributeValue("content", content); return this; } } }
25.865672
99
0.579342
[ "MPL-2.0" ]
HarthTuwist/OneMore
OneMore/Models/Meta.cs
1,736
C#
#region Using directives using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; #endregion namespace Blazorise { /// <summary> /// Base component for all the input component types. /// </summary> public abstract class BaseInputComponent<TValue> : BaseSizableComponent, IValidationInput { #region Members private Size size = Size.None; private bool isReadonly; private bool isDisabled; #endregion #region Methods protected override void OnInitialized() { // link to the parent component if ( ParentValidation != null ) { ParentValidation.InitializeInput( this ); ParentValidation.ValidationStatusChanged += OnValidationStatusChanged; } base.OnInitialized(); } protected override void Dispose( bool disposing ) { if ( disposing ) { if ( ParentValidation != null ) { // To avoid leaking memory, it's important to detach any event handlers in Dispose() ParentValidation.ValidationStatusChanged -= OnValidationStatusChanged; } } base.Dispose( disposing ); } private void OnValidationStatusChanged( object sender, ValidationStatusChangedEventArgs e ) { DirtyClasses(); StateHasChanged(); } /// <summary> /// Handles the parsing of an input value. /// </summary> /// <param name="value">Input value to be parsed.</param> /// <returns>Returns the awaitable task.</returns> protected async Task CurrentValueHandler( string value ) { var empty = false; if ( string.IsNullOrEmpty( value ) ) { empty = true; CurrentValue = default; } if ( !empty ) { var result = await ParseValueFromStringAsync( value ); if ( result.Success ) { CurrentValue = result.ParsedValue; } } // send the value to the validation for processing ParentValidation?.NotifyInputChanged(); } protected abstract Task<ParseValue<TValue>> ParseValueFromStringAsync( string value ); protected virtual string FormatValueAsString( TValue value ) => value?.ToString(); protected virtual object PrepareValueForValidation( TValue value ) => value; /// <summary> /// Raises and event that handles the edit value of Text, Date, Numeric etc. /// </summary> /// <param name="value">New edit value.</param> protected abstract Task OnInternalValueChanged( TValue value ); /// <summary> /// Sets focus on the input element, if it can be focused. /// </summary> /// <param name="scrollToElement">If true the browser should scroll the document to bring the newly-focused element into view.</param> public void Focus( bool scrollToElement = true ) { _ = JSRunner.Focus( ElementRef, ElementId, scrollToElement ); } #endregion #region Properties /// <inheritdoc/> public virtual object ValidationValue => InternalValue; /// <summary> /// Gets or sets the internal edit value. /// </summary> /// <remarks> /// The reason for this to be abstract is so that input components can have /// their own specialized parameters that can be binded(Text, Date, Value etc.) /// </remarks> protected abstract TValue InternalValue { get; set; } protected TValue CurrentValue { get => InternalValue; set { if ( !EqualityComparer<TValue>.Default.Equals( value, InternalValue ) ) { InternalValue = value; _ = OnInternalValueChanged( value ); } } } protected string CurrentValueAsString { get => FormatValueAsString( CurrentValue ); set { _ = CurrentValueHandler( value ); } } /// <summary> /// Sets the size of the input control. /// </summary> [Parameter] public Size Size { get => size; set { size = value; DirtyClasses(); } } /// <summary> /// Add the readonly boolean attribute on an input to prevent modification of the input’s value. /// </summary> [Parameter] public bool IsReadonly { get => isReadonly; set { isReadonly = value; DirtyClasses(); } } /// <summary> /// Add the disabled boolean attribute on an input to prevent user interactions and make it appear lighter. /// </summary> [Parameter] public bool IsDisabled { get => isDisabled; set { isDisabled = value; DirtyClasses(); } } /// <summary> /// Placeholder for validation messages. /// </summary> [Parameter] public RenderFragment Feedback { get; set; } /// <summary> /// Input content. /// </summary> [Parameter] public RenderFragment ChildContent { get; set; } /// <summary> /// Parent validation container. /// </summary> [CascadingParameter] public BaseValidation ParentValidation { get; set; } #endregion } }
28.116822
142
0.527838
[ "MIT" ]
8VAid8/Blazorise
Source/Blazorise/BaseInputComponent.razor.cs
6,021
C#
using Microsoft.Xrm.Tooling.Connector; using System; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Messages; using Microsoft.Xrm.Sdk.Query; using Microsoft.Crm.Sdk.Messages; namespace PowerApps.Samples { public partial class SampleProgram { [STAThread] // Required to support the interactive login experience static void Main(string[] args) { CrmServiceClient service = null; try { service = SampleHelpers.Connect("Connect"); if (service.IsReady) { // Create any entity records that the demonstration code requires SetUpSample(service); #region Demonstrate // TODO Add demonstration code here //<snippetCreateandublishProducts1> // Create a product family Product newProductFamily = new Product { Name = "Example Product Family", ProductNumber = "PF001", ProductStructure = new OptionSetValue(2) }; _productFamilyId = _serviceProxy.Create(newProductFamily); Console.WriteLine("\nCreated '{0}'", newProductFamily.Name); // Create a product property DynamicProperty newProperty = new DynamicProperty { Name = "Example Property", RegardingObjectId = new EntityReference(Product.EntityLogicalName, _productFamilyId), IsReadOnly = true, IsRequired = true, IsHidden = false, DataType = new OptionSetValue(3), //Single line of text DefaultValueString = "Default Value" }; _productPropertyId = _serviceProxy.Create(newProperty); Console.WriteLine("\nCreated '{0}' for the product family", newProperty.Name); // Create couple of product records under the product family Product newProduct1 = new Product { Name = "Example Product 1", ProductNumber = "P001", ProductStructure = new OptionSetValue(1), ParentProductId = new EntityReference(Product.EntityLogicalName, _productFamilyId), QuantityDecimal = 2, DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId), DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _unit.Id) }; _product1Id = _serviceProxy.Create(newProduct1); Console.WriteLine("\nCreated '{0}' under the product family", newProduct1.Name); Product newProduct2 = new Product { Name = "Example Product 2", ProductNumber = "P002", ProductStructure = new OptionSetValue(1), ParentProductId = new EntityReference(Product.EntityLogicalName, _productFamilyId), QuantityDecimal = 2, DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId), DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _unit.Id) }; _product2Id = _serviceProxy.Create(newProduct2); Console.WriteLine("Created '{0}' under the product family", newProduct2.Name); // Create a price list items for the products ProductPriceLevel newPriceListItem1 = new ProductPriceLevel { PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), ProductId = new EntityReference(Product.EntityLogicalName, _product1Id), UoMId = new EntityReference(UoM.EntityLogicalName, _unit.Id), Amount = new Money(20) }; _priceListItem1Id = _serviceProxy.Create(newPriceListItem1); Console.WriteLine("\nCreated price list for '{0}'", newProduct1.Name); ProductPriceLevel newPriceListItem2 = new ProductPriceLevel { PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), ProductId = new EntityReference(Product.EntityLogicalName, _product2Id), UoMId = new EntityReference(UoM.EntityLogicalName, _unit.Id), Amount = new Money(20) }; _priceListItem2Id = _serviceProxy.Create(newPriceListItem2); Console.WriteLine("Created price list for '{0}'", newProduct2.Name); // Set the product relationship // Set Example Product 1 and Example Product 2 as substitute of each other (bi-directional) ProductSubstitute newProductRelation = new ProductSubstitute { SalesRelationshipType = new OptionSetValue(3), Direction = new OptionSetValue(1), ProductId = new EntityReference(Product.EntityLogicalName, _product1Id), SubstitutedProductId = new EntityReference(Product.EntityLogicalName, _product2Id) }; _productRelationId = _serviceProxy.Create(newProductRelation); Console.WriteLine("\nCreated a substitute relation between the two products."); //</snippetCreateandublishProducts1> // Override a product property at the product level // In this case we will override the property for 'Example Product 1' DynamicProperty newOverrideProperty = new DynamicProperty(); newOverrideProperty.BaseDynamicPropertyId = new EntityReference(DynamicProperty.EntityLogicalName, _productPropertyId); newOverrideProperty.RegardingObjectId = new EntityReference(Product.EntityLogicalName, _product1Id); _productOverridenPropertyId = _serviceProxy.Create(newOverrideProperty); // Retrieve the attributes of the cloned property you want to update ColumnSet columns = new ColumnSet(); columns.AddColumns("name", "isreadonly", "isrequired"); DynamicProperty retrievedOverridenProperty = (DynamicProperty)_serviceProxy.Retrieve( DynamicProperty.EntityLogicalName, _productOverridenPropertyId, columns); // Update the attributes retrievedOverridenProperty.Name = "Overridden Example Property"; retrievedOverridenProperty.IsReadOnly = true; retrievedOverridenProperty.IsRequired = false; _serviceProxy.Update(retrievedOverridenProperty); Console.WriteLine("\nOverridden the product property for 'Example Product 1'."); // Prompt the user whether to publish the product family and products bool publishRecords = true; Console.WriteLine("\nDo you want the product records published? (y/n)"); String answer = Console.ReadLine(); publishRecords = (answer.StartsWith("y") || answer.StartsWith("Y")); if (publishRecords) { PublishProductHierarchyRequest publishReq = new PublishProductHierarchyRequest { Target = new EntityReference(Product.EntityLogicalName, _productFamilyId) }; PublishProductHierarchyResponse published = (PublishProductHierarchyResponse)_serviceProxy.Execute(publishReq); if (published.Results != null) { Console.WriteLine("Published the product records"); } // Overwrite a product property Console.WriteLine("\nRevising 'Example Product 1' to demonstrate product property overwrite."); // Retrieve the StateCode of Product that you want to revise ColumnSet cols = new ColumnSet(); cols.AddColumns("name", "statecode"); Product retrievedPublishedProduct = (Product)_serviceProxy.Retrieve( Product.EntityLogicalName, _product1Id, cols); // Update the state of the Product to "Under Revision" retrievedPublishedProduct.StateCode = ProductState.UnderRevision; UpdateRequest updatePropertyState = new UpdateRequest { Target = retrievedPublishedProduct }; _serviceProxy.Execute(updatePropertyState); Console.WriteLine("\nChanged '{0}' to 'Under Revision' state.", retrievedPublishedProduct.Name); DynamicProperty newOverwriteProperty = new DynamicProperty(); newOverwriteProperty.BaseDynamicPropertyId = new EntityReference(DynamicProperty.EntityLogicalName, _productOverridenPropertyId); newOverwriteProperty.RegardingObjectId = new EntityReference(Product.EntityLogicalName, _product1Id); _productOverwrittenPropertyId = _serviceProxy.Create(newOverwriteProperty); // Retrieve the attributes of the cloned property you want to update ColumnSet myCols = new ColumnSet(); myCols.AddColumns("name", "isreadonly", "isrequired"); DynamicProperty retrievedOverwrittenProperty = (DynamicProperty)_serviceProxy.Retrieve( DynamicProperty.EntityLogicalName, _productOverwrittenPropertyId, myCols); // Update the attributes of the cloned property to complete the overwrite retrievedOverwrittenProperty.Name = "Overwritten Example Property"; retrievedOverwrittenProperty.IsReadOnly = true; retrievedOverridenProperty.IsRequired = false; _serviceProxy.Update(retrievedOverwrittenProperty); Console.WriteLine("\nOverwritten the product property for 'Example Product 1'."); // Retrieve the StateCode of Product that you want to publish ColumnSet prodCols = new ColumnSet(); prodCols.AddColumns("name", "statecode"); Product retrievedRevisedProduct = (Product)_serviceProxy.Retrieve( Product.EntityLogicalName, _product1Id, prodCols); // Update the state of the Product to "Active" retrievedRevisedProduct.StateCode = ProductState.Active; UpdateRequest publishProduct1 = new UpdateRequest { Target = retrievedRevisedProduct }; _serviceProxy.Execute(publishProduct1); Console.WriteLine("\nPublished '{0}'.", retrievedRevisedProduct.Name); } #endregion Demonstrate } else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service"; if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR)) { Console.WriteLine("Check the connection string values in cds/App.config."); throw new Exception(service.LastCrmError); } else { throw service.LastCrmException; } } } catch (Exception ex) { SampleHelpers.HandleException(ex); } finally { if (service != null) service.Dispose(); Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } } } }
54.473684
135
0.525455
[ "MIT" ]
Bhaskers-Blu-Org2/Dynamics365-Apps-Samples
sales/AddProductsBundle/AddProductsBundle/SampleProgram.cs
13,457
C#
using System.Text.RegularExpressions; namespace Microsoft.Recognizers.Text.DateTime.Utilities { public interface IDateTimeUtilityConfiguration { Regex AgoRegex { get; } Regex LaterRegex { get; } Regex InConnectorRegex { get; } Regex SinceYearSuffixRegex { get; } Regex WithinNextPrefixRegex { get; } Regex RangeUnitRegex { get; } Regex TimeUnitRegex { get; } Regex DateUnitRegex { get; } Regex AmDescRegex { get; } Regex PmDescRegex { get; } Regex AmPmDescRegex { get; } Regex CommonDatePrefixRegex { get; } Regex RangePrefixRegex { get; } bool CheckBothBeforeAfter { get; } } }
20.916667
56
0.590969
[ "MIT" ]
7i77an/Recognizers-Text
.NET/Microsoft.Recognizers.Text.DateTime/Utilities/IDateTimeUtilityConfiguration.cs
755
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; namespace Microsoft.Bot.Builder.Skills { /// <summary> /// Registration for a BotFrameworkHttpProtocol based Skill endpoint. /// </summary> public class BotFrameworkSkill { /// <summary> /// Gets or sets Id of the skill. /// </summary> /// <value> /// Id of the skill. /// </value> public string Id { get; set; } /// <summary> /// Gets or sets appId of the skill. /// </summary> /// <value> /// AppId of the skill. /// </value> public string AppId { get; set; } /// <summary> /// Gets or sets /api/messages endpoint for the skill. /// </summary> /// <value> /// /api/messages endpoint for the skill. /// </value> public Uri SkillEndpoint { get; set; } } }
25.342105
73
0.524403
[ "MIT" ]
Acidburn0zzz/botbuilder-dotnet
libraries/Microsoft.Bot.Builder/Skills/BotFrameworkSkill.cs
965
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 어셈블리에 대한 일반 정보는 다음 특성 집합을 통해 // 제어됩니다. 어셈블리와 관련된 정보를 수정하려면 // 이러한 특성 값을 변경하세요. [assembly: AssemblyTitle("Reflection")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Reflection")] [assembly: AssemblyCopyright("Copyright © 2022")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible을 false로 설정하면 이 어셈블리의 형식이 COM 구성 요소에 // 표시되지 않습니다. COM에서 이 어셈블리의 형식에 액세스하려면 // 해당 형식에 대해 ComVisible 특성을 true로 설정하세요. [assembly: ComVisible(false)] // 이 프로젝트가 COM에 노출되는 경우 다음 GUID는 typelib의 ID를 나타냅니다. [assembly: Guid("7fc49f05-a834-4dc3-84db-8558bdb37d17")] // 어셈블리의 버전 정보는 다음 네 가지 값으로 구성됩니다. // // 주 버전 // 부 버전 // 빌드 번호 // 수정 버전 // // 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 번호를 // 기본값으로 할 수 있습니다. // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
28.378378
56
0.698095
[ "MIT" ]
c3nb/Reflection
Reflection/Properties/AssemblyInfo.cs
1,483
C#
using System; using System.Collections.Generic; using System.Linq; using Magic.Framework.Schools; using Magic.Framework.Spells; namespace Magic.Framework { /// <summary>Manages the available spells.</summary> internal static class SpellManager { /********* ** Fields *********/ private static readonly Dictionary<string, Spell> Spells = new(); /********* ** Public methods *********/ public static Spell Get(string id) { return !string.IsNullOrEmpty(id) && SpellManager.Spells.TryGetValue(id, out Spell spell) ? spell : null; } public static List<string> GetAll() { return SpellManager.Spells.Keys.ToList<string>(); } internal static void Init(Func<long> getNewId) { SpellManager.Register(new AnalyzeSpell()); SpellManager.Register(new ProjectileSpell(SchoolId.Arcane, "magicmissle", 5, 7, 15, "flameSpell", "flameSpellHit", seeking: true)); SpellManager.Register(new EnchantSpell(false)); SpellManager.Register(new EnchantSpell(true)); SpellManager.Register(new RewindSpell()); SpellManager.Register(new ClearDebrisSpell()); SpellManager.Register(new TillSpell()); SpellManager.Register(new WaterSpell()); SpellManager.Register(new BlinkSpell()); SpellManager.Register(new LanternSpell(getNewId)); SpellManager.Register(new TendrilsSpell()); SpellManager.Register(new ShockwaveSpell()); SpellManager.Register(new PhotosynthesisSpell()); SpellManager.Register(new HealSpell()); SpellManager.Register(new HasteSpell()); SpellManager.Register(new BuffSpell()); SpellManager.Register(new EvacSpell()); SpellManager.Register(new ProjectileSpell(SchoolId.Elemental, "frostbolt", 7, 10, 20, "flameSpell", "flameSpellHit")); SpellManager.Register(new ProjectileSpell(SchoolId.Elemental, "fireball", 7, 10, 20, "flameSpell", "flameSpellHit")); SpellManager.Register(new DescendSpell()); SpellManager.Register(new TeleportSpell()); SpellManager.Register(new MeteorSpell()); SpellManager.Register(new BloodManaSpell()); SpellManager.Register(new LuckStealSpell()); SpellManager.Register(new SpiritSpell()); } /********* ** Private methods *********/ public static void Register(Spell spell) { SpellManager.Spells.Add(spell.ParentSchool.Id + ":" + spell.Id, spell); spell.LoadIcon(); } } }
35.423077
143
0.602606
[ "MIT" ]
ChulkyBow/StardewValleyMods
Magic/Framework/SpellManager.cs
2,763
C#
// (c) Copyright HutongGames, LLC 2010-2013. All rights reserved. namespace HutongGames.PlayMaker.Actions { [ActionCategory(ActionCategory.StateMachine)] [Tooltip("Sends the next event on the state each totalTimeInSeconds the state is entered.")] public class SequenceEvent : FsmStateAction { [HasFloatSlider(0, 10)] public FsmFloat delay; [UIHint(UIHint.Variable)] [Tooltip("Assign a variable to control reset. Set it to True to reset the sequence. Value is set to False after resetting.")] public FsmBool reset; DelayedEvent delayedEvent; int eventIndex; public override void Reset() { delay = null; } public override void OnEnter() { if (reset.Value) { eventIndex = 0; reset.Value = false; } var eventCount = State.Transitions.Length; if (eventCount > 0) { var fsmEvent = State.Transitions[eventIndex].FsmEvent; if (delay.Value < 0.001f) { Fsm.Event(fsmEvent); Finish(); } else { delayedEvent = Fsm.DelayedEvent(fsmEvent, delay.Value); } eventIndex++; if (eventIndex == eventCount) { eventIndex = 0; } } } public override void OnUpdate() { if (DelayedEvent.WasSent(delayedEvent)) { Finish(); } } } }
20.390625
133
0.633716
[ "Unlicense" ]
rachel2386/Studio2Game
Assets/PlayMaker/Actions/StateMachine/SequenceEvent.cs
1,305
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using static Interop; namespace System.Windows.Forms { internal partial class ToolStripGrip { internal class ToolStripGripAccessibleObject : ToolStripButtonAccessibleObject { public ToolStripGripAccessibleObject(ToolStripGrip owner) : base(owner) { } public override string Name { get => Owner.AccessibleName ?? SR.ToolStripGripAccessibleName; set => base.Name = value; } public override AccessibleRole Role { get { AccessibleRole role = Owner.AccessibleRole; if (role != AccessibleRole.Default) { return role; } return AccessibleRole.Grip; } } internal override object GetPropertyValue(UiaCore.UIA propertyID) { switch (propertyID) { case UiaCore.UIA.IsOffscreenPropertyId: return false; } return base.GetPropertyValue(propertyID); } } } }
28.666667
86
0.522572
[ "MIT" ]
Amy-Li03/winforms
src/System.Windows.Forms/src/System/Windows/Forms/ToolStripGrip.ToolStripGripAccessibleObject.cs
1,464
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace V308CMS.Admin { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
25.217391
99
0.587931
[ "Unlicense" ]
giaiphapictcom/mamoo.vn
V308CMS.Admin/App_Start/RouteConfig.cs
582
C#
using UnityEngine; namespace KartGame.KartSystems { /// <summary> /// Should be implemented by MonoBehaviours which are on objects with which a kart can collide. /// </summary> public interface IKartCollider { /// <summary> /// Should be used to change the velocity of a kart when it collides with this object. /// </summary> /// <param name="collidingKart">The kart colliding with this object.</param> /// <param name="collisionHit">Data about the collision.</param> /// <returns>The velocity of the kart after it has been modified by this collision.</returns> Vector3 ModifyVelocity (IKartInfo collidingKart, RaycastHit collisionHit); } }
40.111111
101
0.66759
[ "BSD-3-Clause" ]
ServiceStack/script-unity
MyFirstGame/Assets/UTech/MG-Karting/BasicAssets/Scripts/KartSystems/KartColliders/IKartCollider.cs
724
C#
using System.Collections.Generic; namespace HS.Farm.Authentication.External { public interface IExternalAuthConfiguration { List<ExternalLoginProviderInfo> Providers { get; } } }
20.1
58
0.736318
[ "MIT" ]
tranthebao/HS.Farm
aspnet-core/src/HS.Farm.Web.Core/Authentication/External/IExternalAuthConfiguration.cs
203
C#
#if UNITY_EDITOR using UnityEditor; #endif namespace BehaviourInject.Internal { #if UNITY_EDITOR [CanEditMultipleObjects] [CustomEditor(typeof(Injector))] public class ChooseContextProperyDrawer : Editor { private Settings _settings; private bool _isDropped; private SerializedProperty _choosenContext; private SerializedProperty _useHierarchy; void OnEnable() { _settings = Settings.Load(); _choosenContext = serializedObject.FindProperty("_contextIndex"); ; _useHierarchy = serializedObject.FindProperty("_useHierarchy"); ; } public override void OnInspectorGUI() { serializedObject.Update(); bool useHierarchy = _useHierarchy.boolValue; _useHierarchy.boolValue = EditorGUILayout.Toggle("Use hierarchy", useHierarchy); if (!useHierarchy) { string[] contextNames = _settings.ContextNames; int contextIndex = _choosenContext.intValue; if (contextIndex >= contextNames.Length) { contextIndex = 0; _isDropped = true; } int index = EditorGUILayout.IntPopup("Context", contextIndex, contextNames, _settings.GetOptionValues()); _choosenContext.intValue = index; if (_isDropped) { EditorGUILayout.HelpBox("Context index exceeded. Returned to " + contextNames[0], MessageType.Warning); } } serializedObject.ApplyModifiedProperties(); } } #endif }
24.859649
110
0.705716
[ "MIT" ]
sergeysychov/behaviour_inject
Assets/BInject/Scripts/BehaviourInject/Editor/ChooseContextProperyDrawer.cs
1,419
C#
using UnityEngine; using UnityEngine.SceneManagement; public class MainMenu : MonoBehaviour { public void OnClickPlay() { SceneManager.LoadScene (1); } public void OnClickExit() { Application.Quit (); } public void OnClickHelp() { SceneManager.LoadScene(3); } }
14.095238
39
0.679054
[ "Unlicense" ]
Z3uS11/Rusty-the-Balloon
Assets/Scripts/MainMenu.cs
296
C#
/* Copyright (c) 2011 Steve Revill and Shane Woolcock 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. */ class diddy { public static int systemMillisecs() { DateTime centuryBegin = new DateTime(1970, 1, 1); DateTime currentDate = DateTime.Now; long elapsedTicks = currentDate.Ticks - centuryBegin.Ticks; TimeSpan elapsedSpan = new TimeSpan(elapsedTicks); int millisecs = (int)elapsedSpan.TotalSeconds * 1000; return millisecs; } public static void setGraphics(int w, int h) { } public static void setMouse(int x, int y) { } public static void showKeyboard() { } public static void launchBrowser(String address, String windowName) { } public static void launchEmail(String email, String subject, String text) { } public static void startVibrate(int millisecs) { } public static void stopVibrate() { } public static void startGps() { } public static String getLatitude() { return ""; } public static String getLongitude() { return ""; } public static void showAlertDialog(String title, String message) { } public static String getInputString() { return ""; } // empty function public static void mouseZInit() { } // empty function public static float mouseZ() { return 0; } }
30.465753
460
0.752248
[ "MIT" ]
denise-amiga/diddy
src/diddy/native/diddy.pss.cs
2,224
C#
using System.Collections.Generic; using System.Linq; using Perpetuum.Data; using Perpetuum.Log; using Perpetuum.Network; using Perpetuum.Services.Sessions; namespace Perpetuum.Services.Relay { public class ServerInfo { public static readonly ServerInfo None = new ServerInfo(); public string Name { get; set; } public string Description { get; set; } public string Contact { get; set; } public bool IsOpen { get; set; } public bool IsBroadcast { get; set; } public int UsersCount { get; set; } public Dictionary<string, object> Serialize() { return new Dictionary<string, object>() { {k.name,Name}, {k.description,Description}, {k.contact,Contact}, {k.isOpen,IsOpen}, {k.isBroadcast,IsBroadcast}, {"usersCount",UsersCount } }; } public static ServerInfo Deserialize(IDictionary<string, object> dictionary) { return new ServerInfo { Name = dictionary.GetOrDefault<string>(k.name), Description = dictionary.GetOrDefault<string>(k.description), Contact = dictionary.GetOrDefault<string>(k.contact), IsOpen = dictionary.GetOrDefault<int>(k.isOpen) == 1, IsBroadcast = dictionary.GetOrDefault<int>(k.isBroadcast) == 1, }; } } public interface IServerInfoManager { ServerInfo GetServerInfo(); void SaveServerInfoToDb(ServerInfo serverInfo); void PostCurrentServerInfoToWebService(); } public class ServerInfoManager : IServerInfoManager { private readonly ISessionManager _sessionManager; public ServerInfoManager(ISessionManager sessionManager) { _sessionManager = sessionManager; } public ServerInfo GetServerInfo() { var record = Db.Query().CommandText("saServerInfoGet").ExecuteSingleRow(); if (record == null) return null; var serverInfo = new ServerInfo { Name = record.GetValue<string>("name"), Description = record.GetValue<string>("description"), Contact = record.GetValue<string>("contact"), IsOpen = record.GetValue<bool>("isOpen"), IsBroadcast = record.GetValue<bool>("isBroadcast"), UsersCount = _sessionManager.Sessions.Count(c => c.IsAuthenticated) }; return serverInfo; } public void SaveServerInfoToDb(ServerInfo serverInfo) { Db.Query().CommandText("saServerInfoSet") .SetParameter("name",serverInfo.Name) .SetParameter("description",serverInfo.Description) .SetParameter("contact",serverInfo.Contact) .SetParameter("isopen",serverInfo.IsOpen) .SetParameter("isbroadcast",serverInfo.IsBroadcast) .ExecuteSingleRow(); } public void PostCurrentServerInfoToWebService() { var serverInfo = GetServerInfo(); var data = serverInfo.Serialize(); var reply = Http.Post("http://www.perpetuum-online.com/Server_list", data); Logger.DebugInfo(reply); } } }
33.705882
87
0.580861
[ "MIT" ]
OpenPerpetuum/PerpetuumServer
src/Perpetuum/Services/Relay/ServerStateInfo.cs
3,440
C#
namespace Schema.NET { using System; using System.Runtime.Serialization; using Newtonsoft.Json; /// <summary> /// A radio station. /// </summary> [DataContract] public partial class RadioStation : LocalBusiness { /// <summary> /// Gets the name of the type as specified by schema.org. /// </summary> [DataMember(Name = "@type", Order = 1)] public override string Type => "RadioStation"; } }
23.6
65
0.586864
[ "MIT" ]
AndreSteenbergen/Schema.ORG
Source/Schema.NET/core/RadioStation.cs
472
C#
// <copyright file="CharacterClientReadyPacketHandlerPlugIn.cs" company="MUnique"> // Licensed under the MIT License. See LICENSE file in the project root for full license information. // </copyright> namespace MUnique.OpenMU.GameServer.MessageHandler.Character { using System; using System.Runtime.InteropServices; using MUnique.OpenMU.GameLogic; using MUnique.OpenMU.PlugIns; /// <summary> /// Sub packet handler for 'client ready' packets which are sent by the client after map changes. /// </summary> [PlugIn("Character - Client ready", "Packet handler for 'client ready' packets (0xF3, 0x12 identifier) which are sent after map changes.")] [Guid("8FB0AD6B-B3A6-4BF7-865B-EB4DF3C2A52F")] [BelongsToGroup(CharacterGroupHandlerPlugIn.GroupKey)] internal class CharacterClientReadyPacketHandlerPlugIn : ISubPacketHandlerPlugIn { /// <inheritdoc/> public bool IsEncryptionExpected => false; /// <inheritdoc/> public byte Key => 0x12; /// <inheritdoc /> public void HandlePacket(Player player, Span<byte> packet) { player.ClientReadyAfterMapChange(); } } }
37.125
143
0.693603
[ "MIT" ]
And3rsL/OpenMU
src/GameServer/MessageHandler/Character/CharacterClientReadyPacketHandlerPlugIn.cs
1,190
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/winioctl.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. namespace TerraFX.Interop { public partial struct STORAGE_CRYPTO_CAPABILITY { [NativeTypeName("DWORD")] public uint Version; [NativeTypeName("DWORD")] public uint Size; [NativeTypeName("DWORD")] public uint CryptoCapabilityIndex; public STORAGE_CRYPTO_ALGORITHM_ID AlgorithmId; public STORAGE_CRYPTO_KEY_SIZE KeySize; [NativeTypeName("DWORD")] public uint DataUnitSizeBitmask; } }
28.333333
145
0.699346
[ "MIT" ]
Ethereal77/terrafx.interop.windows
sources/Interop/Windows/um/winioctl/STORAGE_CRYPTO_CAPABILITY.cs
767
C#
//---------------------------------------------------------------------------- // // Copyright (C) Jason Graham. All rights reserved. // // 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. // // History // 27/07/13 Created // //--------------------------------------------------------------------------- namespace System.Windows.Forms { /// <summary> /// Defines the display format for values in the <see cref="GlobalizedNumericTextBox"/>. /// </summary> public enum GlobalizedNumericTextBoxDisplayFormat { /// <summary> /// Indicates that the numeric string is formatted with default formatting. /// </summary> Normal = 0, /// <summary> /// Indicates that the numeric string is formatted with a currency symbol. /// </summary> Currency = 1, /// <summary> /// Indicates that the numeric string is formatted in exponential notation. /// </summary> Exponent = 2, /// <summary> /// Indicates that the numeric string is formatted using the user provided CustomFormat. /// </summary> CustomFormat = 3 } }
41.528302
96
0.630168
[ "MIT" ]
CSharpLabs/GlobalizedNumericTextBox
GlobalizedNumericTextBox/Windows/Forms/GlobalizedNumericTextBoxDisplayFormat.cs
2,203
C#
using CoronaDeployments.Core.Build; using CoronaDeployments.Core.Models; using CoronaDeployments.Core.Runner; using Serilog; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading.Tasks; namespace CoronaDeployments.Core.RepositoryImporter { public sealed class SvnRepositoryStrategy : IRepositoryImportStrategy { public SourceCodeRepositoryType Type => SourceCodeRepositoryType.Svn; public Task<List<RepositoryCommit>> GetLastCommitsAsync(Project entity, AppConfiguration appConfiguration, IRepositoryAuthenticationInfo authInfo, CustomLogger runnerLogger, int count) { return Task.Run(async () => { var info = authInfo as AuthInfo; if (info == null) { return null; } try { var checkoutResult = await ImportAsync(entity, appConfiguration, authInfo, runnerLogger); if (checkoutResult.HasErrors) { return null; } List<RepositoryCommit> result = null; using (var client = new SharpSvn.SvnClient()) { //client.Authentication.DefaultCredentials = new NetworkCredential(info.Username, info.Password); if (client.GetLog(checkoutResult.CheckOutDirectory, new SharpSvn.SvnLogArgs() { Limit = count }, out var items)) { result = items .Select(x => new RepositoryCommit(x.Revision.ToString(), x.LogMessage, x.Time.ToUniversalTime(), $"{x.Author}")) .ToList(); } } try { // Clean up the directory. Directory.Delete(checkoutResult.CheckOutDirectory, recursive: true); } catch (Exception exp) { runnerLogger.Error(exp); } return result; } catch (Exception exp) { runnerLogger.Error(exp); return null; } }); } public Task<RepositoryImportResult> ImportAsync(Project entity, AppConfiguration appConfiguration, IRepositoryAuthenticationInfo authInfo, CustomLogger runnerLogger, string commitId = null) { return Task.Run(() => { var folderName = $"{entity.Name}_{DateTime.UtcNow.Ticks}"; var path = Path.Combine(appConfiguration.BaseDirectory, folderName); var info = authInfo as AuthInfo; if (info == null) { return new RepositoryImportResult(string.Empty, true); } try { Directory.CreateDirectory(path); using (var client = new SharpSvn.SvnClient()) { client.Authentication.DefaultCredentials = new NetworkCredential(info.Username, info.Password); runnerLogger.Information("Checking out..."); bool result = false; if (commitId == null) result = client.CheckOut(new SharpSvn.SvnUriTarget(entity.RepositoryUrl), path); else result = client.CheckOut(new SharpSvn.SvnUriTarget(entity.RepositoryUrl), path, new SharpSvn.SvnCheckOutArgs { Revision = new SharpSvn.SvnRevision(int.Parse(commitId)) }); runnerLogger.Information($"Check out complete. Result = {result}"); } runnerLogger.Information(string.Empty); return new RepositoryImportResult(path, false); } catch (Exception exp) { runnerLogger.Error(exp); return new RepositoryImportResult(string.Empty, true); } }); } } }
38.563025
198
0.483766
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
SherifRefaat/CoronaDeployments
Source/CoronaDeployments.Core/RepositoryImporter/SvnRepositoryStrategy.cs
4,591
C#
using Microsoft.Ajax.Utilities; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using Veracity.Common.OAuth.Providers; using Veracity.Services.Api; using Veracity.Services.Api.Models; namespace HelloWorldVanilla.Controllers { public class HomeController : Controller { private readonly IApiClient _veracityClient; public HomeController(IApiClient veracityClient) { _veracityClient = veracityClient; } public async Task<ActionResult> Index() { var user = new UserInfo(); ViewBag.Title = "Home Page"; if (Request.IsAuthenticated) { try { ViewBag.Email = (User.Identity as ClaimsIdentity)?.Claims .FirstOrDefault(c => c.Type == ClaimTypes.Upn)?.Value; user = await _veracityClient.My.Info(); } catch (System.Exception ex) { } } return View(user); } public void Login(string redirectUrl) { if (!Request.IsAuthenticated) { HttpContext.GetOwinContext().Authentication.Challenge(); return; } if (redirectUrl.IsNullOrWhiteSpace()) redirectUrl = "/"; Response.Redirect(redirectUrl); } [HttpGet] public void Logout(string redirectUrl) { Response.Logout("https://www.veracity.com/auth/logout"); } } }
27.45
85
0.548877
[ "Apache-2.0" ]
tony-dnvgl/Veracity-Identity-and-Services-Api
src/Samples/HelloWorldVanilla/Controllers/HomeController.cs
1,649
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Gov.Lclb.Cllb.Interfaces { using Microsoft.Rest; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// Parentaccount operations. /// </summary> public partial class Parentaccount : IServiceOperations<DynamicsClient>, IParentaccount { /// <summary> /// Initializes a new instance of the Parentaccount class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public Parentaccount(DynamicsClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the DynamicsClient /// </summary> public DynamicsClient Client { get; private set; } /// <summary> /// Get adoxio_ParentAccount from adoxio_leconnections /// </summary> /// <param name='adoxioLeconnectionid'> /// key: adoxio_leconnectionid of adoxio_leconnection /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<MicrosoftDynamicsCRMaccount>> GetWithHttpMessagesAsync(string adoxioLeconnectionid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (adoxioLeconnectionid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "adoxioLeconnectionid"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("adoxioLeconnectionid", adoxioLeconnectionid); tracingParameters.Add("select", select); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "adoxio_leconnections({adoxio_leconnectionid})/adoxio_ParentAccount").ToString(); _url = _url.Replace("{adoxio_leconnectionid}", System.Uri.EscapeDataString(adoxioLeconnectionid)); List<string> _queryParameters = new List<string>(); if (select != null) { _queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select)))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand)))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<MicrosoftDynamicsCRMaccount>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMaccount>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
41.802817
346
0.569856
[ "Apache-2.0" ]
BrendanBeachBC/jag-lcrb-carla-public
cllc-interfaces/Dynamics-Autorest/Parentaccount.cs
8,904
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void MultiplyDoublingWideningSaturateLowerBySelectedScalar_Vector64_Int32_Vector128_Int32_3() { var test = new ImmBinaryOpTest__MultiplyDoublingWideningSaturateLowerBySelectedScalar_Vector64_Int32_Vector128_Int32_3(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmBinaryOpTest__MultiplyDoublingWideningSaturateLowerBySelectedScalar_Vector64_Int32_Vector128_Int32_3 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, Int64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int32> _fld1; public Vector128<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__MultiplyDoublingWideningSaturateLowerBySelectedScalar_Vector64_Int32_Vector128_Int32_3 testClass) { var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar(_fld1, _fld2, 3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmBinaryOpTest__MultiplyDoublingWideningSaturateLowerBySelectedScalar_Vector64_Int32_Vector128_Int32_3 testClass) { fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)), 3 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly byte Imm = 3; private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector64<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private Vector64<Int32> _fld1; private Vector128<Int32> _fld2; private DataTable _dataTable; static ImmBinaryOpTest__MultiplyDoublingWideningSaturateLowerBySelectedScalar_Vector64_Int32_Vector128_Int32_3() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public ImmBinaryOpTest__MultiplyDoublingWideningSaturateLowerBySelectedScalar_Vector64_Int32_Vector128_Int32_3() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, new Int64[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar( Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar( AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar), new Type[] { typeof(Vector64<Int32>), typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr), (byte)3 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar), new Type[] { typeof(Vector64<Int32>), typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)), (byte)3 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar( _clsVar1, _clsVar2, 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar1 = &_clsVar1) fixed (Vector128<Int32>* pClsVar2 = &_clsVar2) { var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar( AdvSimd.LoadVector64((Int32*)(pClsVar1)), AdvSimd.LoadVector128((Int32*)(pClsVar2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar(op1, op2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar(op1, op2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__MultiplyDoublingWideningSaturateLowerBySelectedScalar_Vector64_Int32_Vector128_Int32_3(); var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar(test._fld1, test._fld2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmBinaryOpTest__MultiplyDoublingWideningSaturateLowerBySelectedScalar_Vector64_Int32_Vector128_Int32_3(); fixed (Vector64<Int32>* pFld1 = &test._fld1) fixed (Vector128<Int32>* pFld2 = &test._fld2) { var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar(_fld1, _fld2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar(test._fld1, test._fld2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar( AdvSimd.LoadVector64((Int32*)(&test._fld1)), AdvSimd.LoadVector128((Int32*)(&test._fld2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int32> firstOp, Vector128<Int32> secondOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), firstOp); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), secondOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* firstOp, void* secondOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(secondOp), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] secondOp, Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.MultiplyDoublingWideningSaturate(firstOp[i], secondOp[Imm]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar)}<Int64>(Vector64<Int32>, Vector128<Int32>, 3): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
44.32963
214
0.601053
[ "MIT" ]
2m0nd/runtime
src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/MultiplyDoublingWideningSaturateLowerBySelectedScalar.Vector64.Int32.Vector128.Int32.3.cs
23,938
C#
using AtividadesVeiculoColeta.Views; using System; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace AtividadesVeiculoColeta { public partial class App : Application { public App() { InitializeComponent(); MainPage = new MainPage(); } protected override void OnStart() { // Handle when your app starts } protected override void OnSleep() { // Handle when your app sleeps } protected override void OnResume() { // Handle when your app resumes } } }
19.060606
43
0.553259
[ "MIT" ]
perfeito/AtividadesVeiculoColeta
src/AtividadesVeiculoColeta/AtividadesVeiculoColeta/App.xaml.cs
631
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Session; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Autofac.AspNetCore.Extensions.Middleware { public class MultitenantSessionMiddleware { private readonly RequestDelegate _next; private readonly ILoggerFactory _loggerFactory; private readonly ISessionStore _sessionStore; private readonly IDataProtectionProvider _dataProtectionProvider; public MultitenantSessionMiddleware( RequestDelegate next, ILoggerFactory loggerFactory, IDataProtectionProvider dataProtectionProvider, ISessionStore sessionStore, IOptions<SessionOptions> options) { if (next == null) { throw new ArgumentNullException(nameof(next)); } if (loggerFactory == null) { throw new ArgumentNullException(nameof(loggerFactory)); } if (dataProtectionProvider == null) { throw new ArgumentNullException(nameof(dataProtectionProvider)); } if (sessionStore == null) { throw new ArgumentNullException(nameof(sessionStore)); } _next = next; _loggerFactory = loggerFactory; _dataProtectionProvider = dataProtectionProvider; _sessionStore = sessionStore; } public Task Invoke(HttpContext context) { var options = context.RequestServices.GetRequiredService<IOptions<SessionOptions>>(); var sessionMiddleware = new SessionMiddleware(_next, _loggerFactory, _dataProtectionProvider, _sessionStore, options); return sessionMiddleware.Invoke(context); } } }
34.04918
130
0.66105
[ "MIT" ]
davidikin45/Autofac.AspNetCore.Extensions
src/Autofac.AspNetCore.Extensions/Middleware/MultitenantSessionMiddleware.cs
2,079
C#
namespace MassTransit.Containers.Tests.DependencyInjection_Tests { using System; using Common_Tests; using Microsoft.Extensions.DependencyInjection; using NUnit.Framework; using Saga; [TestFixture] public class DependencyInjection_Saga : Common_Saga { readonly IServiceProvider _provider; public DependencyInjection_Saga() { _provider = new ServiceCollection() .AddMassTransit(ConfigureRegistration) .BuildServiceProvider(true); } protected override IRegistration Registration => _provider.GetRequiredService<IRegistration>(); protected override ISagaRepository<T> GetSagaRepository<T>() { return _provider.GetService<ISagaRepository<T>>(); } } [TestFixture] public class DependencyInjection_Saga_Endpoint : Common_Saga_Endpoint { readonly IServiceProvider _provider; public DependencyInjection_Saga_Endpoint() { _provider = new ServiceCollection() .AddMassTransit(ConfigureRegistration) .BuildServiceProvider(); } protected override IRegistration Registration => _provider.GetRequiredService<IRegistration>(); protected override ISagaRepository<T> GetSagaRepository<T>() { return _provider.GetService<ISagaRepository<T>>(); } } }
27.339623
103
0.652864
[ "ECL-2.0", "Apache-2.0" ]
DamirAinullin/MassTransit
src/Containers/MassTransit.Containers.Tests/DependencyInjection_Tests/DependencyInjection_Saga.cs
1,449
C#
 namespace GameEngine { public class HealingPotion : Item { public int AmountToHeal { get; set; } public HealingPotion(int id, string name, string namePlural, int amountToHeal) : base(id, name, namePlural) { AmountToHeal = amountToHeal; } } }
20.933333
87
0.582803
[ "MIT" ]
IchimGabriel/Game-Engine
GameEngine/Classes/HealingPotion.cs
316
C#
#region Apache License Version 2.0 /*---------------------------------------------------------------- Copyright 2021 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md ----------------------------------------------------------------*/ #endregion Apache License Version 2.0 /*---------------------------------------------------------------- Copyright (C) 2022 Senparc 文件名:GetPageResultJson.cs 文件功能描述:首页和每页信息返回结果 创建标识:Senparc - 20170726 ----------------------------------------------------------------*/ using Senparc.Weixin.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Senparc.Weixin.Open.WxaAPIs { public class GetPageResultJson : WxJsonResult { public List<string> page_list { get; set; } } }
30.083333
90
0.619806
[ "Apache-2.0" ]
YaChengMu/WeiXinMPSDK
src/Senparc.Weixin.Open/Senparc.Weixin.Open/WxaAPIs/Code/CodeJson/GetPageResultJson.cs
1,500
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.jarvis.Transform; using Aliyun.Acs.jarvis.Transform.V20180206; using System.Collections.Generic; namespace Aliyun.Acs.jarvis.Model.V20180206 { public class DescribeAccessWhiteListGroupRequest : RpcAcsRequest<DescribeAccessWhiteListGroupResponse> { public DescribeAccessWhiteListGroupRequest() : base("jarvis", "2018-02-06", "DescribeAccessWhiteListGroup") { } private string srcIP; private string sourceIp; private int? pageSize; private int? currentPage; private int? whiteListType; private string dstIP; private string lang; private string status; private string sourceCode; public string SrcIP { get { return srcIP; } set { srcIP = value; DictionaryUtil.Add(QueryParameters, "SrcIP", value); } } public string SourceIp { get { return sourceIp; } set { sourceIp = value; DictionaryUtil.Add(QueryParameters, "SourceIp", value); } } public int? PageSize { get { return pageSize; } set { pageSize = value; DictionaryUtil.Add(QueryParameters, "PageSize", value.ToString()); } } public int? CurrentPage { get { return currentPage; } set { currentPage = value; DictionaryUtil.Add(QueryParameters, "CurrentPage", value.ToString()); } } public int? WhiteListType { get { return whiteListType; } set { whiteListType = value; DictionaryUtil.Add(QueryParameters, "WhiteListType", value.ToString()); } } public string DstIP { get { return dstIP; } set { dstIP = value; DictionaryUtil.Add(QueryParameters, "DstIP", value); } } public string Lang { get { return lang; } set { lang = value; DictionaryUtil.Add(QueryParameters, "Lang", value); } } public string Status { get { return status; } set { status = value; DictionaryUtil.Add(QueryParameters, "Status", value); } } public string SourceCode { get { return sourceCode; } set { sourceCode = value; DictionaryUtil.Add(QueryParameters, "SourceCode", value); } } public override bool CheckShowJsonItemName() { return false; } public override DescribeAccessWhiteListGroupResponse GetResponse(Core.Transform.UnmarshallerContext unmarshallerContext) { return DescribeAccessWhiteListGroupResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
20.038674
128
0.641026
[ "Apache-2.0" ]
brightness007/unofficial-aliyun-openapi-net-sdk
aliyun-net-sdk-jarvis/Jarvis/Model/V20180206/DescribeAccessWhiteListGroupRequest.cs
3,627
C#
// Copyright (c) Stride contributors (https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using Stride.Core.Mathematics; namespace Stride.TextureConverter.Requests { /// <summary> /// Request to premultiply the alpha on the texture /// </summary> class ColorKeyRequest : IRequest { public override RequestType Type { get { return RequestType.ColorKey; } } /// <summary> /// Gets or sets the color key. /// </summary> /// <value>The color key.</value> public Color ColorKey { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="ColorKeyRequest"/> class. /// </summary> public ColorKeyRequest(Color colorKey) { ColorKey = colorKey; } } }
32.241379
118
0.62246
[ "MIT" ]
Aggror/Stride
sources/tools/Stride.TextureConverter/Backend/Requests/ColorKeyRequest.cs
935
C#
using System.Text; using NLog; using NLog.LayoutRenderers; namespace Nlog.DocumentDBTarget.Renderes { [LayoutRenderer("entity")] public class Entity : LayoutRenderer { protected override void Append(StringBuilder builder, LogEventInfo logEvent) { var entity = logEvent.Properties["Entity"]; if (entity != null) builder.Append(entity); } } }
24
84
0.585526
[ "MIT" ]
Bistech/NLog.DocumentDB
NLog.DocumentDBTarget/Renderes/Entity.cs
458
C#
// ------------------------------------------------------------------------------ // Copyright (c) 2014 Microsoft 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 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. // ------------------------------------------------------------------------------ namespace Microsoft.Live { using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Net; using System.Threading; using System.Threading.Tasks; using System.Windows; using Microsoft.Live.Operations; /// <summary> /// This is the class that applications use to authenticate the user and obtain access token after user /// grants consent to the application. /// </summary> public sealed partial class LiveAuthClient : INotifyPropertyChanged { #region Constructor /// <summary> /// Creates a new instance of the auth client. /// <param name="clientId">Client id of the application.</param> /// </summary> public LiveAuthClient(string clientId) { if (string.IsNullOrEmpty(clientId)) { throw new ArgumentException( string.Format(ResourceHelper.GetString("InvalidNullParameter"), "clientId"), "clientId"); } this.AuthClient = new PhoneAuthClient(this); this.InitializeMembers(clientId, null); } #endregion #region Properties private ThemeType Theme { get { return Platform.GetThemeType(); } } #endregion #region Public Methods /// <summary> /// Initializes the auth client. Detects if user is already signed in, /// If user is already signed in, creates a valid Session. /// This call is UI-less. /// </summary> /// <returns>A Task object representing the asynchronous operation.</returns> public Task<LiveLoginResult> InitializeAsync() { return this.InitializeAsync(null); } /// <summary> /// Initializes the auth client. Detects if user is already signed in, /// If user is already signed in, creates a valid Session. /// This call is UI-less. /// </summary> /// <param name="scopes">The list of offers that the application is requesting user consent for.</param> /// <returns>A Task object representing the asynchronous operation.</returns> public async Task<LiveLoginResult> InitializeAsync(IEnumerable<string> scopes) { this.PrepareForAsync(); // Always make a call to the server instead of relying on cached access token for two reasons: // 1. user may have revoked the scope // 2. user may have previously consented to the scope via a web app, we should not ask again. // Use a refresh token if present, if not, use silent flow. LiveConnectSession currentSession = this.AuthClient.LoadSession(this); this.scopes = (scopes == null) ? new List<string>() : new List<string>(scopes); bool hasRefreshToken = currentSession != null && !string.IsNullOrEmpty(currentSession.RefreshToken); if (hasRefreshToken) { var refreshOp = new RefreshTokenOperation( this, this.clientId, currentSession.RefreshToken, this.scopes, null); var tcs = new TaskCompletionSource<LiveLoginResult>(); try { LiveLoginResult refreshOpResult = await refreshOp.ExecuteAsync(); this.Session = refreshOpResult.Session; this.AuthClient.SaveSession(this.Session); tcs.TrySetResult(refreshOpResult); } catch (Exception exception) { this.Session = null; tcs.TrySetException(exception); } finally { Interlocked.Decrement(ref this.asyncInProgress); } return await tcs.Task; } // If we do NOT have a refresh token, use the silent flow. return await this.AuthenticateAsync(true /* silent flow */); } /// <summary> /// Displays the login/consent UI and returns a Session object when user completes the auth flow. /// </summary> /// <param name="scopes">The list of offers that the application is requesting user consent for.</param> /// <returns>A Task object representing the asynchronous operation.</returns> public async Task<LiveLoginResult> LoginAsync(IEnumerable<string> scopes) { if (scopes == null && this.scopes == null) { throw new ArgumentNullException("scopes"); } if (scopes != null) { this.scopes = new List<string>(scopes); } bool onUiThread = Deployment.Current.CheckAccess(); if (!onUiThread) { throw new InvalidOperationException( string.Format(ResourceHelper.GetString("NotOnUiThread"), "LoginAsync")); } this.PrepareForAsync(); return await this.AuthenticateAsync(false /* silent flow */); } /// <summary> /// Logs user out of the application. Clears any cached Session data. /// </summary> public void Logout() { this.Session = null; this.AuthClient.CloseSession(); } #endregion #region Internal methods /// <summary> /// Creates a LiveConnectSession object based on the parsed response. /// </summary> internal static LiveConnectSession CreateSession(LiveAuthClient client, IDictionary<string, object> result) { var session = new LiveConnectSession(client); Debug.Assert(result.ContainsKey(AuthConstants.AccessToken)); if (result.ContainsKey(AuthConstants.AccessToken)) { session.AccessToken = result[AuthConstants.AccessToken] as string; if (result.ContainsKey(AuthConstants.AuthenticationToken)) { session.AuthenticationToken = result[AuthConstants.AuthenticationToken] as string; } if (result.ContainsKey(AuthConstants.ExpiresIn)) { if (result[AuthConstants.ExpiresIn] is string) { session.Expires = LiveAuthClient.CalculateExpiration(result[AuthConstants.ExpiresIn] as string); } else { session.Expires = DateTimeOffset.UtcNow.AddSeconds((int)result[AuthConstants.ExpiresIn]); } } if (result.ContainsKey(AuthConstants.Scope)) { session.Scopes = LiveAuthClient.ParseScopeString(HttpUtility.UrlDecode(result[AuthConstants.Scope] as string)); } if (result.ContainsKey(AuthConstants.RefreshToken)) { session.RefreshToken = result[AuthConstants.RefreshToken] as string; } } return session; } /// <summary> /// Retrieve a new access token based on current session information. /// </summary> internal bool RefreshToken(Action<LiveLoginResult> completionCallback) { if (this.Session.IsValid) { return false; } var refreshOp = new RefreshTokenOperation( this, this.clientId, this.Session.RefreshToken, this.Session.Scopes, null) { OperationCompletedCallback = completionCallback }; refreshOp.Execute(); return true; } internal Task<LiveLoginResult> RefreshTokenAsync() { var refreshOp = new RefreshTokenOperation( this, this.clientId, this.Session.RefreshToken, this.Session.Scopes, null); return refreshOp.ExecuteAsync(); } private Task<LiveLoginResult> AuthenticateAsync(bool useSilentFlow) { var tcs = new TaskCompletionSource<LiveLoginResult>(); this.AuthClient.AuthenticateAsync( this.clientId, LiveAuthClient.BuildScopeString(this.scopes), useSilentFlow, (string responseData, Exception exception) => { if (exception != null) { tcs.TrySetException(exception); Interlocked.Decrement(ref this.asyncInProgress); } else { this.ProcessAuthResponse(responseData, (LiveLoginResult result) => { if (result.Error != null) { this.Session = null; tcs.TrySetException(result.Error); } else { this.Session = result.Session; this.AuthClient.SaveSession(this.Session); tcs.TrySetResult(result); } Interlocked.Decrement(ref this.asyncInProgress); }); } }); return tcs.Task; } #endregion } }
36.835526
120
0.541436
[ "MIT" ]
TheWhiteEagle/LiveSDK-for-Windows
src/WP8/Source/Public/LiveAuthClient.cs
11,198
C#
namespace BSim { public interface IRobotController { void ExecuteRobotCommand(RobotCommand command, IBehavior behavior); } }
18.25
75
0.705479
[ "MIT" ]
danroth27/BSim
Assets/IRobotController.cs
148
C#
using Nimbus.MessageContracts; namespace Nimbus.UnitTests.InfrastructureTests.MessageContracts { public class MyEventWithALongName : IBusEvent { } }
19.111111
63
0.732558
[ "MIT" ]
sbalkum/Nimbus
src/Tests/Nimbus.UnitTests/InfrastructureTests/MessageContracts/MyEventWithALongName.cs
174
C#
using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Unity.RenderPipelines.HighDefinition.Editor")] [assembly: InternalsVisibleTo("Unity.RenderPipelines.HighDefinition.Editor.Tests")] [assembly: InternalsVisibleTo("Unity.RenderPipelines.HighDefinition.Runtime.Tests")] [assembly: InternalsVisibleTo("HDRP_TestRunner")] [assembly: InternalsVisibleTo("Unity.TextMeshPro.Editor")]
49.5
84
0.838384
[ "MIT" ]
ACBGZM/JasonMaToonRenderPipeline
Packages/com.unity.render-pipelines.high-definition@10.5.0/Runtime/AssemblyInfo.cs
396
C#
public class Solution { public int LengthOfLongestSubstring(string s) { var n = s.Length; var map = new int[128]; int l = 0, r = 0, res = 0; while(r < n){ var c = s[r]; l = Math.Max(map[c], l); res = Math.Max(res, r-l+1); map[c] = ++r; } return res; } }
24.1875
51
0.392765
[ "MIT" ]
Igorium/Leetcode
medium/3. Longest Substring Without Repeating Characters.txt.cs
387
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using SeaQuail.Schema; namespace SeaQuail.SchemaQuery { public class SQRemoveForeignKey : SQSchemaQueryBase { public SQTable FromTable { get; set; } public string FromColumnName { get; set; } public SQTable ToTable { get; set; } public string ToColumnName { get; set; } public string ForeignKeyName { get; set; } } }
25.388889
55
0.680525
[ "MIT" ]
gjcampbell/seaquail-legacy
sourceCode/SeaQuail/SchemaQuery/SQRemoveForeignKey.cs
459
C#
//------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.42000 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ namespace ALinq.Resources { using System; /// <summary> /// 一个强类型的资源类,用于查找本地化的字符串等。 /// </summary> // 此类是由 StronglyTypedResourceBuilder // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen // (以 /str 作为命令选项),或重新生成 VS 项目。 [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class ALinq_SqlClient { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal ALinq_SqlClient() { } /// <summary> /// 返回此类使用的缓存的 ResourceManager 实例。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ALinq.Resources.ALinq.SqlClient", typeof(ALinq_SqlClient).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// 使用此强类型资源类,为所有资源查找 /// 重写当前线程的 CurrentUICulture 属性。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// 查找类似 The string parameter &apos;{0}&apos; was expected to have length greater than zero. 的本地化字符串。 /// </summary> internal static string ArgumentEmpty { get { return ResourceManager.GetString("ArgumentEmpty", resourceCulture); } } /// <summary> /// 查找类似 One or more type mismatches in argument &apos;{0}&apos;. 的本地化字符串。 /// </summary> internal static string ArgumentTypeMismatch { get { return ResourceManager.GetString("ArgumentTypeMismatch", resourceCulture); } } /// <summary> /// 查找类似 The argument &apos;{0}&apos; was the wrong type. Expected &apos;{1}&apos;. Actual &apos;{2}&apos;. 的本地化字符串。 /// </summary> internal static string ArgumentWrongType { get { return ResourceManager.GetString("ArgumentWrongType", resourceCulture); } } /// <summary> /// 查找类似 The argument &apos;{0}&apos; was the wrong value. 的本地化字符串。 /// </summary> internal static string ArgumentWrongValue { get { return ResourceManager.GetString("ArgumentWrongValue", resourceCulture); } } /// <summary> /// 查找类似 A query parameter cannot be of type &apos;{0}&apos;. 的本地化字符串。 /// </summary> internal static string BadParameterType { get { return ResourceManager.GetString("BadParameterType", resourceCulture); } } /// <summary> /// 查找类似 Bad projection in Select. 的本地化字符串。 /// </summary> internal static string BadProjectionInSelect { get { return ResourceManager.GetString("BadProjectionInSelect", resourceCulture); } } /// <summary> /// 查找类似 Binary operator not recognized: {0} 的本地化字符串。 /// </summary> internal static string BinaryOperatorNotRecognized { get { return ResourceManager.GetString("BinaryOperatorNotRecognized", resourceCulture); } } /// <summary> /// 查找类似 The type &apos;{0}&apos; is not supported in aggregation operations. 的本地化字符串。 /// </summary> internal static string CannotAggregateType { get { return ResourceManager.GetString("CannotAggregateType", resourceCulture); } } /// <summary> /// 查找类似 The null value cannot be assigned to a member with type {0} which is a non-nullable value type. 的本地化字符串。 /// </summary> internal static string CannotAssignNull { get { return ResourceManager.GetString("CannotAssignNull", resourceCulture); } } /// <summary> /// 查找类似 Cannot assign value to member &apos;{0}&apos;. It does not define a setter. 的本地化字符串。 /// </summary> internal static string CannotAssignToMember { get { return ResourceManager.GetString("CannotAssignToMember", resourceCulture); } } /// <summary> /// 查找类似 Cannot compare entities associated with different tables. 的本地化字符串。 /// </summary> internal static string CannotCompareItemsAssociatedWithDifferentTable { get { return ResourceManager.GetString("CannotCompareItemsAssociatedWithDifferentTable", resourceCulture); } } /// <summary> /// 查找类似 Cannot convert type &apos;{0}&apos; to EntityRef/Link. 的本地化字符串。 /// </summary> internal static string CannotConvertToEntityRef { get { return ResourceManager.GetString("CannotConvertToEntityRef", resourceCulture); } } /// <summary> /// 查找类似 Cannot delete items of type {0}. 的本地化字符串。 /// </summary> internal static string CannotDeleteTypesOf { get { return ResourceManager.GetString("CannotDeleteTypesOf", resourceCulture); } } /// <summary> /// 查找类似 The query results cannot be enumerated more than once. 的本地化字符串。 /// </summary> internal static string CannotEnumerateResultsMoreThanOnce { get { return ResourceManager.GetString("CannotEnumerateResultsMoreThanOnce", resourceCulture); } } /// <summary> /// 查找类似 Explicit construction of entity type &apos;{0}&apos; in query is not allowed. 的本地化字符串。 /// </summary> internal static string CannotMaterializeEntityType { get { return ResourceManager.GetString("CannotMaterializeEntityType", resourceCulture); } } /// <summary> /// 查找类似 Cannot translate expression to SQL for this server version. 的本地化字符串。 /// </summary> internal static string CannotTranslateExpressionToSql { get { return ResourceManager.GetString("CannotTranslateExpressionToSql", resourceCulture); } } /// <summary> /// 查找类似 Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator. 的本地化字符串。 /// </summary> internal static string CapturedValuesCannotBeSequences { get { return ResourceManager.GetString("CapturedValuesCannotBeSequences", resourceCulture); } } /// <summary> /// 查找类似 Class literals are not allowed: {0}. 的本地化字符串。 /// </summary> internal static string ClassLiteralsNotAllowed { get { return ResourceManager.GetString("ClassLiteralsNotAllowed", resourceCulture); } } /// <summary> /// 查找类似 Client case should not hold &apos;{0}&apos;. It should probably have been SqlSimpleCase. 的本地化字符串。 /// </summary> internal static string ClientCaseShouldNotHold { get { return ResourceManager.GetString("ClientCaseShouldNotHold", resourceCulture); } } /// <summary> /// 查找类似 Expected Node with CLR Type of &apos;bool&apos; to have SQL type of &apos;Bit&apos; or &apos;Predicate&apos;. Instead, it was type &apos;{0}&apos;. 的本地化字符串。 /// </summary> internal static string ClrBoolDoesNotAgreeWithSqlType { get { return ResourceManager.GetString("ClrBoolDoesNotAgreeWithSqlType", resourceCulture); } } /// <summary> /// 查找类似 Column cannot refer to itself. 的本地化字符串。 /// </summary> internal static string ColumnCannotReferToItself { get { return ResourceManager.GetString("ColumnCannotReferToItself", resourceCulture); } } /// <summary> /// 查找类似 Column&apos;s ClrType did not agree with its Expression&apos;s ClrType. 的本地化字符串。 /// </summary> internal static string ColumnClrTypeDoesNotAgreeWithExpressionsClrType { get { return ResourceManager.GetString("ColumnClrTypeDoesNotAgreeWithExpressionsClrType", resourceCulture); } } /// <summary> /// 查找类似 Column &apos;{0}&apos; is defined in multiple places. 的本地化字符串。 /// </summary> internal static string ColumnIsDefinedInMultiplePlaces { get { return ResourceManager.GetString("ColumnIsDefinedInMultiplePlaces", resourceCulture); } } /// <summary> /// 查找类似 Column &apos;{0}&apos; is not accessible through &apos;distinct&apos;. 的本地化字符串。 /// </summary> internal static string ColumnIsNotAccessibleThroughDistinct { get { return ResourceManager.GetString("ColumnIsNotAccessibleThroughDistinct", resourceCulture); } } /// <summary> /// 查找类似 Column &apos;{0}&apos; is not accessible through group-by. 的本地化字符串。 /// </summary> internal static string ColumnIsNotAccessibleThroughGroupBy { get { return ResourceManager.GetString("ColumnIsNotAccessibleThroughGroupBy", resourceCulture); } } /// <summary> /// 查找类似 Column referenced is not in scope: &apos;{0}&apos;. 的本地化字符串。 /// </summary> internal static string ColumnReferencedIsNotInScope { get { return ResourceManager.GetString("ColumnReferencedIsNotInScope", resourceCulture); } } /// <summary> /// 查找类似 Comparison operators not supported for type &apos;{0}&apos; 的本地化字符串。 /// </summary> internal static string ComparisonNotSupportedForType { get { return ResourceManager.GetString("ComparisonNotSupportedForType", resourceCulture); } } /// <summary> /// 查找类似 Compiled queries across DataContexts with different LoadOptions not supported. 的本地化字符串。 /// </summary> internal static string CompiledQueryAgainstMultipleShapesNotSupported { get { return ResourceManager.GetString("CompiledQueryAgainstMultipleShapesNotSupported", resourceCulture); } } /// <summary> /// 查找类似 A compiled query cannot return type &apos;{0}&apos;. 的本地化字符串。 /// </summary> internal static string CompiledQueryCannotReturnType { get { return ResourceManager.GetString("CompiledQueryCannotReturnType", resourceCulture); } } /// <summary> /// 查找类似 Constructed arrays are only supported for &apos;Contains&apos;. 的本地化字符串。 /// </summary> internal static string ConstructedArraysNotSupported { get { return ResourceManager.GetString("ConstructedArraysNotSupported", resourceCulture); } } /// <summary> /// 查找类似 SqlContext is not initialized. 的本地化字符串。 /// </summary> internal static string ContextNotInitialized { get { return ResourceManager.GetString("ContextNotInitialized", resourceCulture); } } /// <summary> /// 查找类似 There is no supported conversion from a Boolean to a Character type. 的本地化字符串。 /// </summary> internal static string ConvertToCharFromBoolNotSupported { get { return ResourceManager.GetString("ConvertToCharFromBoolNotSupported", resourceCulture); } } /// <summary> /// 查找类似 Only DateTimes or strings can be converted to DateTime. 的本地化字符串。 /// </summary> internal static string ConvertToDateTimeOnlyForDateTimeOrString { get { return ResourceManager.GetString("ConvertToDateTimeOnlyForDateTimeOrString", resourceCulture); } } /// <summary> /// 查找类似 Could not assign sequence of {0} to type {1}. 的本地化字符串。 /// </summary> internal static string CouldNotAssignSequence { get { return ResourceManager.GetString("CouldNotAssignSequence", resourceCulture); } } /// <summary> /// 查找类似 MemberInfo &apos;{0}&apos; had no corresponding field or property. 的本地化字符串。 /// </summary> internal static string CouldNotConvertToPropertyOrField { get { return ResourceManager.GetString("CouldNotConvertToPropertyOrField", resourceCulture); } } /// <summary> /// 查找类似 Unable to determine catalog name. 的本地化字符串。 /// </summary> internal static string CouldNotDetermineCatalogName { get { return ResourceManager.GetString("CouldNotDetermineCatalogName", resourceCulture); } } /// <summary> /// 查找类似 Unable to determine SQL type for &apos;{0}&apos; that can also be generated by the server. 的本地化字符串。 /// </summary> internal static string CouldNotDetermineDbGeneratedSqlType { get { return ResourceManager.GetString("CouldNotDetermineDbGeneratedSqlType", resourceCulture); } } /// <summary> /// 查找类似 Unable to determine SQL type for &apos;{0}&apos;. 的本地化字符串。 /// </summary> internal static string CouldNotDetermineSqlType { get { return ResourceManager.GetString("CouldNotDetermineSqlType", resourceCulture); } } /// <summary> /// 查找类似 Could not get the ClrType. 的本地化字符串。 /// </summary> internal static string CouldNotGetClrType { get { return ResourceManager.GetString("CouldNotGetClrType", resourceCulture); } } /// <summary> /// 查找类似 Could not get the SqlType. 的本地化字符串。 /// </summary> internal static string CouldNotGetSqlType { get { return ResourceManager.GetString("CouldNotGetSqlType", resourceCulture); } } /// <summary> /// 查找类似 Could not handle alias ref of {0}. 的本地化字符串。 /// </summary> internal static string CouldNotHandleAliasRef { get { return ResourceManager.GetString("CouldNotHandleAliasRef", resourceCulture); } } /// <summary> /// 查找类似 Could not translate expression &apos;{0}&apos; into SQL and could not treat it as a local expression. 的本地化字符串。 /// </summary> internal static string CouldNotTranslateExpressionForReading { get { return ResourceManager.GetString("CouldNotTranslateExpressionForReading", resourceCulture); } } /// <summary> /// 查找类似 Unable to create database because mapped class &apos;{0}&apos; has zero members. 的本地化字符串。 /// </summary> internal static string CreateDatabaseFailedBecauseOfClassWithNoMembers { get { return ResourceManager.GetString("CreateDatabaseFailedBecauseOfClassWithNoMembers", resourceCulture); } } /// <summary> /// 查找类似 Unable to create database because data context &apos;{0}&apos; has no tables. 的本地化字符串。 /// </summary> internal static string CreateDatabaseFailedBecauseOfContextWithNoTables { get { return ResourceManager.GetString("CreateDatabaseFailedBecauseOfContextWithNoTables", resourceCulture); } } /// <summary> /// 查找类似 Unable to create database because the database &apos;{0}&apos; already exists. 的本地化字符串。 /// </summary> internal static string CreateDatabaseFailedBecauseSqlCEDatabaseAlreadyExists { get { return ResourceManager.GetString("CreateDatabaseFailedBecauseSqlCEDatabaseAlreadyExists", resourceCulture); } } /// <summary> /// 查找类似 Operation not allowed after DeleteDatabase call. 的本地化字符串。 /// </summary> internal static string DatabaseDeleteThroughContext { get { return ResourceManager.GetString("DatabaseDeleteThroughContext", resourceCulture); } } /// <summary> /// 查找类似 Deferred member not one of EntitySet, EntityRef or Link. 的本地化字符串。 /// </summary> internal static string DeferredMemberWrongType { get { return ResourceManager.GetString("DeferredMemberWrongType", resourceCulture); } } /// <summary> /// 查找类似 Did not expect &apos;as&apos; operator in &apos;{0}&apos;. 的本地化字符串。 /// </summary> internal static string DidNotExpectAs { get { return ResourceManager.GetString("DidNotExpectAs", resourceCulture); } } /// <summary> /// 查找类似 Did not expect type binding back. This should result in a type case not a simple case. 的本地化字符串。 /// </summary> internal static string DidNotExpectTypeBinding { get { return ResourceManager.GetString("DidNotExpectTypeBinding", resourceCulture); } } /// <summary> /// 查找类似 Did not expect operation to change result type. Original type was &apos;{0}&apos; new type is &apos;{1}&apos;. 的本地化字符串。 /// </summary> internal static string DidNotExpectTypeChange { get { return ResourceManager.GetString("DidNotExpectTypeChange", resourceCulture); } } /// <summary> /// 查找类似 Distributed transactions are not allowed. 的本地化字符串。 /// </summary> internal static string DistributedTransactionsAreNotAllowed { get { return ResourceManager.GetString("DistributedTransactionsAreNotAllowed", resourceCulture); } } /// <summary> /// 查找类似 Empty case is not supported. 的本地化字符串。 /// </summary> internal static string EmptyCaseNotSupported { get { return ResourceManager.GetString("EmptyCaseNotSupported", resourceCulture); } } /// <summary> /// 查找类似 &apos;Except&apos; is not supported for hierarchical result types. 的本地化字符串。 /// </summary> internal static string ExceptNotSupportedForHierarchicalTypes { get { return ResourceManager.GetString("ExceptNotSupportedForHierarchicalTypes", resourceCulture); } } /// <summary> /// 查找类似 Expected a &apos;Bit&apos; here but found a &apos;Predicate&apos;. 的本地化字符串。 /// </summary> internal static string ExpectedBitFoundPredicate { get { return ResourceManager.GetString("ExpectedBitFoundPredicate", resourceCulture); } } /// <summary> /// 查找类似 Expected Clr Types to agree. One was &apos;{0}&apos; the other was &apos;{1}&apos;. 的本地化字符串。 /// </summary> internal static string ExpectedClrTypesToAgree { get { return ResourceManager.GetString("ExpectedClrTypesToAgree", resourceCulture); } } /// <summary> /// 查找类似 Expected no ObjectType nodes to remain. 的本地化字符串。 /// </summary> internal static string ExpectedNoObjectType { get { return ResourceManager.GetString("ExpectedNoObjectType", resourceCulture); } } /// <summary> /// 查找类似 Expected a &apos;Predicate&apos; here but found a &apos;Bit&apos;. 的本地化字符串。 /// </summary> internal static string ExpectedPredicateFoundBit { get { return ResourceManager.GetString("ExpectedPredicateFoundBit", resourceCulture); } } /// <summary> /// 查找类似 Expected type &apos;{0}&apos; of argument &apos;{1}&apos; to implement IQueryable of &apos;{2}&apos;. 的本地化字符串。 /// </summary> internal static string ExpectedQueryableArgument { get { return ResourceManager.GetString("ExpectedQueryableArgument", resourceCulture); } } /// <summary> /// 查找类似 Expression is not a deferred query source. 的本地化字符串。 /// </summary> internal static string ExpressionNotDeferredQuerySource { get { return ResourceManager.GetString("ExpressionNotDeferredQuerySource", resourceCulture); } } /// <summary> /// 查找类似 General collection materialization is not supported. 的本地化字符串。 /// </summary> internal static string GeneralCollectionMaterializationNotSupported { get { return ResourceManager.GetString("GeneralCollectionMaterializationNotSupported", resourceCulture); } } /// <summary> /// 查找类似 A grouping cannot be used as an order criterion; you may want to use its key instead. 的本地化字符串。 /// </summary> internal static string GroupingNotSupportedAsOrderCriterion { get { return ResourceManager.GetString("GroupingNotSupportedAsOrderCriterion", resourceCulture); } } /// <summary> /// 查找类似 The IIF method returns two separate types: {0}, {1}. Translation to SQL does not support different return types. 的本地化字符串。 /// </summary> internal static string IifReturnTypesMustBeEqual { get { return ResourceManager.GetString("IifReturnTypesMustBeEqual", resourceCulture); } } /// <summary> /// 查找类似 Should not have reached this point. 的本地化字符串。 /// </summary> internal static string Impossible { get { return ResourceManager.GetString("Impossible", resourceCulture); } } /// <summary> /// 查找类似 The translation of String.IndexOf to SQL does not support versions with a StringComparison argument. 的本地化字符串。 /// </summary> internal static string IndexOfWithStringComparisonArgNotSupported { get { return ResourceManager.GetString("IndexOfWithStringComparisonArgNotSupported", resourceCulture); } } /// <summary> /// 查找类似 Descent limit exceeded. 的本地化字符串。 /// </summary> internal static string InfiniteDescent { get { return ResourceManager.GetString("InfiniteDescent", resourceCulture); } } /// <summary> /// 查找类似 The item of an insert must be a constant value expression. 的本地化字符串。 /// </summary> internal static string InsertItemMustBeConstant { get { return ResourceManager.GetString("InsertItemMustBeConstant", resourceCulture); } } /// <summary> /// 查找类似 &apos;Intersect&apos; is not supported for hierarchical result types. 的本地化字符串。 /// </summary> internal static string IntersectNotSupportedForHierarchicalTypes { get { return ResourceManager.GetString("IntersectNotSupportedForHierarchicalTypes", resourceCulture); } } /// <summary> /// 查找类似 &apos;{0}&apos; must be string, or DbConnection. 的本地化字符串。 /// </summary> internal static string InvalidConnectionArgument { get { return ResourceManager.GetString("InvalidConnectionArgument", resourceCulture); } } /// <summary> /// 查找类似 The primary key column of type &apos;{0}&apos; cannot be generated by the server. 的本地化字符串。 /// </summary> internal static string InvalidDbGeneratedType { get { return ResourceManager.GetString("InvalidDbGeneratedType", resourceCulture); } } /// <summary> /// 查找类似 Could not format node &apos;{0}&apos; for execution as SQL. 的本地化字符串。 /// </summary> internal static string InvalidFormatNode { get { return ResourceManager.GetString("InvalidFormatNode", resourceCulture); } } /// <summary> /// 查找类似 The group by operation contains an expression that cannot be translated. 的本地化字符串。 /// </summary> internal static string InvalidGroupByExpression { get { return ResourceManager.GetString("InvalidGroupByExpression", resourceCulture); } } /// <summary> /// 查找类似 A group by expression can only contain non-constant scalars that are comparable by the server. The expression with type &apos;{0}&apos; is not comparable. 的本地化字符串。 /// </summary> internal static string InvalidGroupByExpressionType { get { return ResourceManager.GetString("InvalidGroupByExpressionType", resourceCulture); } } /// <summary> /// 查找类似 The method &apos;{0}&apos; is not mapped as a stored procedure or user-defined function. 的本地化字符串。 /// </summary> internal static string InvalidMethodExecution { get { return ResourceManager.GetString("InvalidMethodExecution", resourceCulture); } } /// <summary> /// 查找类似 An order by expression can only contain non-constant scalars that are order comparable by the server. The expression with type &apos;{0}&apos; is not order comparable. 的本地化字符串。 /// </summary> internal static string InvalidOrderByExpression { get { return ResourceManager.GetString("InvalidOrderByExpression", resourceCulture); } } /// <summary> /// 查找类似 The specified type &apos;{0}&apos; is not a valid provider type. 的本地化字符串。 /// </summary> internal static string InvalidProviderType { get { return ResourceManager.GetString("InvalidProviderType", resourceCulture); } } /// <summary> /// 查找类似 Reference to removed alias discovered during deflation. 的本地化字符串。 /// </summary> internal static string InvalidReferenceToRemovedAliasDuringDeflation { get { return ResourceManager.GetString("InvalidReferenceToRemovedAliasDuringDeflation", resourceCulture); } } /// <summary> /// 查找类似 &apos;{0}&apos; is not a valid return type for a mapped stored procedure method. 的本地化字符串。 /// </summary> internal static string InvalidReturnFromSproc { get { return ResourceManager.GetString("InvalidReturnFromSproc", resourceCulture); } } /// <summary> /// 查找类似 Sequence operator call is only valid for Sequence, Queryable or DataQueryExtensions not for &apos;{0}&apos;. 的本地化字符串。 /// </summary> internal static string InvalidSequenceOperatorCall { get { return ResourceManager.GetString("InvalidSequenceOperatorCall", resourceCulture); } } /// <summary> /// 查找类似 The translation of String.LastIndexOf to SQL does not support versions with a StringComparison argument. 的本地化字符串。 /// </summary> internal static string LastIndexOfWithStringComparisonArgNotSupported { get { return ResourceManager.GetString("LastIndexOfWithStringComparisonArgNotSupported", resourceCulture); } } /// <summary> /// 查找类似 Translation would contain LEN of Text or NText arguments: {0} 的本地化字符串。 /// </summary> internal static string LenOfTextOrNTextNotSupported { get { return ResourceManager.GetString("LenOfTextOrNTextNotSupported", resourceCulture); } } /// <summary> /// 查找类似 Attempting to delete the database &apos;{0}&apos;. 的本地化字符串。 /// </summary> internal static string LogAttemptingToDeleteDatabase { get { return ResourceManager.GetString("LogAttemptingToDeleteDatabase", resourceCulture); } } /// <summary> /// 查找类似 {0}: {1}. 的本地化字符串。 /// </summary> internal static string LogGeneralInfoMessage { get { return ResourceManager.GetString("LogGeneralInfoMessage", resourceCulture); } } /// <summary> /// 查找类似 Execute stored procedure: {0}({1}). 的本地化字符串。 /// </summary> internal static string LogStoredProcedureExecution { get { return ResourceManager.GetString("LogStoredProcedureExecution", resourceCulture); } } /// <summary> /// 查找类似 The type &apos;{0}&apos; must declare a default (parameterless) constructor in order to be constructed during mapping. 的本地化字符串。 /// </summary> internal static string MappedTypeMustHaveDefaultConstructor { get { return ResourceManager.GetString("MappedTypeMustHaveDefaultConstructor", resourceCulture); } } /// <summary> /// 查找类似 For translation to SQL, the Math.Round method needs a MidpointRounding parameter. Use &apos;AwayFromZero&apos; to specify the SQL function ROUND. 的本地化字符串。 /// </summary> internal static string MathRoundNotSupported { get { return ResourceManager.GetString("MathRoundNotSupported", resourceCulture); } } /// <summary> /// 查找类似 Translation would contain an out parameter of type Text, NText or Image: {0} 的本地化字符串。 /// </summary> internal static string MaxSizeNotSupported { get { return ResourceManager.GetString("MaxSizeNotSupported", resourceCulture); } } /// <summary> /// 查找类似 Member access &apos;{0}&apos; of &apos;{1}&apos; not legal on type &apos;{2}. 的本地化字符串。 /// </summary> internal static string MemberAccessIllegal { get { return ResourceManager.GetString("MemberAccessIllegal", resourceCulture); } } /// <summary> /// 查找类似 The member &apos;{0}.{1}&apos; has no supported translation to SQL. 的本地化字符串。 /// </summary> internal static string MemberCannotBeTranslated { get { return ResourceManager.GetString("MemberCannotBeTranslated", resourceCulture); } } /// <summary> /// 查找类似 Member &apos;{0}.{1}&apos; could not be translated. 的本地化字符串。 /// </summary> internal static string MemberCouldNotBeTranslated { get { return ResourceManager.GetString("MemberCouldNotBeTranslated", resourceCulture); } } /// <summary> /// 查找类似 Binding error: Member &apos;{0}.{1}&apos; not found in projection. 的本地化字符串。 /// </summary> internal static string MemberNotPartOfProjection { get { return ResourceManager.GetString("MemberNotPartOfProjection", resourceCulture); } } /// <summary> /// 查找类似 The method &apos;{0}&apos; has a translation to SQL, but the overload &apos;{1}&apos; does not. 的本地化字符串。 /// </summary> internal static string MethodFormHasNoSupportConversionToSql { get { return ResourceManager.GetString("MethodFormHasNoSupportConversionToSql", resourceCulture); } } /// <summary> /// 查找类似 Method &apos;{0}&apos; has no supported translation to SQL. 的本地化字符串。 /// </summary> internal static string MethodHasNoSupportConversionToSql { get { return ResourceManager.GetString("MethodHasNoSupportConversionToSql", resourceCulture); } } /// <summary> /// 查找类似 The method specified ({0}) is not mapped to a stored procedure. 的本地化字符串。 /// </summary> internal static string MethodNotMappedToStoredProcedure { get { return ResourceManager.GetString("MethodNotMappedToStoredProcedure", resourceCulture); } } /// <summary> /// 查找类似 No method in type &apos;{0}&apos; matching arguments. 的本地化字符串。 /// </summary> internal static string NoMethodInTypeMatchingArguments { get { return ResourceManager.GetString("NoMethodInTypeMatchingArguments", resourceCulture); } } /// <summary> /// 查找类似 Only arguments that can be evaluated on the client are supported for the {0} method. 的本地化字符串。 /// </summary> internal static string NonConstantExpressionsNotSupportedFor { get { return ResourceManager.GetString("NonConstantExpressionsNotSupportedFor", resourceCulture); } } /// <summary> /// 查找类似 Only arguments that can be evaluated on the client are supported for the MidpointRounding argument in Math.Round. 的本地化字符串。 /// </summary> internal static string NonConstantExpressionsNotSupportedForRounding { get { return ResourceManager.GetString("NonConstantExpressionsNotSupportedForRounding", resourceCulture); } } /// <summary> /// 查找类似 Parameterless aggregate operator &apos;{0}&apos; is not supported over projections. 的本地化字符串。 /// </summary> internal static string NonCountAggregateFunctionsAreNotValidOnProjections { get { return ResourceManager.GetString("NonCountAggregateFunctionsAreNotValidOnProjections", resourceCulture); } } /// <summary> /// 查找类似 ALinq 的本地化字符串。 /// </summary> internal static string OwningTeam { get { return ResourceManager.GetString("OwningTeam", resourceCulture); } } /// <summary> /// 查找类似 The parameter &apos;{0}&apos; is not in scope. 的本地化字符串。 /// </summary> internal static string ParameterNotInScope { get { return ResourceManager.GetString("ParameterNotInScope", resourceCulture); } } /// <summary> /// 查找类似 Parameters cannot be sequences. 的本地化字符串。 /// </summary> internal static string ParametersCannotBeSequences { get { return ResourceManager.GetString("ParametersCannotBeSequences", resourceCulture); } } /// <summary> /// 查找类似 Provider cannot be accessed after Dispose. 的本地化字符串。 /// </summary> internal static string ProviderCannotBeUsedAfterDispose { get { return ResourceManager.GetString("ProviderCannotBeUsedAfterDispose", resourceCulture); } } /// <summary> /// 查找类似 Cannot open &apos;{0}&apos;. Provider &apos;{1}&apos; not installed. 的本地化字符串。 /// </summary> internal static string ProviderNotInstalled { get { return ResourceManager.GetString("ProviderNotInstalled", resourceCulture); } } /// <summary> /// 查找类似 Queries with local collections are not supported 的本地化字符串。 /// </summary> internal static string QueryOnLocalCollectionNotSupported { get { return ResourceManager.GetString("QueryOnLocalCollectionNotSupported", resourceCulture); } } /// <summary> /// 查找类似 The query operator &apos;{0}&apos; is not supported. 的本地化字符串。 /// </summary> internal static string QueryOperatorNotSupported { get { return ResourceManager.GetString("QueryOperatorNotSupported", resourceCulture); } } /// <summary> /// 查找类似 Unsupported overload used for query operator &apos;{0}&apos;. 的本地化字符串。 /// </summary> internal static string QueryOperatorOverloadNotSupported { get { return ResourceManager.GetString("QueryOperatorOverloadNotSupported", resourceCulture); } } /// <summary> /// 查找类似 Reader used after dispose. 的本地化字符串。 /// </summary> internal static string ReaderUsedAfterDispose { get { return ResourceManager.GetString("ReaderUsedAfterDispose", resourceCulture); } } /// <summary> /// 查找类似 The required column &apos;{0}&apos; does not exist in the results. 的本地化字符串。 /// </summary> internal static string RequiredColumnDoesNotExist { get { return ResourceManager.GetString("RequiredColumnDoesNotExist", resourceCulture); } } /// <summary> /// 查找类似 Result type &apos;{0}&apos; is not mapped to function &apos;{1}&apos;. 的本地化字符串。 /// </summary> internal static string ResultTypeNotMappedToFunction { get { return ResourceManager.GetString("ResultTypeNotMappedToFunction", resourceCulture); } } /// <summary> /// 查找类似 SelectMany does not support strings. 的本地化字符串。 /// </summary> internal static string SelectManyDoesNotSupportStrings { get { return ResourceManager.GetString("SelectManyDoesNotSupportStrings", resourceCulture); } } /// <summary> /// 查找类似 Sequence operators not supported for type &apos;{0}&apos; 的本地化字符串。 /// </summary> internal static string SequenceOperatorsNotSupportedForType { get { return ResourceManager.GetString("SequenceOperatorsNotSupportedForType", resourceCulture); } } /// <summary> /// 查找类似 Simple case should not hold &apos;{0}&apos; should probably have been SqlClientCase. 的本地化字符串。 /// </summary> internal static string SimpleCaseShouldNotHold { get { return ResourceManager.GetString("SimpleCaseShouldNotHold", resourceCulture); } } /// <summary> /// 查找类似 The Skip() operator is valid only over ordered queries. 的本地化字符串。 /// </summary> internal static string SkipIsValidOnlyOverOrderedQueries { get { return ResourceManager.GetString("SkipIsValidOnlyOverOrderedQueries", resourceCulture); } } /// <summary> /// 查找类似 The Skip operator is not supported for sequences containing sequences (with the exception of IGrouping under SQL Server 2005). 的本地化字符串。 /// </summary> internal static string SkipNotSupportedForSequenceTypes { get { return ResourceManager.GetString("SkipNotSupportedForSequenceTypes", resourceCulture); } } /// <summary> /// 查找类似 This provider supports Skip() only over ordered queries returning entities or projections that contain all identity columns, where the query is a single-table (non-join) query, or is a Distinct, Except, Intersect, or Union (not Concat) operation. 的本地化字符串。 /// </summary> internal static string SkipRequiresSingleTableQueryWithPKs { get { return ResourceManager.GetString("SkipRequiresSingleTableQueryWithPKs", resourceCulture); } } /// <summary> /// 查找类似 Source Expression: {0} 的本地化字符串。 /// </summary> internal static string SourceExpressionAnnotation { get { return ResourceManager.GetString("SourceExpressionAnnotation", resourceCulture); } } /// <summary> /// 查找类似 Stored Procedures cannot be used inside queries. 的本地化字符串。 /// </summary> internal static string SprocsCannotBeComposed { get { return ResourceManager.GetString("SprocsCannotBeComposed", resourceCulture); } } /// <summary> /// 查找类似 Method &apos;{0}&apos; cannot be used on the client; it is only for translation to SQL. 的本地化字符串。 /// </summary> internal static string SqlMethodOnlyForSql { get { return ResourceManager.GetString("SqlMethodOnlyForSql", resourceCulture); } } /// <summary> /// 查找类似 Translation would contain an expression of type Text, NText or Image in a SELECT DISTINCT clause: {0} 的本地化字符串。 /// </summary> internal static string TextNTextAndImageCannotOccurInDistinct { get { return ResourceManager.GetString("TextNTextAndImageCannotOccurInDistinct", resourceCulture); } } /// <summary> /// 查找类似 Translation would contain an expression of type Text, NText or Image in a SELECT within a UNION: {0} 的本地化字符串。 /// </summary> internal static string TextNTextAndImageCannotOccurInUnion { get { return ResourceManager.GetString("TextNTextAndImageCannotOccurInUnion", resourceCulture); } } /// <summary> /// 查找类似 Method ToString can only be translated to SQL for primitive types. 的本地化字符串。 /// </summary> internal static string ToStringOnlySupportedForPrimitiveTypes { get { return ResourceManager.GetString("ToStringOnlySupportedForPrimitiveTypes", resourceCulture); } } /// <summary> /// 查找类似 Transaction does not match connection. 的本地化字符串。 /// </summary> internal static string TransactionDoesNotMatchConnection { get { return ResourceManager.GetString("TransactionDoesNotMatchConnection", resourceCulture); } } /// <summary> /// 查找类似 Type Binary operator not recognized. 的本地化字符串。 /// </summary> internal static string TypeBinaryOperatorNotRecognized { get { return ResourceManager.GetString("TypeBinaryOperatorNotRecognized", resourceCulture); } } /// <summary> /// 查找类似 Cannot order by type &apos;{0}&apos;. 的本地化字符串。 /// </summary> internal static string TypeCannotBeOrdered { get { return ResourceManager.GetString("TypeCannotBeOrdered", resourceCulture); } } /// <summary> /// 查找类似 Type column with unhandled source 的本地化字符串。 /// </summary> internal static string TypeColumnWithUnhandledSource { get { return ResourceManager.GetString("TypeColumnWithUnhandledSource", resourceCulture); } } /// <summary> /// 查找类似 Binding error: Member &apos;{0}.{1}&apos; is not a mapped member of &apos;{2}&apos;. 的本地化字符串。 /// </summary> internal static string UnableToBindUnmappedMember { get { return ResourceManager.GetString("UnableToBindUnmappedMember", resourceCulture); } } /// <summary> /// 查找类似 Column declaration found outside row or table declaration. 的本地化字符串。 /// </summary> internal static string UnexpectedFloatingColumn { get { return ResourceManager.GetString("UnexpectedFloatingColumn", resourceCulture); } } /// <summary> /// 查找类似 Unexpected node: {0} 的本地化字符串。 /// </summary> internal static string UnexpectedNode { get { return ResourceManager.GetString("UnexpectedNode", resourceCulture); } } /// <summary> /// 查找类似 Unexpected shared-expression found. 的本地化字符串。 /// </summary> internal static string UnexpectedSharedExpression { get { return ResourceManager.GetString("UnexpectedSharedExpression", resourceCulture); } } /// <summary> /// 查找类似 Unexpected shared-expression reference found. 的本地化字符串。 /// </summary> internal static string UnexpectedSharedExpressionReference { get { return ResourceManager.GetString("UnexpectedSharedExpressionReference", resourceCulture); } } /// <summary> /// 查找类似 Unexpected type code: {0} 的本地化字符串。 /// </summary> internal static string UnexpectedTypeCode { get { return ResourceManager.GetString("UnexpectedTypeCode", resourceCulture); } } /// <summary> /// 查找类似 Unhandled binding type: {0} 的本地化字符串。 /// </summary> internal static string UnhandledBindingType { get { return ResourceManager.GetString("UnhandledBindingType", resourceCulture); } } /// <summary> /// 查找类似 Unhandled Expression Type: {0} 的本地化字符串。 /// </summary> internal static string UnhandledExpressionType { get { return ResourceManager.GetString("UnhandledExpressionType", resourceCulture); } } /// <summary> /// 查找类似 Member &apos;{0}&apos; on node type &apos;{1}&apos; does not have a known translation to SQL. 的本地化字符串。 /// </summary> internal static string UnhandledMemberAccess { get { return ResourceManager.GetString("UnhandledMemberAccess", resourceCulture); } } /// <summary> /// 查找类似 SQL Server does not handle comparison of NText, Text, Xml, or Image data types. 的本地化字符串。 /// </summary> internal static string UnhandledStringTypeComparison { get { return ResourceManager.GetString("UnhandledStringTypeComparison", resourceCulture); } } /// <summary> /// 查找类似 Types in Union or Concat have members assigned in different order. 的本地化字符串。 /// </summary> internal static string UnionDifferentMemberOrder { get { return ResourceManager.GetString("UnionDifferentMemberOrder", resourceCulture); } } /// <summary> /// 查找类似 Types in Union or Concat have different members assigned. 的本地化字符串。 /// </summary> internal static string UnionDifferentMembers { get { return ResourceManager.GetString("UnionDifferentMembers", resourceCulture); } } /// <summary> /// 查找类似 Types in Union or Concat are constructed incompatibly. 的本地化字符串。 /// </summary> internal static string UnionIncompatibleConstruction { get { return ResourceManager.GetString("UnionIncompatibleConstruction", resourceCulture); } } /// <summary> /// 查找类似 Sources of type (GetType() or typeof) are incompatible for Union-like operation. 的本地化字符串。 /// </summary> internal static string UnionOfIncompatibleDynamicTypes { get { return ResourceManager.GetString("UnionOfIncompatibleDynamicTypes", resourceCulture); } } /// <summary> /// 查找类似 Types in Union or Concat cannot be constructed with hierarchy. 的本地化字符串。 /// </summary> internal static string UnionWithHierarchy { get { return ResourceManager.GetString("UnionWithHierarchy", resourceCulture); } } /// <summary> /// 查找类似 Data member &apos;{0}&apos; of type &apos;{1}&apos; is not part of the mapping for type &apos;{2}&apos;. Is the member above the root of an inheritance hierarchy? 的本地化字符串。 /// </summary> internal static string UnmappedDataMember { get { return ResourceManager.GetString("UnmappedDataMember", resourceCulture); } } /// <summary> /// 查找类似 Unrecognized expression node: {0} 的本地化字符串。 /// </summary> internal static string UnrecognizedExpressionNode { get { return ResourceManager.GetString("UnrecognizedExpressionNode", resourceCulture); } } /// <summary> /// 查找类似 &apos;{0}&apos; is not a valid provider mode. 的本地化字符串。 /// </summary> internal static string UnrecognizedProviderMode { get { return ResourceManager.GetString("UnrecognizedProviderMode", resourceCulture); } } /// <summary> /// 查找类似 Unsafe string conversion from {0} to {1} may lead to implicit truncation. Try reshaping the string explicitly with a Substring operation. 的本地化字符串。 /// </summary> internal static string UnsafeStringConversion { get { return ResourceManager.GetString("UnsafeStringConversion", resourceCulture); } } /// <summary> /// 查找类似 DateTime constructor form is not supported. 的本地化字符串。 /// </summary> internal static string UnsupportedDateTimeConstructorForm { get { return ResourceManager.GetString("UnsupportedDateTimeConstructorForm", resourceCulture); } } /// <summary> /// 查找类似 DateTimeOffset constructor form is not supported. 的本地化字符串。 /// </summary> internal static string UnsupportedDateTimeOffsetConstructorForm { get { return ResourceManager.GetString("UnsupportedDateTimeOffsetConstructorForm", resourceCulture); } } /// <summary> /// 查找类似 The node type &apos;{0}&apos; is not supported. 的本地化字符串。 /// </summary> internal static string UnsupportedNodeType { get { return ResourceManager.GetString("UnsupportedNodeType", resourceCulture); } } /// <summary> /// 查找类似 String constructor form is not supported. 的本地化字符串。 /// </summary> internal static string UnsupportedStringConstructorForm { get { return ResourceManager.GetString("UnsupportedStringConstructorForm", resourceCulture); } } /// <summary> /// 查找类似 TimeSpan constructor form is not supported. 的本地化字符串。 /// </summary> internal static string UnsupportedTimeSpanConstructorForm { get { return ResourceManager.GetString("UnsupportedTimeSpanConstructorForm", resourceCulture); } } /// <summary> /// 查找类似 Constructor for server type &apos;{0}&apos; is not supported. 的本地化字符串。 /// </summary> internal static string UnsupportedTypeConstructorForm { get { return ResourceManager.GetString("UnsupportedTypeConstructorForm", resourceCulture); } } /// <summary> /// 查找类似 The item of an update must be a constant value expression. 的本地化字符串。 /// </summary> internal static string UpdateItemMustBeConstant { get { return ResourceManager.GetString("UpdateItemMustBeConstant", resourceCulture); } } /// <summary> /// 查找类似 Value has no literal in SQL: {0} 的本地化字符串。 /// </summary> internal static string ValueHasNoLiteralInSql { get { return ResourceManager.GetString("ValueHasNoLiteralInSql", resourceCulture); } } /// <summary> /// 查找类似 Cannot translate multiple character ranges in the pattern argument. 的本地化字符串。 /// </summary> internal static string VbLikeDoesNotSupportMultipleCharacterRanges { get { return ResourceManager.GetString("VbLikeDoesNotSupportMultipleCharacterRanges", resourceCulture); } } /// <summary> /// 查找类似 Pattern contains unclosed bracket. 的本地化字符串。 /// </summary> internal static string VbLikeUnclosedBracket { get { return ResourceManager.GetString("VbLikeUnclosedBracket", resourceCulture); } } /// <summary> /// 查找类似 The query contains references to items defined on a different data context. 的本地化字符串。 /// </summary> internal static string WrongDataContext { get { return ResourceManager.GetString("WrongDataContext", resourceCulture); } } /// <summary> /// 查找类似 Wrong number of values in &apos;{0}&apos;. Expected {1}. Actually {2}. 的本地化字符串。 /// </summary> internal static string WrongNumberOfValuesInCollectionArgument { get { return ResourceManager.GetString("WrongNumberOfValuesInCollectionArgument", resourceCulture); } } } }
38.941741
274
0.570684
[ "MIT" ]
ansiboy/ALinq
ALinq/Resources/ALinq.SqlClient.Designer.cs
60,886
C#
namespace System.Web.Mvc { using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Web.Mvc.Razor; using System.Web.Mvc.Resources; using System.Web.WebPages; public class RazorView : BuildManagerCompiledView { public RazorView(ControllerContext controllerContext, string viewPath, string layoutPath, bool runViewStartPages, IEnumerable<string> viewStartFileExtensions) : this(controllerContext, viewPath, layoutPath, runViewStartPages, viewStartFileExtensions, null) { } public RazorView(ControllerContext controllerContext, string viewPath, string layoutPath, bool runViewStartPages, IEnumerable<string> viewStartFileExtensions, IViewPageActivator viewPageActivator) : base(controllerContext, viewPath, viewPageActivator) { LayoutPath = layoutPath ?? String.Empty; RunViewStartPages = runViewStartPages; StartPageLookup = StartPage.GetStartPage; ViewStartFileExtensions = viewStartFileExtensions ?? Enumerable.Empty<string>(); } public string LayoutPath { get; private set; } public bool RunViewStartPages { get; private set; } internal StartPageLookupDelegate StartPageLookup { get; set; } public IEnumerable<string> ViewStartFileExtensions { get; private set; } protected override void RenderView(ViewContext viewContext, TextWriter writer, object instance) { if (writer == null) { throw new ArgumentNullException("writer"); } WebViewPage webViewPage = instance as WebViewPage; if (webViewPage == null) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, MvcResources.CshtmlView_WrongViewBase, ViewPath)); } // An overriden master layout might have been specified when the ViewActionResult got returned. // We need to hold on to it so that we can set it on the inner page once it has executed. webViewPage.OverridenLayoutPath = LayoutPath; webViewPage.VirtualPath = ViewPath; webViewPage.ViewContext = viewContext; webViewPage.ViewData = viewContext.ViewData; webViewPage.InitHelpers(); WebPageRenderingBase startPage = null; if (RunViewStartPages) { startPage = StartPageLookup(webViewPage, RazorViewEngine.ViewStartFileName, ViewStartFileExtensions); } webViewPage.ExecutePageHierarchy(new WebPageContext(context: viewContext.HttpContext, page: null, model: null), writer, startPage); } } }
39.72973
204
0.638095
[ "Apache-2.0" ]
121468615/mono
mcs/class/System.Web.Mvc3/Mvc/RazorView.cs
2,942
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; namespace ShapesMVC.Generator { public abstract class ShapeGenerator { /// <summary> /// Generates a shape and returns it as a string. /// </summary> /// <param name="shapeParameters">Shape parameters</param> /// <returns>Generated shape as a string.</returns> public string GetShapeString(ShapeParameters shapeParameters) { return WriteShape(new StringWriter(), shapeParameters).ToString(); } /// <summary> /// Generates a shape, writing it to given <see cref="TextWriter"/> instance. /// </summary> /// <param name="textWriter"><see cref="TextWriter"/> to write shape to/param> /// <param name="shapeParameters">Shape parameters</param> /// <returns>argument <see cref="TextWriter"/></returns> public TextWriter WriteShape(TextWriter textWriter, ShapeParameters shapeParameters) { // Collect all unformatted scanlines. List<String> scanLines = new List<string>(); int scanLineCount = GetScanLineCount(shapeParameters); for (int i = 0; i < scanLineCount; i++) { scanLines.Add(GetScanLine(i, shapeParameters)); } // Output each line, centered with respect to the longest line. int maxLineLength = (scanLines.Count > 0) ? scanLines.Max(s => s.Length) : 0; foreach (string scanLine in scanLines) { textWriter.WriteLine(TextUtils.Center(scanLine, maxLineLength)); } return textWriter; } /// <summary> /// Computes the total number of scanlines in the ASCII-art output. /// </summary> /// <param name="shapeParameters">Shape parameters</param> /// <returns>total number of scanlines in ASCII-art output.</returns> private int GetScanLineCount(ShapeParameters shapeParameters) { // total height should respect the label position. int lineCount = Math.Max(shapeParameters.Height, shapeParameters.LabelRow); lineCount = Math.Max(0, lineCount); return lineCount; } /// <summary> /// Returns a raster scanline for a single row of 'pixels' in the output. /// This scanline should not contain the label, which is inserted by the calling process. /// </summary> /// <param name="line"></param> /// <returns>raster scanline for a single row of 'pixels' in the output</returns> protected virtual string GetScanLine(int line, ShapeParameters shapeParameters) { string scanLine = string.Empty; // collect pixels with boundaries of shape. if (line >= 0 && line < shapeParameters.Height) { scanLine = GetShapePixels(line, shapeParameters); } // Incorporate label into output. if (((shapeParameters.LabelRow - 1) == line) && !string.IsNullOrEmpty(shapeParameters.Label)) { scanLine = TextUtils.Overlay(scanLine, shapeParameters.Label); } return scanLine; } protected abstract string GetShapePixels(int line, ShapeParameters shapeParameters); protected string PixelRun(int runLength) { string value = "X"; if( runLength > 1 ) { value = value + string.Concat(Enumerable.Repeat(" X", runLength - 1)); } return value; } } }
38.905263
107
0.588745
[ "MIT" ]
goldsam/shapes
ShapesMVC/Generator/ShapeGenerator.cs
3,698
C#
namespace DevNots.Domain { public interface IUserRepository: IAsyncRepository<User> { } }
12.875
60
0.699029
[ "MIT" ]
devnots/devnots-backend
src/DevNots.Domain/User/IUserRepository.cs
103
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Text; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Infrastructure; namespace Microsoft.EntityFrameworkCore.Metadata { /// <summary> /// Extension methods for <see cref="IFunctionColumn" />. /// </summary> public static class FunctionColumnExtensions { /// <summary> /// <para> /// Creates a human-readable representation of the given metadata. /// </para> /// <para> /// Warning: Do not rely on the format of the returned string. /// It is designed for debugging only and may change arbitrarily between releases. /// </para> /// </summary> /// <param name="column"> The metadata item. </param> /// <param name="options"> Options for generating the string. </param> /// <param name="indent"> The number of indent spaces to use before each new line. </param> /// <returns> A human-readable representation. </returns> public static string ToDebugString( [NotNull] this IFunctionColumn column, MetadataDebugStringOptions options, int indent = 0) { var builder = new StringBuilder(); var indentString = new string(' ', indent); builder.Append(indentString); var singleLine = (options & MetadataDebugStringOptions.SingleLine) != 0; if (singleLine) { builder.Append($"FunctionColumn: {column.Table.Name}."); } builder.Append(column.Name).Append(" ("); builder.Append(column.StoreType).Append(")"); if (column.IsNullable) { builder.Append(" Nullable"); } else { builder.Append(" NonNullable"); } builder.Append(")"); if (!singleLine && (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) { builder.Append(column.AnnotationsToDebugString(indent + 2)); } return builder.ToString(); } } }
34.086957
111
0.560799
[ "Apache-2.0" ]
Potapy4/EntityFrameworkCore
src/EFCore.Relational/Metadata/FunctionColumnExtensions.cs
2,352
C#
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Compute.V1.Snippets { // [START compute_v1_generated_Instances_Resume_sync_flattened] using Google.Cloud.Compute.V1; using lro = Google.LongRunning; public sealed partial class GeneratedInstancesClientSnippets { /// <summary>Snippet for Resume</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public void Resume() { // Create client InstancesClient instancesClient = InstancesClient.Create(); // Initialize request argument(s) string project = ""; string zone = ""; string instance = ""; // Make the request lro::Operation<Operation, Operation> response = instancesClient.Resume(project, zone, instance); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = instancesClient.PollOnceResume(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } } } // [END compute_v1_generated_Instances_Resume_sync_flattened] }
41.866667
115
0.665207
[ "Apache-2.0" ]
AlexandrTrf/google-cloud-dotnet
apis/Google.Cloud.Compute.V1/Google.Cloud.Compute.V1.GeneratedSnippets/InstancesClient.ResumeSnippet.g.cs
2,512
C#
using UnityEngine; using System.Collections; public class CotsbGameObjectDeserialiser { public static CotsbGameObject Deserialise() { var result = CotsbGameObjectManager.Create<CotsbGameObject>(); return result; } }
20.5
70
0.723577
[ "MIT" ]
astrellon/cotsb_unity_client
Assets/Scripts/Serialisers/CotsbGameObjectDeserialiser.cs
248
C#
using System; using System.Collections.Generic; using System.Text; namespace TicketSystem.DatabaseRepository.Model { class User { } }
13.454545
47
0.72973
[ "MIT" ]
TeknikhogskolanGothenburg/ticketSystem-teamticknet
src/DatabaseRepository/Model/User.cs
150
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; namespace Simplicity.IdentityServer.WebHost.Models { // Add profile data for application users by adding properties to the ApplicationUser class public class ApplicationUser : IdentityUser { } }
26.214286
95
0.792916
[ "Apache-2.0" ]
Simplicity-Alpha/Simplicity.IdentityServer
src/Simplicity.IdentityServer.WebHost/Models/ApplicationUser.cs
369
C#
/* Great Circle Calculator * * This program calculayes various pieces of information about the "Great Circle" based on the Latitude and Longitude * provided by the user. A Great Circle is the shortest distance between two points on a sphere - the Earth in this case. * Coordinates are entered in the form 'XXdYYmZZs' - XX Degrees YY Minutes ZZ Seconds - and converted into a decimal value. * * For these comments, the Start position will be refered to as Latitude1 or Longitude1 * and the Finish positiion will be Latitude2 or Longitude2. * * 'dLong' refers to the angular distance between two points of longitude. * eg. dLong between 20 Degrees 00 Minutes East, and 30 Degrees 00 Minutes East, is 10 Degrees East (Directional) * * Cos(Distance) = Cos(dLong) * Cos(Latitude1) * Cos(Latitude2) +/- Sin(Latitude1) * Sin(Latitude2) * If the Start/End Latitudes are in the same Hemisphere, we add. If They are not, we subtract. * Distance is returned in Nautical Miles. * * Initial Course - The angle in Degrees True, from North, in the direction of the second position. * Formulae give this as a Quadrantal, expressed from either North or South, then East or West. * eg North 45 East -> 045 Degrees True. South 45 Degrees East -> 180 - 45 -> 135 Degrees True. * To calculate this, we need to work out 3 values, refered to in Navigation as A, B, C values. * These are purely numbers with no units, and we only care about the absolute value and "Directions" or "Names", North or South. * * A = Tan(Latitude1)/Tan(dLong) : Named opposite to Latitude1, unless dLong is between 90 and 270 Degrees. * B = Tan(Latitude2)/Sin(dLong) : Always named the same as Latitude2. * C = A +/- B : If A and B are named the same, we add, and C is named the same. If they are different, * we take the difference and C is named after the larger value. * Tan(Initial Course) = 1 / (C * Cos(LatitudeA)) * * Vertex - This is the highest position of Latitude that the Great Circle track will reach, and is * always worked out to the same Hemisphere as the starting Latitude. The other vertex can be easily * worked out as the two are diametrically opposed, ie, exactly and opposite. * * Tan(dLong Longitude1 to Vertex) = 1 / (Tan(Initial Course Quadrantal) * Sin(Latitude1)) * Cos(Latitude Vertex) = Sin(Initial Course Quadrantal) * Cos(Latitude1) * */ /* TODO * Input validation * Error checking ie inputs greater than 90 or 180 degrees, perfectly opposite coords * Database access - save/load Coordinates */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace GreatCircle { public partial class Form1 : Form { //These two Enums are simply used to help checks later, and populate windows forms combo boxes. private enum hemisphereNS { North, South}; private enum hemisphereEW { East, West}; //Anngular distance, variables for calculating Initial Course "ic", and the Vertex private double dLongDistance; private double icAValue; private double icBValue; private double icCValue; private double dLongAV; //Distances typically to 1 dp, so we will round later on private double totalDistance; //Courses typically to 1/2 degree, but will be using integers here private int initialCourseQuad; private int initialCourseTrue; //Directional info private hemisphereEW dLongDirection; private hemisphereNS icADirection; private hemisphereNS icBDirection; private hemisphereNS icCDirection; //Initializing coordinate structs private NavCoords StartCoord = new NavCoords(); private NavCoords EndCoord = new NavCoords(); private NavCoords Vertex1Coord = new NavCoords(); private NavCoords Vertex2Coord = new NavCoords(); private struct NavCoords { /* A struct is used here to store variables and methods relating to the coordinates * to make things cleaner and easier to follow, and to keep data seperate as I go on * */ //Strings containing the original input values, to be worked on string latInput; string longInput; //Hemisphere info public hemisphereNS latHemi; public hemisphereEW longHemi; //Will hold the decimal values of the converted strings, as both Degrees and Radians, for easier calculations public double latitudeDeg; public double longitudeDeg; public double latitudeRad; public double longitudeRad; /* Coord data must have a latitude and longitude, and both hemispheres * Once we have these pieces, just set the other values for use later * Keep the values as degrees and radians for ease of use */ public void SetNavCoords(String x, String y, hemisphereNS h1, hemisphereEW h2) { this.latInput = x; this.longInput = y; this.latHemi = h1; this.longHemi = h2; this.latitudeDeg = StringToNumber(latInput); this.longitudeDeg = StringToNumber(longInput); this.latitudeRad = DegreesToRadians(latitudeDeg); this.longitudeRad = DegreesToRadians(longitudeDeg); } public void SetLatitudeFromRad(double l) { this.latitudeRad = l; this.latitudeDeg = RadiansToDegrees(l); } public void SetLongitudeFromRad(double l) { this.longitudeRad = l; this.longitudeDeg = RadiansToDegrees(l); } private double StringToNumber(String s) { /* This function takes the string from the text boxes, in the correct format * and converts it to a decimal value we can use in calculations * eg "20d30m" (20 Degrees 30 Minutes) should become 20.5 * * We run through the string, and each iteration add the character to the temporary string temp * if the character is one of the formatting characters, we convert the temp string to a decimal * corresponding to whether it's degrees/minutes/seconds and clear the string. */ double d = 0; string temp = ""; for (int i = 0; i < s.Length; i++) { if (s[i] == 'd') { d = Convert.ToDouble(temp); temp = ""; } else if (s[i] == 'm') { d = d + Convert.ToDouble(temp) / 60; temp = ""; } else if (s[i] == 's') { d = d + Convert.ToDouble(temp) / 3600; temp = ""; } else { temp = temp + s[i]; } } return d; } #region Helpers //These are simple helper functions to convert between Radians and Degrees, and various simple tasks private double RadiansToDegrees(double r) { return r * (180 / Math.PI); } private double DegreesToRadians(double d) { return d / (180 / Math.PI); } public void ClearData() { this.latInput = ""; this.longInput = ""; this.latHemi = hemisphereNS.North; this.longHemi = hemisphereEW.East; this.latitudeDeg = 0; this.longitudeDeg = 0; this.latitudeRad = 0; this.longitudeRad = 0; } #endregion } public Form1() { InitializeComponent(); } private void btnSubmit_Click(object sender, EventArgs e) { /* Fills the structs with values from user inputs * In most cases, using the Enum variables to hemispheres makes things easier, * reading and setting values from the drop down boxes needed extra work. * We get the selected item, convert to string, parse it, and then cast to the correct variable type. */ Clear(); StartCoord.SetNavCoords(txtStartLat.Text, txtStartLong.Text, (hemisphereNS)Enum.Parse(typeof(hemisphereNS), cmbStartLatHemi.SelectedItem.ToString()), (hemisphereEW)Enum.Parse(typeof(hemisphereEW), cmbStartLongHemi.SelectedItem.ToString())); EndCoord.SetNavCoords(txtEndLat.Text, txtEndLong.Text, (hemisphereNS)Enum.Parse(typeof(hemisphereNS), cmbEndLatHemi.SelectedItem.ToString()), (hemisphereEW)Enum.Parse(typeof(hemisphereEW), cmbEndLongHemi.SelectedItem.ToString())); CalculateNav(); Output(); } private void btnReset_Click(object sender, EventArgs e) { Clear(); } private void Form1_Load(object sender, EventArgs e) { cmbStartLatHemi.DataSource = Enum.GetValues(typeof(hemisphereNS)); cmbEndLatHemi.DataSource = Enum.GetValues(typeof(hemisphereNS)); cmbStartLongHemi.DataSource = Enum.GetValues(typeof(hemisphereEW)); cmbEndLongHemi.DataSource = Enum.GetValues(typeof(hemisphereEW)); } private void CalculateNav() { #region dLongDistance /* * This section takes the longitude values, as decimals, as well as their respective hemispheres * and calculates the distance and which direction to go * * If the hemispheres are the same, the distance is simply the difference in the two longitudes * if they are different, the distance is (usually) the sum * however at this point if the distance is greater than 180 degrees, it is better to go the opposite direction * which will be 360 degrees - the previously calculated distance */ if (StartCoord.longHemi == EndCoord.longHemi) { dLongDistance = Math.Abs(StartCoord.longitudeRad - EndCoord.longitudeRad); } else { dLongDistance = StartCoord.longitudeRad + EndCoord.longitudeRad; if(dLongDistance > Math.PI) { dLongDistance = (2 * Math.PI) - dLongDistance; } } #endregion #region dLongDirection /* * This function determines if we should be going East or West to get to point B * 's' is just used as a temporary string * * for this function, we need to know the starting/final longitude, the hemispheres, and the distance * we check first if we are staying in the same hemisphere * if so, are we in the east or west, then evaluate which is greater or farther, then we know the direction */ if (StartCoord.longHemi == EndCoord.longHemi) { if (StartCoord.longHemi == hemisphereEW.East) { if (StartCoord.longitudeRad < EndCoord.longitudeRad) { dLongDirection = hemisphereEW.East; } else { dLongDirection = hemisphereEW.West; } } else { if (StartCoord.longitudeRad > EndCoord.longitudeRad) { dLongDirection = hemisphereEW.East; } else { dLongDirection = hemisphereEW.West; } } } else { if ((StartCoord.longitudeRad + EndCoord.longitudeRad) > Math.PI) { if (StartCoord.longHemi == hemisphereEW.East) { dLongDirection = hemisphereEW.East; } else { dLongDirection = hemisphereEW.West; } } else { if (StartCoord.longHemi == hemisphereEW.East) { dLongDirection = hemisphereEW.West; } else { dLongDirection = hemisphereEW.East; } } } #endregion #region TotalDistance //If the lattitudes are in the same hemisphere, we add the cos and sin, else we subtract if (StartCoord.latHemi == EndCoord.latHemi) { totalDistance = Math.Round(60 * (180 / Math.PI) * (Math.Acos(Math.Cos(dLongDistance)*Math.Cos(StartCoord.latitudeRad)*Math.Cos(EndCoord.latitudeRad)+Math.Sin(StartCoord.latitudeRad)*Math.Sin(EndCoord.latitudeRad))), 1); } else { totalDistance = Math.Round(60 * (180 / Math.PI) * (Math.Acos(Math.Cos(dLongDistance) * Math.Cos(StartCoord.latitudeRad) * Math.Cos(EndCoord.latitudeRad) - Math.Sin(StartCoord.latitudeRad) * Math.Sin(EndCoord.latitudeRad))), 1); } #endregion #region InitialCourse /* * To calculate the initial course, we need to work out 3 values, known in navigation as A, B, and C values * The sign of the value is irrelevant, but the 'name' ie North/South is needed */ icAValue = Math.Abs(Math.Tan(StartCoord.latitudeRad)/Math.Tan(dLongDistance)); icBValue = Math.Abs(Math.Tan(EndCoord.latitudeRad)/Math.Sin(dLongDistance)); icBDirection = EndCoord.latHemi; //B always same name as latitude //A is named opposite to lattitude, unless dlong between 90 and 270 degrees if (dLongDistance > (Math.PI / 2) && dLongDistance < (Math.PI * 1.5)) { icADirection = StartCoord.latHemi; } else { if (StartCoord.latHemi == hemisphereNS.North) { icADirection = hemisphereNS.South; } else { icADirection = hemisphereNS.North; } } /*If A and B are same names, C is A + B and same direction * If different names, ie A is North and B is South, C takes the name of the greater value * and takes the value of the difference of A and B */ if (icADirection == icBDirection) { icCValue = icAValue + icBValue; icCDirection = icADirection; } else { icCValue = Math.Abs(icAValue - icBValue); if (icAValue > icBValue) { icCDirection = icADirection; } else { icCDirection = icBDirection; } } /* Tan (Initial Course) = 1 / (C*CosLatA) * This gives us the initial course as a Quadrantal ie North 30 Degrees East or South 50 Degrees West * So need to convert to Degrees True based on C direction and our DLong direction */ initialCourseQuad = Convert.ToInt32((180 / Math.PI) * (Math.Atan(1 / (icCValue * Math.Cos(StartCoord.latitudeRad))))); if (icCDirection == hemisphereNS.North) { if (dLongDirection == hemisphereEW.East) { initialCourseTrue = initialCourseQuad; } else { initialCourseTrue = 360 - initialCourseQuad; } } else { if (dLongDirection == hemisphereEW.East) { initialCourseTrue = 180 - initialCourseQuad; } else { initialCourseTrue = 180 + initialCourseQuad; } } #endregion #region Vertex /* To calculate the vertex we need the dLong - distance from Start to Vertex * We also need to know which hemisphere we are in and direction we are going */ dLongAV = Math.Abs(Math.Atan(1 / (Math.Tan((initialCourseQuad / (180 / Math.PI))) * Math.Sin(StartCoord.latitudeRad)))); if (StartCoord.latHemi == icCDirection && dLongDirection == StartCoord.longHemi) { Vertex1Coord.SetLongitudeFromRad(StartCoord.longitudeRad + dLongAV); } else if (StartCoord.latHemi == icCDirection && dLongDirection != StartCoord.longHemi) { Vertex1Coord.SetLongitudeFromRad(StartCoord.longitudeRad - dLongAV); } else if (StartCoord.latHemi != icCDirection && dLongDirection == StartCoord.longHemi) { Vertex1Coord.SetLongitudeFromRad(StartCoord.longitudeRad - dLongAV); } else // if(StartCoord.latHemi == icCDirection && dLongDirection != StartCoord.longHemi) { Vertex1Coord.SetLongitudeFromRad(StartCoord.longitudeRad + dLongAV); } //Setting an initial hemisphere, can be changed later Vertex1Coord.longHemi = hemisphereEW.East; //If the longitude is < 0 or > 180 degrees we change the hemisphere if (Vertex1Coord.longitudeRad > Math.PI || Vertex1Coord.longitudeRad < 0) { Vertex1Coord.longitudeRad = Math.Abs(Vertex1Coord.longitudeRad); if (Vertex1Coord.longHemi == hemisphereEW.East) { Vertex1Coord.longHemi = hemisphereEW.West; } else { Vertex1Coord.longHemi = hemisphereEW.East; } } Vertex1Coord.latHemi = StartCoord.latHemi; Vertex1Coord.SetLatitudeFromRad(Math.Acos((Math.Sin(initialCourseQuad / (180 / Math.PI))) * Math.Cos(StartCoord.latitudeRad))); #endregion #region Vertex2 /* Set the coordinates for Vertex 2, which are directly opposite the sphere of Vertex 1 * The value for Latitude will remain the same, but hemisphere is swapped * * Longitude hemisphere will also be swapped, but the value will be 180 Degrees - Vertex 1 * */ Vertex2Coord.SetLatitudeFromRad(Vertex1Coord.latitudeRad); if (Vertex1Coord.latHemi == hemisphereNS.North) { Vertex2Coord.latHemi = hemisphereNS.South; } else { Vertex2Coord.latHemi = hemisphereNS.North; } Vertex2Coord.SetLongitudeFromRad(Math.PI - Vertex1Coord.longitudeRad); if(Vertex1Coord.longHemi == hemisphereEW.East) { Vertex2Coord.longHemi = hemisphereEW.West; } else { Vertex2Coord.longHemi = hemisphereEW.East; } #endregion } private String DegreesAsString(double deg) { /* Takes a decimal input and converts it a a human readable string as Degrees and Minutes * eg 40.5 Degrees - 40 will be aded to the string, then removed from the decimal * we are left with 0.5, which is then multiplied by 60 to give us Minutes * then added to the string */ String s = ""; s = s + (Math.Floor(deg)).ToString() + " Degrees, "; deg = (deg - Math.Floor(deg)) * 60; s = s + (Math.Floor(deg)).ToString() + " Minutes"; return s; } private void Output() { lblOutDist.Text += + totalDistance + " Nautical Miles | " + Math.Round((totalDistance * 1.15078), 1) + " Statute Miles | " + Math.Round((totalDistance * 1.852), 1) + " Kilometers"; lblOutCourse.Text += icCDirection + "° " + initialCourseQuad + " " + dLongDirection + "| " + initialCourseTrue + " °T"; lblOutVert1.Text += DegreesAsString(Vertex1Coord.latitudeDeg) + " " + Vertex1Coord.latHemi + ", " + DegreesAsString(Vertex1Coord.longitudeDeg) + " " + Vertex1Coord.longHemi; lblOutVert2.Text += DegreesAsString(Vertex2Coord.latitudeDeg) + " " + Vertex2Coord.latHemi + ", " + DegreesAsString(Vertex2Coord.longitudeDeg) + " " + Vertex2Coord.longHemi; } private void Clear() { StartCoord.ClearData(); EndCoord.ClearData(); Vertex1Coord.ClearData(); Vertex2Coord.ClearData(); lblOutDist.Text = "Total Distance: "; lblOutCourse.Text = "Initial Course: "; lblOutVert1.Text = "Vertex 1: "; lblOutVert2.Text = "Vertex 2: "; } } }
43.645349
253
0.539052
[ "MIT" ]
NeilRichmond/GreatCircle
Form1.cs
22,525
C#
// <copyright file="BlankSpan.cs" company="OpenTelemetry Authors"> // Copyright 2018, OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> namespace OpenTelemetry.Trace { using System; using System.Collections.Generic; /// <summary> /// Blank span. /// </summary> public sealed class BlankSpan : ISpan { /// <summary> /// Blank span instance. /// </summary> public static readonly BlankSpan Instance = new BlankSpan(); private BlankSpan() { } /// <inheritdoc /> public SpanContext Context => SpanContext.Blank; /// <inheritdoc /> public bool IsRecordingEvents => false; /// <inheritdoc /> public Status Status { get => Status.Ok; set { if (!value.IsValid) { throw new ArgumentException(nameof(value)); } } } /// <inheritdoc /> public bool HasEnded { get; } /// <inheritdoc /> public void UpdateName(string name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } } /// <inheritdoc /> public void SetAttribute(KeyValuePair<string, object> keyValuePair) { if (keyValuePair.Key == null || keyValuePair.Value == null) { throw new ArgumentNullException(nameof(keyValuePair)); } } /// <inheritdoc /> public void SetAttribute(string key, string value) { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } } /// <inheritdoc /> public void SetAttribute(string key, long value) { if (key == null) { throw new ArgumentNullException(nameof(key)); } } /// <inheritdoc /> public void SetAttribute(string key, double value) { if (key == null) { throw new ArgumentNullException(nameof(key)); } } /// <inheritdoc /> public void SetAttribute(string key, bool value) { if (key == null) { throw new ArgumentNullException(nameof(key)); } } /// <inheritdoc /> public void AddEvent(string name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } } /// <inheritdoc /> public void AddEvent(string name, IDictionary<string, object> attributes) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (attributes == null) { throw new ArgumentNullException(nameof(attributes)); } } /// <inheritdoc /> public void AddEvent(IEvent newEvent) { if (newEvent == null) { throw new ArgumentNullException(nameof(newEvent)); } } /// <inheritdoc /> public void AddLink(ILink link) { if (link == null) { throw new ArgumentNullException(nameof(link)); } } /// <inheritdoc /> public void End() { } /// <inheritdoc /> public void End(DateTimeOffset endTimestamp) { } } }
25.482353
81
0.49723
[ "Apache-2.0" ]
gibletto/opentelemetry-dotnet
src/OpenTelemetry.Abstractions/Internal/BlankSpan.cs
4,334
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("11.RandNumsInGivenRng")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("11.RandNumsInGivenRng")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("728dc1a1-de1b-43a9-b8a4-71ff7fe0fc7f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.243243
84
0.746996
[ "MIT" ]
TemplarRei/TelerikAcademy
CSharpOne/06.Loops/11.RandNumsInGivenRng/Properties/AssemblyInfo.cs
1,418
C#
using System.Collections.Generic; using System; using System.Text.RegularExpressions; namespace CarDealership.Models { public class Car { private string _makeModel; private int _price; private int _miles; private static List<Car> _instances = new List<Car> {}; public Car (string MakeModel, string Price, string Miles) { Regex regex = new Regex(@"\d+"); Match resultMiles = regex.Match(Miles); Match resultPrice = regex.Match(Price); if (resultMiles.Success && resultPrice.Success) { _price = int.Parse(Price); _miles = int.Parse(Miles); _makeModel = MakeModel; } else { throw new Exception("Please enter in the correct format"); } } public string GetMakeModel() { return _makeModel; } public void SetMakeModel (string newMakeModel) { _makeModel = newMakeModel; } public int GetPrice() { return _price; } public void SetPrice (int newPrice) { _price = newPrice; } public int GetMiles() { return _miles; } public void SetMiles (int newMiles) { _miles = newMiles; } public static List<Car> GetAll() { return _instances; } public void Save(Car newCar) { _instances.Add(newCar); } public static void ClearAll() { _instances.Clear(); } } }
19.555556
66
0.603693
[ "MIT" ]
TheBigTaco/car-dealership
Models/Car.cs
1,408
C#
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.IO; using System.Text; using CookComputing.XmlRpc; using log4net.Core; using XenAdmin; using XenAdmin.Core; using XenAdmin.Network; namespace XenAPI { public partial class Session { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); public bool IsElevatedSession = false; private Session(int timeout, IXenConnection connection, string url) { Connection = connection; _proxy = XmlRpcProxyGen.Create<Proxy>(); _proxy.Url = url; _proxy.NonStandard = XmlRpcNonStandard.All; _proxy.Timeout = timeout; _proxy.UseIndentation = false; _proxy.UserAgent = UserAgent; _proxy.KeepAlive = true; _proxy.RequestEvent += LogRequest; _proxy.ResponseEvent += LogResponse; _proxy.Proxy = Proxy; // reverted because of CA-137829/CA-137959: _proxy.ConnectionGroupName = Guid.NewGuid().ToString(); // this will force the Session onto a different set of TCP streams (see CA-108676) } public Session(Proxy proxy, IXenConnection connection) { Connection = connection; _proxy = proxy; } public Session(Session session, Proxy proxy, IXenConnection connection) : this(proxy, connection) { InitAD(session); } public Session(int timeout, IXenConnection connection, string host, int port) : this(timeout, connection, GetUrl(host, port)) { } /// <summary> /// Create a new Session instance, using the given instance and timeout. The connection details and Xen-API session handle will be /// copied from the given instance, but a new connection will be created. Use this if you want a duplicate connection to a host, /// for example when you need to cancel an operation that is blocking the primary connection. /// </summary> /// <param name="session"></param> /// <param name="timeout"></param> public Session(Session session, IXenConnection connection, int timeout) : this(timeout, connection, session.Url) { InitAD(session); } private void InitAD(Session session) { _uuid = session.uuid; APIVersion = session.APIVersion; _userSid = session.UserSid; _subject = session.Subject; _isLocalSuperuser = session.IsLocalSuperuser; roles = session.Roles; permissions = session.Permissions; } /// <summary> /// When the CacheWarming flag is set, we output logging at Debug rather than Info level. /// This means that we don't spam the logs when the application starts. /// </summary> private bool _cacheWarming = false; public bool CacheWarming { get { return _cacheWarming; } set { _cacheWarming = value; } } private void LogRequest(object o, XmlRpcRequestEventArgs args) { Level logLevel; string xml = DumpStream(args.RequestStream, String.Empty); // Find the method name within the XML string methodName = ""; int methodNameStart = xml.IndexOf("<methodName>"); if (methodNameStart >= 0) { methodNameStart += 12; // skip past "<methodName>" int methodNameEnd = xml.IndexOf('<', methodNameStart); if (methodNameEnd > methodNameStart) methodName = xml.Substring(methodNameStart, methodNameEnd - methodNameStart); } if (CacheWarming) logLevel = Level.Debug; else if (methodName == "event.next" || methodName == "event.from" || methodName == "host.get_servertime" || methodName.StartsWith("task.get_")) // these occur frequently and we don't need to know about them logLevel = Level.Debug; else logLevel = Level.Info; // Only log the full XML at Debug level because it may have sensitive data in: CA-80174 if (logLevel == Level.Debug) LogMsg(logLevel, "Invoking XML-RPC method " + methodName + ": " + xml); else LogMsg(logLevel, "Invoking XML-RPC method " + methodName); } private void LogResponse(object o, XmlRpcResponseEventArgs args) { if(log.IsDebugEnabled) LogMsg(Level.Debug, DumpStream(args.ResponseStream, "XML-RPC response: ")); } private string DumpStream(Stream s, string header) { try { StringBuilder stringBuilder = new StringBuilder(header); using (TextReader r = new StreamReader(s)) { string l; while ((l = r.ReadLine()) != null) stringBuilder.Append(l); } return stringBuilder.ToString(); } catch(OutOfMemoryException ex) { LogMsg(Level.Debug, "Session ran out of memory while trying to log the XML response stream: " + ex.Message); return String.Empty; } } private void LogMsg(Level logLevel, String msg) { if (logLevel == Level.Debug) log.Debug(msg); else if (logLevel == Level.Info) log.Info(msg); else System.Diagnostics.Trace.Assert(false, "Missing log level"); } /// <summary> /// The i18n'd string for the 'Logged in as:' username (AD or local root). /// </summary> public string UserFriendlyName() { if (IsLocalSuperuser) return Messages.AD_LOCAL_ROOT_ACCOUNT; if (!string.IsNullOrEmpty(CurrentUserDetails.UserDisplayName)) return CurrentUserDetails.UserDisplayName.Ellipsise(50); if (!string.IsNullOrEmpty(CurrentUserDetails.UserName)) return CurrentUserDetails.UserName.Ellipsise(50); return Messages.UNKNOWN_AD_USER; } /// <summary> /// Useful as a unique name for logging purposes /// </summary> public string UserLogName() { if (IsLocalSuperuser) return Messages.AD_LOCAL_ROOT_ACCOUNT; if (!string.IsNullOrEmpty(CurrentUserDetails.UserName)) return CurrentUserDetails.UserName; return UserSid; } /// <summary> /// This gives either a friendly csv list of the sessions roles or a friendly string for Local root account. /// If Pre MR gives Pool Admin for AD users. /// </summary> public string FriendlyRoleDescription() { if (IsLocalSuperuser || XenAdmin.Core.Helpers.GetMaster(Connection).external_auth_type != Auth.AUTH_TYPE_AD) return Messages.AD_LOCAL_ROOT_ACCOUNT; return Role.FriendlyCSVRoleList(Roles); } /// <summary> /// This gives either a friendly string for the dominant role on the session or a friendly string for Local root account. /// If Pre MR gives Pool Admin for AD users. /// </summary> public string FriendlySingleRoleDescription() { if (IsLocalSuperuser || XenAdmin.Core.Helpers.GetMaster(Connection).external_auth_type != Auth.AUTH_TYPE_AD) return Messages.AD_LOCAL_ROOT_ACCOUNT; //Sort roles from highest to lowest roles.Sort((r1, r2) => { return r2.CompareTo(r1); }); //Take the highest role return roles[0].FriendlyName(); } public string ConnectionGroupName { get { return _proxy.ConnectionGroupName; } set { _proxy.ConnectionGroupName = value; } } } }
39.493976
220
0.588774
[ "BSD-2-Clause" ]
jijiang/xenadmin
XenModel/XenAPI-Extensions/Session.cs
9,836
C#
using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Media; namespace CodyzeVSPlugin.Highlighting { [Export(typeof(EditorFormatDefinition))] [Name(HighlightingFormatHandler.WarningFormat)] [UserVisible(true)] internal class HighlightWordWarningFormatDefinition : MarkerFormatDefinition { public HighlightWordWarningFormatDefinition() { this.BackgroundColor = Colors.LightSalmon; this.ForegroundColor = Colors.Chocolate; this.DisplayName = "Warning"; this.ZOrder = 5; } } }
28.107143
80
0.730623
[ "Apache-2.0" ]
Fraunhofer-AISEC/codyze-vs-plugin
CodyzeVSPlugin/Highlighting/HighlightWordWarningFormatDefinition.cs
789
C#
// Copyright 2015 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using NodaTime.Utility; static class TestHelper { internal static void AssertConversions<T>(T value, string expectedJson, JsonConverter converter) { var settings = new JsonSerializerSettings { Converters = {converter}, DateParseHandling = DateParseHandling.None }; AssertConversions(value, expectedJson, settings); } internal static void AssertConversions<T>(T value, string expectedJson, JsonSerializerSettings settings) { var actualJson = JsonConvert.SerializeObject(value, Formatting.None, settings); Assert.Equal(expectedJson, actualJson); var deserializedValue = JsonConvert.DeserializeObject<T>(expectedJson, settings); Assert.Equal(value, deserializedValue); } internal static void AssertInvalidJson<T>(string json, JsonSerializerSettings settings) { var exception = Assert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<T>(json, settings)); Assert.IsType<InvalidNodaDataException>(exception.InnerException); } }
38
122
0.716108
[ "MIT" ]
SimonCropp/Argon
src/Tests/NodaTime/TestHelper.cs
1,256
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Lab9.Models { public partial class CourseOffering { public Course CourseOffered { get; set; } public int CompareTo(CourseOffering other) => other == null ? 1 : Year.CompareTo(other.Year); public override string ToString() { return Course_CourseID + " " + Course.CourseTitle + " " + Year + " " + Semester; } } }
24.894737
101
0.630021
[ "MIT" ]
egnsh93/CST8256
Lab9/Lab9/Models/CourseOffering.partial.cs
475
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using GeneticSharp.Domain; using GeneticSharp.Domain.Chromosomes; using GeneticSharp.Domain.Fitnesses; using GeneticSharp.Extensions.Ghostwriter; using GeneticSharp.Infrastructure.Framework.Texts; using GeneticSharp.Infrastructure.Framework.Threading; using GeneticSharp.Runner.ConsoleApp.Samples.Resources; using Newtonsoft.Json; namespace GeneticSharp.Runner.ConsoleApp.Samples { [DisplayName("Ghostwriter")] public class GhostwriterSampleController : SampleControllerBase { private List<string> m_quotes; private List<string> m_words; public GhostwriterSampleController() { var json = JsonConvert.DeserializeObject<dynamic>(SamplesResource.GhostwriterQuoteJson); m_quotes = new List<string>(); m_words = new List<string>(); for (int i = 0; i < json.value.Count; i++) { var quote = json.value[i].joke.Value as string; m_quotes.Add(quote); m_words.AddRange(quote.Split(' ')); } m_words = m_words.Select(w => w.RemovePunctuations()).Distinct().OrderBy(w => w).ToList(); } public override void ConfigGA(GeneticAlgorithm ga) { base.ConfigGA(ga); ga.TaskExecutor = new ParallelTaskExecutor() { MinThreads = 25, MaxThreads = 50 }; } public override IFitness CreateFitness() { return new GhostwriterFitness((text) => { var minDistance = m_quotes.Min(q => LevenshteinDistance(q, text)); return 1 - (minDistance / 100f); }); } public override IChromosome CreateChromosome() { return new GhostwriterChromosome(5, m_words); } public override void Draw(IChromosome bestChromosome) { var c = bestChromosome as GhostwriterChromosome; Console.WriteLine("Text: {0}", c.BuildText()); } private int LevenshteinDistance(string s, string t) { // degenerate cases if (s == t) { return 0; } if (s.Length == 0) { return t.Length; } if (t.Length == 0) { return s.Length; } // create two work vectors of integer distances int[] v0 = new int[t.Length + 1]; int[] v1 = new int[t.Length + 1]; // initialize v0 (the previous row of distances) // this row is A[0][i]: edit distance for an empty s // the distance is just the number of characters to delete from t for (int i = 0; i < v0.Length; i++) { v0[i] = i; } for (int i = 0; i < s.Length; i++) { // calculate v1 (current row distances) from the previous row v0 // first element of v1 is A[i+1][0] // edit distance is delete (i+1) chars from s to match empty t v1[0] = i + 1; // use formula to fill in the rest of the row for (int j = 0; j < t.Length; j++) { var cost = (s[i] == t[j]) ? 0 : 1; v1[j + 1] = Math.Min(Math.Min(v1[j] + 1, v0[j + 1] + 1), v0[j] + cost); } // copy v1 (current row) to v0 (previous row) for next iteration for (int j = 0; j < v0.Length; j++) { v0[j] = v1[j]; } } return v1[t.Length]; } } }
30.52381
102
0.51196
[ "MIT" ]
raminrahimzada/GeneticSharp
src/GeneticSharp.Runner.ConsoleApp/Samples/GhostwriterSampleController.cs
3,848
C#
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; namespace Tasks { public class C { static void Main(string[] args) { var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; Console.SetOut(sw); Solve(); Console.Out.Flush(); } public static void Solve() { var (A, B) = Scanner.Scan<int, int>(); var c10 = B * 100; var answer = -1; for (var i = 0; i < 100; i += 10) { if ((c10 + i) / 125 == A) { answer = (c10 + i) / 10; break; } } Console.WriteLine(answer); } public static class Scanner { private static Queue<string> queue = new Queue<string>(); public static T Next<T>() { if (!queue.Any()) foreach (var item in Console.ReadLine().Trim().Split(" ")) queue.Enqueue(item); return (T)Convert.ChangeType(queue.Dequeue(), typeof(T)); } public static T Scan<T>() => Next<T>(); public static (T1, T2) Scan<T1, T2>() => (Next<T1>(), Next<T2>()); public static (T1, T2, T3) Scan<T1, T2, T3>() => (Next<T1>(), Next<T2>(), Next<T3>()); public static (T1, T2, T3, T4) Scan<T1, T2, T3, T4>() => (Next<T1>(), Next<T2>(), Next<T3>(), Next<T4>()); public static (T1, T2, T3, T4, T5) Scan<T1, T2, T3, T4, T5>() => (Next<T1>(), Next<T2>(), Next<T3>(), Next<T4>(), Next<T5>()); public static IEnumerable<T> ScanEnumerable<T>() => Console.ReadLine().Trim().Split(" ").Select(x => (T)Convert.ChangeType(x, typeof(T))); } } }
34.90566
150
0.474595
[ "CC0-1.0" ]
AconCavy/AtCoder.Tasks.CS
ABC/ABC158/Tasks/C.cs
1,850
C#
using Autofac; using CleanArchitecture.Core.Aggregates; using CleanArchitecture.Core.Aggregates.ToDoAggregate; using CleanArchitecture.Infrastructure; using CleanArchitecture.Infrastructure.DomainEvents; using Xunit; namespace CleanArchitecture.UnitTests.Core.DomainEvents { public class DomainEventDispatcherShould { [Fact] public void NotReturnAnEmptyListOfAvailableHandlers() { var builder = new ContainerBuilder(); builder.RegisterModule(new DefaultInfrastructureModule(isDevelopment: true)); var container = builder.Build(); var domainEventDispatcher = new DomainEventDispatcher(container); var toDoItemCompletedEvent = new ToDoItemCompletedEvent(new ToDoItem()); var handlersForEvent = domainEventDispatcher.GetWrappedHandlers(toDoItemCompletedEvent); Assert.NotEmpty(handlersForEvent); } } }
33.25
100
0.732546
[ "MIT" ]
miklen/CleanArchitecture
tests/CleanArchitecture.UnitTests/Core/DomainEvents/DomainEventDispatcherShould.cs
931
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using Roslyn.Utilities; namespace StarkPlatform.Compiler { internal sealed class CommonDiagnosticComparer : IEqualityComparer<Diagnostic> { internal static readonly CommonDiagnosticComparer Instance = new CommonDiagnosticComparer(); private CommonDiagnosticComparer() { } public bool Equals(Diagnostic x, Diagnostic y) { if (object.ReferenceEquals(x, y)) { return true; } if (x == null || y == null) { return false; } return x.Location == y.Location && x.Id == y.Id; } public int GetHashCode(Diagnostic obj) { if (object.ReferenceEquals(obj, null)) { return 0; } return Hash.Combine(obj.Location, obj.Id.GetHashCode()); } } }
26.238095
161
0.567151
[ "BSD-2-Clause", "MIT" ]
encrypt0r/stark
src/compiler/StarkPlatform.Compiler/Diagnostic/CommonDiagnosticComparer.cs
1,104
C#