content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
// Copyright (c) .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.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Internal
{
/// <summary>
/// A filter that saves temp data.
/// </summary>
public class SaveTempDataFilter : IResourceFilter, IResultFilter
{
// Internal for unit testing
internal static readonly object TempDataSavedKey = new object();
private readonly ITempDataDictionaryFactory _factory;
/// <summary>
/// Creates a new instance of <see cref="SaveTempDataFilter"/>.
/// </summary>
/// <param name="factory">The <see cref="ITempDataDictionaryFactory"/>.</param>
public SaveTempDataFilter(ITempDataDictionaryFactory factory)
{
_factory = factory;
}
/// <inheritdoc />
public void OnResourceExecuting(ResourceExecutingContext context)
{
if (!context.HttpContext.Response.HasStarted)
{
context.HttpContext.Response.OnStarting((state) =>
{
var saveTempDataContext = (SaveTempDataContext)state;
// If temp data was already saved, skip trying to save again as the calls here would potentially fail
// because the session feature might not be available at this point.
// Example: An action returns NoContentResult and since NoContentResult does not write anything to
// the body of the response, this delegate would get executed way late in the pipeline at which point
// the session feature would have been removed.
if (saveTempDataContext.HttpContext.Items.TryGetValue(TempDataSavedKey, out var obj))
{
return Task.CompletedTask;
}
SaveTempData(
result: null,
factory: saveTempDataContext.TempDataDictionaryFactory,
filters: saveTempDataContext.Filters,
httpContext: saveTempDataContext.HttpContext);
return Task.CompletedTask;
},
state: new SaveTempDataContext()
{
Filters = context.Filters,
HttpContext = context.HttpContext,
TempDataDictionaryFactory = _factory
});
}
}
/// <inheritdoc />
public void OnResourceExecuted(ResourceExecutedContext context)
{
}
/// <inheritdoc />
public void OnResultExecuting(ResultExecutingContext context)
{
}
/// <inheritdoc />
public void OnResultExecuted(ResultExecutedContext context)
{
// We are doing this here again because the OnStarting delegate above might get fired too late in scenarios
// where the action result doesn't write anything to the body. This causes the delegate to be executed
// late in the pipeline at which point SessionFeature would not be available.
if (!context.HttpContext.Response.HasStarted)
{
SaveTempData(context.Result, _factory, context.Filters, context.HttpContext);
// If SaveTempDataFilter got added twice this might already be in there.
if (!context.HttpContext.Items.ContainsKey(TempDataSavedKey))
{
context.HttpContext.Items.Add(TempDataSavedKey, true);
}
}
}
private static void SaveTempData(
IActionResult result,
ITempDataDictionaryFactory factory,
IList<IFilterMetadata> filters,
HttpContext httpContext)
{
var tempData = factory.GetTempData(httpContext);
for (var i = 0; i < filters.Count; i++)
{
var callback = filters[i] as ISaveTempDataCallback;
if (callback != null)
{
callback.OnTempDataSaving(tempData);
}
}
if (result is IKeepTempDataResult)
{
tempData.Keep();
}
tempData.Save();
}
private class SaveTempDataContext
{
public IList<IFilterMetadata> Filters { get; set; }
public HttpContext HttpContext { get; set; }
public ITempDataDictionaryFactory TempDataDictionaryFactory { get; set; }
}
}
}
| 38.301587 | 121 | 0.578947 | [
"Apache-2.0"
] | vadzimpm/Mvc | src/Microsoft.AspNetCore.Mvc.ViewFeatures/Internal/SaveTempDataFilter.cs | 4,826 | C# |
namespace BootstrapMvc.Core
{
using System;
using System.Linq.Expressions;
public interface IWritingHelper<TModel> : IWritingHelper
{
void FillControlContext<TProperty>(IControlContext target, Expression<Func<TModel, TProperty>> expression);
IModelValidationResult ValidationResult { get; }
}
}
| 25.692308 | 115 | 0.727545 | [
"MIT"
] | kbalint/BootstrapMvc | src/BootstrapMvc.Core/Core/IWritingHelperOfT.cs | 336 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace TODOList.iOS
{
public class Application
{
// This is the main entry point of the application.
static void Main(string[] args)
{
// if you want to use a different Application Delegate class from "AppDelegate"
// you can specify it here.
UIApplication.Main(args, null, "AppDelegate");
}
}
}
| 22.857143 | 91 | 0.63125 | [
"MIT"
] | BrunoRuiz/EADXamarin | SolutionTodoList/TODOList/TODOList.iOS/Main.cs | 482 | C# |
using System.Linq;
using nscreg.Data.Entities;
namespace nscreg.Server.Common.Services.CodeLookup
{
public class ActivityCodeLookupStrategy : CodeLookupStrategy<ActivityCategory>
{
public override IQueryable<ActivityCategory> Filter(IQueryable<ActivityCategory> query, string wildcard = null,
string userId = null)
{
return userId == null
? query
: query.Where(x => x.ActivityCategoryUsers.Any(u => u.UserId == userId));
}
}
} | 32.5 | 119 | 0.646154 | [
"Apache-2.0"
] | runejo/statbus | src/nscreg.Server.Common/Services/CodeLookup/ActivityCodeLookupStrategy.cs | 520 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Squidex.Identity.Extensions;
#pragma warning disable SA1649 // File name should match first type name
namespace Squidex.Identity.Pages.Manage
{
public sealed class ExternalLoginsModel : ManagePageModelBase<ExternalLoginsModel>
{
public bool ShowRemoveButton { get; set; }
public IList<UserLoginInfo> CurrentLogins { get; set; }
public IList<AuthenticationScheme> OtherLogins { get; set; }
public async Task<IActionResult> OnGetAsync()
{
CurrentLogins = await UserManager.GetLoginsAsync(UserInfo);
OtherLogins =
(await SignInManager.GetExternalAuthenticationSchemesAsync())
.Where(auth => CurrentLogins.All(ul => auth.Name != ul.LoginProvider)).ToList();
ShowRemoveButton = UserInfo.Data.PasswordHash != null || CurrentLogins.Count > 1;
return Page();
}
public async Task<IActionResult> OnPostRemoveLoginAsync(string loginProvider, string providerKey)
{
var result = await UserManager.RemoveLoginAsync(UserInfo, loginProvider, providerKey);
if (!result.Succeeded)
{
throw new ApplicationException($"Unexpected error occurred removing external login for user with ID '{UserInfo.Id}'.");
}
await SignInManager.SignInAsync(UserInfo, false);
StatusMessage = T["ExternalLoginRemoved"];
return RedirectToPage();
}
public async Task<IActionResult> OnPostLinkLoginAsync(string provider)
{
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
var authenticationRedirectUrl = Url.Page("./ExternalLogins", "LinkLoginCallback");
var authenticationProperties = SignInManager.ConfigureExternalAuthenticationProperties(provider, authenticationRedirectUrl, UserInfo.Id.ToString());
return new ChallengeResult(provider, authenticationProperties);
}
public async Task<IActionResult> OnGetLinkLoginCallbackAsync()
{
var loginInfo = await SignInManager.GetExternalLoginInfoAsync(UserInfo.Id.ToString());
if (loginInfo == null)
{
throw new ApplicationException($"Unexpected error occurred loading external login info for user with ID '{UserInfo.Id}'.");
}
var result = await UserManager.AddLoginAsync(UserInfo, loginInfo);
if (!result.Succeeded)
{
throw new ApplicationException($"Unexpected error occurred adding external login for user with ID '{UserInfo.Id}'.");
}
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
StatusMessage = T["ExternalLoginAdded"];
return RedirectToPage();
}
}
}
| 37.293478 | 160 | 0.623433 | [
"MIT"
] | Squidex/squidex-identity | Squidex.Identity/Pages/Manage/ExternalLogins.cshtml.cs | 3,431 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the apigateway-2015-07-09.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.APIGateway.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.APIGateway.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for GetAuthorizers operation
/// </summary>
public class GetAuthorizersResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
GetAuthorizersResponse response = new GetAuthorizersResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("item", targetDepth))
{
var unmarshaller = new ListUnmarshaller<Authorizer, AuthorizerUnmarshaller>(AuthorizerUnmarshaller.Instance);
response.Items = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("position", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.Position = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
if (errorResponse.Code != null && errorResponse.Code.Equals("BadRequestException"))
{
return new BadRequestException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("NotFoundException"))
{
return new NotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyRequestsException"))
{
return new TooManyRequestsException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("UnauthorizedException"))
{
return new UnauthorizedException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
return new AmazonAPIGatewayException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
private static GetAuthorizersResponseUnmarshaller _instance = new GetAuthorizersResponseUnmarshaller();
internal static GetAuthorizersResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static GetAuthorizersResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 41.016807 | 168 | 0.652325 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/APIGateway/Generated/Model/Internal/MarshallTransformations/GetAuthorizersResponseUnmarshaller.cs | 4,881 | C# |
using ClaimManager.Web.Areas.Admin.Models;
using AutoMapper;
using Microsoft.AspNetCore.Identity;
namespace ClaimManager.Web.Areas.Admin.Mappings
{
public class RoleProfile : Profile
{
public RoleProfile()
{
CreateMap<IdentityRole, RoleViewModel>().ReverseMap();
}
}
} | 22.714286 | 66 | 0.676101 | [
"MIT"
] | seungilpark/ClaimManager | ClaimManager.Web/Areas/Admin/Mappings/RoleProfile.cs | 320 | C# |
namespace _11.ArraysEx01SumArrayElements
{
using System;
using System.Collections.Generic;
using System.Linq;
public class SumArrayElements
{
public static void Main()
{
int n = int.Parse(Console.ReadLine());
int sum = 0;
int[] intArray = new int[n];
for (int i = 0; i < intArray.Length; i++)
{
intArray[i] = int.Parse(Console.ReadLine());
}
for (int i = 0; i < intArray.Length; i++)
{
sum += intArray[i];
}
Console.WriteLine(sum);
}
}
}
| 22.928571 | 60 | 0.471963 | [
"MIT"
] | dontito88/ProgrammFundamentalsSecondChance | SecondChance/11.ArraysEx01SumArrayElements/SumArrayElements.cs | 644 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.WafV2.Inputs
{
public sealed class WebAclRuleStatementNotStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryStringGetArgs : Pulumi.ResourceArgs
{
public WebAclRuleStatementNotStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryStringGetArgs()
{
}
}
}
| 33.25 | 153 | 0.783459 | [
"ECL-2.0",
"Apache-2.0"
] | Otanikotani/pulumi-aws | sdk/dotnet/WafV2/Inputs/WebAclRuleStatementNotStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryStringGetArgs.cs | 665 | C# |
using System.Collections.Generic;
using YoYo_Web_App.Models;
namespace YoYo_Web_App.Repository
{
public interface IShuttleRepository
{
List<Shuttle> GetShuttles();
List<string> GetSpeedLevelAndShuttles();
}
}
| 19.916667 | 48 | 0.719665 | [
"Apache-2.0"
] | sathishgovindan/YoYo-Web-App | Repository/IShuttleRepository.cs | 241 | C# |
using System.Text;
using Nerven.Htmler.Fundamentals;
namespace Nerven.Htmler
{
public interface IHtmlDocumentResource : IHtmlResourceNode
{
IHtmlDocument Document { get; set; }
Encoding Encoding { get; }
IHtmlDocumentResource CloneDocumentResource();
}
}
| 19.6 | 62 | 0.70068 | [
"MIT"
] | Nerven/Htmler | source/Nerven.Htmler/IHtmlDocumentResource.cs | 294 | C# |
/*
* Tester.Tests
*
* This file was automatically generated for Stamplay by APIMATIC v2.0 ( https://apimatic.io ) on 08/09/2016
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Threading.Tasks;
using NUnit.Framework;
using Tester.PCL;
using Tester.PCL.Controllers;
using Tester.PCL.Models;
using Tester.PCL.Exceptions;
using Tester.PCL.Http.Client;
using Tester.Tests.Helpers;
namespace Tester.Tests
{
[TestFixture]
public class HeaderControllerTest : ControllerTestBase
{
/// <summary>
/// Controller instance (for all tests)
/// </summary>
private static IHeaderController controller;
/// <summary>
/// Setup test class
/// </summary>
[SetUp]
public static void SetUpClass()
{
controller = GetClient().Header;
applyConfiguration();
}
/// <summary>
/// TODO: Add description for test TestSendHeaders
/// </summary>
[Test]
public async Task TestSendHeaders()
{
// Parameters for the API call
string customHeader = "TestString";
string mvalue = "TestString";
// Perform API call
ServerResponse result = null;
try
{
result = await controller.SendHeadersAsync(customHeader, mvalue);
}
catch(APIException) {};
// Test response code
Assert.AreEqual(200, httpCallBackHandler.Response.StatusCode,
"Status should be 200");
// Test whether the captured response is as we expected
Assert.IsNotNull(result, "Result should exist");
Assert.IsTrue(TestHelper.IsJsonObjectProperSubsetOf(
"{\"passed\":true}",
TestHelper.ConvertStreamToString(httpCallBackHandler.Response.RawBody),
true, true, false),
"Response body should have matching keys");
}
}
}
| 27.421053 | 108 | 0.586372 | [
"MIT"
] | mnaumanali94/CSHARP-SDK | Tester.Tests/HeaderControllerTest.cs | 2,084 | C# |
using System;
namespace TrueCraft.Core.Logic.Items
{
public class SlimeballItem : ItemProvider
{
public static readonly short ItemID = 0x155;
public override short ID { get { return 0x155; } }
public override Tuple<int, int> GetIconTexture(byte metadata)
{
return new Tuple<int, int>(14, 1);
}
public override string DisplayName { get { return "Slimeball"; } }
}
} | 24.444444 | 74 | 0.620455 | [
"MIT"
] | mrj001/TrueCraft | TrueCraft.Core/Logic/Items/SlimeballItem.cs | 440 | C# |
//
// Copyright (c) 2015 Xamarin Inc. (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//TODO:[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(Microsoft.Win32.SafeHandles.SafeX509ChainHandle))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.OpenFlags))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.PublicKey))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.StoreLocation))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.StoreName))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X500DistinguishedName))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X500DistinguishedNameFlags))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X509Certificate))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X509Certificate2))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X509Certificate2Collection))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X509Certificate2Enumerator))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X509CertificateCollection))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X509Chain))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X509ChainElement))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X509ChainElementCollection))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X509ChainElementEnumerator))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X509ChainPolicy))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X509ChainStatus))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X509ChainStatusFlags))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X509ContentType))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X509Extension))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X509ExtensionCollection))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X509ExtensionEnumerator))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X509FindType))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X509KeyStorageFlags))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X509KeyUsageExtension))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X509KeyUsageFlags))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X509NameType))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X509RevocationFlag))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X509RevocationMode))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X509Store))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierHashAlgorithm))]
[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Security.Cryptography.X509Certificates.X509VerificationFlags))]
| 103.737705 | 161 | 0.864096 | [
"Apache-2.0"
] | AvolitesMarkDaniel/mono | mcs/class/Facades/System.Security.Cryptography.X509Certificates/TypeForwarders.cs | 6,328 | C# |
// Copyright 2007-2019 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.ApplicationInsights.Pipeline
{
using System;
using System.Threading.Tasks;
using GreenPipes;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;
using Util;
public class ApplicationInsightsConsumeFilter<T> :
IFilter<ConsumeContext<T>>
where T : class
{
const string MessageId = nameof(MessageId);
const string ConversationId = nameof(ConversationId);
const string CorrelationId = nameof(CorrelationId);
const string DestinationAddress = nameof(DestinationAddress);
const string InputAddress = nameof(InputAddress);
const string RequestId = nameof(RequestId);
const string MessageType = nameof(MessageType);
const string StepName = "MassTransit:Consumer";
readonly Action<IOperationHolder<RequestTelemetry>, ConsumeContext> _configureOperation;
readonly TelemetryClient _telemetryClient;
readonly string _telemetryHeaderRootKey;
readonly string _telemetryHeaderParentKey;
public ApplicationInsightsConsumeFilter(TelemetryClient telemetryClient, string telemetryHeaderRootKey, string telemetryHeaderParentKey,
Action<IOperationHolder<RequestTelemetry>, ConsumeContext> configureOperation)
{
_telemetryClient = telemetryClient;
_configureOperation = configureOperation;
_telemetryHeaderRootKey = telemetryHeaderRootKey;
_telemetryHeaderParentKey = telemetryHeaderParentKey;
}
public void Probe(ProbeContext context)
{
context.CreateFilterScope("TelemetryConsumeFilter");
}
public async Task Send(ConsumeContext<T> context, IPipe<ConsumeContext<T>> next)
{
// After the message is taken from the queue, create RequestTelemetry to track its processing.
var requestTelemetry = new RequestTelemetry
{
Name = $"{StepName} {context.ReceiveContext.InputAddress.LocalPath} {TypeMetadataCache<T>.ShortName}"
};
requestTelemetry.Context.Operation.Id = context.Headers.Get<string>(_telemetryHeaderRootKey);
requestTelemetry.Context.Operation.ParentId = context.Headers.Get<string>(_telemetryHeaderParentKey);
using (IOperationHolder<RequestTelemetry> operation = _telemetryClient.StartOperation(requestTelemetry))
{
operation.Telemetry.Properties.Add(MessageType, TypeMetadataCache<T>.ShortName);
if (context.MessageId.HasValue)
operation.Telemetry.Properties.Add(MessageId, context.MessageId.Value.ToString());
if (context.ConversationId.HasValue)
operation.Telemetry.Properties.Add(ConversationId, context.ConversationId.Value.ToString());
if (context.CorrelationId.HasValue)
operation.Telemetry.Properties.Add(CorrelationId, context.CorrelationId.Value.ToString());
if (context.DestinationAddress != null)
operation.Telemetry.Properties.Add(DestinationAddress, context.DestinationAddress.ToString());
if (context.ReceiveContext.InputAddress != null)
operation.Telemetry.Properties.Add(InputAddress, context.ReceiveContext.InputAddress.ToString());
if (context.RequestId.HasValue)
operation.Telemetry.Properties.Add(RequestId, context.RequestId.Value.ToString());
_configureOperation?.Invoke(operation, context);
try
{
await next.Send(context).ConfigureAwait(false);
operation.Telemetry.Success = true;
}
catch (Exception ex)
{
_telemetryClient.TrackException(ex, operation.Telemetry.Properties);
operation.Telemetry.Success = false;
throw;
}
finally
{
_telemetryClient.StopOperation(operation);
}
}
}
}
} | 44.678571 | 145 | 0.647882 | [
"Apache-2.0"
] | GreenKn1ght/MassTransit | src/MassTransit.ApplicationInsights/Pipeline/ApplicationInsightsConsumeFilter.cs | 5,006 | C# |
using System.Threading.Tasks;
using OmniSharp.Models;
using OmniSharp.Models.FileOpen;
using OmniSharp.Roslyn.CSharp.Services.Files;
using TestUtility;
using Xunit;
using Xunit.Abstractions;
namespace OmniSharp.Roslyn.CSharp.Tests
{
public class OpenCloseFacts : AbstractSingleRequestHandlerTestFixture<FileOpenService>
{
public OpenCloseFacts(ITestOutputHelper output, SharedOmniSharpHostFixture sharedOmniSharpHostFixture)
: base(output, sharedOmniSharpHostFixture)
{
}
protected override string EndpointName => OmniSharpEndpoints.Open;
[Fact]
public async Task AddsOpenFile()
{
var testFile1 = new TestFile("foo.cs", @"using System; class Foo { }");
var testFile2 = new TestFile("bar.cs", @"class Bar { private Foo foo; }");
using (var host = CreateOmniSharpHost(testFile1, testFile2))
{
var documentId = host.Workspace.GetDocumentId("foo.cs");
var requestHandler = GetRequestHandler(host);
var request = new FileOpenRequest
{
FileName = "foo.cs"
};
var response = await requestHandler.Handle(request);
Assert.True(host.Workspace.IsDocumentOpen(documentId));
}
}
}
}
| 31.55814 | 110 | 0.627119 | [
"MIT"
] | 333fred/omnisharp-roslyn | tests/OmniSharp.Roslyn.CSharp.Tests/OpenCloseFacts.cs | 1,357 | C# |
namespace StateMachine.Core.Machines
{
/// <summary>
/// Контейнер для объектов, к которым применяются состояния
/// </summary>
public abstract class MachineContext
{
}
} | 21.666667 | 63 | 0.65641 | [
"MIT"
] | potory/StateMachine | Core/Machines/MachineContext.cs | 245 | C# |
// <auto-generated />
using System;
using OAuthApp.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace OAuthApp.Data.AppMigrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20220126092451_2022012601UpdateAppDbMigration")]
partial class _2022012601UpdateAppDbMigration
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "5.0.12");
modelBuilder.Entity("H5App.Data.App", b =>
{
b.Property<long>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("AppKey")
.HasColumnType("TEXT");
b.Property<DateTime>("CreateDate")
.HasColumnType("DATETIME");
b.Property<string>("Description")
.HasColumnType("TEXT");
b.Property<bool>("IsDelete")
.HasColumnType("BOOLEAN");
b.Property<DateTime>("LastUpdate")
.HasColumnType("DATETIME");
b.Property<string>("Logo")
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasColumnType("TEXT");
b.Property<long>("ProjectID")
.HasColumnType("INTEGER");
b.Property<string>("ServerPath")
.HasColumnType("TEXT");
b.Property<bool>("Share")
.HasColumnType("BOOLEAN");
b.Property<string>("Tags")
.HasColumnType("TEXT");
b.Property<long>("UserID")
.HasColumnType("INTEGER");
b.Property<string>("Website")
.HasColumnType("TEXT");
b.HasKey("ID");
b.ToTable("Apps");
});
modelBuilder.Entity("H5App.Data.AppChatMessage", b =>
{
b.Property<long>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("AppID")
.HasColumnType("INTEGER");
b.Property<string>("Avatar")
.HasColumnType("TEXT");
b.Property<string>("Content")
.HasColumnType("TEXT");
b.Property<DateTime>("CreateDate")
.HasColumnType("DATETIME");
b.Property<string>("GroupName")
.HasColumnType("TEXT");
b.Property<bool>("IsDelete")
.HasColumnType("BOOLEAN");
b.Property<DateTime>("LastUpdate")
.HasColumnType("DATETIME");
b.Property<string>("MessageType")
.HasColumnType("TEXT");
b.Property<string>("NickName")
.HasColumnType("TEXT");
b.Property<string>("OpenID")
.HasColumnType("TEXT");
b.Property<string>("Platform")
.HasColumnType("TEXT");
b.Property<string>("Remark")
.HasColumnType("TEXT");
b.Property<int>("ShowIndex")
.HasColumnType("INTEGER");
b.Property<string>("Tags")
.HasColumnType("TEXT");
b.HasKey("ID");
b.ToTable("AppChatMessages");
});
modelBuilder.Entity("H5App.Data.AppRank", b =>
{
b.Property<long>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("AppID")
.HasColumnType("INTEGER");
b.Property<string>("Avatar")
.HasColumnType("TEXT");
b.Property<DateTime>("CreateDate")
.HasColumnType("DATETIME");
b.Property<string>("Data")
.HasColumnType("TEXT");
b.Property<bool>("IsDelete")
.HasColumnType("BOOLEAN");
b.Property<DateTime>("LastUpdate")
.HasColumnType("DATETIME");
b.Property<long>("MaximumScore")
.HasColumnType("INTEGER");
b.Property<string>("NickName")
.HasColumnType("TEXT");
b.Property<string>("Platform")
.HasColumnType("TEXT");
b.Property<string>("RankKey")
.HasColumnType("TEXT");
b.Property<long>("Score")
.HasColumnType("INTEGER");
b.Property<string>("UnionID")
.HasColumnType("TEXT");
b.Property<long>("UserID")
.HasColumnType("INTEGER");
b.HasKey("ID");
b.ToTable("AppRanks");
});
modelBuilder.Entity("H5App.Data.AppUser", b =>
{
b.Property<long>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("AppID")
.HasColumnType("INTEGER");
b.Property<string>("Avatar")
.HasColumnType("TEXT");
b.Property<DateTime>("CreateDate")
.HasColumnType("DATETIME");
b.Property<string>("Data")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasColumnType("TEXT");
b.Property<bool>("EmailIsValid")
.HasColumnType("INTEGER");
b.Property<bool>("IsDelete")
.HasColumnType("BOOLEAN");
b.Property<DateTime>("LastUpdate")
.HasColumnType("DATETIME");
b.Property<string>("NickName")
.HasColumnType("TEXT");
b.Property<string>("Phone")
.HasColumnType("TEXT");
b.Property<bool>("PhoneIsValid")
.HasColumnType("INTEGER");
b.Property<string>("Platform")
.HasColumnType("TEXT");
b.Property<string>("Pwd")
.HasColumnType("TEXT");
b.Property<string>("UnionID")
.HasColumnType("TEXT");
b.Property<long>("UserID")
.HasColumnType("INTEGER");
b.Property<string>("UserName")
.HasColumnType("TEXT");
b.HasKey("ID");
b.ToTable("AppUsers");
});
modelBuilder.Entity("H5App.Data.AppVersion", b =>
{
b.Property<long>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("AppID")
.HasColumnType("INTEGER");
b.Property<long>("AppServerID")
.HasColumnType("INTEGER");
b.Property<DateTime>("CreateDate")
.HasColumnType("DATETIME");
b.Property<string>("Description")
.HasColumnType("TEXT");
b.Property<bool>("IsDelete")
.HasColumnType("BOOLEAN");
b.Property<DateTime>("LastUpdate")
.HasColumnType("DATETIME");
b.Property<string>("PackageBackupUri")
.HasColumnType("TEXT");
b.Property<string>("Tag")
.HasColumnType("TEXT");
b.Property<long>("UserID")
.HasColumnType("INTEGER");
b.Property<string>("Ver")
.HasColumnType("TEXT");
b.HasKey("ID");
b.ToTable("AppVersions");
});
modelBuilder.Entity("H5App.Data.MarketTag", b =>
{
b.Property<long>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("ChannelCode")
.HasColumnType("TEXT");
b.Property<DateTime>("CreateDate")
.HasColumnType("DATETIME");
b.Property<string>("Description")
.HasColumnType("TEXT");
b.Property<bool>("IsDelete")
.HasColumnType("BOOLEAN");
b.Property<DateTime>("LastUpdate")
.HasColumnType("DATETIME");
b.Property<string>("Name")
.HasColumnType("TEXT");
b.Property<int>("Priority")
.HasColumnType("INTEGER");
b.Property<bool>("ShowFlag")
.HasColumnType("BOOLEAN");
b.Property<long>("UserID")
.HasColumnType("INTEGER");
b.HasKey("ID");
b.ToTable("MarketTags");
});
modelBuilder.Entity("H5App.Data.Project", b =>
{
b.Property<long>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<DateTime>("CreateDate")
.HasColumnType("DATETIME");
b.Property<string>("Description")
.HasColumnType("TEXT");
b.Property<bool>("IsDelete")
.HasColumnType("BOOLEAN");
b.Property<DateTime>("LastUpdate")
.HasColumnType("DATETIME");
b.Property<string>("Logo")
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasColumnType("TEXT");
b.Property<long>("UserID")
.HasColumnType("INTEGER");
b.HasKey("ID");
b.ToTable("Projects");
});
modelBuilder.Entity("H5App.Data.PropertySetting", b =>
{
b.Property<long>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("ChannelAppId")
.HasColumnType("INTEGER");
b.Property<string>("ChannelCode")
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasColumnType("TEXT");
b.Property<string>("Value")
.HasColumnType("TEXT");
b.HasKey("ID");
b.ToTable("PropertySettings");
});
modelBuilder.Entity("H5App.Data.Team", b =>
{
b.Property<long>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("ChannelAppID")
.HasColumnType("TEXT");
b.Property<string>("ChannelCode")
.HasColumnType("TEXT");
b.Property<DateTime>("CreateDate")
.HasColumnType("DATETIME");
b.Property<bool>("IsDelete")
.HasColumnType("BOOLEAN");
b.Property<DateTime>("LastUpdate")
.HasColumnType("DATETIME");
b.Property<string>("Permission")
.HasColumnType("TEXT");
b.Property<string>("Role")
.HasColumnType("TEXT");
b.Property<long>("UserID")
.HasColumnType("INTEGER");
b.HasKey("ID");
b.ToTable("Teams");
});
modelBuilder.Entity("H5App.Data.User", b =>
{
b.Property<long>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Avatar")
.HasColumnType("TEXT");
b.Property<DateTime>("CreateDate")
.HasColumnType("DATETIME");
b.Property<string>("Email")
.HasColumnType("TEXT");
b.Property<bool>("EmailIsValid")
.HasColumnType("BOOLEAN");
b.Property<bool>("IsDelete")
.HasColumnType("BOOLEAN");
b.Property<DateTime>("LastUpdate")
.HasColumnType("DATETIME");
b.Property<string>("NickName")
.HasColumnType("TEXT");
b.Property<string>("Password")
.HasColumnType("TEXT");
b.Property<string>("Phone")
.HasColumnType("TEXT");
b.Property<bool>("PhoneIsValid")
.HasColumnType("BOOLEAN");
b.Property<string>("UserName")
.HasColumnType("TEXT");
b.HasKey("ID");
b.ToTable("Users");
});
modelBuilder.Entity("H5App.Data.UserAppServer", b =>
{
b.Property<long>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("AppServerID")
.HasColumnType("INTEGER");
b.Property<DateTime>("CreateDate")
.HasColumnType("DATETIME");
b.Property<bool>("IsDelete")
.HasColumnType("BOOLEAN");
b.Property<DateTime>("LastUpdate")
.HasColumnType("DATETIME");
b.Property<long>("UserID")
.HasColumnType("INTEGER");
b.HasKey("ID");
b.ToTable("UserAppServers");
});
modelBuilder.Entity("H5App.Data.UserClaim", b =>
{
b.Property<long>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("ClaimType")
.HasColumnType("TEXT");
b.Property<string>("ClaimValue")
.HasColumnType("TEXT");
b.Property<long>("UserID")
.HasColumnType("INTEGER");
b.HasKey("ID");
b.ToTable("UserClaims");
});
#pragma warning restore 612, 618
}
}
}
| 32.381818 | 75 | 0.411691 | [
"Apache-2.0"
] | seven1986/IdentityServer4.MicroService | Data/AppMigrations/20220126092451_2022012601UpdateAppDbMigration.Designer.cs | 16,031 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
namespace Filemanager
{
/// <summary>
/// Filemanager configuration settings
/// </summary>
public class FilemanagerConfig
{
/// <summary>
/// Root directory for all file uploads [string]
/// Set in web.config. E.g. <add key="Filemanager_RootPath" value="/uploads/"/>
/// </summary>
public string RootPath { get; set; }
/// <summary>
/// Directory for icons. [string]
/// Set in web.config E.g. <add key="Filemanager_IconDirectory" value="/Scripts/filemanager/images/fileicons/"/>
/// </summary>
public string IconDirectory { get; set; }
/// <summary>
/// White list of allowed file extensions
/// </summary>
public List<string> AllowedExtensions { get; set; }
/// <summary>
/// List of image file extensions
/// </summary>
public List<string> ImgExtensions { get; set; }
/// <summary>
/// Constructor
/// </summary>
public FilemanagerConfig()
{
RootPath = WebConfigurationManager.AppSettings["FileManager_RootPath"];
IconDirectory = WebConfigurationManager.AppSettings["Filemanager_IconDirectory"];
AllowedExtensions = new List<string> { ".ai", ".asx", ".avi", ".bmp", ".csv", ".dat", ".doc", ".docx", ".epub", ".fla", ".flv", ".gif", ".html", ".ico", ".jpeg", ".jpg", ".m4a", ".mobi", ".mov", ".mp3", ".mp4", ".mpa", ".mpg", ".mpp", ".pdf", ".png", ".pps", ".ppsx", ".ppt", ".pptx", ".ps", ".psd", ".qt", ".ra", ".ram", ".rar", ".rm", ".rtf", ".svg", ".swf", ".tif", ".txt", ".vcf", ".vsd", ".wav", ".wks", ".wma", ".wmv", ".wps", ".xls", ".xlsx", ".xml", ".zip" };
ImgExtensions = new List<string> { ".gif", ".jpe", ".jpeg", ".jpg", ".png", ".svg" };
}
}
} | 41.404255 | 479 | 0.540082 | [
"MIT"
] | Meltos/BlogPhp1131 | tpl/back-end/assets/fm/connectors/mvc/FilemanagerConfig.cs | 1,948 | C# |
/*
Copyright 2015 University of Washington
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Xml;
using System.Xml.XPath;
namespace CometUI.ViewResults
{
public class PepXMLReader
{
private const String NamespaceURI = "http://regis-web.systemsbiology.net/pepXML";
private String FileName { get; set; }
private XPathDocument PepXmlXPathDoc { get; set; }
private XPathNavigator PepXmlXPathNav { get; set; }
private XmlNamespaceManager PepXmlNamespaceMgr { get; set; }
/// <summary>
/// Constructor for the PepXMLReader that creates the document
/// navigator. It throws exceptions that the caller must handle.
/// such as invalid file name.
/// </summary>
/// <param name="fileName"></param>
public PepXMLReader(String fileName)
{
FileName = fileName;
CreateDocNavigator();
}
private void CreateDocNavigator()
{
PepXmlXPathDoc = new XPathDocument(FileName);
PepXmlXPathNav = PepXmlXPathDoc.CreateNavigator();
// Create prefix<->namespace mappings
if (PepXmlXPathNav.NameTable != null)
{
PepXmlNamespaceMgr = new XmlNamespaceManager(PepXmlXPathNav.NameTable);
PepXmlNamespaceMgr.AddNamespace("pepXML", NamespaceURI);
}
}
private String GetFullNodeName(String name)
{
var fullName = String.Empty;
var nodeNames = name.Split('/');
foreach (var nodeName in nodeNames)
{
if (!nodeName.Equals(String.Empty))
{
fullName += "/" + "pepXML:" + nodeName;
}
}
return fullName;
}
public XPathNodeIterator ReadNodes(String name)
{
return PepXmlXPathNav.Select(GetFullNodeName(name), PepXmlNamespaceMgr);
}
public XPathNodeIterator ReadDescendants(XPathNavigator nodeNav, String name)
{
return nodeNav.SelectDescendants(name, NamespaceURI, true);
}
public XPathNavigator ReadFirstMatchingDescendant(XPathNavigator nodeNav, String name)
{
var descendants = nodeNav.SelectDescendants(name, NamespaceURI, true);
if (descendants.Count == 0)
{
return null;
}
descendants.MoveNext();
return descendants.Current;
}
public XPathNodeIterator ReadChildren(XPathNavigator nodeNav, String name)
{
return nodeNav.SelectChildren(name, NamespaceURI);
}
public XPathNavigator ReadFirstMatchingChild(XPathNavigator nodeNav, String name)
{
var children = nodeNav.SelectChildren(name, NamespaceURI);
if (children.Count == 0)
{
return null;
}
children.MoveNext();
return children.Current;
}
public XPathNavigator ReadFirstMatchingNode(String name)
{
var iterator = ReadNodes(name);
iterator.MoveNext();
return iterator.Current;
}
public String ReadAttribute(XPathNavigator nodeNav, String attributeName)
{
return nodeNav.GetAttribute(attributeName, String.Empty);
}
public bool ReadAttribute<T>(XPathNavigator nodeNavigator, String attributeName, out T attribute)
{
attribute = default(T);
var attributeStrValue = ReadAttribute(nodeNavigator, attributeName);
if (attributeStrValue.Equals(String.Empty))
{
return false;
}
attribute = (T)Convert.ChangeType(attributeStrValue, typeof(T));
return true;
}
public String ReadAttributeFromFirstMatchingNode(String nodeName, String attributeName)
{
var nodeNav = ReadFirstMatchingNode(nodeName);
var attribute = ReadAttribute(nodeNav, attributeName);
return attribute;
}
public bool ReadAttributeFromFirstMatchingNode<T>(String nodeName, String attributeName, out T attribute)
{
attribute = default(T);
var attributeStrValue = ReadAttributeFromFirstMatchingNode(nodeName, attributeName);
if (attributeStrValue.Equals(String.Empty))
{
return false;
}
attribute = (T) Convert.ChangeType(attributeStrValue, typeof (T));
return true;
}
}
}
| 33.904459 | 114 | 0.588202 | [
"Apache-2.0"
] | UWPR/Comet | CometUI/ViewResults/PepXMLReader.cs | 5,325 | 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.CostManagement.V20191101.Inputs
{
/// <summary>
/// The filter expression to be used in the export.
/// </summary>
public sealed class QueryFilterArgs : Pulumi.ResourceArgs
{
[Input("and")]
private InputList<Inputs.QueryFilterArgs>? _and;
/// <summary>
/// The logical "AND" expression. Must have at least 2 items.
/// </summary>
public InputList<Inputs.QueryFilterArgs> And
{
get => _and ?? (_and = new InputList<Inputs.QueryFilterArgs>());
set => _and = value;
}
/// <summary>
/// Has comparison expression for a dimension
/// </summary>
[Input("dimensions")]
public Input<Inputs.QueryComparisonExpressionArgs>? Dimensions { get; set; }
[Input("or")]
private InputList<Inputs.QueryFilterArgs>? _or;
/// <summary>
/// The logical "OR" expression. Must have at least 2 items.
/// </summary>
public InputList<Inputs.QueryFilterArgs> Or
{
get => _or ?? (_or = new InputList<Inputs.QueryFilterArgs>());
set => _or = value;
}
/// <summary>
/// Has comparison expression for a tag
/// </summary>
[Input("tags")]
public Input<Inputs.QueryComparisonExpressionArgs>? Tags { get; set; }
public QueryFilterArgs()
{
}
}
}
| 29.661017 | 84 | 0.592 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/CostManagement/V20191101/Inputs/QueryFilterArgs.cs | 1,750 | C# |
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF;
using Microsoft.eShopOnContainers.Services.Ordering.API.Infrastructure;
using Microsoft.eShopOnContainers.Services.Ordering.Infrastructure;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using Microsoft.Extensions.Options;
using Pivotal.Extensions.Configuration.ConfigServer;
using Steeltoe.Extensions.Logging;
using System.Collections.Generic;
using System.IO;
namespace Microsoft.eShopOnContainers.Services.Ordering.API
{
public class Program
{
public static void Main(string[] args)
{
LoggerFactory logFactory = new LoggerFactory();
logFactory.AddConsole(new ConsoleLoggerSettings { DisableColors = true, Switches = new Dictionary<string, LogLevel> { { "Default", LogLevel.Information } } });
BuildWebHost(args, logFactory)
.MigrateDbContext<OrderingContext>((context, services) =>
{
var env = services.GetService<IHostingEnvironment>();
var settings = services.GetService<IOptions<OrderingSettings>>();
var logger = services.GetService<ILogger<OrderingContextSeed>>();
new OrderingContextSeed()
.SeedAsync(context, env, settings, logger)
.Wait();
})
.MigrateDbContext<IntegrationEventLogContext>((_,__)=>{})
.Run();
}
public static IWebHost BuildWebHost(string[] args, LoggerFactory logfactory) =>
WebHost.CreateDefaultBuilder(args)
.UseCloudFoundryHosting()
.UseStartup<Startup>()
.UseHealthChecks("/hc")
.UseContentRoot(Directory.GetCurrentDirectory())
.AddExternalConfigSources(logfactory)
.ConfigureLogging((hostingContext, builder) =>
{
builder.ClearProviders();
builder.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
builder.AddDynamicConsole();
builder.AddDebug();
})
.UseApplicationInsights()
.Build();
}
}
| 42.172414 | 171 | 0.635732 | [
"MIT"
] | spring-operator/eShopOnContainers | src/Services/Ordering/Ordering.API/Program.cs | 2,448 | C# |
using System.Collections.Generic;
using System.Xml.Linq;
using SmartFormat.Core.Extensions;
namespace SmartFormat.Extensions
{
public class XElementFormatter : IFormatter
{
public string[] Names { get; set; } = {"xelement", "xml", "x", ""};
public bool TryEvaluateFormat(IFormattingInfo formattingInfo)
{
var format = formattingInfo.Format;
var current = formattingInfo.CurrentValue;
XElement currentXElement = null;
if (format != null && format.HasNested) return false;
// if we need to format list of XElements then we just take and format first
var xElmentsAsList = current as IList<XElement>;
if (xElmentsAsList != null && xElmentsAsList.Count > 0) currentXElement = xElmentsAsList[0];
var currentAsXElement = currentXElement ?? current as XElement;
if (currentAsXElement != null)
{
formattingInfo.Write(currentAsXElement.Value);
return true;
}
return false;
}
}
} | 34.1875 | 104 | 0.613346 | [
"MIT"
] | cohero/SmartFormat.NET | src/SmartFormat/Extensions/XElementFormatter.cs | 1,096 | 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("Problem3-ExcelColumns")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Problem3-ExcelColumns")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3c6e0a74-5d7f-4584-89c8-dcdac6f9372a")]
// 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"
] | pavelhristov/CSharpFundamentals | ExamPreparation28Dec2012/Problem3-ExcelColumns/Properties/AssemblyInfo.cs | 1,418 | 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("Our.Umbraco.ContentList")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Our.Umbraco.ContentList")]
[assembly: AssemblyCopyright("Copyright © 2020 Lars-Erik Aabech")]
[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("ecb32c86-99b9-4568-969d-0ad9b2580c93")]
// 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.*")]
[assembly: AssemblyInformationalVersion("1.0.0-beta31")] | 40.166667 | 84 | 0.750346 | [
"MIT"
] | lars-erik/Our.Umbraco.ContentList | Our.Umbraco.ContentList/Properties/AssemblyInfo.cs | 1,449 | C# |
public class CommonItem : IItem
{
private string name;
private int strengthBonus;
private int agilityBonus;
private int intelligenceBonus;
private int hitPointsBonus;
private int damageBonus;
public CommonItem(string name, int strengthBonus, int agilityBonus,
int intelligenceBonus, int hitPointsBonus, int damageBonus)
{
this.name = name;
this.strengthBonus = strengthBonus;
this.agilityBonus = agilityBonus;
this.intelligenceBonus = intelligenceBonus;
this.hitPointsBonus = hitPointsBonus;
this.damageBonus = damageBonus;
}
public string Name => this.name;
public int StrengthBonus => this.strengthBonus;
public int AgilityBonus => this.agilityBonus;
public int IntelligenceBonus => this.intelligenceBonus;
public int HitPointsBonus => this.hitPointsBonus;
public int DamageBonus => this.damageBonus;
} | 29.4375 | 81 | 0.697452 | [
"MIT"
] | Rusev12/Software-University-SoftUni | C# OOP Advanced/10-ExamPreparation-Hell/Hell/Entities/Items/CommonItem.cs | 944 | C# |
// Copyright (c) Dolittle. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
namespace Dolittle.Runtime.Configuration.Files
{
/// <summary>
/// Exception that gets thrown when there is no parser capable of parsing the configuration file.
/// </summary>
public class MissingParserForConfigurationFile : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="MissingParserForConfigurationFile"/> class.
/// </summary>
/// <param name="filename">Name of the file.</param>
public MissingParserForConfigurationFile(string filename)
: base($"Missing parser for configuration file '{filename}'")
{
}
}
} | 36.227273 | 101 | 0.670013 | [
"MIT"
] | dolittle/Runtime | Source/Configuration.Files/MissingParserForConfigurationFile.cs | 797 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ram-2018-01-04.normal.json service model.
*/
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Amazon.Runtime;
using Amazon.RAM.Model;
namespace Amazon.RAM
{
/// <summary>
/// Interface for accessing RAM
///
/// Use AWS Resource Access Manager to share AWS resources between AWS accounts. To share
/// a resource, you create a resource share, associate the resource with the resource
/// share, and specify the principals that can access the resources associated with the
/// resource share. The following principals are supported: AWS accounts, organizational
/// units (OU) from AWS Organizations, and organizations from AWS Organizations.
///
///
/// <para>
/// For more information, see the <a href="https://docs.aws.amazon.com/ram/latest/userguide/">AWS
/// Resource Access Manager User Guide</a>.
/// </para>
/// </summary>
public partial interface IAmazonRAM : IAmazonService, IDisposable
{
#region AcceptResourceShareInvitation
/// <summary>
/// Accepts an invitation to a resource share from another AWS account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the AcceptResourceShareInvitation service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the AcceptResourceShareInvitation service method, as returned by RAM.</returns>
/// <exception cref="Amazon.RAM.Model.IdempotentParameterMismatchException">
/// A client token input parameter was reused with an operation, but at least one of the
/// other input parameters is different from the previous call to the operation.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidClientTokenException">
/// A client token is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.MalformedArnException">
/// The format of an Amazon Resource Name (ARN) is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.OperationNotPermittedException">
/// The requested operation is not permitted.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ResourceShareInvitationAlreadyAcceptedException">
/// The invitation was already accepted.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ResourceShareInvitationAlreadyRejectedException">
/// The invitation was already rejected.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ResourceShareInvitationArnNotFoundException">
/// The Amazon Resource Name (ARN) for an invitation was not found.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ResourceShareInvitationExpiredException">
/// The invitation is expired.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServerInternalException">
/// The service could not respond to the request due to an internal problem.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServiceUnavailableException">
/// The service is not available.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/AcceptResourceShareInvitation">REST API Reference for AcceptResourceShareInvitation Operation</seealso>
Task<AcceptResourceShareInvitationResponse> AcceptResourceShareInvitationAsync(AcceptResourceShareInvitationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region AssociateResourceShare
/// <summary>
/// Associates the specified resource share with the specified principals and resources.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the AssociateResourceShare service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the AssociateResourceShare service method, as returned by RAM.</returns>
/// <exception cref="Amazon.RAM.Model.IdempotentParameterMismatchException">
/// A client token input parameter was reused with an operation, but at least one of the
/// other input parameters is different from the previous call to the operation.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidClientTokenException">
/// A client token is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidParameterException">
/// A parameter is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidStateTransitionException">
/// The requested state transition is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidStateTransitionException">
/// The requested state transition is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.MalformedArnException">
/// The format of an Amazon Resource Name (ARN) is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.OperationNotPermittedException">
/// The requested operation is not permitted.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ResourceShareLimitExceededException">
/// The requested resource share exceeds the limit for your account.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServerInternalException">
/// The service could not respond to the request due to an internal problem.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServiceUnavailableException">
/// The service is not available.
/// </exception>
/// <exception cref="Amazon.RAM.Model.UnknownResourceException">
/// A specified resource was not found.
/// </exception>
/// <exception cref="Amazon.RAM.Model.UnknownResourceException">
/// A specified resource was not found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/AssociateResourceShare">REST API Reference for AssociateResourceShare Operation</seealso>
Task<AssociateResourceShareResponse> AssociateResourceShareAsync(AssociateResourceShareRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region AssociateResourceSharePermission
/// <summary>
/// Associates a permission with a resource share.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the AssociateResourceSharePermission service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the AssociateResourceSharePermission service method, as returned by RAM.</returns>
/// <exception cref="Amazon.RAM.Model.InvalidClientTokenException">
/// A client token is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidParameterException">
/// A parameter is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.MalformedArnException">
/// The format of an Amazon Resource Name (ARN) is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.OperationNotPermittedException">
/// The requested operation is not permitted.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServerInternalException">
/// The service could not respond to the request due to an internal problem.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServiceUnavailableException">
/// The service is not available.
/// </exception>
/// <exception cref="Amazon.RAM.Model.UnknownResourceException">
/// A specified resource was not found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/AssociateResourceSharePermission">REST API Reference for AssociateResourceSharePermission Operation</seealso>
Task<AssociateResourceSharePermissionResponse> AssociateResourceSharePermissionAsync(AssociateResourceSharePermissionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region CreateResourceShare
/// <summary>
/// Creates a resource share.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateResourceShare service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the CreateResourceShare service method, as returned by RAM.</returns>
/// <exception cref="Amazon.RAM.Model.IdempotentParameterMismatchException">
/// A client token input parameter was reused with an operation, but at least one of the
/// other input parameters is different from the previous call to the operation.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidClientTokenException">
/// A client token is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidParameterException">
/// A parameter is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidStateTransitionException">
/// The requested state transition is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.MalformedArnException">
/// The format of an Amazon Resource Name (ARN) is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.OperationNotPermittedException">
/// The requested operation is not permitted.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ResourceShareLimitExceededException">
/// The requested resource share exceeds the limit for your account.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServerInternalException">
/// The service could not respond to the request due to an internal problem.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServiceUnavailableException">
/// The service is not available.
/// </exception>
/// <exception cref="Amazon.RAM.Model.TagPolicyViolationException">
/// The specified tag is a reserved word and cannot be used.
/// </exception>
/// <exception cref="Amazon.RAM.Model.UnknownResourceException">
/// A specified resource was not found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/CreateResourceShare">REST API Reference for CreateResourceShare Operation</seealso>
Task<CreateResourceShareResponse> CreateResourceShareAsync(CreateResourceShareRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeleteResourceShare
/// <summary>
/// Deletes the specified resource share.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteResourceShare service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteResourceShare service method, as returned by RAM.</returns>
/// <exception cref="Amazon.RAM.Model.IdempotentParameterMismatchException">
/// A client token input parameter was reused with an operation, but at least one of the
/// other input parameters is different from the previous call to the operation.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidClientTokenException">
/// A client token is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidParameterException">
/// A parameter is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidStateTransitionException">
/// The requested state transition is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.MalformedArnException">
/// The format of an Amazon Resource Name (ARN) is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.OperationNotPermittedException">
/// The requested operation is not permitted.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServerInternalException">
/// The service could not respond to the request due to an internal problem.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServiceUnavailableException">
/// The service is not available.
/// </exception>
/// <exception cref="Amazon.RAM.Model.UnknownResourceException">
/// A specified resource was not found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/DeleteResourceShare">REST API Reference for DeleteResourceShare Operation</seealso>
Task<DeleteResourceShareResponse> DeleteResourceShareAsync(DeleteResourceShareRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DisassociateResourceShare
/// <summary>
/// Disassociates the specified principals or resources from the specified resource share.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DisassociateResourceShare service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DisassociateResourceShare service method, as returned by RAM.</returns>
/// <exception cref="Amazon.RAM.Model.IdempotentParameterMismatchException">
/// A client token input parameter was reused with an operation, but at least one of the
/// other input parameters is different from the previous call to the operation.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidClientTokenException">
/// A client token is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidParameterException">
/// A parameter is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidStateTransitionException">
/// The requested state transition is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.MalformedArnException">
/// The format of an Amazon Resource Name (ARN) is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.OperationNotPermittedException">
/// The requested operation is not permitted.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ResourceShareLimitExceededException">
/// The requested resource share exceeds the limit for your account.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServerInternalException">
/// The service could not respond to the request due to an internal problem.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServiceUnavailableException">
/// The service is not available.
/// </exception>
/// <exception cref="Amazon.RAM.Model.UnknownResourceException">
/// A specified resource was not found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/DisassociateResourceShare">REST API Reference for DisassociateResourceShare Operation</seealso>
Task<DisassociateResourceShareResponse> DisassociateResourceShareAsync(DisassociateResourceShareRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DisassociateResourceSharePermission
/// <summary>
/// Disassociates an AWS RAM permission from a resource share.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DisassociateResourceSharePermission service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DisassociateResourceSharePermission service method, as returned by RAM.</returns>
/// <exception cref="Amazon.RAM.Model.InvalidClientTokenException">
/// A client token is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidParameterException">
/// A parameter is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.MalformedArnException">
/// The format of an Amazon Resource Name (ARN) is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.OperationNotPermittedException">
/// The requested operation is not permitted.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServerInternalException">
/// The service could not respond to the request due to an internal problem.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServiceUnavailableException">
/// The service is not available.
/// </exception>
/// <exception cref="Amazon.RAM.Model.UnknownResourceException">
/// A specified resource was not found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/DisassociateResourceSharePermission">REST API Reference for DisassociateResourceSharePermission Operation</seealso>
Task<DisassociateResourceSharePermissionResponse> DisassociateResourceSharePermissionAsync(DisassociateResourceSharePermissionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region EnableSharingWithAwsOrganization
/// <summary>
/// Enables resource sharing within your AWS Organization.
///
///
/// <para>
/// The caller must be the master account for the AWS Organization.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the EnableSharingWithAwsOrganization service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the EnableSharingWithAwsOrganization service method, as returned by RAM.</returns>
/// <exception cref="Amazon.RAM.Model.OperationNotPermittedException">
/// The requested operation is not permitted.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServerInternalException">
/// The service could not respond to the request due to an internal problem.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServiceUnavailableException">
/// The service is not available.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/EnableSharingWithAwsOrganization">REST API Reference for EnableSharingWithAwsOrganization Operation</seealso>
Task<EnableSharingWithAwsOrganizationResponse> EnableSharingWithAwsOrganizationAsync(EnableSharingWithAwsOrganizationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetPermission
/// <summary>
/// Gets the contents of an AWS RAM permission in JSON format.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetPermission service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetPermission service method, as returned by RAM.</returns>
/// <exception cref="Amazon.RAM.Model.InvalidParameterException">
/// A parameter is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.MalformedArnException">
/// The format of an Amazon Resource Name (ARN) is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.OperationNotPermittedException">
/// The requested operation is not permitted.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServerInternalException">
/// The service could not respond to the request due to an internal problem.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServiceUnavailableException">
/// The service is not available.
/// </exception>
/// <exception cref="Amazon.RAM.Model.UnknownResourceException">
/// A specified resource was not found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/GetPermission">REST API Reference for GetPermission Operation</seealso>
Task<GetPermissionResponse> GetPermissionAsync(GetPermissionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetResourcePolicies
/// <summary>
/// Gets the policies for the specified resources that you own and have shared.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetResourcePolicies service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetResourcePolicies service method, as returned by RAM.</returns>
/// <exception cref="Amazon.RAM.Model.InvalidNextTokenException">
/// The specified value for NextToken is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidParameterException">
/// A parameter is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.MalformedArnException">
/// The format of an Amazon Resource Name (ARN) is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ResourceArnNotFoundException">
/// An Amazon Resource Name (ARN) was not found.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServerInternalException">
/// The service could not respond to the request due to an internal problem.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServiceUnavailableException">
/// The service is not available.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/GetResourcePolicies">REST API Reference for GetResourcePolicies Operation</seealso>
Task<GetResourcePoliciesResponse> GetResourcePoliciesAsync(GetResourcePoliciesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetResourceShareAssociations
/// <summary>
/// Gets the resources or principals for the resource shares that you own.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetResourceShareAssociations service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetResourceShareAssociations service method, as returned by RAM.</returns>
/// <exception cref="Amazon.RAM.Model.InvalidNextTokenException">
/// The specified value for NextToken is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidParameterException">
/// A parameter is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.MalformedArnException">
/// The format of an Amazon Resource Name (ARN) is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.OperationNotPermittedException">
/// The requested operation is not permitted.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServerInternalException">
/// The service could not respond to the request due to an internal problem.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServiceUnavailableException">
/// The service is not available.
/// </exception>
/// <exception cref="Amazon.RAM.Model.UnknownResourceException">
/// A specified resource was not found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/GetResourceShareAssociations">REST API Reference for GetResourceShareAssociations Operation</seealso>
Task<GetResourceShareAssociationsResponse> GetResourceShareAssociationsAsync(GetResourceShareAssociationsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetResourceShareInvitations
/// <summary>
/// Gets the invitations for resource sharing that you've received.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetResourceShareInvitations service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetResourceShareInvitations service method, as returned by RAM.</returns>
/// <exception cref="Amazon.RAM.Model.InvalidMaxResultsException">
/// The specified value for MaxResults is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidNextTokenException">
/// The specified value for NextToken is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidParameterException">
/// A parameter is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.MalformedArnException">
/// The format of an Amazon Resource Name (ARN) is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ResourceShareInvitationArnNotFoundException">
/// The Amazon Resource Name (ARN) for an invitation was not found.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServerInternalException">
/// The service could not respond to the request due to an internal problem.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServiceUnavailableException">
/// The service is not available.
/// </exception>
/// <exception cref="Amazon.RAM.Model.UnknownResourceException">
/// A specified resource was not found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/GetResourceShareInvitations">REST API Reference for GetResourceShareInvitations Operation</seealso>
Task<GetResourceShareInvitationsResponse> GetResourceShareInvitationsAsync(GetResourceShareInvitationsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetResourceShares
/// <summary>
/// Gets the resource shares that you own or the resource shares that are shared with
/// you.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetResourceShares service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetResourceShares service method, as returned by RAM.</returns>
/// <exception cref="Amazon.RAM.Model.InvalidNextTokenException">
/// The specified value for NextToken is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidParameterException">
/// A parameter is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.MalformedArnException">
/// The format of an Amazon Resource Name (ARN) is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServerInternalException">
/// The service could not respond to the request due to an internal problem.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServiceUnavailableException">
/// The service is not available.
/// </exception>
/// <exception cref="Amazon.RAM.Model.UnknownResourceException">
/// A specified resource was not found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/GetResourceShares">REST API Reference for GetResourceShares Operation</seealso>
Task<GetResourceSharesResponse> GetResourceSharesAsync(GetResourceSharesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListPendingInvitationResources
/// <summary>
/// Lists the resources in a resource share that is shared with you but that the invitation
/// is still pending for.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListPendingInvitationResources service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListPendingInvitationResources service method, as returned by RAM.</returns>
/// <exception cref="Amazon.RAM.Model.InvalidNextTokenException">
/// The specified value for NextToken is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidParameterException">
/// A parameter is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.MalformedArnException">
/// The format of an Amazon Resource Name (ARN) is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.MissingRequiredParameterException">
/// A required input parameter is missing.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ResourceShareInvitationAlreadyRejectedException">
/// The invitation was already rejected.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ResourceShareInvitationArnNotFoundException">
/// The Amazon Resource Name (ARN) for an invitation was not found.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ResourceShareInvitationExpiredException">
/// The invitation is expired.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServerInternalException">
/// The service could not respond to the request due to an internal problem.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServiceUnavailableException">
/// The service is not available.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/ListPendingInvitationResources">REST API Reference for ListPendingInvitationResources Operation</seealso>
Task<ListPendingInvitationResourcesResponse> ListPendingInvitationResourcesAsync(ListPendingInvitationResourcesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListPermissions
/// <summary>
/// Lists the AWS RAM permissions.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListPermissions service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListPermissions service method, as returned by RAM.</returns>
/// <exception cref="Amazon.RAM.Model.InvalidNextTokenException">
/// The specified value for NextToken is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidParameterException">
/// A parameter is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.OperationNotPermittedException">
/// The requested operation is not permitted.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServerInternalException">
/// The service could not respond to the request due to an internal problem.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServiceUnavailableException">
/// The service is not available.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/ListPermissions">REST API Reference for ListPermissions Operation</seealso>
Task<ListPermissionsResponse> ListPermissionsAsync(ListPermissionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListPrincipals
/// <summary>
/// Lists the principals that you have shared resources with or that have shared resources
/// with you.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListPrincipals service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListPrincipals service method, as returned by RAM.</returns>
/// <exception cref="Amazon.RAM.Model.InvalidNextTokenException">
/// The specified value for NextToken is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidParameterException">
/// A parameter is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.MalformedArnException">
/// The format of an Amazon Resource Name (ARN) is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServerInternalException">
/// The service could not respond to the request due to an internal problem.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServiceUnavailableException">
/// The service is not available.
/// </exception>
/// <exception cref="Amazon.RAM.Model.UnknownResourceException">
/// A specified resource was not found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/ListPrincipals">REST API Reference for ListPrincipals Operation</seealso>
Task<ListPrincipalsResponse> ListPrincipalsAsync(ListPrincipalsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListResources
/// <summary>
/// Lists the resources that you added to a resource shares or the resources that are
/// shared with you.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListResources service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListResources service method, as returned by RAM.</returns>
/// <exception cref="Amazon.RAM.Model.InvalidNextTokenException">
/// The specified value for NextToken is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidParameterException">
/// A parameter is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidResourceTypeException">
/// The specified resource type is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.MalformedArnException">
/// The format of an Amazon Resource Name (ARN) is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServerInternalException">
/// The service could not respond to the request due to an internal problem.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServiceUnavailableException">
/// The service is not available.
/// </exception>
/// <exception cref="Amazon.RAM.Model.UnknownResourceException">
/// A specified resource was not found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/ListResources">REST API Reference for ListResources Operation</seealso>
Task<ListResourcesResponse> ListResourcesAsync(ListResourcesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListResourceSharePermissions
/// <summary>
/// Lists the AWS RAM permissions that are associated with a resource share.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListResourceSharePermissions service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListResourceSharePermissions service method, as returned by RAM.</returns>
/// <exception cref="Amazon.RAM.Model.InvalidNextTokenException">
/// The specified value for NextToken is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidParameterException">
/// A parameter is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.MalformedArnException">
/// The format of an Amazon Resource Name (ARN) is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.OperationNotPermittedException">
/// The requested operation is not permitted.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServerInternalException">
/// The service could not respond to the request due to an internal problem.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServiceUnavailableException">
/// The service is not available.
/// </exception>
/// <exception cref="Amazon.RAM.Model.UnknownResourceException">
/// A specified resource was not found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/ListResourceSharePermissions">REST API Reference for ListResourceSharePermissions Operation</seealso>
Task<ListResourceSharePermissionsResponse> ListResourceSharePermissionsAsync(ListResourceSharePermissionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListResourceTypes
/// <summary>
/// Lists the shareable resource types supported by AWS RAM.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListResourceTypes service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListResourceTypes service method, as returned by RAM.</returns>
/// <exception cref="Amazon.RAM.Model.InvalidNextTokenException">
/// The specified value for NextToken is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidParameterException">
/// A parameter is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServerInternalException">
/// The service could not respond to the request due to an internal problem.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServiceUnavailableException">
/// The service is not available.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/ListResourceTypes">REST API Reference for ListResourceTypes Operation</seealso>
Task<ListResourceTypesResponse> ListResourceTypesAsync(ListResourceTypesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region PromoteResourceShareCreatedFromPolicy
/// <summary>
/// Resource shares that were created by attaching a policy to a resource are visible
/// only to the resource share owner, and the resource share cannot be modified in AWS
/// RAM.
///
///
/// <para>
/// Use this API action to promote the resource share. When you promote the resource share,
/// it becomes:
/// </para>
/// <ul> <li>
/// <para>
/// Visible to all principals that it is shared with.
/// </para>
/// </li> <li>
/// <para>
/// Modifiable in AWS RAM.
/// </para>
/// </li> </ul>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PromoteResourceShareCreatedFromPolicy service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the PromoteResourceShareCreatedFromPolicy service method, as returned by RAM.</returns>
/// <exception cref="Amazon.RAM.Model.InvalidParameterException">
/// A parameter is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.MalformedArnException">
/// The format of an Amazon Resource Name (ARN) is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.MissingRequiredParameterException">
/// A required input parameter is missing.
/// </exception>
/// <exception cref="Amazon.RAM.Model.OperationNotPermittedException">
/// The requested operation is not permitted.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServerInternalException">
/// The service could not respond to the request due to an internal problem.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServiceUnavailableException">
/// The service is not available.
/// </exception>
/// <exception cref="Amazon.RAM.Model.UnknownResourceException">
/// A specified resource was not found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/PromoteResourceShareCreatedFromPolicy">REST API Reference for PromoteResourceShareCreatedFromPolicy Operation</seealso>
Task<PromoteResourceShareCreatedFromPolicyResponse> PromoteResourceShareCreatedFromPolicyAsync(PromoteResourceShareCreatedFromPolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region RejectResourceShareInvitation
/// <summary>
/// Rejects an invitation to a resource share from another AWS account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RejectResourceShareInvitation service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the RejectResourceShareInvitation service method, as returned by RAM.</returns>
/// <exception cref="Amazon.RAM.Model.IdempotentParameterMismatchException">
/// A client token input parameter was reused with an operation, but at least one of the
/// other input parameters is different from the previous call to the operation.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidClientTokenException">
/// A client token is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.MalformedArnException">
/// The format of an Amazon Resource Name (ARN) is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.OperationNotPermittedException">
/// The requested operation is not permitted.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ResourceShareInvitationAlreadyAcceptedException">
/// The invitation was already accepted.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ResourceShareInvitationAlreadyRejectedException">
/// The invitation was already rejected.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ResourceShareInvitationArnNotFoundException">
/// The Amazon Resource Name (ARN) for an invitation was not found.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ResourceShareInvitationExpiredException">
/// The invitation is expired.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServerInternalException">
/// The service could not respond to the request due to an internal problem.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServiceUnavailableException">
/// The service is not available.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/RejectResourceShareInvitation">REST API Reference for RejectResourceShareInvitation Operation</seealso>
Task<RejectResourceShareInvitationResponse> RejectResourceShareInvitationAsync(RejectResourceShareInvitationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region TagResource
/// <summary>
/// Adds the specified tags to the specified resource share that you own.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the TagResource service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the TagResource service method, as returned by RAM.</returns>
/// <exception cref="Amazon.RAM.Model.InvalidParameterException">
/// A parameter is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.MalformedArnException">
/// The format of an Amazon Resource Name (ARN) is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ResourceArnNotFoundException">
/// An Amazon Resource Name (ARN) was not found.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServerInternalException">
/// The service could not respond to the request due to an internal problem.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServiceUnavailableException">
/// The service is not available.
/// </exception>
/// <exception cref="Amazon.RAM.Model.TagLimitExceededException">
/// The requested tags exceed the limit for your account.
/// </exception>
/// <exception cref="Amazon.RAM.Model.TagPolicyViolationException">
/// The specified tag is a reserved word and cannot be used.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/TagResource">REST API Reference for TagResource Operation</seealso>
Task<TagResourceResponse> TagResourceAsync(TagResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region UntagResource
/// <summary>
/// Removes the specified tags from the specified resource share that you own.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UntagResource service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the UntagResource service method, as returned by RAM.</returns>
/// <exception cref="Amazon.RAM.Model.InvalidParameterException">
/// A parameter is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServerInternalException">
/// The service could not respond to the request due to an internal problem.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServiceUnavailableException">
/// The service is not available.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/UntagResource">REST API Reference for UntagResource Operation</seealso>
Task<UntagResourceResponse> UntagResourceAsync(UntagResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region UpdateResourceShare
/// <summary>
/// Updates the specified resource share that you own.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateResourceShare service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the UpdateResourceShare service method, as returned by RAM.</returns>
/// <exception cref="Amazon.RAM.Model.IdempotentParameterMismatchException">
/// A client token input parameter was reused with an operation, but at least one of the
/// other input parameters is different from the previous call to the operation.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidClientTokenException">
/// A client token is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.InvalidParameterException">
/// A parameter is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.MalformedArnException">
/// The format of an Amazon Resource Name (ARN) is not valid.
/// </exception>
/// <exception cref="Amazon.RAM.Model.MissingRequiredParameterException">
/// A required input parameter is missing.
/// </exception>
/// <exception cref="Amazon.RAM.Model.OperationNotPermittedException">
/// The requested operation is not permitted.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServerInternalException">
/// The service could not respond to the request due to an internal problem.
/// </exception>
/// <exception cref="Amazon.RAM.Model.ServiceUnavailableException">
/// The service is not available.
/// </exception>
/// <exception cref="Amazon.RAM.Model.UnknownResourceException">
/// A specified resource was not found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/UpdateResourceShare">REST API Reference for UpdateResourceShare Operation</seealso>
Task<UpdateResourceShareResponse> UpdateResourceShareAsync(UpdateResourceShareRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
}
} | 53.314477 | 240 | 0.658766 | [
"Apache-2.0"
] | NGL321/aws-sdk-net | sdk/src/Services/RAM/Generated/_mobile/IAmazonRAM.cs | 55,607 | C# |
using NUnit.Framework;
namespace Whois
{
[TestFixture]
public class EmbeddedPatternReaderTest
{
private EmbeddedPatternReader reader;
[SetUp]
public void SetUp()
{
reader = new EmbeddedPatternReader();
}
[Test]
public void TestListAllPatternsInAssembly()
{
var patterns = reader.GetResourceNames(GetType().Assembly, "Whois.Patterns");
Assert.AreEqual(2, patterns.Count);
Assert.AreEqual("Whois.Patterns.TestPatternOne.txt", patterns[0]);
Assert.AreEqual("Whois.Patterns.TestPatternTwo.txt", patterns[1]);
}
[Test]
public void TestListAllWhoisPatterns()
{
var patterns = reader.GetResourceNames();
Assert.Less(0, patterns.Count);
}
[Test]
public void TestReadEmbeddedResource()
{
var result = reader.Read(GetType().Assembly, "Whois.Patterns.TestPatternOne.txt");
Assert.AreEqual("Test Pattern One", result);
}
[Test]
public void TestReadEmbeddedResources()
{
var result = reader.ReadNamespace(GetType().Assembly, "Whois.Patterns");
Assert.AreEqual(2, result.Count);
Assert.AreEqual("Test Pattern One", result[0]);
Assert.AreEqual("Test Pattern Two", result[1]);
}
}
}
| 26.754717 | 94 | 0.5811 | [
"MIT"
] | txdv/whois | Whois.Tests/EmbeddedPatternReaderTest.cs | 1,420 | C# |
#region license
// The MIT License (MIT)
// AssemblyInfo.cs
// Copyright (c) 2016 Alexander Lüdemann
// alexander.luedemann@outlook.com
// luedeman@rhrk.uni-kl.de
// Computational Systems Biology, Technical University of Kaiserslautern, Germany
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System.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("MzLite.SQL")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MzLite.SQL")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8a1e7fa2-42ed-424c-a3f3-2ca68bbd1fa8")]
// 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.1.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 40.61194 | 84 | 0.757075 | [
"MIT"
] | CSBiology/MzLite | src/MzLite.SQL/Properties/AssemblyInfo.cs | 2,725 | 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.Collections.Generic;
using System.Reflection;
using Xunit;
namespace Microsoft.EntityFrameworkCore.Tools
{
public class ExeTest
{
[Fact]
public void ToArguments_works()
{
var result = ToArguments(
new[]
{
"Good",
"Good\\",
"Needs quotes",
"Needs escaping\\",
"Needs escaping\\\\",
"Needs \"escaping\"",
"Needs \\\"escaping\"",
"Needs escaping\\\\too"
});
Assert.Equal(
"Good "
+ "Good\\ "
+ "\"Needs quotes\" "
+ "\"Needs escaping\\\\\" "
+ "\"Needs escaping\\\\\\\\\" "
+ "\"Needs \\\"escaping\\\"\" "
+ "\"Needs \\\\\\\"escaping\\\"\" "
+ "\"Needs escaping\\\\\\\\too\"",
result);
}
private static string ToArguments(IReadOnlyList<string> args)
=> (string)typeof(Exe).GetTypeInfo().GetMethod("ToArguments", BindingFlags.Static | BindingFlags.NonPublic)
.Invoke(null, new object[] { args });
}
}
| 31.955556 | 119 | 0.454798 | [
"Apache-2.0"
] | StanleyGoldman/EntityFrameworkCore | test/dotnet-ef.Tests/ExeTest.cs | 1,440 | C# |
using System;
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: ComVisible(false)]
[assembly: CLSCompliant(true)]
[assembly: AssemblyTitle("ChunkingChannel")]
[assembly: AssemblyDescription("ChunkingChannel")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyProduct("Windows Communication Foundation and Windows Workflow Foundation SDK")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("4.0.0.0")]
[assembly: AssemblyFileVersion("4.0.0.0")]
| 41.478261 | 99 | 0.781971 | [
"Apache-2.0"
] | jdm7dv/visual-studio | Samples/NET 4.6/WF_WCF_Samples/WCF/Extensibility/Channels/ChunkingChannel/CS/ChunkingChannel/Properties/AssemblyInfo.cs | 956 | C# |
using ForgedOnce.TsLanguageServices.FullSyntaxTree.TransportModel;
using System;
using System.Collections.Generic;
using System.Text;
namespace ForgedOnce.TsLanguageServices.Host.Commands
{
public class ParseCommand : Command
{
public ParseCommand()
{
this.CommandType = CommandType.Parse;
}
public string Payload { get; set; }
public ScriptKind ScriptKind { get; set; }
}
}
| 23.1 | 68 | 0.651515 | [
"MIT"
] | YevgenNabokov/ForgedOnce.TSLanguageServices | ForgedOnce.TsLanguageServices.Host/Commands/ParseCommand.cs | 464 | C# |
namespace Lab9
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.textBox1 = new System.Windows.Forms.TextBox();
this.textBox2 = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.FilesNames = new System.Windows.Forms.ListBox();
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(130, 6);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(275, 20);
this.textBox1.TabIndex = 0;
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(129, 41);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(276, 20);
this.textBox2.TabIndex = 1;
this.textBox2.Text = "Size Greater Than";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(13, 13);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(35, 13);
this.label1.TabIndex = 2;
this.label1.Text = "Path :";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(12, 48);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(86, 13);
this.label2.TabIndex = 3;
this.label2.Text = "(bytes) File Size :";
//
// FilesNames
//
this.FilesNames.FormattingEnabled = true;
this.FilesNames.Location = new System.Drawing.Point(12, 115);
this.FilesNames.Name = "FilesNames";
this.FilesNames.Size = new System.Drawing.Size(393, 329);
this.FilesNames.TabIndex = 4;
//
// button1
//
this.button1.Location = new System.Drawing.Point(330, 86);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 5;
this.button1.Text = "Search";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(421, 450);
this.Controls.Add(this.button1);
this.Controls.Add(this.FilesNames);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.textBox2);
this.Controls.Add(this.textBox1);
this.Name = "Form1";
this.Text = "Search";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ListBox FilesNames;
private System.Windows.Forms.Button button1;
}
}
| 37.672269 | 107 | 0.546286 | [
"MIT"
] | HeshamFawzy/Search-by-File-Size | Lab9/Form1.Designer.cs | 4,485 | C# |
/*
* SCORM Cloud Rest API
*
* REST API used for SCORM Cloud integrations.
*
* OpenAPI spec version: 2.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Reflection;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
namespace Com.RusticiSoftware.Cloud.V2.Client
{
/// <summary>
/// <see cref="GlobalConfiguration"/> provides a compile-time extension point for globally configuring
/// API Clients.
/// </summary>
/// <remarks>
/// A customized implementation via partial class may reside in another file and may
/// be excluded from automatic generation via a .swagger-codegen-ignore file.
/// </remarks>
public partial class GlobalConfiguration : Configuration
{
}
} | 24.617647 | 106 | 0.702509 | [
"Apache-2.0"
] | RusticiSoftware/scormcloud-api-v2-client-net | src/Com.RusticiSoftware.Cloud.V2/Client/GlobalConfiguration.cs | 837 | C# |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.PythonTools.Analysis.Values;
using Microsoft.PythonTools.Interpreter;
namespace Microsoft.PythonTools.Analysis {
/// <summary>
/// Maintains the list of modules loaded into the PythonAnalyzer.
///
/// This keeps track of the builtin modules as well as the user defined modules. It's wraps
/// up various elements we need to keep track of such as thread safety and lazy loading of built-in
/// modules.
/// </summary>
class ModuleTable : IEnumerable<KeyValuePair<string, ModuleLoadState>> {
private readonly IPythonInterpreter _interpreter;
private readonly PythonAnalyzer _analyzer;
private readonly ConcurrentDictionary<IPythonModule, BuiltinModule> _builtinModuleTable = new ConcurrentDictionary<IPythonModule, BuiltinModule>();
private readonly ConcurrentDictionary<string, ModuleReference> _modules = new ConcurrentDictionary<string, ModuleReference>(StringComparer.Ordinal);
public ModuleTable(PythonAnalyzer analyzer, IPythonInterpreter interpreter) {
_analyzer = analyzer;
_interpreter = interpreter;
}
public bool Contains(string name) {
return _modules.ContainsKey(name);
}
/// <summary>
/// Gets a reference to a module that has already been imported. You
/// probably want to use <see cref="TryImport"/>.
/// </summary>
/// <returns>
/// True if an attempt to import the module was made during the analysis
/// that used this module table. The reference may be null, or the
/// module within the reference may be null, even if this function
/// returns true.
/// </returns>
/// <remarks>
/// This exists for inspecting the results of an analysis (for example,
/// <see cref="SaveAnalysis"/>). To get access to a module while
/// analyzing code, even (especially!) if the module may not exist,
/// you should call <see cref="TryImport"/>.
/// </remarks>
internal bool TryGetImportedModule(string name, out ModuleReference res) {
return _modules.TryGetValue(name, out res);
}
/// <summary>
/// Gets a reference to a module.
/// </summary>
/// <param name="name">The full import name of the module.</param>
/// <param name="res">The module reference object.</param>
/// <returns>
/// True if the module is available. This means that <c>res.Module</c>
/// is not null. If this function returns false, <paramref name="res"/>
/// may be valid and should not be replaced, but it is an unresolved
/// reference.
/// </returns>
public async Task<ModuleReference> TryImportAsync(string name) {
ModuleReference res;
bool firstImport = false;
if (!_modules.TryGetValue(name, out res) || res == null) {
var mod = await Task.Run(() => _interpreter.ImportModule(name));
_modules[name] = res = new ModuleReference(GetBuiltinModule(mod));
firstImport = true;
}
if (res != null && res.Module == null) {
var mod = await Task.Run(() => _interpreter.ImportModule(name));
res.Module = GetBuiltinModule(mod);
}
if (firstImport && res != null && res.Module != null) {
await Task.Run(() => _analyzer.DoDelayedSpecialization(name));
}
if (res != null && res.Module == null) {
return null;
}
return res;
}
/// <summary>
/// Gets a reference to a module.
/// </summary>
/// <param name="name">The full import name of the module.</param>
/// <param name="res">The module reference object.</param>
/// <returns>
/// True if the module is available. This means that <c>res.Module</c>
/// is not null. If this function returns false, <paramref name="res"/>
/// may be valid and should not be replaced, but it is an unresolved
/// reference.
/// </returns>
public bool TryImport(string name, out ModuleReference res) {
bool firstImport = false;
if (!_modules.TryGetValue(name, out res) || res == null) {
_modules[name] = res = new ModuleReference(GetBuiltinModule(_interpreter.ImportModule(name)));
firstImport = true;
}
if (res != null && res.Module == null) {
res.Module = GetBuiltinModule(_interpreter.ImportModule(name));
}
if (firstImport && res != null && res.Module != null) {
_analyzer.DoDelayedSpecialization(name);
}
return res != null && res.Module != null;
}
public bool TryRemove(string name, out ModuleReference res) {
return _modules.TryRemove(name, out res);
}
public ModuleReference this[string name] {
get {
ModuleReference res;
if (!TryImport(name, out res)) {
throw new KeyNotFoundException(name);
}
return res;
}
set {
_modules[name] = value;
}
}
public ModuleReference GetOrAdd(string name) {
return _modules.GetOrAdd(name, _ => new ModuleReference());
}
/// <summary>
/// Reloads the modules when the interpreter says they've changed.
/// Modules that are already in the table as builtins are replaced or
/// removed, but no new modules are added.
/// </summary>
public void ReInit() {
var newNames = new HashSet<string>(_interpreter.GetModuleNames(), StringComparer.Ordinal);
foreach (var keyValue in _modules) {
var name = keyValue.Key;
var moduleRef = keyValue.Value;
var builtinModule = moduleRef.Module as BuiltinModule;
if (builtinModule != null) {
if (!newNames.Contains(name)) {
// this module was unloaded
ModuleReference dummy;
_modules.TryRemove(name, out dummy);
BuiltinModule removedModule;
_builtinModuleTable.TryRemove(builtinModule.InterpreterModule, out removedModule);
foreach (var child in builtinModule.InterpreterModule.GetChildrenModules()) {
_modules.TryRemove(builtinModule.Name + "." + child, out dummy);
}
} else {
// this module was replaced with a new module
var newModule = _interpreter.ImportModule(name);
if (builtinModule.InterpreterModule != newModule) {
BuiltinModule removedModule;
_builtinModuleTable.TryRemove(builtinModule.InterpreterModule, out removedModule);
moduleRef.Module = GetBuiltinModule(newModule);
ImportChildren(newModule);
}
}
}
}
}
internal BuiltinModule GetBuiltinModule(IPythonModule attr) {
if (attr == null) {
return null;
}
BuiltinModule res;
if (!_builtinModuleTable.TryGetValue(attr, out res)) {
_builtinModuleTable[attr] = res = new BuiltinModule(attr, _analyzer);
}
return res;
}
internal void ImportChildren(IPythonModule interpreterModule) {
BuiltinModule module = null;
foreach (var child in interpreterModule.GetChildrenModules()) {
module = module ?? GetBuiltinModule(interpreterModule);
ModuleReference modRef;
var fullname = module.Name + "." + child;
if (!_modules.TryGetValue(fullname, out modRef) || modRef == null || modRef.Module == null) {
IAnalysisSet value;
if (module.TryGetMember(child, out value)) {
var mod = value as IModule;
if (mod != null) {
_modules[fullname] = new ModuleReference(mod);
}
}
}
}
}
#region IEnumerable<KeyValuePair<string,ModuleReference>> Members
public IEnumerator<KeyValuePair<string, ModuleLoadState>> GetEnumerator() {
var unloadedNames = new HashSet<string>(_interpreter.GetModuleNames(), StringComparer.Ordinal);
var unresolvedNames = _analyzer.GetAllUnresolvedModuleNames();
foreach (var keyValue in _modules) {
unloadedNames.Remove(keyValue.Key);
unresolvedNames.Remove(keyValue.Key);
yield return new KeyValuePair<string, ModuleLoadState>(keyValue.Key, new InitializedModuleLoadState(keyValue.Value));
}
foreach (var name in unloadedNames) {
yield return new KeyValuePair<string, ModuleLoadState>(name, new UninitializedModuleLoadState(this, name));
}
foreach (var name in unresolvedNames) {
yield return new KeyValuePair<string, ModuleLoadState>(name, new UnresolvedModuleLoadState());
}
}
class UnresolvedModuleLoadState : ModuleLoadState {
public override AnalysisValue Module {
get { return null; }
}
public override bool HasModule {
get { return false; }
}
public override bool HasReferences {
get { return false; }
}
public override bool IsValid {
get { return true; }
}
public override PythonMemberType MemberType {
get { return PythonMemberType.Unknown; }
}
internal override bool ModuleContainsMember(IModuleContext context, string name) {
return false;
}
}
class UninitializedModuleLoadState : ModuleLoadState {
private readonly ModuleTable _moduleTable;
private readonly string _name;
private PythonMemberType? _type;
public UninitializedModuleLoadState(ModuleTable moduleTable, string name) {
this._moduleTable = moduleTable;
this._name = name;
}
public override AnalysisValue Module {
get {
ModuleReference res;
if (_moduleTable.TryImport(_name, out res)) {
return res.AnalysisModule;
}
return null;
}
}
public override bool IsValid {
get {
return true;
}
}
public override bool HasReferences {
get {
return false;
}
}
public override bool HasModule {
get {
return true;
}
}
public override PythonMemberType MemberType {
get {
if (_type == null) {
var mod = _moduleTable._interpreter.ImportModule(_name);
if (mod != null) {
_type = mod.MemberType;
} else {
_type = PythonMemberType.Module;
}
}
return _type.Value;
}
}
internal override bool ModuleContainsMember(IModuleContext context, string name) {
var mod = _moduleTable._interpreter.ImportModule(_name);
if (mod != null) {
return BuiltinModuleContainsMember(context, name, mod);
}
return false;
}
}
class InitializedModuleLoadState : ModuleLoadState {
private readonly ModuleReference _reference;
public InitializedModuleLoadState(ModuleReference reference) {
_reference = reference;
}
public override AnalysisValue Module {
get {
return _reference.AnalysisModule;
}
}
public override bool HasReferences {
get {
return _reference.HasReferences;
}
}
public override bool IsValid {
get {
return Module != null || HasReferences;
}
}
public override bool HasModule {
get {
return Module != null;
}
}
public override PythonMemberType MemberType {
get {
if (Module != null) {
return Module.MemberType;
}
return PythonMemberType.Module;
}
}
internal override bool ModuleContainsMember(IModuleContext context, string name) {
BuiltinModule builtin = Module as BuiltinModule;
if (builtin != null) {
return BuiltinModuleContainsMember(context, name, builtin.InterpreterModule);
}
ModuleInfo modInfo = Module as ModuleInfo;
if (modInfo != null) {
VariableDef varDef;
if (modInfo.Scope.Variables.TryGetValue(name, out varDef) &&
varDef.VariableStillExists) {
var types = varDef.TypesNoCopy;
if (types.Count > 0) {
foreach (var type in types) {
if (type is ModuleInfo || type is BuiltinModule) {
// we find modules via our modules list, dont duplicate these
return false;
}
foreach (var location in type.Locations) {
if (location.ProjectEntry != modInfo.ProjectEntry) {
// declared in another module
return false;
}
}
}
}
return true;
}
}
return false;
}
}
private static bool BuiltinModuleContainsMember(IModuleContext context, string name, IPythonModule interpModule) {
var mem = interpModule.GetMember(context, name);
if (mem != null) {
if (IsExcludedBuiltin(interpModule, mem)) {
// if a module imports a builtin and exposes it don't report it for purposes of adding imports
return false;
}
IPythonMultipleMembers multiMem = mem as IPythonMultipleMembers;
if (multiMem != null) {
foreach (var innerMem in multiMem.Members) {
if (IsExcludedBuiltin(interpModule, innerMem)) {
// if something non-excludable aliased w/ something excluable we probably
// only care about the excluable (for example a module and None - timeit.py
// does this in the std lib)
return false;
}
}
}
return true;
}
return false;
}
private static bool IsExcludedBuiltin(IPythonModule builtin, IMember mem) {
IPythonFunction func;
IPythonType type;
IPythonConstant constant;
if (mem is IPythonModule || // modules are handled specially
((func = mem as IPythonFunction) != null && func.DeclaringModule != builtin) || // function imported into another module
((type = mem as IPythonType) != null && type.DeclaringModule != builtin) || // type imported into another module
((constant = mem as IPythonConstant) != null && constant.Type.TypeId == BuiltinTypeId.Object)) { // constant which we have no real type info for.
return true;
}
if (constant != null) {
if (constant.Type.DeclaringModule.Name == "__future__" &&
constant.Type.Name == "_Feature" &&
builtin.Name != "__future__") {
// someone has done a from __future__ import blah, don't include import in another
// module in the list of places where you can import this from.
return true;
}
}
return false;
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
return GetEnumerator();
}
#endregion
}
abstract class ModuleLoadState {
public abstract AnalysisValue Module {
get;
}
public abstract bool HasModule {
get;
}
public abstract bool HasReferences {
get;
}
public abstract bool IsValid {
get;
}
public abstract PythonMemberType MemberType {
get;
}
internal abstract bool ModuleContainsMember(IModuleContext context, string name);
}
}
| 40.573805 | 165 | 0.510402 | [
"Apache-2.0"
] | nanshuiyu/pytools | Python/Product/Analysis/ModuleTable.cs | 19,518 | C# |
using UnityEngine;
using ParadoxNotion.Design;
using NodeCanvas.Framework;
using NodeCanvas.DialogueTrees;
namespace NodeCanvas.Tasks.Actions{
[Category("Dialogue")]
[AgentType(typeof(IDialogueActor))]
[Description("Starts a Dialogue Tree with specified agent for 'Instigator'\nPlease Drag & Drop the DialogueTree Component rather than the GameObject for assignement")]
[Icon("Dialogue")]
public class StartDialogueTree : ActionTask {
[RequiredField]
public BBParameter<DialogueTree> dialogueTree;
public bool waitActionFinish = true;
protected override string info{
get {return string.Format("Start Dialogue {0}", dialogueTree.ToString());}
}
protected override void OnExecute(){
var actor = (IDialogueActor)agent;
if (waitActionFinish){
dialogueTree.value.StartDialogue(actor, (success)=> {EndAction(success);} );
} else {
dialogueTree.value.StartDialogue(actor);
EndAction();
}
}
}
} | 28.575758 | 168 | 0.744433 | [
"MIT"
] | CereVenteo/Fuck-the-Police | FuckThePolice/Assets/ParadoxNotion/NodeCanvas/Tasks/Actions/Dialogue/StartDialogueTree.cs | 945 | C# |
//
// Copyright (c) Microsoft. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
namespace Microsoft.Azure.Commands.Network.Models
{
using Newtonsoft.Json;
public class PSPeeringStats
{
[JsonProperty(Order = 1)]
public int BytesIn { get; set; }
[JsonProperty(Order = 1)]
public int BytesOut { get; set; }
}
}
| 31.62069 | 76 | 0.677208 | [
"MIT"
] | Andrean/azure-powershell | src/StackAdmin/Network/Commands.Network/Models/PSPeeringStats.cs | 891 | C# |
/*
ChessLib, a chess data structure library
MIT License
Copyright (c) 2017-2020 Rudy Alex Kohn
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using BenchmarkDotNet.Running;
namespace Chess.Benchmark
{
/*
// * Summary *
BenchmarkDotNet=v0.11.3, OS=Windows 10.0.17763.379 (1809/October2018Update/Redstone5)
Intel Core i7-8086K CPU 4.00GHz (Coffee Lake), 1 CPU, 12 logical and 6 physical cores
.NET Core SDK=2.2.101
[Host] : .NET Core 2.2.0 (CoreCLR 4.6.27110.04, CoreFX 4.6.27110.04), 64bit RyuJIT [AttachedDebugger]
DefaultJob : .NET Core 2.2.0 (CoreCLR 4.6.27110.04, CoreFX 4.6.27110.04), 64bit RyuJIT
Method N Mean Error StdDev
Result 1 296.4 us 1.496 us 1.326 us
Result 2 300.2 us 1.678 us 1.570 us
Result 3 379.0 us 1.897 us 1.584 us
Result 4 2,408.1 us 12.816 us 11.988 us
Result 5 64,921.2 us 1,310.703 us 1,402.437 us
Result 6 1,912,300.6 us 3,551.167 us 3,148.017 us
Method | Job | Runtime | N | Mean | Error | StdDev | Ratio | RatioSD |
Result | Core | Core | 1 | 285.1 us | 1.088 us | 1.017 us | ? | ? |
Result | Core | Core | 2 | 292.6 us | 2.725 us | 2.549 us | ? | ? |
Result | Core | Core | 3 | 329.5 us | 1.161 us | 1.029 us | ? | ? |
Result | Core | Core | 4 | 1,762.3 us | 10.213 us | 9.053 us | ? | ? |
Result | Core | Core | 5 | 50,636.9 us | 998.394 us | 1,262.649 us | ? | ? |
Result | Core | Core | 6 | 1,537,741.3 us | 11,692.917 us | 10,365.466 us | ? | ? |
Method | N | Mean | Error | StdDev |
------- |-- |----------------:|--------------:|--------------:|
Result | 1 | 98.25 us | 0.7352 us | 0.6518 us |
Result | 2 | 103.12 us | 0.3322 us | 0.2774 us |
Result | 3 | 160.12 us | 0.7573 us | 0.6713 us |
Result | 4 | 1,588.79 us | 3.5257 us | 3.2979 us |
Result | 5 | 51,304.89 us | 1,006.0687 us | 1,235.5427 us |
Result | 6 | 1,547,075.27 us | 2,673.5871 us | 2,500.8751 us |
Method | N | Mean | Error | StdDev |
------- |-- |-------------:|----------:|----------:|
Result | 4 | 1.569 ms | 0.0032 ms | 0.0030 ms |
Result | 5 | 49.873 ms | 0.6022 ms | 0.5029 ms |
Result | 6 | 1,525.450 ms | 2.8101 ms | 2.3466 ms |
Method | N | Mean | Error | StdDev |
------- |-- |-------------:|----------:|----------:|
Result | 4 | 1.426 ms | 0.0039 ms | 0.0033 ms |
Result | 5 | 48.468 ms | 0.2311 ms | 0.2048 ms |
Result | 6 | 1,487.300 ms | 2.3406 ms | 1.9545 ms |
v2: with perft cache
Method | N | Mean | Error | StdDev |
------- |-- |---------:|----------:|----------:|
Result | 4 | 58.50 us | 0.1632 us | 0.1527 us |
Result | 5 | 61.89 us | 1.1856 us | 1.4994 us |
Result | 6 | 63.71 us | 0.7055 us | 0.6599 us |
No perft cache:
Method | N | Mean | Error | StdDev |
------- |-- |-------------:|----------:|----------:|
Result | 4 | 1.561 ms | 0.0044 ms | 0.0041 ms |
Result | 5 | 50.971 ms | 0.6585 ms | 0.5837 ms |
Result | 6 | 1,545.322 ms | 2.1404 ms | 1.7873 ms |
*/
public class PerftBenchRunner
{
public static void Main(string[] args) => BenchmarkSwitcher.FromAssembly(typeof(PerftBenchRunner).Assembly).Run(args);
}
} | 43.79798 | 126 | 0.571956 | [
"MIT"
] | MattyMatMat/ChessLib | Chess.Benchmark/PerftBenchRunner.cs | 4,338 | 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.Jag.PillPressRegistry.Interfaces
{
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for Locationactivitypointers.
/// </summary>
public static partial class LocationactivitypointersExtensions
{
/// <summary>
/// Get bcgov_location_ActivityPointers from bcgov_locations
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='bcgovLocationid'>
/// key: bcgov_locationid of bcgov_location
/// </param>
/// <param name='top'>
/// </param>
/// <param name='skip'>
/// </param>
/// <param name='search'>
/// </param>
/// <param name='filter'>
/// </param>
/// <param name='count'>
/// </param>
/// <param name='orderby'>
/// Order items by property values
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
public static MicrosoftDynamicsCRMactivitypointerCollection Get(this ILocationactivitypointers operations, string bcgovLocationid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>))
{
return operations.GetAsync(bcgovLocationid, top, skip, search, filter, count, orderby, select, expand).GetAwaiter().GetResult();
}
/// <summary>
/// Get bcgov_location_ActivityPointers from bcgov_locations
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='bcgovLocationid'>
/// key: bcgov_locationid of bcgov_location
/// </param>
/// <param name='top'>
/// </param>
/// <param name='skip'>
/// </param>
/// <param name='search'>
/// </param>
/// <param name='filter'>
/// </param>
/// <param name='count'>
/// </param>
/// <param name='orderby'>
/// Order items by property values
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<MicrosoftDynamicsCRMactivitypointerCollection> GetAsync(this ILocationactivitypointers operations, string bcgovLocationid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(bcgovLocationid, top, skip, search, filter, count, orderby, select, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get bcgov_location_ActivityPointers from bcgov_locations
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='bcgovLocationid'>
/// key: bcgov_locationid of bcgov_location
/// </param>
/// <param name='activityid'>
/// key: activityid of activitypointer
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
public static MicrosoftDynamicsCRMactivitypointer ActivityPointersByKey(this ILocationactivitypointers operations, string bcgovLocationid, string activityid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>))
{
return operations.ActivityPointersByKeyAsync(bcgovLocationid, activityid, select, expand).GetAwaiter().GetResult();
}
/// <summary>
/// Get bcgov_location_ActivityPointers from bcgov_locations
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='bcgovLocationid'>
/// key: bcgov_locationid of bcgov_location
/// </param>
/// <param name='activityid'>
/// key: activityid of activitypointer
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<MicrosoftDynamicsCRMactivitypointer> ActivityPointersByKeyAsync(this ILocationactivitypointers operations, string bcgovLocationid, string activityid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ActivityPointersByKeyWithHttpMessagesAsync(bcgovLocationid, activityid, select, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| 46.356164 | 516 | 0.560727 | [
"Apache-2.0"
] | GeorgeWalker/jag-pill-press-registry | pill-press-interfaces/Dynamics-Autorest/LocationactivitypointersExtensions.cs | 6,768 | C# |
using Newtonsoft.Json;
using DSM.FunctionClient;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
internal class DebugHook : StateMachineObserver
{
public DebugHook()
{
}
private void OnDebugEvent(IDictionary<string, object> data)
{
foreach (var key in data.Keys)
{
Console.WriteLine($"{key} = {JsonConvert.SerializeObject(data[key])}");
}
Console.WriteLine();
}
protected override Task OnEnterStateMachine(IDictionary<string, object> data)
{
OnDebugEvent(data);
return base.OnEnterStateMachine(data);
}
protected override Task OnExitStateMachine(IDictionary<string, object> data)
{
OnDebugEvent(data);
return base.OnExitStateMachine(data);
}
protected override Task OnEnterState(IDictionary<string, object> data)
{
OnDebugEvent(data);
return base.OnEnterState(data);
}
protected override Task OnExitState(IDictionary<string, object> data)
{
OnDebugEvent(data);
return base.OnExitState(data);
}
protected override Task OnMakeTransition(IDictionary<string, object> data)
{
OnDebugEvent(data);
return base.OnMakeTransition(data);
}
protected override Task OnBeforeAction(IDictionary<string, object> data)
{
OnDebugEvent(data);
return base.OnBeforeAction(data);
}
protected override Task OnAfterAction(IDictionary<string, object> data)
{
OnDebugEvent(data);
return base.OnAfterAction(data);
}
}
}
| 26.623188 | 87 | 0.593903 | [
"MIT"
] | jplane/DurableStateMachines | Samples/StronglyTypedClient/ConsoleApp1/DebugHook.cs | 1,839 | C# |
// Microsoft Research Singularity
// Copyright (c) Microsoft Corporation. All rights reserved.
// Choose a TCP port and listen for an incoming connection to the port.
// Then read from the connection, dumping the data to stdout.
// Arguments: none
// (Note: the tcp port is chosen by the underlying socket implementation,
// and printed to stderr when this program runs.)
using System;
using System.Net;
using System.Net.Sockets;
class TcpCat
{
static void Main(string[] args)
{
TcpListener listener = new TcpListener(IPAddress.Any, 0);
listener.Start();
Console.Error.WriteLine(listener.LocalEndpoint);
System.IO.Stream o = Console.OpenStandardOutput();
TcpClient c = listener.AcceptTcpClient();
NetworkStream stm = c.GetStream();
for (;;) {
int i = stm.ReadByte();
if (i == -1) break;
o.WriteByte((byte) i);
}
}
}
| 30.064516 | 73 | 0.651288 | [
"MIT"
] | pmache/singularityrdk | SOURCE/base/Windows/tcpcat/TcpCat.cs | 932 | C# |
using System;
using NUnit.Framework;
using NUnit.Framework.Internal;
using Sequence;
namespace VectorTests
{
[TestFixture]
public class VectorIntTests
{
private IVector<int> vector;
[SetUp]
public void Init()
{
this.vector = VectorFactory<int>.Create();
}
[Test]
public void TestEmpty()
{
Assert.AreEqual(0, this.vector.Size);
Assert.AreEqual(true, this.vector.Empty);
}
[Test]
public void TestInsert()
{
int[] values = new[] { 0, 4, 9, -1, int.MaxValue, int.MinValue };
InsertToVector(values);
Assert.AreEqual(6, this.vector.Size);
for(int i=0; i < values.Length; i++)
{
Assert.AreEqual(values[i], this.vector[i]);
}
this.vector.Insert(4, 8);
Assert.AreEqual(7, this.vector.Size);
Assert.AreEqual(8, this.vector[4]);
}
private void InsertToVector(params int[] args)
{
foreach (var arg in args)
{
this.vector.Insert(arg);
}
}
[Test]
public void TestFind()
{
int[] values = new[] { 0, 4, 9, -1, int.MaxValue, int.MinValue, 9 };
InsertToVector(values);
Assert.AreEqual(1, this.vector.Find(4));
Assert.AreEqual(-1, this.vector.Find(100));
Assert.AreEqual(6, this.vector.Find(9));
Assert.AreEqual(-1, this.vector.Find(int.MaxValue, 0, 3));
Assert.AreEqual(2, this.vector.Find(9, 0, 4));
}
[Test]
public void TestSearch()
{
int[] values = new[] { int.MinValue, -100, 10, 0, 99, 4901, int.MaxValue };
InsertToVector(values);
Assert.AreEqual(0, this.vector.Search(int.MinValue));
Assert.AreEqual(4, this.vector.Search(99));
Assert.AreEqual(-1, this.vector.Search(-92));
}
[Test]
public void TestRemove()
{
int[] values = new[] { 0, 4, 9, -1, int.MaxValue, int.MinValue, 9 };
InsertToVector(values);
Assert.AreEqual(7, this.vector.Size);
Assert.AreEqual(4, this.vector.Remove(1));
Assert.AreEqual(6, this.vector.Size);
Assert.AreEqual(2, this.vector.Remove(0, 2));
Assert.AreEqual(4, this.vector.Size);
}
[Test]
public void TestDisorder()
{
int[] values = new[] { 0, 4, 9, -1, int.MaxValue, int.MinValue, 9 };
InsertToVector(values);
Assert.AreEqual(9, this.vector.DisOrdered());
}
[Test]
public void TestDuplicate()
{
int[] values = new[] { 10, 9, 9, int.MaxValue, -1, 8 };
InsertToVector(values);
Assert.AreEqual(1, this.vector.Deduplicate());
Assert.AreEqual(int.MaxValue, this.vector[2]);
}
[Test]
public void TestUniquey()
{
int[] values = new[] { -10, 9, 9, 10 };
InsertToVector(values);
Assert.AreEqual(1, this.vector.Deduplicate());
Assert.AreEqual(10, this.vector[2]);
}
[Test]
public void TestCompareTo()
{
IVector<int> smaller = VectorFactory<int>.Create(new[] { 10 }, 1);
int[] values = new[] { -10, 9, 9, 10 };
InsertToVector(values);
Assert.AreEqual(1, this.vector.CompareTo(smaller));
IVector<int> equal = VectorFactory<int>.Create(new[] { 1, 2, 3, 4 }, 4);
Assert.AreEqual(0, this.vector.CompareTo(equal));
IVector<int> bigger = VectorFactory<int>.Create(new[] { 1, 2, 3, 4, 5 }, 5);
Assert.AreEqual(-1, this.vector.CompareTo(bigger));
}
[Test]
public void TestAny()
{
int[] values = new[] { 10, 9, 9, int.MaxValue, -1, 8 };
InsertToVector(values);
Assert.IsTrue(this.vector.Any(i => i % 2 == 0));
Assert.IsFalse(this.vector.Any(i => i < -5));
}
[Test]
public void TestFirstOrDefault()
{
int[] values = new[] { 10, 9, 9, int.MaxValue, -1, 6 };
InsertToVector(values);
Assert.AreEqual(9, this.vector.FirstOrDefault(i => i % 3 == 0));
Assert.AreEqual(0, this.vector.FirstOrDefault(i => i == 23));
}
[Test]
public void TestFirst()
{
int[] values = new[] { 10, 9, 9, int.MaxValue, -1, 6 };
InsertToVector(values);
Assert.AreEqual(9, this.vector.First(i => i % 3 == 0));
}
[Test]
public void TestFirstNotExist()
{
int[] values = new[] { 10, 9, 9, int.MaxValue, -1, 6 };
InsertToVector(values);
Assert.Throws<InvalidOperationException>(() => this.vector.First(i => i < -3));
}
[Test]
public void TestBinarySearch()
{
int[] values = new[] { -10, -2, 8, 9, 10, 20, int.MaxValue };
InsertToVector(values);
Assert.AreEqual(3, this.vector.Search(9));
}
}
}
| 31.813253 | 91 | 0.500852 | [
"Apache-2.0"
] | gaufung/DS | DataStructure/VectorTest/VectorIntTests.cs | 5,283 | C# |
// Copyright (c) 2012-2013 Rotorz Limited. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#if UNITY_EDITOR
using System;
namespace InControl.ReorderableList
{
/// <summary>
/// Additional flags which can be passed into reorderable list field.
/// </summary>
/// <example>
/// <para>Multiple flags can be specified if desired:</para>
/// <code language="csharp"><![CDATA[
/// var flags = ReorderableListFlags.HideAddButton | ReorderableListFlags.HideRemoveButtons;
/// ReorderableListGUI.ListField(list, flags);
/// ]]></code>
/// </example>
[Flags]
public enum ReorderableListFlags
{
/// <summary>
/// Hide grab handles and disable reordering of list items.
/// </summary>
DisableReordering = 0x01,
/// <summary>
/// Hide add button at base of control.
/// </summary>
HideAddButton = 0x02,
/// <summary>
/// Hide remove buttons from list items.
/// </summary>
HideRemoveButtons = 0x04,
/// <summary>
/// Do not display context menu upon right-clicking grab handle.
/// </summary>
DisableContextMenu = 0x08,
/// <summary>
/// Hide "Duplicate" option from context menu.
/// </summary>
DisableDuplicateCommand = 0x10,
/// <summary>
/// Do not automatically focus first control of newly added items.
/// </summary>
DisableAutoFocus = 0x20,
/// <summary>
/// Show zero-based index of array elements.
/// </summary>
ShowIndices = 0x40,
/// <summary>
/// Do not attempt to clip items which are out of view.
/// </summary>
/// <remarks>
/// <para>Clipping helps to boost performance, though may lead to issues on
/// some interfaces.</para>
/// </remarks>
DisableClipping = 0x80,
}
}
#endif
| 27.777778 | 93 | 0.667429 | [
"MIT"
] | SamOatesJams/Ludumdare33 | Assets/Extensions/InControl/Editor/ReorderableList/ReorderableListFlags.cs | 1,750 | C# |
using System.Diagnostics.Contracts;
namespace Examples
{
public class GenericStackSetFields<T>
{
public const int capacity = 5;
public int size;
public T[] data;
[ContractInvariantMethod]
private void Invariant()
{
Contract.Invariant(size >= 0);
Contract.Invariant(size <= capacity);
Contract.Invariant(data.Length == capacity);
}
public GenericStackSetFields()
{
size = 0;
data = new T[capacity];
}
public void Push(T item)
{
Contract.Requires(size < capacity);
if (!Belongs(item))
{
data[size] = item;
size++;
}
}
public T Pop()
{
Contract.Requires(size > 0);
return data[--size];
}
[Pure]
public bool Belongs(T item)
{
bool result = false;
for (int i = 0; !result && i < size; i++)
{
result = data[i].Equals(item);
}
return result;
}
}
}
| 21.127273 | 56 | 0.447504 | [
"MIT"
] | lleraromero/contractor-net | Examples/GenericStackSetFields.cs | 1,164 | C# |
// Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License, version 2.0, as
// published by the Free Software Foundation.
//
// This program is also distributed with certain software (including
// but not limited to OpenSSL) that is licensed under separate terms,
// as designated in a particular file or component or in included license
// documentation. The authors of MySQL hereby grant you an
// additional permission to link the program and your derivative works
// with the separately licensed software that they have included with
// MySQL.
//
// Without limiting anything contained in the foregoing, this file,
// which is part of MySQL Connector/NET, is also subject to the
// Universal FOSS Exception, version 1.0, a copy of which can be found at
// http://oss.oracle.com/licenses/universal-foss-exception.
//
// 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, version 2.0, for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
using System;
using System.Collections.Generic;
using System.Diagnostics;
using MySqlX.XDevAPI.Common;
using MySqlX.Sessions;
using MySql.Data.MySqlClient;
using System.Collections.ObjectModel;
using System.Linq;
namespace MySqlX.XDevAPI.Relational
{
/// <summary>
/// Represents a resultset that contains rows of data.
/// </summary>
public class InternalRowResult : BufferingResult<Row>
{
internal InternalRowResult(InternalSession session) : base(session)
{
}
/// <summary>
/// Gets the columns in this resultset.
/// </summary>
#if NET_45_OR_GREATER
public IReadOnlyList<Column> Columns
#else
public ReadOnlyCollection<Column> Columns
#endif
{
get { return _columns.AsReadOnly(); }
}
/// <summary>
/// Gets the number of columns in this resultset.
/// </summary>
public Int32 ColumnCount
{
get { return _columns.Count; }
}
/// <summary>
/// Gets a list containing the column names in this resultset.
/// </summary>
public List<string> ColumnNames
{
get { return _columns.Select(o => o.ColumnLabel).ToList(); }
}
/// <summary>
/// Gets the rows of this resultset. This collection will be incomplete unless all the rows have been read
/// either by using the Next method or the Buffer method.
/// </summary>
#if NET_45_OR_GREATER
public IReadOnlyList<Row> Rows
#else
public ReadOnlyCollection<Row> Rows
#endif
{
get { return _items.AsReadOnly(); }
}
/// <summary>
/// Gets the value of the column value at the current index.
/// </summary>
/// <param name="index">The column index.</param>
/// <returns>The CLR value at the column index.</returns>
public object this[int index]
{
get { return GetValue(index); }
}
/// <summary>
/// Allows getting the value of the column value at the current index.
/// </summary>
/// <param name="index">The column index.</param>
/// <returns>The CLR value at the column index.</returns>
private object GetValue(int index)
{
if (_position == _items.Count)
throw new InvalidOperationException("No data at position");
return _items[_position][index];
}
/// <summary>
/// Returns the index of the given column name.
/// </summary>
/// <param name="name">The name of the column to find.</param>
/// <returns>The numeric index of column.</returns>
public int IndexOf(string name)
{
if (!NameMap.ContainsKey(name))
throw new MySqlException("Column not found '" + name + "'");
return NameMap[name];
}
protected override Row ReadItem(bool dumping)
{
///TODO: fix this
List<byte[]> values = Protocol.ReadRow(this);
if (values == null) return null;
if (dumping) return new Row(NameMap, null);
Debug.Assert(values.Count == _columns.Count, "Value count does not equal column count");
object[] clrValues = new object[values.Count];
for (int i = 0; i < values.Count; i++)
clrValues[i] = Columns[i]._decoder.ClrValueDecoder(values[i]);
Row row = new Row(NameMap, clrValues);
return row;
}
}
}
| 32.929078 | 110 | 0.676502 | [
"BSD-3-Clause"
] | zhouweiaccp/MySQL.Data | X/XDevAPI/Relational/InternalRowResult.cs | 4,643 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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 Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.Common.Authentication.Models;
using Microsoft.Azure.Commands.Profile.Common;
using Microsoft.Azure.Commands.Profile.Properties;
using Microsoft.Azure.Commands.ResourceManager.Common;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.IO;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Profile.Context
{
[Cmdlet(VerbsCommon.Clear, "AzureRmContext", SupportsShouldProcess = true)]
[OutputType(typeof(bool))]
public class ClearAzureRmContext : AzureContextModificationCmdlet
{
[Parameter(Mandatory = false, HelpMessage = "Return a value indicating success or failure")]
public SwitchParameter PassThru { get; set; }
[Parameter(Mandatory = false, HelpMessage = "Delete all users and groups from the global scope without prompting")]
public SwitchParameter Force { get; set; }
public override void ExecuteCmdlet()
{
switch (GetContextModificationScope())
{
case ContextModificationScope.Process:
if (ShouldProcess(Resources.ClearContextProcessMessage, Resources.ClearContextProcessTarget))
{
ModifyContext(ClearContext);
}
break;
case ContextModificationScope.CurrentUser:
ConfirmAction(Force.IsPresent, Resources.ClearContextUserContinueMessage,
Resources.ClearContextUserProcessMessage, Resources.ClearContextUserTarget,
() => ModifyContext(ClearContext),
() =>
{
var session = AzureSession.Instance;
var contextFilePath = Path.Combine(session.ARMProfileDirectory, session.ARMProfileFile);
return session.DataStore.FileExists(contextFilePath);
});
break;
}
}
void ClearContext(AzureRmProfile profile, RMProfileClient client)
{
bool result = false;
if (profile != null)
{
var contexts = profile.Contexts.Values;
foreach (var context in contexts)
{
client.TryRemoveContext(context);
}
var defaultContext = new AzureContext();
var cache = AzureSession.Instance.TokenCache;
if (GetContextModificationScope() == ContextModificationScope.CurrentUser)
{
var fileCache = cache as ProtectedFileTokenCache;
if (fileCache == null)
{
try
{
var session = AzureSession.Instance;
fileCache = new ProtectedFileTokenCache(Path.Combine(session.TokenCacheDirectory, session.TokenCacheFile), session.DataStore);
fileCache.Clear();
}
catch
{
// ignore exceptions from creating a token cache
}
}
cache.Clear();
}
else
{
var localCache = cache as AuthenticationStoreTokenCache;
if (localCache != null)
{
localCache.Clear();
}
}
defaultContext.TokenCache = cache;
profile.TrySetDefaultContext(defaultContext);
result = true;
}
if (PassThru.IsPresent)
{
WriteObject(result);
}
}
}
}
| 42.321739 | 155 | 0.532566 | [
"MIT"
] | ethanmoffat/azure-powershell | src/ResourceManager/Profile/Commands.Profile/Context/ClearAzureRmContext.cs | 4,755 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MatrixTests : MonoBehaviour
{
void Start()
{
/* {
// ADD, MULTIPLY, AND RANDOMIZE TESTS.
Matrix matrix = new Matrix(3, 3);
Debug.Log("DEFAULT MATRIX:");
matrix.PrintMatrix();
Debug.Log("-----------------");
Debug.Log("ADD:");
matrix.Add(2);
matrix.PrintMatrix();
Debug.Log("-----------------");
Debug.Log("MULTIPLY:");
matrix.Multiply(-2);
matrix.PrintMatrix();
Debug.Log("-----------------");
Debug.Log("RANDOMIZE:");
matrix.Randomize();
matrix.PrintMatrix();
Debug.Log("-----------------");
Matrix matrix2 = new Matrix(3, 3);
matrix2.Randomize();
Debug.Log("DEFAULT MATRIX2:");
matrix2.PrintMatrix();
Debug.Log("-----------------");
Debug.Log("MATRIXES ADDED TOGETHER:");
matrix.Add(matrix2);
matrix.PrintMatrix();
Debug.Log("-----------------");
} */
/* {
// PRODUCT
Debug.Log("FIRST MATRIX:");
Matrix matrix = new Matrix(2, 3);
matrix.Randomize();
matrix.PrintMatrix();
Debug.Log("----------------");
Debug.Log("SECOND MATRIX:");
Matrix matrix2 = new Matrix(3, 2);
matrix2.Randomize();
matrix2.PrintMatrix();
Debug.Log("----------------");
Debug.Log("PRODUCT MATRIX:");
Matrix productMatrix = Matrix.Product(matrix, matrix2);
productMatrix.PrintMatrix();
Debug.Log("----------------");
} */
/* {
// MAP
Matrix matrix = new Matrix(3,3);
matrix.Add(2);
matrix.Map(doubleIt);
matrix.PrintMatrix();
} */
}
// To test Map().
float doubleIt(float val){
return val * 2;
}
}
| 26.475 | 67 | 0.428706 | [
"MIT"
] | Anton1337/Jumpy-NeuralNetwork | Assets/Scripts/AI LIBRARY/MatrixTests.cs | 2,120 | C# |
using Orchard.ContentManagement.MetaData;
using Orchard.Core.Contents.Extensions;
using Orchard.Data.Migration;
namespace CSM.Socrata
{
public class Migrations : DataMigrationImpl
{
public int Create()
{
ContentDefinitionManager.AlterPartDefinition("SocrataSettingsPart", part => part
.Attachable()
);
return 1;
}
}
} | 22.666667 | 92 | 0.625 | [
"MIT"
] | CityofSantaMonica/OrchardSocrata | Migrations.cs | 410 | C# |
//
// This file contains a generic version of NSArray
//
// Authors:
// Alex Soto (alex.soto@xamarin.com)
//
// Copyright 2015, Xamarin Inc.
//
using System;
using System.Collections.Generic;
using System.Collections;
using System.Runtime.InteropServices;
using ObjCRuntime;
namespace Foundation {
[Register (SkipRegistration = true)]
public sealed partial class NSArray<TKey> : NSArray, IEnumerable<TKey>
where TKey : class, INativeObject {
public NSArray ()
{
}
public NSArray (NSCoder coder) : base (coder)
{
}
internal NSArray (IntPtr handle) : base (handle)
{
}
static public NSArray<TKey> FromNSObjects (params TKey [] items)
{
if (items == null)
throw new ArgumentNullException (nameof (items));
return FromNSObjects (items.Length, items);
}
static public NSArray<TKey> FromNSObjects (int count, params TKey [] items)
{
if (items == null)
throw new ArgumentNullException (nameof (items));
if (count > items.Length)
throw new ArgumentException ("count is larger than the number of items", "count");
IntPtr buf = Marshal.AllocHGlobal ((IntPtr) (count * IntPtr.Size));
for (nint i = 0; i < count; i++) {
var item = items [i];
IntPtr h = item == null ? NSNull.Null.Handle : item.Handle;
Marshal.WriteIntPtr (buf, (int)(i * IntPtr.Size), h);
}
IntPtr ret = NSArray.FromObjects (buf, count);
NSArray<TKey> arr = Runtime.GetNSObject<NSArray<TKey>> (ret);
Marshal.FreeHGlobal (buf);
return arr;
}
#region IEnumerable<TKey>
IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator ()
{
return new NSFastEnumerator<TKey> (this);
}
#endregion
#region IEnumerable implementation
IEnumerator IEnumerable.GetEnumerator ()
{
return new NSFastEnumerator<TKey> (this);
}
#endregion
public TKey this [nint idx] {
get {
return GetItem<TKey> ((nuint)idx);
}
}
}
}
| 22.831325 | 86 | 0.674934 | [
"BSD-3-Clause"
] | dalexsoto/xamarin-macios | src/Foundation/NSArray_1.cs | 1,895 | C# |
namespace ClassLib060
{
public class Class032
{
public static string Property => "ClassLib060";
}
}
| 15 | 55 | 0.633333 | [
"MIT"
] | 333fred/performance | src/scenarios/weblarge2.0/src/ClassLib060/Class032.cs | 120 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Bangershare_Backend.Models;
using Bangershare_Backend.Interfaces;
using Bangershare_Backend.Repositories;
using Bangershare_Backend.Services.Communications;
using Microsoft.EntityFrameworkCore;
namespace Bangershare_Backend.Services
{
public class SongService : BaseService<BangerShareContext, Song, SongRepository, BaseResponse<Song>, IUnitOfWork>
{
private readonly SongRepository _songRepository;
private readonly PlaylistService _playlistService;
private readonly SpotifyAPIService _spotifyAPIService;
private readonly YoutubeAPIService _youtubeAPIService;
private readonly IRepository<UserPlaylist> _userPlaylistRepository;
private readonly IRepository<UserLike> _userLikeRepository;
private readonly IUnitOfWork _unitOfWork;
public SongService(SongRepository songRepository,
PlaylistService playlistService,
SpotifyAPIService spotifyAPIService,
YoutubeAPIService youtubeAPIService,
IRepository<UserLike> userLikeRepository,
IRepository<UserPlaylist> userPlaylistRepository,
IUnitOfWork unitOfWork) : base(songRepository, unitOfWork)
{
_songRepository = songRepository;
_playlistService = playlistService;
_spotifyAPIService = spotifyAPIService;
_youtubeAPIService = youtubeAPIService;
_userLikeRepository = userLikeRepository;
_userPlaylistRepository = userPlaylistRepository;
_unitOfWork = unitOfWork;
}
public async Task<BaseResponse<Song>> AddSpotifySongToPlaylist(int userId, int playlistId, string spotifySongId)
{
var result = await _spotifyAPIService.getSpotifySongInformation(spotifySongId);
if (!result.Success)
{
return result;
}
return await AddSongToPlaylist(userId, playlistId, result.Resource);
}
public async Task<BaseResponse<Song>> AddYoutubeVideoToPlaylist(int userId, int playlistId, string youtubeId, Song song)
{
var result = await _youtubeAPIService.getYoutubeVideoInfo(youtubeId, song);
if (!result.Success)
{
return result;
}
return await AddSongToPlaylist(userId, playlistId, result.Resource);
}
public async Task<BaseResponse<Song>> AddSongToPlaylist(int userId, int playlistId, Song song)
{
var playlist = await _playlistService.GetByKeys(playlistId);
if(playlist == null)
{
return new BaseResponse<Song>("Playlist does not exist");
}
var userPlaylist = await _userPlaylistRepository.GetByKeys(userId, playlistId);
if(userPlaylist == null)
{
return new BaseResponse<Song>("User does not follow playlist");
}
// Only the owner of a playlist can directly add a song to a playlist
if(userPlaylist.IsOwner)
{
song.IsPending = false;
}
else
{
song.IsPending = true;
}
song.Hearts = 0;
song.PlaylistId = playlistId;
song.Playlist = playlist;
var response = await Add(song);
return response;
}
public async Task<BaseResponse<Song>> DeleteSongFromPlaylist(int userId, int playlistId, int songId)
{
var playlist = await _playlistService.GetByKeys(playlistId);
if (playlist == null)
{
return new BaseResponse<Song>("Playlist does not exist");
}
var userPlaylist = await _userPlaylistRepository.GetByKeys(userId, playlistId);
if (userPlaylist == null)
{
return new BaseResponse<Song>("User does not follow playlist");
}
else if (!userPlaylist.IsOwner)
{
return new BaseResponse<Song>("User does not have permission to remove songs");
}
var song = await GetByKeys(songId);
if(song == null)
{
return new BaseResponse<Song>("Song does not exist");
}
else if(song.PlaylistId != playlistId)
{
return new BaseResponse<Song>("Song does not belong in playlist");
}
var response = await Delete(songId);
return response;
}
public async Task<BaseResponse<Song>> UpdateSong(int songId, Song song)
{
var existingSong = await GetByKeys(songId);
if(existingSong == null)
{
return new BaseResponse<Song>("Song does not exist");
}
existingSong.Artist = song.Artist;
existingSong.Hearts = song.Hearts;
existingSong.IsPending = song.IsPending;
existingSong.Link = song.Link;
existingSong.Name = song.Name;
existingSong.SongType = song.SongType;
try
{
_songRepository.UpdateSong(existingSong);
await _unitOfWork.CompleteAsync();
return new BaseResponse<Song>(existingSong);
}
catch(Exception e)
{
return new BaseResponse<Song>($"An error occurred when updating the song: {e.Message}");
}
}
public async Task<BaseResponse<Song>> LikeSong(int userId, int songId)
{
var song = await FindFirstOrDefault(s => s.Id.Equals(songId));
song.Hearts += 1;
var userLike = new UserLike { Song = song, SongId = songId, UserId = userId };
try
{
await _userLikeRepository.Add(userLike);
var result = await UpdateSong(songId, song);
if (!result.Success)
{
return result;
}
return new BaseResponse<Song>(song);
}
catch(Exception e)
{
return new BaseResponse<Song>($"An error occurred when liking the song: {e.Message}");
}
}
public async Task<BaseResponse<Song>> DislikeSong(int userId, int songId)
{
var userLike = await _userLikeRepository.FindFirstOrDefault(u => u.UserId.Equals(userId) && u.SongId.Equals(songId), include: source => source.Include(s => s.Song));
if (userLike == null)
{
return new BaseResponse<Song>("User like not found");
}
userLike.Song.Hearts -= 1;
try
{
_userLikeRepository.Delete(userLike);
var result = await UpdateSong(songId, userLike.Song);
if (!result.Success)
{
return result;
}
return new BaseResponse<Song>(userLike.Song);
}
catch(Exception e)
{
return new BaseResponse<Song>($"An error occurred when disliking the song: {e.Message}");
}
}
public async Task<BaseResponse<ICollection<Song>>> GetUserLikedSongs(int userId)
{
var userLikes = await _userLikeRepository.Get(u => u.UserId.Equals(userId), includeProperties: "Song");
if(userLikes == null)
{
return new BaseResponse<ICollection<Song>>("User has no liked songs");
}
var songList = new List<Song>();
foreach(UserLike userLike in userLikes)
{
songList.Add(userLike.Song);
}
return new BaseResponse<ICollection<Song>>(songList);
}
}
}
| 34.163866 | 177 | 0.565613 | [
"MIT"
] | clyanide/Group-6-Gray-Goat | Bangershare Backend/Services/SongService.cs | 8,133 | C# |
using log4net;
using System;
using System.Collections.Generic;
namespace Microsoft.Extensions.Logging.Scope.Registers
{
public sealed class Log4NetObjectScopedRegister : Log4NetScopedRegister
{
public Log4NetObjectScopedRegister()
{
base.Type = typeof(object);
}
public override IEnumerable<IDisposable> AddToScope(object state)
{
if (state != null)
{
yield return LogicalThreadContext.Stacks[DefaultStackName].Push(state.ToString());
}
}
}
} | 25.863636 | 98 | 0.627417 | [
"Apache-2.0"
] | houbi56/Microsoft.Extensions.Logging.Log4Net.AspNetCore | src/Microsoft.Extensions.Logging.Log4Net.AspNetCore/Scope/Registers/Log4NetObjectScopedRegister.cs | 571 | C# |
using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace ContainerView
{
internal class SerializedContainer
{
[JsonPropertyName("name")]
public string Name { get; set; } = null!;
[JsonPropertyName("address")]
public string Address { get; set; } = null!;
[JsonPropertyName("installers")]
public string[] Installers { get; set; } = Array.Empty<string>();
[JsonPropertyName("contracts")]
public string[] Contracts { get; set; } = Array.Empty<string>();
[JsonPropertyName("children")]
public List<SerializedContainer> Children { get; set; } = new();
}
} | 28.583333 | 73 | 0.629738 | [
"MIT"
] | ProjectSIRA/ContainerTree | ContainerView/SerializedContainer.cs | 688 | C# |
namespace NewsSystem.Services.Contracts
{
using Models;
public interface ILikesServices
{
Like GetByAuthorAndArticle(string authorId, int articleId);
Like Create(Like like);
}
}
| 19.272727 | 67 | 0.683962 | [
"MIT"
] | EmilMitev/Telerik-Academy | ASP.NET Web Forms/Exam/2016-NewsSite/NewsSystem.Services/Contracts/ILikesServices.cs | 214 | C# |
// LabelComponent.cs
//
// Copyright (C) BEditor
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Reactive.Disposables;
using System.Text.Json;
namespace BEditor.Data.Property
{
/// <summary>
/// Represents a project that shows a string in the UI.
/// </summary>
[DebuggerDisplay("Text = {Text}")]
public class LabelComponent : PropertyElement<PropertyElementMetadata>, IEasingProperty, IObservable<string>, IObserver<string>
{
private static readonly PropertyChangedEventArgs _textArgs = new(nameof(Text));
private List<IObserver<string>>? _list;
private string _text = string.Empty;
/// <summary>
/// Gets or sets the string to be shown.
/// </summary>
public string Text
{
get => _text;
set
{
if (SetAndRaise(value, ref _text, _textArgs))
{
foreach (var observer in Collection)
{
try
{
observer.OnNext(_text);
}
catch (Exception ex)
{
observer.OnError(ex);
}
}
}
}
}
private List<IObserver<string>> Collection => _list ??= new();
/// <inheritdoc/>
public void OnCompleted()
{
}
/// <inheritdoc/>
public void OnError(Exception error)
{
}
/// <inheritdoc/>
public void OnNext(string value)
{
Text = value;
}
/// <inheritdoc/>
public IDisposable Subscribe(IObserver<string> observer)
{
if (observer is null) throw new ArgumentNullException(nameof(observer));
Collection.Add(observer);
return Disposable.Create((observer, this), state =>
{
state.observer.OnCompleted();
state.Item2.Collection.Remove(state.observer);
});
}
/// <inheritdoc/>
public override void GetObjectData(Utf8JsonWriter writer)
{
base.GetObjectData(writer);
writer.WriteString(nameof(Text), Text);
}
/// <inheritdoc/>
public override void SetObjectData(DeserializeContext context)
{
base.SetObjectData(context);
var element = context.Element;
Text = element.TryGetProperty(nameof(Text), out var value) ? value.GetString() ?? string.Empty : string.Empty;
}
}
} | 29.112245 | 131 | 0.528917 | [
"MIT"
] | b-editor/BEditor | src/libraries/BEditor.Core/Data/Property/LabelComponent.cs | 2,855 | C# |
/****************************************************
文件:PEMsg.cs
作者:Plane
邮箱: 1785275942@qq.com
日期:2018/10/30 11:20
功能:消息定义类
*****************************************************/
namespace PENet {
using System;
/// <summary>
/// 自定义消息类的基类,它表示网络传输的实体对象,即最终把这个对象的实例转换为字节数组发送
/// </summary>
[Serializable]
public abstract class PEMsg {
public int seq;
/// <summary>
/// 表示消息的类型,它是解析消息方式的依据,它需要在消息实例化时指定
/// </summary>
public int cmd;//遗留:这个表征消息类型的属性是否应当放在构造函数里
/// <summary>
/// 表示消息的错误码
/// </summary>
public int err;
}
} | 22.642857 | 54 | 0.466877 | [
"MIT"
] | MonsterZhangChen/PESocket-1.0 | PESocket/PEMsg.cs | 890 | C# |
// ==========================================================================
// Notifo.io
// ==========================================================================
// Copyright (c) Sebastian Stehle
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
namespace Notifo.Infrastructure.Scheduling.Implementation
{
public interface ISchedulingProvider
{
IScheduling<T> GetScheduling<T>(IServiceProvider serviceProvider, SchedulerOptions options);
}
}
| 37.2 | 100 | 0.435484 | [
"MIT"
] | anhgeeky/notifo | backend/src/Notifo.Infrastructure/Scheduling/Implementation/ISchedulingProvider.cs | 560 | 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.Linq;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using Microsoft.EntityFrameworkCore.Benchmarks.EFCore2.Models.Orders;
using Microsoft.EntityFrameworkCore.Storage;
using Xunit;
namespace Microsoft.EntityFrameworkCore.Benchmarks.EFCore2.UpdatePipeline
{
public class SimpleUpdatePipelineTests
{
public abstract class Base
{
protected static readonly SimpleUpdatePipelineFixture _fixture = new SimpleUpdatePipelineFixture();
protected OrdersContext _context;
private IDbContextTransaction _transaction;
private int _recordsAffected = -1;
[Params(true, false)]
public bool Async;
[Params(true, false)]
public bool Batching;
[IterationSetup]
public virtual void InitializeContext()
{
_context = _fixture.CreateContext(Batching);
_transaction = _context.Database.BeginTransaction();
}
[IterationCleanup]
public virtual void CleanupContext()
{
if (_recordsAffected != -1)
{
Assert.Equal(1000, _recordsAffected);
}
_transaction.Dispose();
_context.Dispose();
}
[Benchmark]
public async Task UpdatePipeline()
{
_recordsAffected = Async
? await _context.SaveChangesAsync()
: _context.SaveChanges();
}
}
public class Insert : Base
{
[IterationSetup]
public override void InitializeContext()
{
base.InitializeContext();
var customers = _fixture.CreateCustomers(1000, setPrimaryKeys: false);
_context.Customers.AddRange(customers);
}
}
public class Update : Base
{
[IterationSetup]
public override void InitializeContext()
{
base.InitializeContext();
foreach (var customer in _context.Customers)
{
customer.FirstName += " Modified";
}
}
}
public class Delete : Base
{
[IterationSetup]
public override void InitializeContext()
{
base.InitializeContext();
_context.Customers.RemoveRange(_context.Customers.ToList());
}
}
public class Mixed : Base
{
[IterationSetup]
public override void InitializeContext()
{
base.InitializeContext();
var existingCustomers = _context.Customers.ToArray();
var newCustomers = _fixture.CreateCustomers(333, setPrimaryKeys: false);
_context.Customers.AddRange(newCustomers);
for (var i = 0; i < 1000; i += 3)
{
_context.Customers.Remove(existingCustomers[i]);
}
for (var i = 1; i < 1000; i += 3)
{
existingCustomers[i].FirstName += " Modified";
}
}
}
public class SimpleUpdatePipelineFixture : OrdersFixture
{
public SimpleUpdatePipelineFixture()
: base("Perf_UpdatePipeline_Simple", 0, 1000, 0, 0)
{
}
public OrdersContext CreateContext(bool batching)
{
return new OrdersContext(ConnectionString, disableBatching: !batching);
}
}
}
}
| 30.123077 | 111 | 0.534474 | [
"Apache-2.0"
] | tonysneed/Forks.EntityFrameworkCore | benchmarks/EFCore.Benchmarks.EFCore2/UpdatePipeline/SimpleUpdatePipelineTests.cs | 3,916 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Network.V20180101.Inputs
{
/// <summary>
/// Probe of the application gateway.
/// </summary>
public sealed class ApplicationGatewayProbeArgs : Pulumi.ResourceArgs
{
/// <summary>
/// A unique read-only string that changes whenever the resource is updated.
/// </summary>
[Input("etag")]
public Input<string>? Etag { get; set; }
/// <summary>
/// Host name to send the probe to.
/// </summary>
[Input("host")]
public Input<string>? Host { get; set; }
/// <summary>
/// Resource ID.
/// </summary>
[Input("id")]
public Input<string>? Id { get; set; }
/// <summary>
/// The probing interval in seconds. This is the time interval between two consecutive probes. Acceptable values are from 1 second to 86400 seconds.
/// </summary>
[Input("interval")]
public Input<int>? Interval { get; set; }
/// <summary>
/// Criterion for classifying a healthy probe response.
/// </summary>
[Input("match")]
public Input<Inputs.ApplicationGatewayProbeHealthResponseMatchArgs>? Match { get; set; }
/// <summary>
/// Minimum number of servers that are always marked healthy. Default value is 0.
/// </summary>
[Input("minServers")]
public Input<int>? MinServers { get; set; }
/// <summary>
/// Name of the resource that is unique within a resource group. This name can be used to access the resource.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// Relative path of probe. Valid path starts from '/'. Probe is sent to <Protocol>://<host>:<port><path>
/// </summary>
[Input("path")]
public Input<string>? Path { get; set; }
/// <summary>
/// Whether the host header should be picked from the backend http settings. Default value is false.
/// </summary>
[Input("pickHostNameFromBackendHttpSettings")]
public Input<bool>? PickHostNameFromBackendHttpSettings { get; set; }
/// <summary>
/// Protocol.
/// </summary>
[Input("protocol")]
public InputUnion<string, Pulumi.AzureNextGen.Network.V20180101.ApplicationGatewayProtocol>? Protocol { get; set; }
/// <summary>
/// Provisioning state of the backend http settings resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
/// </summary>
[Input("provisioningState")]
public Input<string>? ProvisioningState { get; set; }
/// <summary>
/// the probe timeout in seconds. Probe marked as failed if valid response is not received with this timeout period. Acceptable values are from 1 second to 86400 seconds.
/// </summary>
[Input("timeout")]
public Input<int>? Timeout { get; set; }
/// <summary>
/// Type of the resource.
/// </summary>
[Input("type")]
public Input<string>? Type { get; set; }
/// <summary>
/// The probe retry count. Backend server is marked down after consecutive probe failure count reaches UnhealthyThreshold. Acceptable values are from 1 second to 20.
/// </summary>
[Input("unhealthyThreshold")]
public Input<int>? UnhealthyThreshold { get; set; }
public ApplicationGatewayProbeArgs()
{
}
}
}
| 36.224299 | 178 | 0.597007 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Network/V20180101/Inputs/ApplicationGatewayProbeArgs.cs | 3,876 | C# |
namespace ScadaAdmin.Remote
{
partial class CtrlServerConn
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.gbConnection = new System.Windows.Forms.GroupBox();
this.btnRemoveConn = new System.Windows.Forms.Button();
this.btnEditConn = new System.Windows.Forms.Button();
this.btnCreateConn = new System.Windows.Forms.Button();
this.cbConnection = new System.Windows.Forms.ComboBox();
this.gbConnection.SuspendLayout();
this.SuspendLayout();
//
// gbConnection
//
this.gbConnection.Controls.Add(this.btnRemoveConn);
this.gbConnection.Controls.Add(this.btnEditConn);
this.gbConnection.Controls.Add(this.btnCreateConn);
this.gbConnection.Controls.Add(this.cbConnection);
this.gbConnection.Location = new System.Drawing.Point(0, 0);
this.gbConnection.Name = "gbConnection";
this.gbConnection.Padding = new System.Windows.Forms.Padding(10, 3, 10, 10);
this.gbConnection.Size = new System.Drawing.Size(469, 55);
this.gbConnection.TabIndex = 1;
this.gbConnection.TabStop = false;
this.gbConnection.Text = "Connect to server";
//
// btnRemoveConn
//
this.btnRemoveConn.Location = new System.Drawing.Point(381, 19);
this.btnRemoveConn.Name = "btnRemoveConn";
this.btnRemoveConn.Size = new System.Drawing.Size(75, 23);
this.btnRemoveConn.TabIndex = 3;
this.btnRemoveConn.Text = "Delete";
this.btnRemoveConn.UseVisualStyleBackColor = true;
this.btnRemoveConn.Click += new System.EventHandler(this.btnRemoveConn_Click);
//
// btnEditConn
//
this.btnEditConn.Location = new System.Drawing.Point(300, 19);
this.btnEditConn.Name = "btnEditConn";
this.btnEditConn.Size = new System.Drawing.Size(75, 23);
this.btnEditConn.TabIndex = 2;
this.btnEditConn.Text = "Edit";
this.btnEditConn.UseVisualStyleBackColor = true;
this.btnEditConn.Click += new System.EventHandler(this.btnEditConn_Click);
//
// btnCreateConn
//
this.btnCreateConn.Location = new System.Drawing.Point(219, 19);
this.btnCreateConn.Name = "btnCreateConn";
this.btnCreateConn.Size = new System.Drawing.Size(75, 23);
this.btnCreateConn.TabIndex = 1;
this.btnCreateConn.Text = "Create";
this.btnCreateConn.UseVisualStyleBackColor = true;
this.btnCreateConn.Click += new System.EventHandler(this.btnCreateConn_Click);
//
// cbConnection
//
this.cbConnection.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbConnection.FormattingEnabled = true;
this.cbConnection.Location = new System.Drawing.Point(13, 20);
this.cbConnection.Name = "cbConnection";
this.cbConnection.Size = new System.Drawing.Size(200, 21);
this.cbConnection.TabIndex = 0;
this.cbConnection.SelectedIndexChanged += new System.EventHandler(this.cbConnection_SelectedIndexChanged);
//
// CtrlServerConn
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.gbConnection);
this.Name = "CtrlServerConn";
this.Size = new System.Drawing.Size(469, 55);
this.gbConnection.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox gbConnection;
private System.Windows.Forms.Button btnRemoveConn;
private System.Windows.Forms.Button btnEditConn;
private System.Windows.Forms.Button btnCreateConn;
private System.Windows.Forms.ComboBox cbConnection;
}
}
| 43.614035 | 118 | 0.601368 | [
"Apache-2.0"
] | shouqitao/scada | ScadaAdmin/ScadaAdmin/Remote/CtrlServerConn.Designer.cs | 4,974 | C# |
#region License
//------------------------------------------------------------------------------------------------
// <License>
// <Copyright> 2017 © Top Nguyen → AspNetCore → Monkey </Copyright>
// <Url> http://topnguyen.net/ </Url>
// <Author> Top </Author>
// <Project> Puppy </Project>
// <File>
// <Name> LogEntityMap.cs </Name>
// <Created> 23/08/17 10:15:52 AM </Created>
// <Key> b067bfc2-29a6-4cf7-a414-0644c26edef2 </Key>
// </File>
// <Summary>
// LogEntityMap.cs
// </Summary>
// <License>
//------------------------------------------------------------------------------------------------
#endregion License
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Puppy.EF.Maps;
using Puppy.Logger.Core.Models;
namespace Puppy.Logger.SQLite.Map
{
public class LogMap : ITypeConfiguration<LogEntity>
{
public void Map(EntityTypeBuilder<LogEntity> builder)
{
builder.ToTable(nameof(LogEntity));
builder.HasKey(x => x.Id);
builder.Ignore(x => x.Exception).Ignore(x => x.HttpContext);
builder.HasIndex(x => x.Id);
builder.HasIndex(x => x.CreatedTime);
builder.HasIndex(x => x.Level);
}
}
} | 32.875 | 98 | 0.510266 | [
"Unlicense"
] | stssoftware/Puppy | Puppy.Logger/SQLite/Map/LogEntityMap.cs | 1,322 | 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("Clarity")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Clarity")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4f9817ad-cd96-4431-8c8d-8098477465c3")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.444444 | 84 | 0.739614 | [
"MIT"
] | Zulkir/ClarityWorlds | Source/Clarity/Properties/AssemblyInfo.cs | 1,351 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Data;
using System.Globalization;
namespace Ragnarok.Presentation.Converter
{
/// <summary>
/// 値を比較し一致するかどうか調べます。
/// </summary>
[ValueConversion(typeof(object), typeof(bool))]
public class ValueCompareToBooleanConverter : IValueConverter
{
/// <summary>
/// 真の時使われるオブジェクトを取得または設定します。
/// </summary>
public object TrueObject
{
get;
set;
}
/// <summary>
/// 偽の時使われるオブジェクトを取得または設定します。
/// </summary>
public object FalseObject
{
get;
set;
}
/// <summary>
/// 値が一致するか調べます。
/// </summary>
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
return Util.GenericEquals(value, TrueObject);
}
/// <summary>
/// 真偽値を対象となる値に直します。
/// </summary>
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
return ((bool)value ? TrueObject : FalseObject);
}
}
}
| 24.444444 | 72 | 0.541667 | [
"MIT"
] | ebifrier/Ragnarok | Ragnarok.Presentation/Converter/ValueCompareToBooleanConverter.cs | 1,514 | C# |
namespace _01._RedBlackTree
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class RedBlackTree<TK, TV> where TK : IComparable<TK>
{
private Node root;
private int size;
public RedBlackTree()
{
this.size = 0;
this.root = null;
}
public void Add(TK key, TV value)
{
var node = new Node(key, value);
if (this.root == null)
{
this.root = node;
this.root.IsBlack = true;
this.size++;
return;
}
this.Add(this.root, node);
this.size++;
this.root.IsBlack = true;
}
public int Height()
{
if (this.root == null)
{
return 0;
}
return this.Height(this.root) - 1;
}
private int Height(Node node)
{
if (node == null)
{
return 0;
}
var leftHeight = this.Height(node?.Left) + 1;
var rightHeight = this.Height(node?.Right) + 1;
if (leftHeight > rightHeight)
{
return leftHeight;
}
return rightHeight;
}
public int BlackNodes()
{
return this.BlackNodes(this.root);
}
private int BlackNodes(Node node)
{
if (node == null)
{
return 1;
}
var rightBlackNodes = this.BlackNodes(node.Right);
var leftBlackNodes = this.BlackNodes(node.Left);
if (rightBlackNodes != leftBlackNodes)
{
//throw an error
//or fix a tree
//throw new Exception("Internal tree exception invalid black nodes count");
}
if (node.IsBlack)
{
leftBlackNodes++;
}
return leftBlackNodes;
}
private void Add(Node parent, Node newNode)
{
//newNode > parent
if (newNode.Key.CompareTo(parent.Key) > 0)
{
if (parent.Right == null)
{
parent.Right = newNode;
newNode.Parent = parent;
newNode.IsLeftChild = false;
newNode.IsBlack = false;
}
else
{
this.Add(parent.Right, newNode);
}
}
//newNode < parent
if (newNode.Key.CompareTo(parent.Key) < 0)
{
if (parent.Left == null)
{
parent.Left = newNode;
newNode.Parent = parent;
newNode.IsLeftChild = true;
newNode.IsBlack = false;
}
else
{
this.Add(parent.Left, newNode);
}
}
//Change value if the same key
if (newNode.Key.CompareTo(parent.Key) == 0)
{
parent.Value = newNode.Value;
return;
}
this.CheckColor(newNode);
}
private void CheckColor(Node node)
{
//root is always black
//new nodes are red
//nulls are black
//no two consecutive red nodes !!!
//same number of black nodes on every path
//if nodes cause for violation
//black aunt -> rotate
//red aunt -> color flip
if (node == this.root)
{
return;
}
//Handling duplicates
if (node?.Parent == null)
{
return;
}
//two consecutive red
if (!node.IsBlack && !node.Parent.IsBlack)
{
this.CorrectTree(node);
}
this.CheckColor(node.Parent);
}
private void CorrectTree(Node node)
{
if (node.Parent.IsLeftChild)
{
//aunt = node.Parent.Parent.Right
//var aunt = node.Parent.Parent?.Right.IsBlack;
if (node.Parent.Parent.Right == null || node.Parent.Parent.Right.IsBlack)
{
this.root.PrintPretty("", true, "Before Rotation");
this.Rotate(node);
//this.root.PrintPretty("", true, "After Rotation");
return;
}
this.root.PrintPretty("", true, "Before Color Flip");
if (node.Parent.Parent.Right != null)
{
node.Parent.Parent.Right.IsBlack = true;
}
node.Parent.Parent.IsBlack = false;
node.Parent.IsBlack = true;
//this.root.PrintPretty("", true, "After Color Flip");
return;
}
//aunt = node.Parent.Parent.Left
//var aunt = node.Parent.Parent?.Left.IsBlack;
if (!node.Parent.IsLeftChild)
{
if (node.Parent.Parent.Left == null || node.Parent.Parent.Left.IsBlack)
{
this.root.PrintPretty("", true, "Before Rotation");
this.Rotate(node);
//this.root.PrintPretty("", true, "After Rotation");
return;
}
this.root.PrintPretty("", true, "Before Color Flip");
if (node.Parent.Parent.Left != null)
{
node.Parent.Parent.Left.IsBlack = true;
}
node.Parent.Parent.IsBlack = false;
node.Parent.IsBlack = true;
//this.root.PrintPretty("", true, "After Color Flip");
return;
}
}
//Input node causes the violation
private void Rotate(Node node)
{
if (node.IsLeftChild)
{
//if child is left and parent is left -> right rotation
if (node.Parent.IsLeftChild)
{
this.RightRotate(node.Parent.Parent);
node.IsBlack = false;
node.Parent.IsBlack = true;
if (node.Parent.Right != null)
{
node.Parent.Right.IsBlack = false;
}
return;
}
//if parent right child is left -> right<->left rotation
this.RightLeftRotate(node.Parent.Parent);
node.IsBlack = true;
node.Right.IsBlack = false;
node.Left.IsBlack = false;
return;
}
if (!node.IsLeftChild)
{
//if child is right and parent is right -> left rotation
if (!node.Parent.IsLeftChild)
{
this.LeftRotate(node.Parent.Parent);
node.IsBlack = false;
node.Parent.IsBlack = true;
if (node.Parent.Left != null)
{
node.Parent.Left.IsBlack = false;
}
return;
}
//if parent left child is right -> left<->right rotation
this.LeftRightRotate(node.Parent.Parent);
node.IsBlack = true;
node.Right.IsBlack = false;
node.Left.IsBlack = false;
return;
}
}
private void LeftRotate(Node node)
{
var temp = node.Right;
node.Right = temp.Left;
if (node.Right != null)
{
node.Right.Parent = node;
node.Right.IsLeftChild = false;
}
if (node.Parent == null)
{
this.root = temp;
temp.Parent = null;
}
else
{
temp.Parent = node.Parent;
if (node.IsLeftChild)
{
temp.IsLeftChild = true;
temp.Parent.Left = temp;
}
else
{
temp.IsLeftChild = false;
temp.Parent.Right = temp;
}
}
temp.Left = node;
node.IsLeftChild = true;
node.Parent = temp;
}
private void RightRotate(Node node)
{
var temp = node.Left;
node.Left = temp.Right;
if (node.Left != null)
{
node.Left.Parent = node;
node.Left.IsLeftChild = false;
}
if (node.Parent == null)
{
this.root = temp;
temp.Parent = null;
}
else
{
temp.Parent = node.Parent;
if (!node.IsLeftChild)
{
temp.IsLeftChild = false;
temp.Parent.Right = temp;
}
else
{
temp.IsLeftChild = true;
temp.Parent.Left = temp;
}
}
temp.Right = node;
node.IsLeftChild = false;
node.Parent = temp;
}
private void RightLeftRotate(Node node)
{
this.RightRotate(node.Right);
this.LeftRotate(node);
}
private void LeftRightRotate(Node node)
{
this.LeftRotate(node.Left);
this.RightRotate(node);
}
public void Print(string message = null)
{
this.root.PrintPretty("", true, message);
Console.WriteLine(new string('-', 200));
}
private class Node
{
public TK Key { get; private set; }
public TV Value { get; set; }
public Node Left { get; set; }
public Node Right { get; set; }
public Node Parent { get; set; }
public bool IsLeftChild { get; set; }
public bool IsBlack { get; set; }
public Node(TK key, TV value)
{
this.Key = key;
this.Value = value;
this.Left = this.Right = this.Parent = null;
this.IsBlack = false;
this.IsLeftChild = false;
}
public void PrintPretty(string indent, bool last, string message)
{
if (message != null)
{
Console.WriteLine(message);
}
Console.Write(indent);
if (last)
{
if (this.IsLeftChild)
{
Console.Write("/-");
}
else
{
Console.Write("\\-");
}
indent += " ";
}
else
{
Console.Write("|-");
indent += "| ";
}
if (this.IsBlack)
{
Console.ForegroundColor = ConsoleColor.Blue;
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
}
Console.WriteLine(this.Value.ToString());
Console.ForegroundColor = ConsoleColor.Gray;
this.Left?.PrintPretty(indent, this.Right == null, null);
this.Right?.PrintPretty(indent, true, null);
}
}
}
} | 26.667401 | 91 | 0.407285 | [
"MIT"
] | pirocorp/Data-Structures-with-CSharp | 06. B-TREES AND RED-BLACK TREES/Demos/01. RedBlackTree/RedBlackTree.cs | 12,109 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace NetCoreAzureAD
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 25.777778 | 70 | 0.646552 | [
"MIT"
] | JimXu199545/NetCoreWeb | NetCoreAzureAD/Program.cs | 696 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110
{
using Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.PowerShell;
/// <summary>
/// A PowerShell PSTypeConverter to support converting to an instance of <see cref="EventQueryParameter" />
/// </summary>
public partial class EventQueryParameterTypeConverter : global::System.Management.Automation.PSTypeConverter
{
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>.
/// </returns>
public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue);
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="EventQueryParameter"
/// /> type.</param>
/// <returns>
/// <c>true</c> if the instance could be converted to a <see cref="EventQueryParameter" /> type, otherwise <c>false</c>
/// </returns>
public static bool CanConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return true;
}
global::System.Type type = sourceValue.GetType();
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
// we say yest to PSObjects
return true;
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
// we say yest to Hashtables/dictionaries
return true;
}
try
{
if (null != sourceValue.ToJsonString())
{
return true;
}
}
catch
{
// Not one of our objects
}
try
{
string text = sourceValue.ToString()?.Trim();
return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonType.Object;
}
catch
{
// Doesn't look like it can be treated as JSON
}
return false;
}
/// <summary>
/// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>
/// </returns>
public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false;
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>
/// an instance of <see cref="EventQueryParameter" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue);
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the value to convert into an instance of <see cref="EventQueryParameter" />.</param>
/// <returns>
/// an instance of <see cref="EventQueryParameter" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IEventQueryParameter ConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return null;
}
global::System.Type type = sourceValue.GetType();
if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IEventQueryParameter).IsAssignableFrom(type))
{
return sourceValue;
}
try
{
return EventQueryParameter.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());;
}
catch
{
// Unable to use JSON pattern
}
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
return EventQueryParameter.DeserializeFromPSObject(sourceValue);
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
return EventQueryParameter.DeserializeFromDictionary(sourceValue);
}
return null;
}
/// <summary>NotImplemented -- this will return <c>null</c></summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>will always return <c>null</c>.</returns>
public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null;
}
} | 51.577465 | 245 | 0.583697 | [
"MIT"
] | 3quanfeng/azure-powershell | src/Migrate/generated/api/Models/Api20180110/EventQueryParameter.TypeConverter.cs | 7,183 | C# |
using System;
using EShopOnAbp.PaymentService.PaymentRequests;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.PostgreSql;
using Volo.Abp.Modularity;
namespace EShopOnAbp.PaymentService.EntityFrameworkCore
{
[DependsOn(
typeof(PaymentServiceDomainModule),
typeof(AbpEntityFrameworkCorePostgreSqlModule)
)]
public class PaymentServiceEntityFrameworkCoreModule : AbpModule
{
public override void PreConfigureServices(ServiceConfigurationContext context)
{
PaymentServiceEfCoreEntityExtensionMappings.Configure();
}
public override void ConfigureServices(ServiceConfigurationContext context)
{
context.Services.AddAbpDbContext<PaymentServiceDbContext>(options =>
{
options.AddRepository<PaymentRequest, EfCorePaymentRequestRepository>();
});
// https://www.npgsql.org/efcore/release-notes/6.0.html#opting-out-of-the-new-timestamp-mapping-logic
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
Configure<AbpDbContextOptions>(options =>
{
/* The main point to change your DBMS.
* See also PaymentServiceMigrationsDbContextFactory for EF Core tooling. */
options.UseNpgsql(b =>
{
b.MigrationsHistoryTable("__PaymentService_Migrations");
});
});
}
}
}
| 36.116279 | 113 | 0.666452 | [
"MIT"
] | 271943794/eShopOnAbp | services/payment/src/EShopOnAbp.PaymentService.EntityFrameworkCore/EntityFrameworkCore/PaymentServiceEntityFrameworkCoreModule.cs | 1,555 | C# |
namespace MassTransit.AzureStorage.MessageData
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Identity;
using Azure.Storage;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Blobs.Specialized;
public class AzureStorageMessageDataRepository :
IMessageDataRepository,
IBusObserver
{
readonly BlobContainerClient _container;
readonly IBlobNameGenerator _nameGenerator;
public AzureStorageMessageDataRepository(string connectionString, string containerName)
: this(new BlobServiceClient(connectionString), containerName)
{
}
public AzureStorageMessageDataRepository(Uri serviceUri, string containerName, string accountName, string accountKey)
: this(new BlobServiceClient(serviceUri, new StorageSharedKeyCredential(accountName, accountKey)), containerName)
{
}
public AzureStorageMessageDataRepository(Uri serviceUri, string containerName, string signature)
: this(new BlobServiceClient(serviceUri, new AzureSasCredential(signature)), containerName)
{
}
public AzureStorageMessageDataRepository(Uri serviceUri, string containerName, string tenantId, string clientId, string clientSecret)
: this(new BlobServiceClient(serviceUri, new ClientSecretCredential(tenantId, clientId, clientSecret)), containerName)
{
}
public AzureStorageMessageDataRepository(BlobServiceClient client, string containerName)
: this(client, containerName, new NewIdBlobNameGenerator())
{
}
public AzureStorageMessageDataRepository(BlobServiceClient client, string containerName, IBlobNameGenerator nameGenerator)
{
_container = client.GetBlobContainerClient(containerName);
_nameGenerator = nameGenerator;
}
public void PostCreate(IBus bus)
{
}
public void CreateFaulted(Exception exception)
{
}
public async Task PreStart(IBus bus)
{
try
{
Response<bool> containerExists = await _container.ExistsAsync().ConfigureAwait(false);
if (!containerExists)
{
try
{
await _container.CreateIfNotExistsAsync().ConfigureAwait(false);
}
catch (RequestFailedException exception)
{
LogContext.Warning?.Log(exception, "Azure Storage Container does not exist: {Address}", _container.Uri);
}
}
}
catch (Exception exception)
{
LogContext.Error?.Log(exception, "Azure Storage failure.");
}
}
public Task PostStart(IBus bus, Task<BusReady> busReady)
{
return Task.CompletedTask;
}
public Task StartFaulted(IBus bus, Exception exception)
{
return Task.CompletedTask;
}
public Task PreStop(IBus bus)
{
return Task.CompletedTask;
}
public Task PostStop(IBus bus)
{
return Task.CompletedTask;
}
public Task StopFaulted(IBus bus, Exception exception)
{
return Task.CompletedTask;
}
public async Task<Stream> Get(Uri address, CancellationToken cancellationToken = default)
{
var blobName = new BlobUriBuilder(address).BlobName;
var blob = _container.GetBlobClient(blobName);
try
{
LogContext.Debug?.Log("GET Message Data: {Address} ({Blob})", address, blob.Name);
return await blob.OpenReadAsync(new BlobOpenReadOptions(false), cancellationToken).ConfigureAwait(false);
}
catch (RequestFailedException exception)
{
throw new MessageDataException($"MessageData content not found: {blob.BlobContainerName}/{blob.Name}", exception);
}
}
public async Task<Uri> Put(Stream stream, TimeSpan? timeToLive = default, CancellationToken cancellationToken = default)
{
var blobName = _nameGenerator.GenerateBlobName();
var blob = _container.GetBlobClient(blobName);
await blob.UploadAsync(stream, cancellationToken).ConfigureAwait(false);
await SetBlobExpiration(blob, timeToLive).ConfigureAwait(false);
LogContext.Debug?.Log("PUT Message Data: {Address} ({Blob})", blob.Uri, blob.Name);
return blob.Uri;
}
static async Task SetBlobExpiration(BlobBaseClient blob, TimeSpan? timeToLive)
{
if (timeToLive.HasValue)
{
var utcNow = DateTime.UtcNow;
var expirationDate = utcNow + timeToLive.Value;
if (expirationDate <= utcNow)
expirationDate = utcNow + TimeSpan.FromMinutes(1);
var metadata = new Dictionary<string, string> { { "ValidUntilUtc", expirationDate.ToString("O") } };
await blob.SetMetadataAsync(metadata).ConfigureAwait(false);
}
}
}
}
| 34.903846 | 141 | 0.612121 | [
"ECL-2.0",
"Apache-2.0"
] | AlexanderMeier/MassTransit | src/Persistence/MassTransit.Azure.Storage/AzureStorage/MessageData/AzureStorageMessageDataRepository.cs | 5,445 | C# |
namespace NrsLib.ClassFileGenerator.Core.Templates {
public enum Language {
CSharp,
Typescript
}
}
| 18.571429 | 54 | 0.615385 | [
"Apache-2.0"
] | nrslib/ClassFileGeneratorCSharp | NrsLib.ClassFileGenerator/Core/Templates/Language.cs | 132 | C# |
using DbFacade.DataLayer.Models;
using DbFacadeUnitTests.TestFacade;
using System;
using System.Collections.Generic;
using System.Net.Mail;
using System.Threading.Tasks;
namespace DbFacadeUnitTests.Models
{
public enum FetchDataEnum
{
Fail = 0,
Pass = 1,
}
internal class FetchData : DbDataModel
{
public FetchDataEnum MyEnum { get; internal set; }
public string MyString { get; internal set; }
public string MyChar { get; internal set; }
public int Integer { get; internal set; }
public int? IntegerOptional { get; internal set; }
public int? IntegerOptionalNull { get; internal set; }
public Guid PublicKey { get; internal set; }
public byte MyByte { get; internal set; }
public int MyByteAsInt { get; internal set; }
protected override void Init()
{
bool isAltCall = IsDbCommand(UnitTestConnection.TestFetchDataAlt);
MyEnum = GetColumn<FetchDataEnum>(isAltCall ? "MyEnumAlt" : "MyEnum");
MyString = GetColumn<string>(isAltCall ? "MyStringAlt" : "MyString");
MyChar = GetColumn<string>(isAltCall ? "MyCharAlt" : "MyChar");
Integer = GetColumn<int>(isAltCall ? "IntegerAlt" : "Integer");
IntegerOptional = GetColumn<int?>(isAltCall ? "IntegerOptionalAlt" : "IntegerOptional");
IntegerOptionalNull = GetColumn<int?>(isAltCall ? "IntegerOptionalAlt" : "IntegerOptional");
PublicKey = GetColumn<Guid>(isAltCall ? "PublicKeyAlt" : "PublicKey");
MyByte = GetColumn<byte>(isAltCall ? "MyByteAlt" : "MyByte");
MyByteAsInt = GetColumn<int>(isAltCall ? "MyByteAlt" : "MyByte");
}
protected override async Task InitAsync()
{
bool isAltCall = await IsDbCommandAsync(UnitTestConnection.TestFetchDataAlt);
MyEnum = await GetColumnAsync<FetchDataEnum>(isAltCall ? "MyEnumAlt" : "MyEnum");
MyString = await GetColumnAsync<string>(isAltCall ? "MyStringAlt" : "MyString");
Integer = await GetColumnAsync<int>(isAltCall ? "IntegerAlt" : "Integer");
IntegerOptional = await GetColumnAsync<int?>(isAltCall ? "IntegerOptionalAlt" : "IntegerOptional");
IntegerOptionalNull = await GetColumnAsync<int?>(isAltCall ? "IntegerOptionalAlt" : "IntegerOptional");
PublicKey = await GetColumnAsync<Guid>(isAltCall ? "PublicKeyAlt" : "PublicKey");
MyByte = await GetColumnAsync<byte>(isAltCall ? "MyByteAlt" : "MyByte");
MyByteAsInt = await GetColumnAsync<int>(isAltCall ? "MyByteAlt" : "MyByte");
}
}
internal class FetchDataWithBadDbColumn : FetchData
{
protected override void Init()
{
MyString = GetColumn<string>("BadMyString");
Integer = GetColumn<int>("BadInteger");
IntegerOptional = GetColumn<int?>("BadIntegerOptional");
IntegerOptionalNull = GetColumn<int?>("BadIntegerOptional");
PublicKey = GetColumn<Guid>("BadPublicKey");
MyByte = GetColumn<byte>("BadMyByte");
MyByteAsInt = GetColumn<int>("BadMyByte");
}
protected override async Task InitAsync()
{
MyString = await GetColumnAsync<string>("BadMyString");
Integer = await GetColumnAsync<int>("BadInteger");
IntegerOptional = await GetColumnAsync<int?>("BadIntegerOptional");
IntegerOptionalNull = await GetColumnAsync<int?>("BadIntegerOptional");
PublicKey = await GetColumnAsync<Guid>("BadPublicKey");
MyByte = await GetColumnAsync<byte>("BadMyByte");
MyByteAsInt = await GetColumnAsync<int>("BadMyByte");
}
}
internal class FetchDataWithNested : DbDataModel
{
public FetchDataEnumerable EnumerableData { get; internal set; }
public FetchDataDates DateData { get; internal set; }
public FetchDataEmail EmailData { get; internal set; }
public FetchDataFlags FlagData { get; internal set; }
protected override void Init()
{
EnumerableData = CreateNestedModel<FetchDataEnumerable>();
DateData = CreateNestedModel<FetchDataDates>();
EmailData = CreateNestedModel<FetchDataEmail>();
FlagData = CreateNestedModel<FetchDataFlags>();
}
protected override async Task InitAsync()
{
EnumerableData = await CreateNestedModelAsync<FetchDataEnumerable>();
DateData = await CreateNestedModelAsync<FetchDataDates>();
EmailData = await CreateNestedModelAsync<FetchDataEmail>();
FlagData = await CreateNestedModelAsync<FetchDataFlags>();
}
}
internal class FetchDataEnumerable : DbDataModel
{
public IEnumerable<string> Data { get; internal set; }
public IEnumerable<short> ShortData { get; internal set; }
public IEnumerable<int> IntData { get; internal set; }
public IEnumerable<long> LongData { get; internal set; }
public IEnumerable<double> DoubleData { get; internal set; }
public IEnumerable<float> FloatData { get; internal set; }
public IEnumerable<decimal> DecimalData { get; internal set; }
public IEnumerable<string> DataCustom { get; internal set; }
protected override void Init()
{
Data = GetEnumerableColumn<string>("EnumerableData");
ShortData = GetEnumerableColumn<short>("EnumerableData");
IntData = GetEnumerableColumn<int>("EnumerableData");
LongData = GetEnumerableColumn<long>("EnumerableData");
DoubleData = GetEnumerableColumn<double>("EnumerableData");
FloatData = GetEnumerableColumn<float>("EnumerableData");
DecimalData = GetEnumerableColumn<decimal>("EnumerableData");
DataCustom = GetEnumerableColumn<string>("EnumerableDataCustom",";");
}
protected override async Task InitAsync()
{
Data = await GetEnumerableColumnAsync<string>("EnumerableData");
ShortData = await GetEnumerableColumnAsync<short>("EnumerableData");
IntData = await GetEnumerableColumnAsync<int>("EnumerableData");
LongData = await GetEnumerableColumnAsync<long>("EnumerableData");
DoubleData = await GetEnumerableColumnAsync<double>("EnumerableData");
FloatData = await GetEnumerableColumnAsync<float>("EnumerableData");
DecimalData = await GetEnumerableColumnAsync<decimal>("EnumerableData");
DataCustom = await GetEnumerableColumnAsync<string>("EnumerableDataCustom", ";");
}
}
internal class FetchDataDates : DbDataModel
{
public DateTime? DateTimeFromString { get; internal set; }
public string FormattedDate { get; internal set; }
protected override void Init()
{
DateTimeFromString = GetDateTimeColumn("DateString", "MM/dd/yyyy");
FormattedDate = GetFormattedDateTimeStringColumn("Date", "MM/dd/yyyy");
}
protected override async Task InitAsync()
{
DateTimeFromString = await GetDateTimeColumnAsync("DateString", "MM/dd/yyyy");
FormattedDate = await GetFormattedDateTimeStringColumnAsync("Date", "MM/dd/yyyy");
}
}
internal class FetchDataEmail : DbDataModel
{
public MailAddress Email { get; internal set; }
public IEnumerable<MailAddress> EmailList { get; internal set; }
protected override void Init()
{
Email = GetColumn<MailAddress>("Email");
EmailList = GetEnumerableColumn<MailAddress>("EmailList");
}
protected override async Task InitAsync()
{
Email = await GetColumnAsync<MailAddress>("Email");
EmailList = await GetEnumerableColumnAsync<MailAddress>("EmailList");
}
}
internal class FetchDataFlags : DbDataModel
{
public bool Flag { get; internal set; }
public bool FlagInt { get; internal set; }
public bool FlagFalse { get; internal set; }
public bool FlagIntFalse { get; internal set; }
protected override void Init()
{
Flag = GetFlagColumn("Flag", "TRUE");
FlagInt = GetFlagColumn("FlagInt", 1);
FlagFalse = GetFlagColumn("FlagFalse", "TRUE");
FlagIntFalse = GetFlagColumn("FlagIntFalse", 1);
}
protected override async Task InitAsync()
{
Flag = await GetFlagColumnAsync("Flag", "TRUE");
FlagInt = await GetFlagColumnAsync("FlagInt", 1);
FlagFalse = await GetFlagColumnAsync("FlagFalse", "TRUE");
FlagIntFalse = await GetFlagColumnAsync("FlagIntFalse", 1);
}
}
}
| 47.59893 | 115 | 0.636782 | [
"MIT"
] | JSystemsTech/DBFacade.Net | DbFacadeUnitTest.Shared/Models/FetchData.cs | 8,903 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using tourseek_backend.domain;
namespace tourseek_backend.domain.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20210901112345_initial migration")]
partial class initialmigration
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasPostgresExtension("postgis")
.HasAnnotation("Relational:MaxIdentifierLength", 63)
.HasAnnotation("ProductVersion", "5.0.9")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.DeviceFlowCodes", b =>
{
b.Property<string>("UserCode")
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<string>("ClientId")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<DateTime>("CreationTime")
.HasColumnType("timestamp without time zone");
b.Property<string>("Data")
.IsRequired()
.HasMaxLength(50000)
.HasColumnType("character varying(50000)");
b.Property<string>("Description")
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<string>("DeviceCode")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<DateTime?>("Expiration")
.IsRequired()
.HasColumnType("timestamp without time zone");
b.Property<string>("SessionId")
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<string>("SubjectId")
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.HasKey("UserCode");
b.HasIndex("DeviceCode")
.IsUnique();
b.HasIndex("Expiration");
b.ToTable("DeviceCodes");
});
modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.PersistedGrant", b =>
{
b.Property<string>("Key")
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<string>("ClientId")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<DateTime?>("ConsumedTime")
.HasColumnType("timestamp without time zone");
b.Property<DateTime>("CreationTime")
.HasColumnType("timestamp without time zone");
b.Property<string>("Data")
.IsRequired()
.HasMaxLength(50000)
.HasColumnType("character varying(50000)");
b.Property<string>("Description")
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<DateTime?>("Expiration")
.HasColumnType("timestamp without time zone");
b.Property<string>("SessionId")
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<string>("SubjectId")
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<string>("Type")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.HasKey("Key");
b.HasIndex("Expiration");
b.HasIndex("SubjectId", "ClientId", "Type");
b.HasIndex("SubjectId", "SessionId", "Type");
b.ToTable("PersistedGrants");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Discriminator")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("AspNetRoles");
b.HasDiscriminator<string>("Discriminator").HasValue("IdentityRole");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<string>("ProviderKey")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<string>("ProviderDisplayName")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("RoleId")
.HasColumnType("text");
b.Property<string>("Discriminator")
.IsRequired()
.HasColumnType("text");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
b.HasDiscriminator<string>("Discriminator").HasValue("IdentityUserRole<string>");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("LoginProvider")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<string>("Name")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<string>("Value")
.HasColumnType("text");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("tourseek_backend.domain.Entities.ApplicationUser", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("AccessFailedCount")
.HasColumnType("integer");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("CreatedBy")
.HasColumnType("text");
b.Property<DateTime>("CreatedOn")
.HasColumnType("timestamp without time zone");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("boolean");
b.Property<bool>("LockoutEnabled")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("timestamp with time zone");
b.Property<string>("ModifiedBy")
.HasColumnType("text");
b.Property<DateTime>("ModifiedOn")
.HasColumnType("timestamp without time zone");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.HasColumnType("text");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("boolean");
b.Property<string>("SecurityStamp")
.HasColumnType("text");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("boolean");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("tourseek_backend.domain.Entities.ApplicationRole", b =>
{
b.HasBaseType("Microsoft.AspNetCore.Identity.IdentityRole");
b.Property<string>("CreatedBy")
.HasColumnType("text");
b.Property<DateTime>("CreatedOn")
.HasColumnType("timestamp without time zone");
b.Property<string>("ModifiedBy")
.HasColumnType("text");
b.Property<DateTime>("ModifiedOn")
.HasColumnType("timestamp without time zone");
b.HasDiscriminator().HasValue("ApplicationRole");
});
modelBuilder.Entity("tourseek_backend.domain.Entities.ApplicationUserRole", b =>
{
b.HasBaseType("Microsoft.AspNetCore.Identity.IdentityUserRole<string>");
b.Property<string>("CreatedBy")
.HasColumnType("text");
b.Property<DateTime>("CreatedOn")
.HasColumnType("timestamp without time zone");
b.Property<string>("ModifiedBy")
.HasColumnType("text");
b.Property<DateTime>("ModifiedOn")
.HasColumnType("timestamp without time zone");
b.HasDiscriminator().HasValue("ApplicationUserRole");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("tourseek_backend.domain.Entities.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("tourseek_backend.domain.Entities.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("tourseek_backend.domain.Entities.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("tourseek_backend.domain.Entities.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 37.943439 | 128 | 0.468249 | [
"MIT"
] | Sasa94s/tourseek | tourseek_backend.domain/Migrations/20210901112345_initial migration.Designer.cs | 16,773 | C# |
using Microsoft.WindowsAzure.Storage.Table;
namespace EtherData.Data.Entities
{
public class PublicKeyEntity : TableEntity
{
}
}
| 15.888889 | 46 | 0.734266 | [
"MIT"
] | aquiladev/etherdata | EtherData.Data/Entities/PublicKeyEntity.cs | 145 | C# |
using System;
using System.ComponentModel;
using System.Data.Linq;
using System.Linq;
using System.Data.Linq.Mapping;
using System.Data.SqlClient;
using System.Data;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Reflection;
using Dg.Deblazer;
using Dg.Deblazer.Validation;
using Dg.Deblazer.CodeAnnotation;
using Dg.Deblazer.Api;
using Dg.Deblazer.Visitors;
using Dg.Deblazer.Cache;
using Dg.Deblazer.SqlGeneration;
using Deblazer.WideWorldImporter.DbLayer.Queries;
using Deblazer.WideWorldImporter.DbLayer.Wrappers;
using Dg.Deblazer.Read;
namespace Deblazer.WideWorldImporter.DbLayer
{
public partial class Warehouse_ColdRoomTemperature : DbEntity, ILongId
{
private DbValue<System.Int64> _ColdRoomTemperatureID = new DbValue<System.Int64>();
private DbValue<System.Int32> _ColdRoomSensorNumber = new DbValue<System.Int32>();
private DbValue<System.DateTime> _RecordedWhen = new DbValue<System.DateTime>();
private DbValue<System.Decimal> _Temperature = new DbValue<System.Decimal>();
private DbValue<System.DateTime> _ValidFrom = new DbValue<System.DateTime>();
private DbValue<System.DateTime> _ValidTo = new DbValue<System.DateTime>();
long ILongId.Id => ColdRoomTemperatureID;
[Validate]
public System.Int64 ColdRoomTemperatureID
{
get
{
return _ColdRoomTemperatureID.Entity;
}
set
{
_ColdRoomTemperatureID.Entity = value;
}
}
[Validate]
public System.Int32 ColdRoomSensorNumber
{
get
{
return _ColdRoomSensorNumber.Entity;
}
set
{
_ColdRoomSensorNumber.Entity = value;
}
}
[StringColumn(7, false)]
[Validate]
public System.DateTime RecordedWhen
{
get
{
return _RecordedWhen.Entity;
}
set
{
_RecordedWhen.Entity = value;
}
}
[Validate]
public System.Decimal Temperature
{
get
{
return _Temperature.Entity;
}
set
{
_Temperature.Entity = value;
}
}
[StringColumn(7, false)]
[Validate]
public System.DateTime ValidFrom
{
get
{
return _ValidFrom.Entity;
}
set
{
_ValidFrom.Entity = value;
}
}
[StringColumn(7, false)]
[Validate]
public System.DateTime ValidTo
{
get
{
return _ValidTo.Entity;
}
set
{
_ValidTo.Entity = value;
}
}
protected override void ModifyInternalState(FillVisitor visitor)
{
SendIdChanging();
_ColdRoomTemperatureID.Load(visitor.GetValue<System.Int64>());
SendIdChanged();
_ColdRoomSensorNumber.Load(visitor.GetInt32());
_RecordedWhen.Load(visitor.GetDateTime());
_Temperature.Load(visitor.GetDecimal());
_ValidFrom.Load(visitor.GetDateTime());
_ValidTo.Load(visitor.GetDateTime());
this._db = visitor.Db;
isLoaded = true;
}
protected sealed override void CheckProperties(IUpdateVisitor visitor)
{
_ColdRoomSensorNumber.Welcome(visitor, "ColdRoomSensorNumber", "Int NOT NULL", false);
_RecordedWhen.Welcome(visitor, "RecordedWhen", "DateTime2(7) NOT NULL", false);
_Temperature.Welcome(visitor, "Temperature", "Decimal(10,2) NOT NULL", false);
_ValidFrom.Welcome(visitor, "ValidFrom", "DateTime2(7) NOT NULL", false);
_ValidTo.Welcome(visitor, "ValidTo", "DateTime2(7) NOT NULL", false);
}
protected override void HandleChildren(DbEntityVisitorBase visitor)
{
}
}
public static class Db_Warehouse_ColdRoomTemperatureQueryGetterExtensions
{
public static Warehouse_ColdRoomTemperatureTableQuery<Warehouse_ColdRoomTemperature> Warehouse_ColdRoomTemperatures(this IDb db)
{
var query = new Warehouse_ColdRoomTemperatureTableQuery<Warehouse_ColdRoomTemperature>(db as IDb);
return query;
}
}
}
namespace Deblazer.WideWorldImporter.DbLayer.Queries
{
public class Warehouse_ColdRoomTemperatureQuery<K, T> : Query<K, T, Warehouse_ColdRoomTemperature, Warehouse_ColdRoomTemperatureWrapper, Warehouse_ColdRoomTemperatureQuery<K, T>> where K : QueryBase where T : DbEntity, ILongId
{
public Warehouse_ColdRoomTemperatureQuery(IDb db): base (db)
{
}
protected sealed override Warehouse_ColdRoomTemperatureWrapper GetWrapper()
{
return Warehouse_ColdRoomTemperatureWrapper.Instance;
}
}
public class Warehouse_ColdRoomTemperatureTableQuery<T> : Warehouse_ColdRoomTemperatureQuery<Warehouse_ColdRoomTemperatureTableQuery<T>, T> where T : DbEntity, ILongId
{
public Warehouse_ColdRoomTemperatureTableQuery(IDb db): base (db)
{
}
}
}
namespace Deblazer.WideWorldImporter.DbLayer.Helpers
{
public class Warehouse_ColdRoomTemperatureHelper : QueryHelper<Warehouse_ColdRoomTemperature>, IHelper<Warehouse_ColdRoomTemperature>
{
string[] columnsInSelectStatement = new[]{"{0}.ColdRoomTemperatureID", "{0}.ColdRoomSensorNumber", "{0}.RecordedWhen", "{0}.Temperature", "{0}.ValidFrom", "{0}.ValidTo"};
public sealed override string[] ColumnsInSelectStatement => columnsInSelectStatement;
string[] columnsInInsertStatement = new[]{"{0}.ColdRoomSensorNumber", "{0}.RecordedWhen", "{0}.Temperature", "{0}.ValidFrom", "{0}.ValidTo"};
public sealed override string[] ColumnsInInsertStatement => columnsInInsertStatement;
private static readonly string createTempTableCommand = "CREATE TABLE #Warehouse_ColdRoomTemperature ([ColdRoomSensorNumber] Int NOT NULL,[RecordedWhen] DateTime2(7) NOT NULL,[Temperature] Decimal(10,2) NOT NULL,[ValidFrom] DateTime2(7) NOT NULL,[ValidTo] DateTime2(7) NOT NULL, [RowIndexForSqlBulkCopy] INT NOT NULL)";
public sealed override string CreateTempTableCommand => createTempTableCommand;
public sealed override string FullTableName => "[Warehouse].[ColdRoomTemperatures]";
public sealed override bool IsForeignKeyTo(Type other)
{
return false;
}
private const string insertCommand = "INSERT INTO [Warehouse].[ColdRoomTemperatures] ([{TableName = \"Warehouse].[ColdRoomTemperatures\";}].[ColdRoomSensorNumber], [{TableName = \"Warehouse].[ColdRoomTemperatures\";}].[RecordedWhen], [{TableName = \"Warehouse].[ColdRoomTemperatures\";}].[Temperature], [{TableName = \"Warehouse].[ColdRoomTemperatures\";}].[ValidFrom], [{TableName = \"Warehouse].[ColdRoomTemperatures\";}].[ValidTo]) VALUES ([@ColdRoomSensorNumber],[@RecordedWhen],[@Temperature],[@ValidFrom],[@ValidTo]); SELECT SCOPE_IDENTITY()";
public sealed override void FillInsertCommand(SqlCommand sqlCommand, Warehouse_ColdRoomTemperature _Warehouse_ColdRoomTemperature)
{
sqlCommand.CommandText = insertCommand;
sqlCommand.Parameters.AddWithValue("@ColdRoomSensorNumber", _Warehouse_ColdRoomTemperature.ColdRoomSensorNumber);
sqlCommand.Parameters.AddWithValue("@RecordedWhen", _Warehouse_ColdRoomTemperature.RecordedWhen);
sqlCommand.Parameters.AddWithValue("@Temperature", _Warehouse_ColdRoomTemperature.Temperature);
sqlCommand.Parameters.AddWithValue("@ValidFrom", _Warehouse_ColdRoomTemperature.ValidFrom);
sqlCommand.Parameters.AddWithValue("@ValidTo", _Warehouse_ColdRoomTemperature.ValidTo);
}
public sealed override void ExecuteInsertCommand(SqlCommand sqlCommand, Warehouse_ColdRoomTemperature _Warehouse_ColdRoomTemperature)
{
using (var sqlDataReader = sqlCommand.ExecuteReader(CommandBehavior.SequentialAccess))
{
sqlDataReader.Read();
_Warehouse_ColdRoomTemperature.ColdRoomTemperatureID = Convert.ToInt32(sqlDataReader.GetValue(0));
}
}
private static Warehouse_ColdRoomTemperatureWrapper _wrapper = Warehouse_ColdRoomTemperatureWrapper.Instance;
public QueryWrapper Wrapper
{
get
{
return _wrapper;
}
}
}
}
namespace Deblazer.WideWorldImporter.DbLayer.Wrappers
{
public class Warehouse_ColdRoomTemperatureWrapper : QueryLongWrapper<Warehouse_ColdRoomTemperature>
{
public readonly QueryElMemberStruct<System.Int32> ColdRoomSensorNumber = new QueryElMemberStruct<System.Int32>("ColdRoomSensorNumber");
public readonly QueryElMemberStruct<System.DateTime> RecordedWhen = new QueryElMemberStruct<System.DateTime>("RecordedWhen");
public readonly QueryElMemberStruct<System.Decimal> Temperature = new QueryElMemberStruct<System.Decimal>("Temperature");
public readonly QueryElMemberStruct<System.DateTime> ValidFrom = new QueryElMemberStruct<System.DateTime>("ValidFrom");
public readonly QueryElMemberStruct<System.DateTime> ValidTo = new QueryElMemberStruct<System.DateTime>("ValidTo");
public static readonly Warehouse_ColdRoomTemperatureWrapper Instance = new Warehouse_ColdRoomTemperatureWrapper();
private Warehouse_ColdRoomTemperatureWrapper(): base ("[Warehouse].[ColdRoomTemperatures]", "Warehouse_ColdRoomTemperature")
{
}
}
} | 41.045643 | 557 | 0.666195 | [
"MIT"
] | renezweifel/Deblazer.Artifacts | Deblazer.WideWorldImporter.DbLayer/Artifacts/Warehouse_ColdRoomTemperatures.Artifact.cs | 9,892 | C# |
/*
Copyright (C) 2020 Jean-Camille Tournier (mail@tournierjc.fr)
This file is part of QLCore Project https://github.com/OpenDerivatives/QLCore
QLCore is free software: you can redistribute it and/or modify it
under the terms of the QLCore and QLNet license. You should have received a
copy of the license along with this program; if not, license is
available at https://github.com/OpenDerivatives/QLCore/LICENSE.
QLCore is a forked of QLNet which is a based on QuantLib, a free-software/open-source
library for financial quantitative analysts and developers - http://quantlib.org/
The QuantLib license is available online at http://quantlib.org/license.shtml and the
QLNet license is available online at https://github.com/amaggiulli/QLNet/blob/develop/LICENSE.
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 PARTICAR PURPOSE. See the license for more details.
*/
using System;
using System.Collections.Generic;
using System.Linq;
namespace QLCore
{
//! Integral of a 1-dimensional function using the Gauss quadratures method
/*! References:
Gauss quadratures and orthogonal polynomials
G.H. Gloub and J.H. Welsch: Calculation of Gauss quadrature rule.
Math. Comput. 23 (1986), 221-230
"Numerical Recipes in C", 2nd edition,
Press, Teukolsky, Vetterling, Flannery,
\test the correctness of the result is tested by checking it
against known good values.
*/
public class GaussianQuadrature
{
public GaussianQuadrature(int n, GaussianOrthogonalPolynomial orthPoly)
{
x_ = new Vector(n);
w_ = new Vector(n);
// set-up matrix to compute the roots and the weights
Vector e = new Vector(n - 1);
int i;
for (i = 1; i < n; ++i)
{
x_[i] = orthPoly.alpha(i);
e[i - 1] = Math.Sqrt(orthPoly.beta(i));
}
x_[0] = orthPoly.alpha(0);
TqrEigenDecomposition tqr = new TqrEigenDecomposition(x_, e,
TqrEigenDecomposition.EigenVectorCalculation.OnlyFirstRowEigenVector,
TqrEigenDecomposition.ShiftStrategy.Overrelaxation);
x_ = tqr.eigenvalues();
Matrix ev = tqr.eigenvectors();
double mu_0 = orthPoly.mu_0();
for (i = 0; i < n; ++i)
{
w_[i] = mu_0 * ev[0, i] * ev[0, i] / orthPoly.w(x_[i]);
}
}
public double value(Func<double, double> f)
{
double sum = 0.0;
for (int i = order() - 1; i >= 0; --i)
{
sum += w_[i] * f(x_[i]);
}
return sum;
}
public int order() { return x_.size(); }
public Vector weights() { return w_; }
public Vector x() { return x_; }
private Vector x_, w_;
}
//! generalized Gauss-Laguerre integration
// This class performs a 1-dimensional Gauss-Laguerre integration.
public class GaussLaguerreIntegration : GaussianQuadrature
{
public GaussLaguerreIntegration(int n, double s = 0.0)
: base(n, new GaussLaguerrePolynomial(s)) {}
}
//! generalized Gauss-Hermite integration
// This class performs a 1-dimensional Gauss-Hermite integration.
public class GaussHermiteIntegration : GaussianQuadrature
{
public GaussHermiteIntegration(int n, double mu = 0.0)
: base(n, new GaussHermitePolynomial(mu)) {}
}
//! Gauss-Jacobi integration
// This class performs a 1-dimensional Gauss-Jacobi integration.
public class GaussJacobiIntegration : GaussianQuadrature
{
public GaussJacobiIntegration(int n, double alpha, double beta)
: base(n, new GaussJacobiPolynomial(alpha, beta)) {}
}
//! Gauss-Hyperbolic integration
// This class performs a 1-dimensional Gauss-Hyperbolic integration.
public class GaussHyperbolicIntegration : GaussianQuadrature
{
public GaussHyperbolicIntegration(int n)
: base(n, new GaussHyperbolicPolynomial()) {}
}
//! Gauss-Legendre integration
// This class performs a 1-dimensional Gauss-Legendre integration.
public class GaussLegendreIntegration : GaussianQuadrature
{
public GaussLegendreIntegration(int n)
: base(n, new GaussJacobiPolynomial(0.0, 0.0)) {}
}
//! Gauss-Chebyshev integration
// This class performs a 1-dimensional Gauss-Chebyshev integration.
public class GaussChebyshevIntegration : GaussianQuadrature
{
public GaussChebyshevIntegration(int n)
: base(n, new GaussJacobiPolynomial(-0.5, -0.5)) {}
}
//! Gauss-Chebyshev integration (second kind)
// This class performs a 1-dimensional Gauss-Chebyshev integration.
public class GaussChebyshev2ndIntegration : GaussianQuadrature
{
public GaussChebyshev2ndIntegration(int n)
: base(n, new GaussJacobiPolynomial(0.5, 0.5)) {}
}
//! Gauss-Gegenbauer integration
// This class performs a 1-dimensional Gauss-Gegenbauer integration.
public class GaussGegenbauerIntegration : GaussianQuadrature
{
public GaussGegenbauerIntegration(int n, double lambda)
: base(n, new GaussJacobiPolynomial(lambda - 0.5, lambda - 0.5)) {}
}
//! tabulated Gauss-Legendre quadratures
public class TabulatedGaussLegendre
{
public TabulatedGaussLegendre(int n = 20) { order(n); }
public double value(Func<double, double> f)
{
Utils.QL_REQUIRE(w_ != null, () => "Null weights");
Utils.QL_REQUIRE(x_ != null, () => "Null abscissas");
int startIdx;
double val;
int isOrderOdd = order_ & 1;
if (isOrderOdd > 0)
{
Utils.QL_REQUIRE((n_ > 0), () => "assume at least 1 point in quadrature");
val = w_[0] * f(x_[0]);
startIdx = 1;
}
else
{
val = 0.0;
startIdx = 0;
}
for (int i = startIdx; i < n_; ++i)
{
val += w_[i] * f(x_[i]);
val += w_[i] * f(-x_[i]);
}
return val;
}
public void order(int order)
{
switch (order)
{
case (6):
order_ = order; x_ = x6.ToList(); w_ = w6.ToList(); n_ = n6;
break;
case (7):
order_ = order; x_ = x7.ToList(); w_ = w7.ToList(); n_ = n7;
break;
case (12):
order_ = order; x_ = x12.ToList(); w_ = w12.ToList(); n_ = n12;
break;
case (20):
order_ = order; x_ = x20.ToList(); w_ = w20.ToList(); n_ = n20;
break;
default:
Utils.QL_FAIL("order " + order + " not supported");
break;
}
}
public int order() { return order_; }
private int order_;
private List<double> w_;
private List<double> x_;
private int n_;
private static double[] w6 = { 0.467913934572691, 0.360761573048139, 0.171324492379170 };
private static double[] x6 = { 0.238619186083197, 0.661209386466265, 0.932469514203152 };
private static int n6 = 3;
private static double[] w7 = { 0.417959183673469, 0.381830050505119, 0.279705391489277, 0.129484966168870 };
private static double[] x7 = { 0.000000000000000, 0.405845151377397, 0.741531185599394, 0.949107912342759 };
private static int n7 = 4;
private static double[] w12 = { 0.249147045813403, 0.233492536538355, 0.203167426723066, 0.160078328543346,
0.106939325995318, 0.047175336386512
};
private static double[] x12 = { 0.125233408511469, 0.367831498998180, 0.587317954286617, 0.769902674194305,
0.904117256370475, 0.981560634246719
};
private static int n12 = 6;
private static double[] w20 = { 0.152753387130726, 0.149172986472604, 0.142096109318382, 0.131688638449177,
0.118194531961518, 0.101930119817240, 0.083276741576704, 0.062672048334109,
0.040601429800387, 0.017614007139152
};
private static double[] x20 = { 0.076526521133497, 0.227785851141645, 0.373706088715420, 0.510867001950827,
0.636053680726515, 0.746331906460151, 0.839116971822219, 0.912234428251326,
0.963971927277914, 0.993128599185095
};
private static int n20 = 10;
}
}
| 35.777328 | 132 | 0.598619 | [
"BSD-3-Clause"
] | OpenDerivatives/QLCore | QLCore/Math/Integrals/GaussianQuadratures.cs | 8,839 | C# |
using I8Beef.Ecobee.Protocol.Objects;
using System.Runtime.Serialization;
namespace I8Beef.Ecobee.Protocol.Functions
{
[DataContract]
[KnownType(typeof(DeleteVacationParams))]
public class DeleteVacationFunction : Function
{
public DeleteVacationFunction()
{
Params = new DeleteVacationParams();
}
/// <summary>
/// The function type name. See the type name in the function documentation.
/// </summary>
[DataMember(Name = "type")]
public override string Type { get { return "deleteVacation"; } set { } }
/// <summary>
/// A map of key=value pairs as the parameters to the function. See
/// individual function documentation for the properties.
/// </summary>
[DataMember(Name = "params")]
public override FunctionParams Params { get; set; }
}
[DataContract]
public class DeleteVacationParams : FunctionParams
{
/// <summary>
/// The vacation event name. It must be unique.
/// </summary>
[DataMember(Name = "name")]
public string Name { get; set; }
}
}
| 29.74359 | 84 | 0.606034 | [
"MIT"
] | k-rol/EcobeeLib | src/I8Beef.Ecobee/Protocol/Objects/Functions/DeleteVacationFunction.cs | 1,162 | C# |
using Robust.Shared.GameObjects;
namespace Content.Server.MachineLinking.Events
{
public sealed class SignalReceivedEvent : EntityEventArgs
{
public readonly string Port;
public readonly object? Value;
public SignalReceivedEvent(string port, object? value)
{
Port = port;
Value = value;
}
}
}
| 21.823529 | 62 | 0.630728 | [
"MIT"
] | Alainx277/space-station-14 | Content.Server/MachineLinking/Events/SignalReceivedEvent.cs | 371 | C# |
namespace SheepReaper.GameSaves.Klei
{
public class TemplateMember
{
public string Name { get; set; }
public TypeInfo Type { get; set; }
}
} | 21.125 | 42 | 0.615385 | [
"MIT"
] | SheepReaper/OniSaveParser | src/ParserLib.Klei/Model/TypeTemplates/TemplateMember.cs | 171 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ApiCatalogoJogos.Exceptions
{
public class JogoNaoCadastradoException : Exception
{
public JogoNaoCadastradoException()
: base("Este jogo não está cadastrado")
{
}
}
}
| 20.3125 | 55 | 0.683077 | [
"MIT"
] | pedrohorita/BCAvanade-ApiCatalogosJogos | ApiCatalogoJogos/ApiCatalogoJogos/Exceptions/JogoNaoCadastradoException.cs | 329 | C# |
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Api.Gax;
using Google.Cloud.Diagnostics.Common;
using Google.Cloud.Trace.V1;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using TraceProto = Google.Cloud.Trace.V1.Trace;
namespace Google.Cloud.Diagnostics.AspNetCore
{
/// <summary>
/// Uses the Google Cloud Trace Middleware.
/// Traces the time taken for all subsequent delegates to run. The time taken
/// and metadata will be sent to the Stackdriver Trace API. Also allows for more
/// finely grained manual tracing.
/// </summary>
///
/// <example>
/// <code>
/// public void ConfigureServices(IServiceCollection services)
/// {
/// string projectId = "[Google Cloud Platform project ID]";
/// services.AddGoogleTrace(projectId);
/// ...
/// }
/// </code>
/// </example>
///
/// <example>
/// <code>
/// public void Configure(IApplicationBuilder app)
/// {
/// // Use at the start of the request pipeline to ensure the entire
/// // request is traced.
/// app.UseGoogleTrace();
/// ...
/// }
/// </code>
/// </example>
///
/// <example>
/// <code>
/// public void SomeFunction(IManagedTracer tracer)
/// {
/// tracer.StartSpan(nameof(SomeFunction));
/// ...
/// // Do work.
/// ...
/// tracer.EndSpan();
/// }
/// </code>
/// </example>
///
/// <remarks>
/// Traces requests and reports them to Google Cloud Trace.
/// Docs: https://cloud.google.com/trace/docs/
/// </remarks>
public static class CloudTraceExtension
{
/// <summary>
/// Uses middleware that will trace time taken for all subsequent delegates to run.
/// The time taken and metadata will be sent to the Stackdriver Trace API. To be
/// used with <see cref="AddGoogleTrace"/>,
/// </summary>
public static void UseGoogleTrace(this IApplicationBuilder app)
{
GaxPreconditions.CheckNotNull(app, nameof(app));
app.UseMiddleware<CloudTraceMiddleware>();
}
/// <summary>
/// Adds the needed services for Google Cloud Tracing. Used with <see cref="UseGoogleTrace"/>.
/// </summary>
/// <param name="services">The service collection. Cannot be null.</param>
/// <param name="projectId">Optional if running on Google App Engine or Google Compute Engine.
/// The Google Cloud Platform project ID. If unspecified and running on GAE or GCE the project ID will be
/// detected from the platform.</param>
/// <param name="config">Optional trace configuration, if unset the default will be used.</param>
/// <param name="client">Optional Trace client, if unset the default will be used.</param>
/// <param name="traceFallbackPredicate">Optional function to trace requests. If the trace header is not set
/// then this function will be called to determine if a given request should be traced. This will
/// not override trace headers.</param>
public static void AddGoogleTrace(
this IServiceCollection services, string projectId = null,
TraceConfiguration config = null, TraceServiceClient client = null,
TraceDecisionPredicate traceFallbackPredicate = null)
{
GaxPreconditions.CheckNotNull(services, nameof(services));
client = client ?? TraceServiceClient.Create();
config = config ?? TraceConfiguration.Create();
traceFallbackPredicate = traceFallbackPredicate ?? TraceDecisionPredicate.Default;
projectId = CommonUtils.GetAndCheckProjectId(projectId);
var consumer = ConsumerFactory<TraceProto>.GetConsumer(
new GrpcTraceConsumer(client), MessageSizer<TraceProto>.GetSize, config.BufferOptions);
var tracerFactory = new ManagedTracerFactory(projectId, consumer,
RateLimitingTraceOptionsFactory.Create(config), TraceIdFactory.Create());
services.AddScoped(CreateTraceHeaderContext);
services.AddSingleton<IManagedTracerFactory>(tracerFactory);
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton(CreateManagedTracer);
services.AddSingleton(CreateTraceHeaderPropagatingHandler);
services.AddSingleton(traceFallbackPredicate);
}
/// <summary>
/// Creates an <see cref="TraceHeaderPropagatingHandler"/>.
/// </summary>
private static TraceHeaderPropagatingHandler CreateTraceHeaderPropagatingHandler(IServiceProvider provider)
{
var tracer = provider.GetServiceCheckNotNull<IManagedTracer>();
return new TraceHeaderPropagatingHandler(() => tracer);
}
/// <summary>
/// Creates an <see cref="TraceHeaderContext"/> based on the current <see cref="HttpContext"/>
/// and a <see cref="TraceDecisionPredicate"/>.
/// </summary>
internal static TraceHeaderContext CreateTraceHeaderContext(IServiceProvider provider)
{
var accessor = provider.GetServiceCheckNotNull<IHttpContextAccessor>();
var traceDecisionPredicate = provider.GetServiceCheckNotNull<TraceDecisionPredicate>();
string header = accessor.HttpContext?.Request?.Headers[TraceHeaderContext.TraceHeader];
Func<bool?> shouldTraceFunc = () =>
traceDecisionPredicate.ShouldTrace(accessor.HttpContext?.Request);
return TraceHeaderContext.FromHeader(header, shouldTraceFunc);
}
/// <summary>
/// Creates a singleton <see cref="IManagedTracer"/> that is a <see cref="DelegatingTracer"/>.
/// The <see cref="DelegatingTracer"/> will use an <see cref="IHttpContextAccessor"/> under the hood
/// to get the current tracer which is set by the <see cref="ContextTracerManager"/>.
/// </summary>
internal static IManagedTracer CreateManagedTracer(IServiceProvider provider)
{
var accessor = provider.GetServiceCheckNotNull<IHttpContextAccessor>();
return new DelegatingTracer(() => ContextTracerManager.GetCurrentTracer(accessor));
}
}
}
| 43.060976 | 117 | 0.64925 | [
"Apache-2.0"
] | Acidburn0zzz/google-cloud-dotnet | apis/Google.Cloud.Diagnostics.AspNetCore/Google.Cloud.Diagnostics.AspNetCore/Trace/CloudTraceExtension.cs | 7,064 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.17626
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Skypiea.WP8.Resources
{
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", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class AppResources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal AppResources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager
{
get
{
if (object.ReferenceEquals(resourceMan, null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Skypiea.WP8.Resources.AppResources", typeof(AppResources).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)]
public static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to LeftToRight.
/// </summary>
public static string ResourceFlowDirection
{
get
{
return ResourceManager.GetString("ResourceFlowDirection", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to us-EN.
/// </summary>
public static string ResourceLanguage
{
get
{
return ResourceManager.GetString("ResourceLanguage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to MY APPLICATION.
/// </summary>
public static string ApplicationTitle
{
get
{
return ResourceManager.GetString("ApplicationTitle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to button.
/// </summary>
public static string AppBarButtonText
{
get
{
return ResourceManager.GetString("AppBarButtonText", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to menu item.
/// </summary>
public static string AppBarMenuItemText
{
get
{
return ResourceManager.GetString("AppBarMenuItemText", resourceCulture);
}
}
}
}
| 34.140625 | 182 | 0.568879 | [
"MIT"
] | JaakkoLipsanen/Skypiea | Skypiea/Skypiea/Resources/AppResources.Designer.cs | 4,372 | C# |
using UnityEngine;
namespace Builder.MeshLoadIndicator
{
public class DCLBuilderMeshLoadIndicator : MonoBehaviour
{
[SerializeField] private Camera builderCamera = null;
public long loadingEntityId { set; get; }
private const float RELATIVE_SCALE_RATIO = 0.032f;
private void LateUpdate()
{
transform.LookAt(transform.position + builderCamera.transform.rotation * Vector3.forward,
builderCamera.transform.rotation * Vector3.up);
float dist = GetCameraPlaneDistance(builderCamera, transform.position);
transform.localScale = new Vector3(RELATIVE_SCALE_RATIO * dist, RELATIVE_SCALE_RATIO * dist, RELATIVE_SCALE_RATIO * dist);
}
private static float GetCameraPlaneDistance(Camera camera, Vector3 objectPosition)
{
Plane plane = new Plane(camera.transform.forward, camera.transform.position);
return plane.GetDistanceToPoint(objectPosition);
}
}
} | 36.035714 | 134 | 0.68781 | [
"Apache-2.0"
] | Timothyoung97/unity-renderer | unity-renderer/Assets/Builder/Scripts/MeshLoadIndicator/DCLBuilderMeshLoadIndicator.cs | 1,009 | 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("PhotoMSK.Data")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PhotoMSK.Data")]
[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("c1fc7ba8-6596-405c-805f-c1f677e1cd32")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.810811 | 84 | 0.744103 | [
"MIT"
] | MarkusMokler/photomsmsk-by | PhotoMSK/Core/PhotoMSK.Data/Properties/AssemblyInfo.cs | 1,402 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace SM.Common
{
public enum OptionImport
{
IsAddUpdate = 1,
IsOnlyUpdate = 2,
IsOnlyAdd = 3,
IsOnlyInactive = 4
}
}
| 15.666667 | 33 | 0.612766 | [
"Unlicense"
] | quocthuanth92/Distributor | Core/SM.Common/EnumMV.cs | 237 | 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 System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Avro.File
{
public interface IFileReader<T> : IDisposable
{
/// <summary>
/// Return the header for the input
/// file / stream
/// </summary>
/// <returns></returns>
Header GetHeader();
/// <summary>
/// Return the schema as read from
/// the input file / stream
/// </summary>
/// <returns></returns>
Schema GetSchema();
/// <summary>
/// Return the list of keys in the metadata
/// </summary>
/// <returns></returns>
ICollection<string> GetMetaKeys();
/// <summary>
/// Return an enumeration of the remaining entries in the file
/// </summary>
/// <returns></returns>
IEnumerable<T> NextEntries { get; }
/// <summary>
/// Read the next datum from the file.
/// </summary>
T Next();
/// <summary>
/// True if more entries remain in this file.
/// </summary>
bool HasNext();
/// <summary>
/// Return the byte value of a metadata property
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
byte[] GetMeta(string key);
/// <summary>
/// Return the long value of a metadata property
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
long GetMetaLong(string key);
/// <summary>
/// Return the string value of a metadata property
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
string GetMetaString(string key);
/// <summary>
/// Return true if past the next synchronization
/// point after a position
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
bool PastSync(long position);
/// <summary>
/// Return the last synchronization point before
/// our current position
/// </summary>
/// <returns></returns>
long PreviousSync();
/// <summary>
/// Move to a specific, known synchronization point,
/// one returned from IFileWriter.Sync() while writing
/// </summary>
/// <param name="position"></param>
void Seek(long position);
/// <summary>
/// Move to the next synchronization point
/// after a position
/// </summary>
/// <param name="position"></param>
void Sync(long position);
/// <summary>
/// Return the current position in the input
/// </summary>
/// <returns></returns>
long Tell();
}
}
| 30.316667 | 75 | 0.564871 | [
"Apache-2.0"
] | Adikteev/avro | lang/csharp/src/apache/main/File/IFileReader.cs | 3,640 | C# |
////////////////////////////////////////////////////////////////////////////////
//
// ADOBE SYSTEMS INCORPORATED
// Copyright 2006 Adobe Systems Incorporated
// All Rights Reserved.
//
// NOTICE: Adobe permits you to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////
using System;
namespace Flash.Swf.Tags
{
/// <summary> Stores the name and copyright information for a font.
///
/// </summary>
/// <author> Brian Deitte
/// </author>
public class DefineFontName:DefineTag
{
public DefineFontName():base(Flash.Swf.TagValues.stagDefineFontName)
{
}
public override void visit(Flash.Swf.TagHandler h)
{
h.defineFontName(this);
}
public override bool Equals(System.Object object_Renamed)
{
bool isEqual = false;
if (base.Equals(object_Renamed) && (object_Renamed is DefineFontName))
{
DefineFontName defineFontName = (DefineFontName) object_Renamed;
isEqual = (equals(font, defineFontName.font) && (equals(fontName, defineFontName.fontName)) && (equals(copyright, defineFontName.copyright)));
}
return isEqual;
}
public DefineFont font;
public String fontName;
public String copyright;
public override int GetHashCode()
{
return base.GetHashCode();
}
}
}
| 27.283019 | 147 | 0.599585 | [
"MIT"
] | Acidburn0zzz/flashdevelop | External/Archive/FlashDebugger/FlexSDK/SwfUtils/flash/swf/tags/DefineFontName.cs | 1,394 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.4016
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Engage.Dnn.Booking {
public partial class ModuleMessage {
/// <summary>
/// messageLabel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label messageLabel;
}
}
| 32.115385 | 85 | 0.467066 | [
"MIT"
] | EngageSoftware/Engage-Booking | Source/Controls/ModuleMessage.ascx.designer.cs | 835 | C# |
using Anotar.NServiceBus;
// ReSharper disable UnusedTypeParameter
public class GenericClass<T>
{
public void Debug()
{
LogTo.Debug();
}
} | 16.8 | 41 | 0.630952 | [
"MIT"
] | Fody/Anotar | NServiceBus/AssemblyToProcess/GenericClass.cs | 168 | C# |
using Cosmos.Business.Extensions.Holiday.Core;
using Cosmos.I18N.Countries;
namespace Cosmos.Business.Extensions.Holiday.Definitions.SouthAmerica.Ecuador.Public
{
/// <summary>
/// New Year's Day
/// </summary>
public class NewYearsDay : BaseFixedHolidayFunc
{
/// <inheritdoc />
public override Country Country { get; } = Country.Ecuador;
/// <inheritdoc />
public override Country BelongsToCountry { get; } = Country.Ecuador;
/// <inheritdoc />
public override string Name { get; } = "Año Nuevo";
/// <inheritdoc />
public override HolidayType HolidayType { get; set; } = HolidayType.Public;
/// <inheritdoc />
public override int Month { get; set; } = 1;
/// <inheritdoc />
public override int Day { get; set; } = 1;
/// <inheritdoc />
public override string I18NIdentityCode { get; } = "i18n_holiday_ec_new_years_day";
}
} | 30.28125 | 91 | 0.613003 | [
"Apache-2.0"
] | cosmos-open/Holiday | src/Cosmos.Business.Extensions.Holiday/Cosmos/Business/Extensions/Holiday/Definitions/SouthAmerica/Ecuador/Public/NewYearsDay.cs | 970 | C# |
/*
* Copyright 2012-2017 The Pkcs11Interop Project
*
* 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.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <jimrich@jimrich.sk>
*/
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.LowLevelAPI41.MechanismParams;
using NativeULong = System.UInt32;
namespace Net.Pkcs11Interop.HighLevelAPI41.MechanismParams
{
/// <summary>
/// Parameters for the CKM_RC5_ECB and CKM_RC5_MAC mechanisms
/// </summary>
public class CkRc5Params : IMechanismParams
{
/// <summary>
/// Low level mechanism parameters
/// </summary>
private CK_RC5_PARAMS _lowLevelStruct = new CK_RC5_PARAMS();
/// <summary>
/// Initializes a new instance of the CkRc5Params class.
/// </summary>
/// <param name='wordsize'>Wordsize of RC5 cipher in bytes</param>
/// <param name='rounds'>Number of rounds of RC5 encipherment</param>
public CkRc5Params(NativeULong wordsize, NativeULong rounds)
{
_lowLevelStruct.Wordsize = wordsize;
_lowLevelStruct.Rounds = rounds;
}
#region IMechanismParams
/// <summary>
/// Returns managed object that can be marshaled to an unmanaged block of memory
/// </summary>
/// <returns>A managed object holding the data to be marshaled. This object must be an instance of a formatted class.</returns>
public object ToMarshalableStructure()
{
return _lowLevelStruct;
}
#endregion
}
}
| 33.857143 | 135 | 0.658228 | [
"Apache-2.0"
] | arkkadin/pkcs11Interop | src/Pkcs11Interop/Pkcs11Interop/HighLevelAPI41/MechanismParams/CkRc5Params.cs | 2,133 | C# |
// Uncomment the following to provide samples for PageResult<T>. Must also add the Microsoft.AspNet.WebApi.OData
// package to your project.
////#define Handle_PageResultOfT
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http.Headers;
using System.Reflection;
using System.Web;
using System.Web.Http;
#if Handle_PageResultOfT
using System.Web.Http.OData;
#endif
namespace lab_34_API_Northwind.Areas.HelpPage
{
/// <summary>
/// Use this class to customize the Help Page.
/// For example you can set a custom <see cref="System.Web.Http.Description.IDocumentationProvider"/> to supply the documentation
/// or you can provide the samples for the requests/responses.
/// </summary>
public static class HelpPageConfig
{
[SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters",
MessageId = "lab_34_API_Northwind.Areas.HelpPage.TextSample.#ctor(System.String)",
Justification = "End users may choose to merge this string with existing localized resources.")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly",
MessageId = "bsonspec",
Justification = "Part of a URI.")]
public static void Register(HttpConfiguration config)
{
//// Uncomment the following to use the documentation from XML documentation file.
//config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));
//// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type.
//// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type
//// formats by the available formatters.
//config.SetSampleObjects(new Dictionary<Type, object>
//{
// {typeof(string), "sample string"},
// {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}}
//});
// Extend the following to provide factories for types not handled automatically (those lacking parameterless
// constructors) or for which you prefer to use non-default property values. Line below provides a fallback
// since automatic handling will fail and GeneratePageResult handles only a single type.
#if Handle_PageResultOfT
config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult);
#endif
// Extend the following to use a preset object directly as the sample for all actions that support a media
// type, regardless of the body parameter or return type. The lines below avoid display of binary content.
// The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object.
config.SetSampleForMediaType(
new TextSample("Binary JSON content. See http://bsonspec.org for details."),
new MediaTypeHeaderValue("application/bson"));
//// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format
//// and have IEnumerable<string> as the body parameter or return type.
//config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>));
//// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values"
//// and action named "Put".
//config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put");
//// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png"
//// on the controller named "Values" and action named "Get" with parameter "id".
//config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id");
//// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>.
//// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter.
//config.SetActualRequestType(typeof(string), "Values", "Get");
//// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>.
//// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string.
//config.SetActualResponseType(typeof(string), "Values", "Post");
}
#if Handle_PageResultOfT
private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type)
{
if (type.IsGenericType)
{
Type openGenericType = type.GetGenericTypeDefinition();
if (openGenericType == typeof(PageResult<>))
{
// Get the T in PageResult<T>
Type[] typeParameters = type.GetGenericArguments();
Debug.Assert(typeParameters.Length == 1);
// Create an enumeration to pass as the first parameter to the PageResult<T> constuctor
Type itemsType = typeof(List<>).MakeGenericType(typeParameters);
object items = sampleGenerator.GetSampleObject(itemsType);
// Fill in the other information needed to invoke the PageResult<T> constuctor
Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), };
object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, };
// Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor
ConstructorInfo constructor = type.GetConstructor(parameterTypes);
return constructor.Invoke(parameters);
}
}
return null;
}
#endif
}
} | 57.619469 | 149 | 0.666871 | [
"MIT"
] | Ryan-Paul-Burdus/2019-09-c-sharp-labs | labs/lab_34_API_Northwind/Areas/HelpPage/App_Start/HelpPageConfig.cs | 6,511 | C# |
//---------------------------------------------------------------------------------------------------------
// ▽ Submarine Mirage Framework for Unity
// Copyright (c) 2020 夢想海の水底より(from Seabed of Reverie)
// Released under the MIT License :
// https://github.com/FromSeabedOfReverie/SubmarineMirageFrameworkForUnity/blob/master/LICENSE
//---------------------------------------------------------------------------------------------------------
//#define TestService
namespace SubmarineMirage.Service {
using System;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
using KoganeUnityLib;
using Event;
using Extension;
using Utility;
using Setting;
using Debug;
///====================================================================================================
/// <summary>
/// ■ オブジェクト注入のクラス
/// </summary>
///====================================================================================================
public static class SMServiceLocator {
///------------------------------------------------------------------------------------------------
/// ● 要素
///------------------------------------------------------------------------------------------------
[SMShowLine] public static bool s_isDisposed => s_disposables._isDispose;
static readonly SMDisposable s_disposables = new SMDisposable();
public static readonly Dictionary<Type, ISMService> s_container = new Dictionary<Type, ISMService>();
public static readonly SMAsyncCanceler s_defaultCanceler = new SMAsyncCanceler();
///------------------------------------------------------------------------------------------------
/// ● 作成、削除
///------------------------------------------------------------------------------------------------
/// <summary>
/// ● コンストラクタ
/// </summary>
static SMServiceLocator() {
#if TestService
SMLog.Debug( $"{nameof( SMServiceLocator )}()", SMLogTag.Service );
#endif
s_disposables.AddFirst( () => {
#if TestService
SMLog.Debug( $"{nameof( SMServiceLocator )}.{nameof( Dispose )}", SMLogTag.Service );
#endif
s_defaultCanceler.Dispose();
s_container.ForEach( pair => pair.Value?.Dispose() );
s_container.Clear();
} );
}
/// <summary>
/// ● 解放
/// </summary>
public static void Dispose()
=> s_disposables.Dispose();
public static T Register<T>( T instance ) where T : class, ISMService {
if ( s_isDisposed ) { return null; }
var type = typeof( T );
if ( s_container.ContainsKey( type ) ) {
throw new InvalidOperationException( $"既に登録済 : {type}" );
}
#if TestService
SMLog.Debug( $"{nameof( SMServiceLocator )}.{nameof( Register )} : {type.GetAboutName()}",
SMLogTag.Service );
#endif
s_container[type] = instance;
return instance;
}
public static void Unregister<T>( bool isCallDispose = true ) where T : class, ISMService {
if ( s_isDisposed ) { return; }
var type = typeof( T );
#if TestService
SMLog.Debug( $"{nameof( SMServiceLocator )}.{nameof( Unregister )} : {type.GetAboutName()}",
SMLogTag.Service );
#endif
if ( isCallDispose ) {
var instance = s_container.GetOrDefault( type );
instance?.Dispose();
}
s_container.Remove( type );
}
public static T Resolve<T>() where T : class, ISMService {
if ( s_isDisposed ) { return null; }
return s_container.GetOrDefault( typeof( T ) ) as T;
}
public static async UniTask<T> WaitResolve<T>( SMAsyncCanceler canceler = null ) where T : class, ISMService {
if ( s_isDisposed ) { return null; }
canceler = canceler ?? s_defaultCanceler;
var type = typeof( T );
ISMService instance = null;
await UTask.WaitWhile( canceler, () => {
instance = s_container.GetOrDefault( type );
return instance == null;
} );
return instance as T;
}
}
} | 33.610619 | 112 | 0.528963 | [
"MIT"
] | TatemonSugorokuGame/TatemonSugorokuGame | Assets/SubmarineMirageFramework/Scripts/Core/Service/SMServiceLocator.cs | 3,892 | C# |
using AutoMapper;
using FinancesCore.App.ViewModels;
using FinancesCore.Business.Models;
namespace FinancesCore.App.AutoMapper
{
public class AutoMapperConfig : Profile
{
public AutoMapperConfig()
{
CreateMap<Category, CategoryViewModel>().ReverseMap();
CreateMap<Transaction, TransactionViewModel>().ReverseMap();
}
}
}
| 23.9375 | 72 | 0.678851 | [
"MIT"
] | EvertonAlmeida/FinancesCore | src/FinancesCore.App/AutoMapper/AutoMapperConfig.cs | 385 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Threading
{
/// <summary>Signals to a <see cref="CancellationToken"/> that it should be canceled.</summary>
/// <remarks>
/// <para>
/// <see cref="CancellationTokenSource"/> is used to instantiate a <see cref="CancellationToken"/> (via
/// the source's <see cref="Token">Token</see> property) that can be handed to operations that wish to be
/// notified of cancellation or that can be used to register asynchronous operations for cancellation. That
/// token may have cancellation requested by calling to the source's <see cref="Cancel()"/> method.
/// </para>
/// <para>
/// All members of this class, except <see cref="Dispose"/>, are thread-safe and may be used
/// concurrently from multiple threads.
/// </para>
/// </remarks>
public class CancellationTokenSource : IDisposable
{
/// <summary>A <see cref="CancellationTokenSource"/> that's already canceled.</summary>
internal static readonly CancellationTokenSource s_canceledSource = new CancellationTokenSource() { _state = NotifyingCompleteState };
/// <summary>A <see cref="CancellationTokenSource"/> that's never canceled. This isn't enforced programmatically, only by usage. Do not cancel!</summary>
internal static readonly CancellationTokenSource s_neverCanceledSource = new CancellationTokenSource();
/// <summary>Delegate used with <see cref="Timer"/> to trigger cancellation of a <see cref="CancellationTokenSource"/>.</summary>
private static readonly TimerCallback s_timerCallback = obj =>
((CancellationTokenSource)obj).NotifyCancellation(throwOnFirstException: false); // skip ThrowIfDisposed() check in Cancel()
/// <summary>The number of callback partitions to use in a <see cref="CancellationTokenSource"/>. Must be a power of 2.</summary>
private static readonly int s_numPartitions = GetPartitionCount();
/// <summary><see cref="s_numPartitions"/> - 1, used to quickly mod into <see cref="_callbackPartitions"/>.</summary>
private static readonly int s_numPartitionsMask = s_numPartitions - 1;
/// <summary>The current state of the CancellationTokenSource.</summary>
private volatile int _state;
/// <summary>The ID of the thread currently executing the main body of CTS.Cancel()</summary>
/// <remarks>
/// This helps us to know if a call to ctr.Dispose() is running 'within' a cancellation callback.
/// This is updated as we move between the main thread calling cts.Cancel() and any syncContexts
/// that are used to actually run the callbacks.
/// </remarks>
private volatile int _threadIDExecutingCallbacks = -1;
/// <summary>Tracks the running callback to assist ctr.Dispose() to wait for the target callback to complete.</summary>
private long _executingCallbackId;
/// <summary>Partitions of callbacks. Split into multiple partitions to help with scalability of registering/unregistering; each is protected by its own lock.</summary>
private volatile CallbackPartition[] _callbackPartitions;
/// <summary>Timer used by CancelAfter and Timer-related ctors.</summary>
private volatile Timer _timer;
/// <summary><see cref="System.Threading.WaitHandle"/> lazily initialized and returned from <see cref="WaitHandle"/>.</summary>
private volatile ManualResetEvent _kernelEvent;
/// <summary>Whether this <see cref="CancellationTokenSource"/> has been disposed.</summary>
private bool _disposed;
// legal values for _state
private const int NotCanceledState = 1;
private const int NotifyingState = 2;
private const int NotifyingCompleteState = 3;
/// <summary>Gets whether cancellation has been requested for this <see cref="CancellationTokenSource" />.</summary>
/// <value>Whether cancellation has been requested for this <see cref="CancellationTokenSource" />.</value>
/// <remarks>
/// <para>
/// This property indicates whether cancellation has been requested for this token source, such as
/// due to a call to its <see cref="Cancel()"/> method.
/// </para>
/// <para>
/// If this property returns true, it only guarantees that cancellation has been requested. It does not
/// guarantee that every handler registered with the corresponding token has finished executing, nor
/// that cancellation requests have finished propagating to all registered handlers. Additional
/// synchronization may be required, particularly in situations where related objects are being
/// canceled concurrently.
/// </para>
/// </remarks>
public bool IsCancellationRequested => _state >= NotifyingState;
/// <summary>A simple helper to determine whether cancellation has finished.</summary>
internal bool IsCancellationCompleted => _state == NotifyingCompleteState;
/// <summary>A simple helper to determine whether disposal has occurred.</summary>
internal bool IsDisposed => _disposed;
/// <summary>The ID of the thread that is running callbacks.</summary>
internal int ThreadIDExecutingCallbacks
{
get => _threadIDExecutingCallbacks;
set => _threadIDExecutingCallbacks = value;
}
/// <summary>Gets the <see cref="CancellationToken"/> associated with this <see cref="CancellationTokenSource"/>.</summary>
/// <value>The <see cref="CancellationToken"/> associated with this <see cref="CancellationTokenSource"/>.</value>
/// <exception cref="ObjectDisposedException">The token source has been disposed.</exception>
public CancellationToken Token
{
get
{
ThrowIfDisposed();
return new CancellationToken(this);
}
}
internal WaitHandle WaitHandle
{
get
{
ThrowIfDisposed();
// Return the handle if it was already allocated.
if (_kernelEvent != null)
{
return _kernelEvent;
}
// Lazily-initialize the handle.
var mre = new ManualResetEvent(false);
if (Interlocked.CompareExchange(ref _kernelEvent, mre, null) != null)
{
mre.Dispose();
}
// There is a race condition between checking IsCancellationRequested and setting the event.
// However, at this point, the kernel object definitely exists and the cases are:
// 1. if IsCancellationRequested = true, then we will call Set()
// 2. if IsCancellationRequested = false, then NotifyCancellation will see that the event exists, and will call Set().
if (IsCancellationRequested)
{
_kernelEvent.Set();
}
return _kernelEvent;
}
}
/// <summary>Gets the ID of the currently executing callback.</summary>
internal long ExecutingCallback => Volatile.Read(ref _executingCallbackId);
/// <summary>Initializes the <see cref="CancellationTokenSource"/>.</summary>
public CancellationTokenSource() => _state = NotCanceledState;
/// <summary>
/// Constructs a <see cref="CancellationTokenSource"/> that will be canceled after a specified time span.
/// </summary>
/// <param name="delay">The time span to wait before canceling this <see cref="CancellationTokenSource"/></param>
/// <exception cref="ArgumentOutOfRangeException">
/// The exception that is thrown when <paramref name="delay"/> is less than -1 or greater than int.MaxValue.
/// </exception>
/// <remarks>
/// <para>
/// The countdown for the delay starts during the call to the constructor. When the delay expires,
/// the constructed <see cref="CancellationTokenSource"/> is canceled, if it has
/// not been canceled already.
/// </para>
/// <para>
/// Subsequent calls to CancelAfter will reset the delay for the constructed
/// <see cref="CancellationTokenSource"/>, if it has not been
/// canceled already.
/// </para>
/// </remarks>
public CancellationTokenSource(TimeSpan delay)
{
long totalMilliseconds = (long)delay.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(delay));
}
InitializeWithTimer((int)totalMilliseconds);
}
/// <summary>
/// Constructs a <see cref="CancellationTokenSource"/> that will be canceled after a specified time span.
/// </summary>
/// <param name="millisecondsDelay">The time span to wait before canceling this <see cref="CancellationTokenSource"/></param>
/// <exception cref="ArgumentOutOfRangeException">
/// The exception that is thrown when <paramref name="millisecondsDelay"/> is less than -1.
/// </exception>
/// <remarks>
/// <para>
/// The countdown for the millisecondsDelay starts during the call to the constructor. When the millisecondsDelay expires,
/// the constructed <see cref="CancellationTokenSource"/> is canceled (if it has
/// not been canceled already).
/// </para>
/// <para>
/// Subsequent calls to CancelAfter will reset the millisecondsDelay for the constructed
/// <see cref="CancellationTokenSource"/>, if it has not been
/// canceled already.
/// </para>
/// </remarks>
public CancellationTokenSource(int millisecondsDelay)
{
if (millisecondsDelay < -1)
{
throw new ArgumentOutOfRangeException(nameof(millisecondsDelay));
}
InitializeWithTimer(millisecondsDelay);
}
/// <summary>Common initialization logic when constructing a CTS with a delay parameter</summary>
private void InitializeWithTimer(int millisecondsDelay)
{
_state = NotCanceledState;
_timer = new Timer(s_timerCallback, this, millisecondsDelay, -1, flowExecutionContext: false);
// The timer roots this CTS instance while it's scheduled. That is by design, so
// that code like:
// CancellationToken ct = new CancellationTokenSource(timeout).Token;
// will successfully cancel the token after the timeout.
}
/// <summary>Communicates a request for cancellation.</summary>
/// <remarks>
/// <para>
/// The associated <see cref="CancellationToken" /> will be notified of the cancellation
/// and will transition to a state where <see cref="CancellationToken.IsCancellationRequested"/> returns true.
/// Any callbacks or cancelable operations registered with the <see cref="CancellationToken"/> will be executed.
/// </para>
/// <para>
/// Cancelable operations and callbacks registered with the token should not throw exceptions.
/// However, this overload of Cancel will aggregate any exceptions thrown into a <see cref="AggregateException"/>,
/// such that one callback throwing an exception will not prevent other registered callbacks from being executed.
/// </para>
/// <para>
/// The <see cref="ExecutionContext"/> that was captured when each callback was registered
/// will be reestablished when the callback is invoked.
/// </para>
/// </remarks>
/// <exception cref="AggregateException">An aggregate exception containing all the exceptions thrown
/// by the registered callbacks on the associated <see cref="CancellationToken"/>.</exception>
/// <exception cref="ObjectDisposedException">This <see cref="CancellationTokenSource"/> has been disposed.</exception>
public void Cancel() => Cancel(false);
/// <summary>Communicates a request for cancellation.</summary>
/// <remarks>
/// <para>
/// The associated <see cref="CancellationToken" /> will be notified of the cancellation and will transition to a state where
/// <see cref="CancellationToken.IsCancellationRequested"/> returns true. Any callbacks or cancelable operationsregistered
/// with the <see cref="CancellationToken"/> will be executed.
/// </para>
/// <para>
/// Cancelable operations and callbacks registered with the token should not throw exceptions.
/// If <paramref name="throwOnFirstException"/> is true, an exception will immediately propagate out of the
/// call to Cancel, preventing the remaining callbacks and cancelable operations from being processed.
/// If <paramref name="throwOnFirstException"/> is false, this overload will aggregate any
/// exceptions thrown into a <see cref="AggregateException"/>,
/// such that one callback throwing an exception will not prevent other registered callbacks from being executed.
/// </para>
/// <para>
/// The <see cref="ExecutionContext"/> that was captured when each callback was registered
/// will be reestablished when the callback is invoked.
/// </para>
/// </remarks>
/// <param name="throwOnFirstException">Specifies whether exceptions should immediately propagate.</param>
/// <exception cref="AggregateException">An aggregate exception containing all the exceptions thrown
/// by the registered callbacks on the associated <see cref="CancellationToken"/>.</exception>
/// <exception cref="ObjectDisposedException">This <see cref="CancellationTokenSource"/> has been disposed.</exception>
public void Cancel(bool throwOnFirstException)
{
ThrowIfDisposed();
NotifyCancellation(throwOnFirstException);
}
/// <summary>Schedules a Cancel operation on this <see cref="CancellationTokenSource"/>.</summary>
/// <param name="delay">The time span to wait before canceling this <see cref="CancellationTokenSource"/>.
/// </param>
/// <exception cref="ObjectDisposedException">The exception thrown when this <see
/// cref="CancellationTokenSource"/> has been disposed.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The exception thrown when <paramref name="delay"/> is less than -1 or
/// greater than int.MaxValue.
/// </exception>
/// <remarks>
/// <para>
/// The countdown for the delay starts during this call. When the delay expires,
/// this <see cref="CancellationTokenSource"/> is canceled, if it has
/// not been canceled already.
/// </para>
/// <para>
/// Subsequent calls to CancelAfter will reset the delay for this
/// <see cref="CancellationTokenSource"/>, if it has not been canceled already.
/// </para>
/// </remarks>
public void CancelAfter(TimeSpan delay)
{
long totalMilliseconds = (long)delay.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(delay));
}
CancelAfter((int)totalMilliseconds);
}
/// <summary>
/// Schedules a Cancel operation on this <see cref="CancellationTokenSource"/>.
/// </summary>
/// <param name="millisecondsDelay">The time span to wait before canceling this <see
/// cref="CancellationTokenSource"/>.
/// </param>
/// <exception cref="ObjectDisposedException">The exception thrown when this <see
/// cref="CancellationTokenSource"/> has been disposed.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The exception thrown when <paramref name="millisecondsDelay"/> is less than -1.
/// </exception>
/// <remarks>
/// <para>
/// The countdown for the millisecondsDelay starts during this call. When the millisecondsDelay expires,
/// this <see cref="CancellationTokenSource"/> is canceled, if it has
/// not been canceled already.
/// </para>
/// <para>
/// Subsequent calls to CancelAfter will reset the millisecondsDelay for this
/// <see cref="CancellationTokenSource"/>, if it has not been
/// canceled already.
/// </para>
/// </remarks>
public void CancelAfter(int millisecondsDelay)
{
ThrowIfDisposed();
if (millisecondsDelay < -1)
{
throw new ArgumentOutOfRangeException(nameof(millisecondsDelay));
}
if (IsCancellationRequested)
{
return;
}
// There is a race condition here as a Cancel could occur between the check of
// IsCancellationRequested and the creation of the timer. This is benign; in the
// worst case, a timer will be created that has no effect when it expires.
// Also, if Dispose() is called right here (after ThrowIfDisposed(), before timer
// creation), it would result in a leaked Timer object (at least until the timer
// expired and Disposed itself). But this would be considered bad behavior, as
// Dispose() is not thread-safe and should not be called concurrently with CancelAfter().
Timer timer = _timer;
if (timer == null)
{
// Lazily initialize the timer in a thread-safe fashion.
// Initially set to "never go off" because we don't want to take a
// chance on a timer "losing" the initialization and then
// cancelling the token before it (the timer) can be disposed.
timer = new Timer(s_timerCallback, this, -1, -1, flowExecutionContext: false);
Timer currentTimer = Interlocked.CompareExchange(ref _timer, timer, null);
if (currentTimer != null)
{
// We did not initialize the timer. Dispose the new timer.
timer.Dispose();
timer = currentTimer;
}
}
// It is possible that _timer has already been disposed, so we must do
// the following in a try/catch block.
try
{
timer.Change(millisecondsDelay, -1);
}
catch (ObjectDisposedException)
{
// Just eat the exception. There is no other way to tell that
// the timer has been disposed, and even if there were, there
// would not be a good way to deal with the observe/dispose
// race condition.
}
}
/// <summary>Releases the resources used by this <see cref="CancellationTokenSource" />.</summary>
/// <remarks>This method is not thread-safe for any other concurrent calls.</remarks>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases the unmanaged resources used by the <see cref="CancellationTokenSource" /> class and optionally releases the managed resources.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
// We specifically tolerate that a callback can be unregistered
// after the CTS has been disposed and/or concurrently with cts.Dispose().
// This is safe without locks because Dispose doesn't interact with values
// in the callback partitions, only nulling out the ref to existing partitions.
//
// We also tolerate that a callback can be registered after the CTS has been
// disposed. This is safe because InternalRegister is tolerant
// of _callbackPartitions becoming null during its execution. However,
// we run the acceptable risk of _callbackPartitions getting reinitialized
// to non-null if there is a race between Dispose and Register, in which case this
// instance may unnecessarily hold onto a registered callback. But that's no worse
// than if Dispose wasn't safe to use concurrently, as Dispose would never be called,
// and thus no handlers would be dropped.
//
// And, we tolerate Dispose being used concurrently with Cancel. This is necessary
// to properly support, e.g., LinkedCancellationTokenSource, where, due to common usage patterns,
// it's possible for this pairing to occur with valid usage (e.g. a component accepts
// an external CancellationToken and uses CreateLinkedTokenSource to combine it with an
// internal source of cancellation, then Disposes of that linked source, which could
// happen at the same time the external entity is requesting cancellation).
Timer timer = _timer;
if (timer != null)
{
_timer = null;
timer.Dispose(); // Timer.Dispose is thread-safe
}
_callbackPartitions = null; // free for GC; Cancel correctly handles a null field
// If a kernel event was created via WaitHandle, we'd like to Dispose of it. However,
// we only want to do so if it's not being used by Cancel concurrently. First, we
// interlocked exchange it to be null, and then we check whether cancellation is currently
// in progress. NotifyCancellation will only try to set the event if it exists after it's
// transitioned to and while it's in the NotifyingState.
if (_kernelEvent != null)
{
ManualResetEvent mre = Interlocked.Exchange(ref _kernelEvent, null);
if (mre != null && _state != NotifyingState)
{
mre.Dispose();
}
}
_disposed = true;
}
}
/// <summary>Throws an exception if the source has been disposed.</summary>
private void ThrowIfDisposed()
{
if (_disposed)
{
ThrowObjectDisposedException();
}
}
/// <summary>Throws an <see cref="ObjectDisposedException"/>. Separated out from ThrowIfDisposed to help with inlining.</summary>
private static void ThrowObjectDisposedException() =>
throw new ObjectDisposedException(null, SR.CancellationTokenSource_Disposed);
/// <summary>
/// Registers a callback object. If cancellation has already occurred, the
/// callback will have been run by the time this method returns.
/// </summary>
internal CancellationTokenRegistration InternalRegister(
Action<object> callback, object stateForCallback, SynchronizationContext syncContext, ExecutionContext executionContext)
{
Debug.Assert(this != s_neverCanceledSource, "This source should never be exposed via a CancellationToken.");
// If not canceled, register the handler; if canceled already, run the callback synchronously.
// This also ensures that during ExecuteCallbackHandlers() there will be no mutation of the _callbackPartitions.
if (!IsCancellationRequested)
{
// In order to enable code to not leak too many handlers, we allow Dispose to be called concurrently
// with Register. While this is not a recommended practice, consumers can and do use it this way.
// We don't make any guarantees about whether the CTS will hold onto the supplied callback if the CTS
// has already been disposed when the callback is registered, but we try not to while at the same time
// not paying any non-negligible overhead. The simple compromise is to check whether we're disposed
// (not volatile), and if we see we are, to return an empty registration. If there's a race and _disposed
// is false even though it's been disposed, or if the disposal request comes in after this line, we simply
// run the minor risk of having _callbackPartitions reinitialized (after it was cleared to null during Dispose).
if (_disposed)
{
return new CancellationTokenRegistration();
}
// Get the partitions...
CallbackPartition[] partitions = _callbackPartitions;
if (partitions == null)
{
partitions = new CallbackPartition[s_numPartitions];
partitions = Interlocked.CompareExchange(ref _callbackPartitions, partitions, null) ?? partitions;
}
// ...and determine which partition to use.
int partitionIndex = Environment.CurrentManagedThreadId & s_numPartitionsMask;
Debug.Assert(partitionIndex < partitions.Length, $"Expected {partitionIndex} to be less than {partitions.Length}");
CallbackPartition partition = partitions[partitionIndex];
if (partition == null)
{
partition = new CallbackPartition(this);
partition = Interlocked.CompareExchange(ref partitions[partitionIndex], partition, null) ?? partition;
}
// Store the callback information into the callback arrays.
long id;
CallbackNode node;
bool lockTaken = false;
partition.Lock.Enter(ref lockTaken);
try
{
// Assign the next available unique ID.
id = partition.NextAvailableId++;
// Get a node, from the free list if possible or else a new one.
node = partition.FreeNodeList;
if (node != null)
{
partition.FreeNodeList = node.Next;
Debug.Assert(node.Prev == null, "Nodes in the free list should all have a null Prev");
// node.Next will be overwritten below so no need to set it here.
}
else
{
node = new CallbackNode(partition);
}
// Configure the node.
node.Id = id;
node.Callback = callback;
node.CallbackState = stateForCallback;
node.ExecutionContext = executionContext;
node.SynchronizationContext = syncContext;
// Add it to the callbacks list.
node.Next = partition.Callbacks;
if (node.Next != null)
{
node.Next.Prev = node;
}
partition.Callbacks = node;
}
finally
{
partition.Lock.Exit(useMemoryBarrier: false); // no check on lockTaken needed without thread aborts
}
// If cancellation hasn't been requested, return the registration.
// if cancellation has been requested, try to undo the registration and run the callback
// ourselves, but if we can't unregister it (e.g. the thread running Cancel snagged
// our callback for execution), return the registration so that the caller can wait
// for callback completion in ctr.Dispose().
var ctr = new CancellationTokenRegistration(id, node);
if (!IsCancellationRequested || !partition.Unregister(id, node))
{
return ctr;
}
}
// Cancellation already occurred. Run the callback on this thread and return an empty registration.
callback(stateForCallback);
return default;
}
private void NotifyCancellation(bool throwOnFirstException)
{
// If we're the first to signal cancellation, do the main extra work.
if (!IsCancellationRequested && Interlocked.CompareExchange(ref _state, NotifyingState, NotCanceledState) == NotCanceledState)
{
// Dispose of the timer, if any. Dispose may be running concurrently here, but Timer.Dispose is thread-safe.
Timer timer = _timer;
if (timer != null)
{
_timer = null;
timer.Dispose();
}
// Set the event if it's been lazily initialized and hasn't yet been disposed of. Dispose may
// be running concurrently, in which case either it'll have set m_kernelEvent back to null and
// we won't see it here, or it'll see that we've transitioned to NOTIFYING and will skip disposing it,
// leaving cleanup to finalization.
_kernelEvent?.Set(); // update the MRE value.
// - late enlisters to the Canceled event will have their callbacks called immediately in the Register() methods.
// - Callbacks are not called inside a lock.
// - After transition, no more delegates will be added to the
// - list of handlers, and hence it can be consumed and cleared at leisure by ExecuteCallbackHandlers.
ExecuteCallbackHandlers(throwOnFirstException);
Debug.Assert(IsCancellationCompleted, "Expected cancellation to have finished");
}
}
/// <summary>Invoke all registered callbacks.</summary>
/// <remarks>The handlers are invoked synchronously in LIFO order.</remarks>
private void ExecuteCallbackHandlers(bool throwOnFirstException)
{
Debug.Assert(IsCancellationRequested, "ExecuteCallbackHandlers should only be called after setting IsCancellationRequested->true");
// Record the threadID being used for running the callbacks.
ThreadIDExecutingCallbacks = Thread.CurrentThread.ManagedThreadId;
// If there are no callbacks to run, we can safely exit. Any race conditions to lazy initialize it
// will see IsCancellationRequested and will then run the callback themselves.
CallbackPartition[] partitions = Interlocked.Exchange(ref _callbackPartitions, null);
if (partitions == null)
{
Interlocked.Exchange(ref _state, NotifyingCompleteState);
return;
}
List<Exception> exceptionList = null;
try
{
// For each partition, and each callback in that partition, execute the associated handler.
// We call the delegates in LIFO order on each partition so that callbacks fire 'deepest first'.
// This is intended to help with nesting scenarios so that child enlisters cancel before their parents.
foreach (CallbackPartition partition in partitions)
{
if (partition == null)
{
// Uninitialized partition. Nothing to do.
continue;
}
// Iterate through all nodes in the partition. We remove each node prior
// to processing it. This allows for unregistration of subsequent registrations
// to still be effective even as other registrations are being invoked.
while (true)
{
CallbackNode node;
bool lockTaken = false;
partition.Lock.Enter(ref lockTaken);
try
{
// Pop the next registration from the callbacks list.
node = partition.Callbacks;
if (node == null)
{
// No more registrations to process.
break;
}
else
{
Debug.Assert(node.Prev == null);
if (node.Next != null) node.Next.Prev = null;
partition.Callbacks = node.Next;
}
// Publish the intended callback ID, to ensure ctr.Dispose can tell if a wait is necessary.
// This write happens while the lock is held so that Dispose is either able to successfully
// unregister or is guaranteed to see an accurate executing callback ID, since it takes
// the same lock to remove the node from the callback list.
_executingCallbackId = node.Id;
// Now that we've grabbed the Id, reset the node's Id to 0. This signals
// to code unregistering that the node is no longer associated with a callback.
node.Id = 0;
}
finally
{
partition.Lock.Exit(useMemoryBarrier: false); // no check on lockTaken needed without thread aborts
}
// Invoke the callback on this thread if there's no sync context or on the
// target sync context if there is one.
try
{
if (node.SynchronizationContext != null)
{
// Transition to the target syncContext and continue there.
node.SynchronizationContext.Send(s =>
{
var n = (CallbackNode)s;
n.Partition.Source.ThreadIDExecutingCallbacks = Thread.CurrentThread.ManagedThreadId;
n.ExecuteCallback();
}, node);
ThreadIDExecutingCallbacks = Thread.CurrentThread.ManagedThreadId; // above may have altered ThreadIDExecutingCallbacks, so reset it
}
else
{
node.ExecuteCallback();
}
}
catch (Exception ex) when (!throwOnFirstException)
{
// Store the exception and continue
(exceptionList ?? (exceptionList = new List<Exception>())).Add(ex);
}
// Drop the node. While we could add it to the free list, doing so has cost (we'd need to take the lock again)
// and very limited value. Since a source can only be canceled once, and after it's canceled registrations don't
// need nodes, the only benefit to putting this on the free list would be if Register raced with cancellation
// occurring, such that it could have used this free node but would instead need to allocate a new node (if
// there wasn't another free node available).
}
}
}
finally
{
_state = NotifyingCompleteState;
Volatile.Write(ref _executingCallbackId, 0);
Interlocked.MemoryBarrier(); // for safety, prevent reorderings crossing this point and seeing inconsistent state.
}
if (exceptionList != null)
{
Debug.Assert(exceptionList.Count > 0, $"Expected {exceptionList.Count} > 0");
throw new AggregateException(exceptionList);
}
}
/// <summary>Gets the number of callback partitions to use based on the number of cores.</summary>
/// <returns>A power of 2 representing the number of partitions to use.</returns>
private static int GetPartitionCount()
{
int procs = PlatformHelper.ProcessorCount;
int count =
procs > 8 ? 16 : // capped at 16 to limit memory usage on larger machines
procs > 4 ? 8 :
procs > 2 ? 4 :
procs > 1 ? 2 :
1;
Debug.Assert(count > 0 && (count & (count - 1)) == 0, $"Got {count}, but expected a power of 2");
return count;
}
/// <summary>
/// Creates a <see cref="CancellationTokenSource"/> that will be in the canceled state
/// when any of the source tokens are in the canceled state.
/// </summary>
/// <param name="token1">The first <see cref="CancellationToken">CancellationToken</see> to observe.</param>
/// <param name="token2">The second <see cref="CancellationToken">CancellationToken</see> to observe.</param>
/// <returns>A <see cref="CancellationTokenSource"/> that is linked
/// to the source tokens.</returns>
public static CancellationTokenSource CreateLinkedTokenSource(CancellationToken token1, CancellationToken token2) =>
!token1.CanBeCanceled ? CreateLinkedTokenSource(token2) :
token2.CanBeCanceled ? new Linked2CancellationTokenSource(token1, token2) :
(CancellationTokenSource)new Linked1CancellationTokenSource(token1);
/// <summary>
/// Creates a <see cref="CancellationTokenSource"/> that will be in the canceled state
/// when any of the source tokens are in the canceled state.
/// </summary>
/// <param name="token">The first <see cref="CancellationToken">CancellationToken</see> to observe.</param>
/// <returns>A <see cref="CancellationTokenSource"/> that is linked to the source tokens.</returns>
internal static CancellationTokenSource CreateLinkedTokenSource(CancellationToken token) =>
token.CanBeCanceled ? new Linked1CancellationTokenSource(token) : new CancellationTokenSource();
/// <summary>
/// Creates a <see cref="CancellationTokenSource"/> that will be in the canceled state
/// when any of the source tokens are in the canceled state.
/// </summary>
/// <param name="tokens">The <see cref="CancellationToken">CancellationToken</see> instances to observe.</param>
/// <returns>A <see cref="CancellationTokenSource"/> that is linked to the source tokens.</returns>
/// <exception cref="System.ArgumentNullException"><paramref name="tokens"/> is null.</exception>
public static CancellationTokenSource CreateLinkedTokenSource(params CancellationToken[] tokens)
{
if (tokens == null)
{
throw new ArgumentNullException(nameof(tokens));
}
switch (tokens.Length)
{
case 0:
throw new ArgumentException(SR.CancellationToken_CreateLinkedToken_TokensIsEmpty);
case 1:
return CreateLinkedTokenSource(tokens[0]);
case 2:
return CreateLinkedTokenSource(tokens[0], tokens[1]);
default:
// a defensive copy is not required as the array has value-items that have only a single reference field,
// hence each item cannot be null itself, and reads of the payloads cannot be torn.
return new LinkedNCancellationTokenSource(tokens);
}
}
/// <summary>
/// Wait for a single callback to complete (or, more specifically, to not be running).
/// It is ok to call this method if the callback has already finished.
/// Calling this method before the target callback has been selected for execution would be an error.
/// </summary>
internal void WaitForCallbackToComplete(long id)
{
var sw = new SpinWait();
while (ExecutingCallback == id)
{
sw.SpinOnce(); // spin, as we assume callback execution is fast and that this situation is rare.
}
}
private sealed class Linked1CancellationTokenSource : CancellationTokenSource
{
private readonly CancellationTokenRegistration _reg1;
internal Linked1CancellationTokenSource(CancellationToken token1)
{
_reg1 = token1.UnsafeRegister(LinkedNCancellationTokenSource.s_linkedTokenCancelDelegate, this);
}
protected override void Dispose(bool disposing)
{
if (!disposing || _disposed)
{
return;
}
_reg1.Dispose();
base.Dispose(disposing);
}
}
private sealed class Linked2CancellationTokenSource : CancellationTokenSource
{
private readonly CancellationTokenRegistration _reg1;
private readonly CancellationTokenRegistration _reg2;
internal Linked2CancellationTokenSource(CancellationToken token1, CancellationToken token2)
{
_reg1 = token1.UnsafeRegister(LinkedNCancellationTokenSource.s_linkedTokenCancelDelegate, this);
_reg2 = token2.UnsafeRegister(LinkedNCancellationTokenSource.s_linkedTokenCancelDelegate, this);
}
protected override void Dispose(bool disposing)
{
if (!disposing || _disposed)
{
return;
}
_reg1.Dispose();
_reg2.Dispose();
base.Dispose(disposing);
}
}
private sealed class LinkedNCancellationTokenSource : CancellationTokenSource
{
internal static readonly Action<object> s_linkedTokenCancelDelegate =
s => ((CancellationTokenSource)s).NotifyCancellation(throwOnFirstException: false); // skip ThrowIfDisposed() check in Cancel()
private CancellationTokenRegistration[] _linkingRegistrations;
internal LinkedNCancellationTokenSource(params CancellationToken[] tokens)
{
_linkingRegistrations = new CancellationTokenRegistration[tokens.Length];
for (int i = 0; i < tokens.Length; i++)
{
if (tokens[i].CanBeCanceled)
{
_linkingRegistrations[i] = tokens[i].UnsafeRegister(s_linkedTokenCancelDelegate, this);
}
// Empty slots in the array will be default(CancellationTokenRegistration), which are nops to Dispose.
// Based on usage patterns, such occurrences should also be rare, such that it's not worth resizing
// the array and incurring the related costs.
}
}
protected override void Dispose(bool disposing)
{
if (!disposing || _disposed)
{
return;
}
CancellationTokenRegistration[] linkingRegistrations = _linkingRegistrations;
if (linkingRegistrations != null)
{
_linkingRegistrations = null; // release for GC once we're done enumerating
for (int i = 0; i < linkingRegistrations.Length; i++)
{
linkingRegistrations[i].Dispose();
}
}
base.Dispose(disposing);
}
}
internal sealed class CallbackPartition
{
/// <summary>The associated source that owns this partition.</summary>
public readonly CancellationTokenSource Source;
/// <summary>Lock that protects all state in the partition.</summary>
public SpinLock Lock = new SpinLock(enableThreadOwnerTracking: false); // mutable struct; do not make this readonly
/// <summary>Doubly-linked list of callbacks registered with the partition. Callbacks are removed during unregistration and as they're invoked.</remarks>
public CallbackNode Callbacks;
/// <summary>Singly-linked list of free nodes that can be used for subsequent callback registrations.</summary>
public CallbackNode FreeNodeList;
/// <summary>Every callback is assigned a unique, never-reused ID. This defines the next available ID.</summary>
public long NextAvailableId = 1; // avoid using 0, as that's the default long value and used to represent an empty node
public CallbackPartition(CancellationTokenSource source)
{
Debug.Assert(source != null, "Expected non-null source");
Source = source;
}
internal bool Unregister(long id, CallbackNode node)
{
Debug.Assert(id != 0, "Expected non-zero id");
Debug.Assert(node != null, "Expected non-null node");
bool lockTaken = false;
Lock.Enter(ref lockTaken);
try
{
if (node.Id != id)
{
// Either:
// - The callback is currently or has already been invoked, in which case node.Id
// will no longer equal the assigned id, as it will have transitioned to 0.
// - The registration was already disposed of, in which case node.Id will similarly
// no longer equal the assigned id, as it will have transitioned to 0 and potentially
// then to another (larger) value when reused for a new registration.
// In either case, there's nothing to unregister.
return false;
}
// The registration must still be in the callbacks list. Remove it.
if (Callbacks == node)
{
Debug.Assert(node.Prev == null);
Callbacks = node.Next;
}
else
{
Debug.Assert(node.Prev != null);
node.Prev.Next = node.Next;
}
if (node.Next != null)
{
node.Next.Prev = node.Prev;
}
// Clear out the now unused node and put it on the singly-linked free list.
// The only field we don't clear out is the associated Partition, as that's fixed
// throughout the nodes lifetime, regardless of how many times its reused by
// the same partition (it's never used on a different partition).
node.Id = 0;
node.Callback = null;
node.CallbackState = null;
node.ExecutionContext = null;
node.SynchronizationContext = null;
node.Prev = null;
node.Next = FreeNodeList;
FreeNodeList = node;
return true;
}
finally
{
Lock.Exit(useMemoryBarrier: false); // no check on lockTaken needed without thread aborts
}
}
}
/// <summary>All of the state associated a registered callback, in a node that's part of a linked list of registered callbacks.</summary>
internal sealed class CallbackNode
{
public readonly CallbackPartition Partition;
public CallbackNode Prev;
public CallbackNode Next;
public long Id;
public Action<object> Callback;
public object CallbackState;
public ExecutionContext ExecutionContext;
public SynchronizationContext SynchronizationContext;
public CallbackNode(CallbackPartition partition)
{
Debug.Assert(partition != null, "Expected non-null partition");
Partition = partition;
}
public void ExecuteCallback()
{
ExecutionContext context = ExecutionContext;
if (context != null)
{
ExecutionContext.RunInternal(context, s =>
{
CallbackNode n = (CallbackNode)s;
n.Callback(n.CallbackState);
}, this);
}
else
{
Callback(CallbackState);
}
}
}
}
}
| 51.042254 | 177 | 0.580594 | [
"MIT"
] | Frassle/coreclr | src/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs | 50,736 | 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.Globalization;
using BenchmarkDotNet.Attributes;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure;
namespace Microsoft.AspNetCore.Server.Kestrel.Microbenchmarks
{
public class StringUtilitiesBenchmark
{
private const int Iterations = 500_000;
[Benchmark(Baseline = true, OperationsPerInvoke = Iterations)]
public void UintToString()
{
var connectionId = CorrelationIdGenerator.GetNextId();
for (uint i = 0; i < Iterations; i++)
{
var id = connectionId + ':' + i.ToString("X8", CultureInfo.InvariantCulture);
}
}
[Benchmark(OperationsPerInvoke = Iterations)]
public void ConcatAsHexSuffix()
{
var connectionId = CorrelationIdGenerator.GetNextId();
for (uint i = 0; i < Iterations; i++)
{
var id = StringUtilities.ConcatAsHexSuffix(connectionId, ':', i);
}
}
}
}
| 33.861111 | 111 | 0.639048 | [
"Apache-2.0"
] | 1175169074/aspnetcore | src/Servers/Kestrel/perf/Microbenchmarks/StringUtilitiesBenchmark.cs | 1,219 | C# |
namespace TY.Services.Bank.Cqrs
{
public interface IQuery<TResult>
{
}
} | 13.428571 | 36 | 0.585106 | [
"MIT"
] | daidorian09/TY.Kong | TY.Services.Bank/TY.Services.Bank/Cqrs/IQuery.cs | 96 | C# |
using EasyNetQ.Interception;
using NSubstitute;
using System;
using System.Text;
using Xunit;
namespace EasyNetQ.Tests.Interception
{
public class BuildInInterceptorsTests
{
[Fact]
public void ShouldCompressAndDecompress()
{
var interceptor = new GZipInterceptor();
var body = Encoding.UTF8.GetBytes("haha");
var outgoingMessage = new ProducedMessage(new MessageProperties(), body);
var message = interceptor.OnProduce(outgoingMessage);
var incomingMessage = new ConsumedMessage(null, message.Properties, message.Body);
Assert.Equal(body, interceptor.OnConsume(incomingMessage).Body.ToArray());
}
[Fact]
public void ShouldEncryptAndDecrypt()
{
var interceptor = new TripleDESInterceptor(Convert.FromBase64String("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"), Convert.FromBase64String("aaaaaaaaaaa="));
var body = Encoding.UTF8.GetBytes("haha");
var outgoingMessage = new ProducedMessage(new MessageProperties(), body);
var message = interceptor.OnProduce(outgoingMessage);
var incomingMessage = new ConsumedMessage(null, message.Properties, message.Body);
Assert.Equal(body, interceptor.OnConsume(incomingMessage).Body.ToArray());
}
[Fact]
public void ShouldCallAddedInterceptorsOnProduce()
{
var sourceMessage = new ProducedMessage(new MessageProperties(), new byte[0]);
var firstMessage = new ProducedMessage(new MessageProperties(), new byte[0]);
var secondMessage = new ProducedMessage(new MessageProperties(), new byte[0]);
var first = Substitute.For<IProduceConsumeInterceptor>();
var second = Substitute.For<IProduceConsumeInterceptor>();
first.OnProduce(sourceMessage).Returns(firstMessage);
second.OnProduce(firstMessage).Returns(secondMessage);
var compositeInterceptor = new CompositeInterceptor();
compositeInterceptor.Add(first);
compositeInterceptor.Add(second);
Assert.Equal(secondMessage, compositeInterceptor.OnProduce(sourceMessage));
}
[Fact]
public void ShouldCallAddedInterceptorsOnConsume()
{
var sourceMessage = new ConsumedMessage(null, new MessageProperties(), new byte[0]);
var firstMessage = new ConsumedMessage(null, new MessageProperties(), new byte[0]);
var secondMessage = new ConsumedMessage(null, new MessageProperties(), new byte[0]);
var first = Substitute.For<IProduceConsumeInterceptor>();
var second = Substitute.For<IProduceConsumeInterceptor>();
first.OnConsume(secondMessage).Returns(firstMessage);
second.OnConsume(sourceMessage).Returns(secondMessage);
var compositeInterceptor = new CompositeInterceptor();
compositeInterceptor.Add(first);
compositeInterceptor.Add(second);
Assert.Equal(firstMessage, compositeInterceptor.OnConsume(sourceMessage));
}
}
}
| 44.928571 | 159 | 0.67027 | [
"MIT"
] | 10088/EasyNetQ | Source/EasyNetQ.Tests/Interception/BuildInInterceptorsTests.cs | 3,145 | C# |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression test to demonstrate importing and trading on custom data.
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="custom data" />
/// <meta name="tag" content="crypto" />
/// <meta name="tag" content="regression test" />
public class CustomDataRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private bool _warmedUpChecked = false;
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2011, 9, 14);
SetEndDate(2015, 12, 01);
//Set the cash for the strategy:
SetCash(100000);
//Define the symbol and "type" of our generic data:
var resolution = LiveMode ? Resolution.Second : Resolution.Daily;
AddData<Bitcoin>("BTC", resolution);
var seeder = new FuncSecuritySeeder(GetLastKnownPrices);
SetSecurityInitializer(security => seeder.SeedSecurity(security));
}
/// <summary>
/// Event Handler for Bitcoin Data Events: These Bitcoin objects are created from our
/// "Bitcoin" type below and fired into this event handler.
/// </summary>
/// <param name="data">One(1) Bitcoin Object, streamed into our algorithm synchronised in time with our other data streams</param>
public void OnData(Bitcoin data)
{
//If we don't have any bitcoin "SHARES" -- invest"
if (!Portfolio.Invested)
{
//Bitcoin used as a tradable asset, like stocks, futures etc.
if (data.Close != 0)
{
//Access custom data symbols using <ticker>.<custom-type>
Order("BTC.Bitcoin", Portfolio.MarginRemaining / Math.Abs(data.Close + 1));
}
}
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
changes.FilterCustomSecurities = false;
foreach (var addedSecurity in changes.AddedSecurities)
{
if (addedSecurity.Symbol.Value == "BTC")
{
_warmedUpChecked = true;
}
if (!addedSecurity.HasData)
{
throw new Exception($"Security {addedSecurity.Symbol} was not warmed up!");
}
}
}
public override void OnEndOfAlgorithm()
{
if (!_warmedUpChecked)
{
throw new Exception($"Security was not warmed up!");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 8942;
/// </summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "157.655%"},
{"Drawdown", "84.800%"},
{"Expectancy", "0"},
{"Net Profit", "5319.007%"},
{"Sharpe Ratio", "2.123"},
{"Probabilistic Sharpe Ratio", "70.581%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "1.776"},
{"Beta", "0.059"},
{"Annual Standard Deviation", "0.84"},
{"Annual Variance", "0.706"},
{"Information Ratio", "1.962"},
{"Tracking Error", "0.847"},
{"Treynor Ratio", "30.455"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "BTC.Bitcoin 2S"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "2.271"},
{"Return Over Maximum Drawdown", "1.86"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "50faa37f15732bf5c24ad1eeaa335bc7"}
};
/// <summary>
/// Custom Data Type: Bitcoin data from Quandl - http://www.quandl.com/help/api-for-bitcoin-data
/// </summary>
public class Bitcoin : BaseData
{
[JsonProperty("timestamp")]
public int Timestamp = 0;
[JsonProperty("open")]
public decimal Open = 0;
[JsonProperty("high")]
public decimal High = 0;
[JsonProperty("low")]
public decimal Low = 0;
[JsonProperty("last")]
public decimal Close = 0;
[JsonProperty("bid")]
public decimal Bid = 0;
[JsonProperty("ask")]
public decimal Ask = 0;
[JsonProperty("vwap")]
public decimal WeightedPrice = 0;
[JsonProperty("volume")]
public decimal VolumeBTC = 0;
public decimal VolumeUSD = 0;
/// <summary>
/// 1. DEFAULT CONSTRUCTOR: Custom data types need a default constructor.
/// We search for a default constructor so please provide one here. It won't be used for data, just to generate the "Factory".
/// </summary>
public Bitcoin()
{
Symbol = "BTC";
}
/// <summary>
/// 2. RETURN THE STRING URL SOURCE LOCATION FOR YOUR DATA:
/// This is a powerful and dynamic select source file method. If you have a large dataset, 10+mb we recommend you break it into smaller files. E.g. One zip per year.
/// We can accept raw text or ZIP files. We read the file extension to determine if it is a zip file.
/// </summary>
/// <param name="config">Configuration object</param>
/// <param name="date">Date of this source file</param>
/// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param>
/// <returns>String URL of source file.</returns>
public override SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode)
{
if (isLiveMode)
{
return new SubscriptionDataSource("https://www.bitstamp.net/api/ticker/", SubscriptionTransportMedium.Rest);
}
//return "http://my-ftp-server.com/futures-data-" + date.ToString("Ymd") + ".zip";
// OR simply return a fixed small data file. Large files will slow down your backtest
return new SubscriptionDataSource("https://www.quantconnect.com/api/v2/proxy/quandl/api/v3/datasets/BCHARTS/BITSTAMPUSD.csv?order=asc&api_key=WyAazVXnq7ATy_fefTqm", SubscriptionTransportMedium.RemoteFile);
}
/// <summary>
/// 3. READER METHOD: Read 1 line from data source and convert it into Object.
/// Each line of the CSV File is presented in here. The backend downloads your file, loads it into memory and then line by line
/// feeds it into your algorithm
/// </summary>
/// <param name="line">string line from the data source file submitted above</param>
/// <param name="config">Subscription data, symbol name, data type</param>
/// <param name="date">Current date we're requesting. This allows you to break up the data source into daily files.</param>
/// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param>
/// <returns>New Bitcoin Object which extends BaseData.</returns>
public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode)
{
var coin = new Bitcoin();
if (isLiveMode)
{
//Example Line Format:
//{"high": "441.00", "last": "421.86", "timestamp": "1411606877", "bid": "421.96", "vwap": "428.58", "volume": "14120.40683975", "low": "418.83", "ask": "421.99"}
try
{
coin = JsonConvert.DeserializeObject<Bitcoin>(line);
coin.EndTime = DateTime.UtcNow.ConvertFromUtc(config.ExchangeTimeZone);
coin.Value = coin.Close;
}
catch { /* Do nothing, possible error in json decoding */ }
return coin;
}
//Example Line Format:
//Date Open High Low Close Volume (BTC) Volume (Currency) Weighted Price
//2011-09-13 5.8 6.0 5.65 5.97 58.37138238, 346.0973893944 5.929230648356
try
{
string[] data = line.Split(',');
coin.Time = DateTime.Parse(data[0], CultureInfo.InvariantCulture);
coin.EndTime = coin.Time.AddDays(1);
coin.Open = Convert.ToDecimal(data[1], CultureInfo.InvariantCulture);
coin.High = Convert.ToDecimal(data[2], CultureInfo.InvariantCulture);
coin.Low = Convert.ToDecimal(data[3], CultureInfo.InvariantCulture);
coin.Close = Convert.ToDecimal(data[4], CultureInfo.InvariantCulture);
coin.VolumeBTC = Convert.ToDecimal(data[5], CultureInfo.InvariantCulture);
coin.VolumeUSD = Convert.ToDecimal(data[6], CultureInfo.InvariantCulture);
coin.WeightedPrice = Convert.ToDecimal(data[7], CultureInfo.InvariantCulture);
coin.Value = coin.Close;
}
catch { /* Do nothing, skip first title row */ }
return coin;
}
}
}
}
| 45.814545 | 221 | 0.561711 | [
"Apache-2.0"
] | StefanWarringa/Lean | Algorithm.CSharp/CustomDataRegressionAlgorithm.cs | 12,599 | C# |
using Delta.CapiNet.Asn1;
using Delta.Icao.Logging;
namespace Delta.Icao.Asn1
{
public sealed class Asn1Mrz : BaseAsn1String
{
private static readonly ILogService log = LogManager.GetLogger(typeof(Asn1Mrz));
private string[] decoded = null;
public Asn1Mrz(Asn1Document document, TaggedObject content, Asn1Object parentObject)
: base(document, content, parentObject) { }
public string[] Mrz
{
get
{
if (decoded == null) decoded = DecodeMrz(Value);
return decoded;
}
}
public override string ToString() => $"MRZ: \r\n{string.Join("\r\n", Mrz)}";
private string[] DecodeMrz(string input)
{
var mrz = new string[0]; // default
if (string.IsNullOrEmpty(input))
return mrz;
var mrzFormat = MrzFormat.FindByTotalLength(input);
if (mrzFormat == null)
{
log.Warning($"Invalid MRZ: {input}");
return mrz;
}
var parser = MrzParser.Create(input);
if (!parser.Parse())
{
log.Warning($"MRZ ({mrzFormat}) could not be decoded.");
return mrz;
}
mrz = parser.MrzArray;
log.Verbose($"MRZ ({mrzFormat}) was successfully decoded: \r\n{string.Join("\r\n", mrz)}");
return mrz;
}
}
}
| 27.943396 | 103 | 0.520594 | [
"MIT"
] | odalet/CertXplorer | src/Delta.Icao/Asn1/Asn1Mrz.cs | 1,483 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the runtime.lex.v2-2020-08-07.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.LexRuntimeV2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.LexRuntimeV2.Model.Internal.MarshallTransformations
{
/// <summary>
/// Intent Marshaller
/// </summary>
public class IntentMarshaller : IRequestMarshaller<Intent, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(Intent requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetConfirmationState())
{
context.Writer.WritePropertyName("confirmationState");
context.Writer.Write(requestObject.ConfirmationState);
}
if(requestObject.IsSetName())
{
context.Writer.WritePropertyName("name");
context.Writer.Write(requestObject.Name);
}
if(requestObject.IsSetSlots())
{
context.Writer.WritePropertyName("slots");
context.Writer.WriteObjectStart();
foreach (var requestObjectSlotsKvp in requestObject.Slots)
{
context.Writer.WritePropertyName(requestObjectSlotsKvp.Key);
var requestObjectSlotsValue = requestObjectSlotsKvp.Value;
context.Writer.WriteObjectStart();
var marshaller = SlotMarshaller.Instance;
marshaller.Marshall(requestObjectSlotsValue, context);
context.Writer.WriteObjectEnd();
}
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetState())
{
context.Writer.WritePropertyName("state");
context.Writer.Write(requestObject.State);
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static IntentMarshaller Instance = new IntentMarshaller();
}
} | 33.870968 | 112 | 0.628571 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/LexRuntimeV2/Generated/Model/Internal/MarshallTransformations/IntentMarshaller.cs | 3,150 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.