content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
using System;
using Newtonsoft.Json;
using TMDbLib.Objects.Account;
using TMDbLib.Objects.Authentication;
using TMDbLib.Objects.General;
using TMDbLib.Utilities.Converters;
using ParameterType = TMDbLib.Rest.ParameterType;
using RestClient = TMDbLib.Rest.RestClient;
using RestRequest = TMDbLib.Rest.RestRequest;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace TMDbLib.Client
{
public partial class TMDbClient : IDisposable
{
private const string ApiVersion = "3";
private const string ProductionUrl = "api.themoviedb.org";
private readonly JsonSerializer _serializer;
private RestClient _client;
private TMDbConfig _config;
public TMDbClient(string apiKey, bool useSsl = true, string baseUrl = ProductionUrl, JsonSerializer serializer = null, IWebProxy proxy = null)
{
DefaultLanguage = null;
DefaultCountry = null;
_serializer = serializer ?? JsonSerializer.CreateDefault();
_serializer.Converters.Add(new ChangeItemConverter());
_serializer.Converters.Add(new AccountStateConverter());
_serializer.Converters.Add(new KnownForConverter());
_serializer.Converters.Add(new SearchBaseConverter());
_serializer.Converters.Add(new TaggedImageConverter());
_serializer.Converters.Add(new TolerantEnumConverter());
//Setup proxy to use during requests
//Proxy is optional. If passed, will be used in every request.
WebProxy = proxy;
Initialize(baseUrl, useSsl, apiKey);
}
/// <summary>
/// The account details of the user account associated with the current user session
/// </summary>
/// <remarks>This value is automaticly populated when setting a user session</remarks>
public AccountDetails ActiveAccount { get; private set; }
public string ApiKey { get; private set; }
public TMDbConfig Config
{
get
{
if (!HasConfig)
throw new InvalidOperationException("Call GetConfig() or SetConfig() first");
return _config;
}
private set { _config = value; }
}
/// <summary>
/// ISO 3166-1 code. Ex. US
/// </summary>
public string DefaultCountry { get; set; }
/// <summary>
/// ISO 639-1 code. Ex en
/// </summary>
public string DefaultLanguage { get; set; }
public bool HasConfig { get; private set; }
/// <summary>
/// Throw exceptions when TMDbs API returns certain errors, such as Not Found.
/// </summary>
public bool ThrowApiExceptions
{
get => _client.ThrowApiExceptions;
set => _client.ThrowApiExceptions = value;
}
/// <summary>
/// The maximum number of times a call to TMDb will be retried
/// </summary>
/// <remarks>Default is 0</remarks>
public int MaxRetryCount
{
get => _client.MaxRetryCount;
set => _client.MaxRetryCount = value;
}
/// <summary>
/// The session id that will be used when TMDb requires authentication
/// </summary>
/// <remarks>Use 'SetSessionInformation' to assign this value</remarks>
public string SessionId { get; private set; }
/// <summary>
/// The type of the session id, this will determine the level of access that is granted on the API
/// </summary>
/// <remarks>Use 'SetSessionInformation' to assign this value</remarks>
public SessionType SessionType { get; private set; }
/// <summary>
/// Gets or sets the Web Proxy to use during requests to TMDb API.
/// </summary>
/// <remarks>
/// The Web Proxy is optional. If set, every request will be sent through it.
/// Use the constructor for setting it.
///
/// For convenience, this library also offers a <see cref="IWebProxy"/> implementation.
/// Check <see cref="Utilities.TMDbAPIProxy"/> for more information.
/// </remarks>
public IWebProxy WebProxy { get; private set; }
/// <summary>
/// Used internally to assign a session id to a request. If no valid session is found, an exception is thrown.
/// </summary>
/// <param name="req">Request</param>
/// <param name="targetType">The target session type to set. If set to Unassigned, the method will take the currently set session.</param>
/// <param name="parameterType">The location of the paramter in the resulting query</param>
private void AddSessionId(RestRequest req, SessionType targetType = SessionType.Unassigned, ParameterType parameterType = ParameterType.QueryString)
{
if ((targetType == SessionType.Unassigned && SessionType == SessionType.GuestSession) ||
(targetType == SessionType.GuestSession))
{
// Either
// - We needed ANY session ID and had a Guest session id
// - We needed a Guest session id and had it
req.AddParameter("guest_session_id", SessionId, parameterType);
return;
}
if ((targetType == SessionType.Unassigned && SessionType == SessionType.UserSession) ||
(targetType == SessionType.UserSession))
{
// Either
// - We needed ANY session ID and had a User session id
// - We needed a User session id and had it
req.AddParameter("session_id", SessionId, parameterType);
return;
}
// We did not have the required session type ready
throw new UserSessionRequiredException();
}
public async Task<TMDbConfig> GetConfigAsync()
{
TMDbConfig config = await _client.Create("configuration").ExecuteGet<TMDbConfig>(CancellationToken.None);
if (config == null)
throw new Exception("Unable to retrieve configuration");
// Store config
Config = config;
HasConfig = true;
return config;
}
public Uri GetImageUrl(string size, string filePath, bool useSsl = false)
{
string baseUrl = useSsl ? Config.Images.SecureBaseUrl : Config.Images.BaseUrl;
return new Uri(baseUrl + size + filePath);
}
private void Initialize(string baseUrl, bool useSsl, string apiKey)
{
if (string.IsNullOrWhiteSpace(baseUrl))
throw new ArgumentException("baseUrl");
if (string.IsNullOrWhiteSpace(apiKey))
throw new ArgumentException("apiKey");
ApiKey = apiKey;
// Cleanup the provided url so that we don't get any issues when we are configuring the client
if (baseUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
baseUrl = baseUrl.Substring("http://".Length);
else if (baseUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
baseUrl = baseUrl.Substring("https://".Length);
string httpScheme = useSsl ? "https" : "http";
_client = new RestClient(new Uri(string.Format("{0}://{1}/{2}/", httpScheme, baseUrl, ApiVersion)), _serializer, WebProxy);
_client.AddDefaultQueryString("api_key", apiKey);
}
/// <summary>
/// Used internally to determine if the current client has the required session set, if not an appropriate exception will be thrown
/// </summary>
/// <param name="sessionType">The type of session that is required by the calling method</param>
/// <exception cref="UserSessionRequiredException">Thrown if the calling method requires a user session and one isn't set on the client object</exception>
/// <exception cref="GuestSessionRequiredException">Thrown if the calling method requires a guest session and no session is set on the client object. (neither user or client type session)</exception>
private void RequireSessionId(SessionType sessionType)
{
if (string.IsNullOrWhiteSpace(SessionId))
{
if (sessionType == SessionType.GuestSession)
throw new UserSessionRequiredException();
else
throw new GuestSessionRequiredException();
}
if (sessionType == SessionType.UserSession && SessionType == SessionType.GuestSession)
throw new UserSessionRequiredException();
}
public void SetConfig(TMDbConfig config)
{
// Store config
Config = config;
HasConfig = true;
}
/// <summary>
/// Use this method to set the current client's authentication information.
/// The session id assigned here will be used by the client when ever TMDb requires it.
/// </summary>
/// <param name="sessionId">The session id to use when making calls that require authentication</param>
/// <param name="sessionType">The type of session id</param>
/// <remarks>
/// - Use the 'AuthenticationGetUserSessionAsync' and 'AuthenticationCreateGuestSessionAsync' methods to optain the respective session ids.
/// - User sessions have access to far for methods than guest sessions, these can currently only be used to rate media.
/// </remarks>
public void SetSessionInformation(string sessionId, SessionType sessionType)
{
ActiveAccount = null;
SessionId = sessionId;
if (!string.IsNullOrWhiteSpace(sessionId) && sessionType == SessionType.Unassigned)
{
throw new ArgumentException("When setting the session id it must always be either a guest or user session");
}
SessionType = string.IsNullOrWhiteSpace(sessionId) ? SessionType.Unassigned : sessionType;
// Populate the related account information
if (sessionType == SessionType.UserSession)
{
try
{
ActiveAccount = AccountGetDetailsAsync().Result;
}
catch (Exception)
{
// Unable to complete the full process so reset all values and throw the exception
ActiveAccount = null;
SessionId = null;
SessionType = SessionType.Unassigned;
throw;
}
}
}
public void Dispose()
{
_client?.Dispose();
}
}
} | 41.520913 | 207 | 0.601374 | [
"MIT"
] | Sl1MBoy/TMDbLib | TMDbLib/Client/TMDbClient.cs | 10,922 | C# |
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace ApiClient
{
public class DataService
{
private static DataService _instance = new DataService();
private HttpClient _client = new HttpClient();
private string _baseUrl = "SET_YOUR_SERVER_ADDRESS_HERE";
protected DataService()
{
}
public static DataService GetInstance()
{
return _instance;
}
public async Task<string> LoginAsync(string userName, string password)
{
var json = new JObject { { "UserName", userName }, { "Password", password } };
return await PostAsync("auth.php", json.ToString());
}
public async Task<string> LogoutAsync()
{
return await PostAsync("logout.php", string.Empty);
}
private async Task<string> PostAsync(string script, string json)
{
try
{
var response = await _client.PostAsync($"{_baseUrl}/{script}", new StringContent(json));
// Если нужно отправить как содержимое формы
//var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("data", json) });
//var response = await _client.PostAsync($"{_baseUrl}/{script}", content);
return await response.Content.ReadAsStringAsync();
}
catch (Exception e)
{
return e.Message;
}
}
public async Task<string> GetOrdersAsync()
{
try
{
return await _client.GetStringAsync($"{_baseUrl}/orders.php");
}
catch (Exception e)
{
return e.Message;
}
}
}
}
| 22.641791 | 104 | 0.684245 | [
"MIT"
] | ArtUstimovInMoscowPolytech/BasicPhpApi | csharp/ApiClient/ApiClient/DataService.cs | 1,555 | C# |
using System;
namespace Milou.Deployer.Waws
{
public sealed class DeploymentException : Exception
{
public DeploymentException(string message) : base(message)
{
}
}
} | 18.545455 | 66 | 0.642157 | [
"MIT"
] | niklaslundberg/milou.deployer | src/Milou.Deployer.Waws/DeploymentException.cs | 206 | C# |
using System.Collections.Generic;
using Essensoft.AspNetCore.Payment.Alipay.Response;
namespace Essensoft.AspNetCore.Payment.Alipay.Request
{
/// <summary>
/// alipay.daowei.order.confirm
/// </summary>
public class AlipayDaoweiOrderConfirmRequest : IAlipayRequest<AlipayDaoweiOrderConfirmResponse>
{
/// <summary>
/// 订单确认接口
/// </summary>
public string BizContent { get; set; }
#region IAlipayRequest Members
private bool needEncrypt = false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AlipayObject bizModel;
public void SetNeedEncrypt(bool needEncrypt)
{
this.needEncrypt = needEncrypt;
}
public bool GetNeedEncrypt()
{
return needEncrypt;
}
public void SetNotifyUrl(string notifyUrl)
{
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl()
{
return notifyUrl;
}
public void SetReturnUrl(string returnUrl)
{
this.returnUrl = returnUrl;
}
public string GetReturnUrl()
{
return returnUrl;
}
public void SetTerminalType(string terminalType)
{
this.terminalType = terminalType;
}
public string GetTerminalType()
{
return terminalType;
}
public void SetTerminalInfo(string terminalInfo)
{
this.terminalInfo = terminalInfo;
}
public string GetTerminalInfo()
{
return terminalInfo;
}
public void SetProdCode(string prodCode)
{
this.prodCode = prodCode;
}
public string GetProdCode()
{
return prodCode;
}
public string GetApiName()
{
return "alipay.daowei.order.confirm";
}
public void SetApiVersion(string apiVersion)
{
this.apiVersion = apiVersion;
}
public string GetApiVersion()
{
return apiVersion;
}
public IDictionary<string, string> GetParameters()
{
var parameters = new AlipayDictionary
{
{ "biz_content", BizContent }
};
return parameters;
}
public AlipayObject GetBizModel()
{
return bizModel;
}
public void SetBizModel(AlipayObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 22.532258 | 99 | 0.545097 | [
"MIT"
] | Msy1989/payment | src/Essensoft.AspNetCore.Payment.Alipay/Request/AlipayDaoweiOrderConfirmRequest.cs | 2,808 | C# |
using System.Xml.Serialization;
namespace Amazon.Elb
{
public class DescribeTargetGroupAttributesResponse : IElbResponse
{
[XmlElement]
public DescribeTargetGroupAttributesResult DescribeTargetGroupAttributesResult { get; set; }
}
public class DescribeTargetGroupAttributesResult
{
[XmlArray]
[XmlArrayItem("member")]
public TargetGroupAttribute[] Attributes { get; set; }
}
}
/*
<DescribeTargetGroupAttributesResponse xmlns="http://elasticloadbalancing.amazonaws.com/doc/2015-12-01/">
<DescribeTargetGroupAttributesResult>
<Attributes>
<member>
<Value>300</Value>
<Key>deregistration_delay.timeout_seconds</Key>
</member>
</Attributes>
</DescribeTargetGroupAttributesResult>
<ResponseMetadata>
<RequestId>54618294-f3a8-11e5-bb98-57195a6eb84a</RequestId>
</ResponseMetadata>
</DescribeTargetGroupAttributesResponse>
*/ | 29.606061 | 106 | 0.69089 | [
"MIT"
] | alexandercamps/Amazon | src/Amazon.Elb/Actions/DescribeTargetGroupAttributesResponse.cs | 979 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using TEA.MVVM;
using TestTools;
namespace TEA.MVVMTest {
public class OneSelectionRenderTest {
public enum Selection {
NoneSelection,
First,
Second,
Third,
}
[Test]
[TestCase(Selection.NoneSelection)]
[TestCase(Selection.First)]
public void InitialTest(Selection noneSelection) {
var render = new OneSelectionRender<Selection>(noneSelection);
render.Value.Is(noneSelection);
}
public record NotifyData<TKind>(string PropertyName, TKind Kind);
[Test]
public void NoneSelectionRenderTest() {
var render = new OneSelectionRender<Selection>(Selection.NoneSelection);
render.Render(Selection.First);
var actualNotify = new List<NotifyData<Selection>>();
render.PropertyChanged += (sender, args) => {
var val = (sender as OneSelectionRender<Selection>)!;
actualNotify.Add(new(args.PropertyName!, val.Value));
};
var notify1 = render[Selection.First];
notify1.Value.Is(true);
var notify2 = render[Selection.Second];
notify2.Value.Is(false);
actualNotify.ToArray().Is(Array.Empty<NotifyData<Selection>>());
render.Render(Selection.NoneSelection);
notify1.Value.Is(false);
notify2.Value.Is(false);
actualNotify.ToArray().Is(new NotifyData<Selection>[] { new(nameof(OneSelectionRender<Selection>.Value), Selection.NoneSelection) });
}
[Test]
[TestCase(Selection.NoneSelection)]
[TestCase("")]
public void ExceptionOnGetNoneSelection<T>(T noneSelection) {
var render = new OneSelectionRender<T>(noneSelection);
Assert.That(() => { var _ = render[noneSelection]; }, Throws.Exception.TypeOf<ArgumentException>());
}
[Test]
public void ExceptionOnGetNull() {
void Check<T>(T noneSelection, T? nullValue) {
var render = new OneSelectionRender<T?>(noneSelection);
Assert.That(() => { var _ = render[nullValue]; }, Throws.Exception.TypeOf<ArgumentException>());
}
Check("", null);
Check<int?>(1, null);
}
[Test]
[TestCase(Selection.NoneSelection, Selection.First, false)]
[TestCase(Selection.NoneSelection, Selection.First, true)]
[TestCase(Selection.NoneSelection, Selection.Third, true)]
[TestCase(Selection.NoneSelection, Selection.Third, false)]
[TestCase(null, "", true)]
[TestCase(null, "", false)]
public void RenderTest<T>(T noneSelection, T nextSelection, bool renderAndGetValue) {
var render = new OneSelectionRender<T>(noneSelection);
var actualNotify = new List<NotifyData<T>>();
render.PropertyChanged += (sender, args) => {
var val = (sender as OneSelectionRender<T>)!;
actualNotify.Add(new(args.PropertyName!, val.Value));
};
if (renderAndGetValue) {
// render and get value.
render.Render(nextSelection);
render[nextSelection].Value.Is(true);
}
else {
// get value and render.
var notify = render[nextSelection];
notify.Value.Is(false);
render.Render(nextSelection);
notify.Value.Is(true);
}
actualNotify.ToArray().Is(
new NotifyData<T>[] { new(nameof(OneSelectionRender<Selection>.Value), nextSelection) });
}
[Test]
public void RenderNullTest() {
void Check<T>(T noneSelection, T initialSelection, T nextSelection) {
var render = new OneSelectionRender<T>(noneSelection);
var actualNotify = new List<NotifyData<T>>();
render.PropertyChanged += (sender, args) => {
var val = (sender as OneSelectionRender<T>)!;
actualNotify.Add(new(args.PropertyName!, val.Value));
};
void CheckNotiry(T prevValue, T renderedValue) {
actualNotify.ToArray().Is(
EqualityComparer<T>.Default.Equals(prevValue, renderedValue)
? Array.Empty<NotifyData<T>>()
: new[] { new NotifyData<T>(nameof(OneSelectionRender<T>.Value), renderedValue) });
}
render.Render(initialSelection);
render.Value.Is(initialSelection);
CheckNotiry(noneSelection, initialSelection);
actualNotify.Clear();
render.Render(nextSelection);
render.Value.Is(nextSelection);
CheckNotiry(initialSelection, nextSelection);
}
Check<int?>(null, 8, null);
Check<string?>(null, "", null);
}
[Test]
public void SetValueTest() {
var render = new OneSelectionRender<Selection>(Selection.NoneSelection);
var values = new[] {
render[Selection.First],
render[Selection.Second],
render[Selection.Third]
};
values[2].Value = true;
values.Select(x => x.Value).Is(new[] { false, false, true});
values[0].Value = true;
values.Select(x => x.Value).Is(new[] { true, false, false});
values[0].Value = false;
values.Select(x => x.Value).Is(new[] { false, false, false});
}
}
}
| 37.901961 | 145 | 0.559062 | [
"MIT"
] | Sinsjr2/TEA | src/TEA.MVVMTest/OneSelectionRenderTest.cs | 5,799 | C# |
// Copyright 2018 by JCoder58. See License.txt for license
// Auto-generated --- Do not modify.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UE4.Core;
using UE4.CoreUObject;
using UE4.CoreUObject.Native;
using UE4.InputCore;
using UE4.Native;
namespace UE4.Engine {
///<summary>Cylinder Height Axis</summary>
public enum CylinderHeightAxis {
PMLPC_HEIGHTAXIS_X = 0x00000000,
PMLPC_HEIGHTAXIS_Y = 0x00000001,
PMLPC_HEIGHTAXIS_Z = 0x00000002,
PMLPC_HEIGHTAXIS_MAX = 0x00000003
}
}
| 27.380952 | 59 | 0.733913 | [
"MIT"
] | UE4DotNet/Plugin | DotNet/DotNet/UE4/Generated/Engine/CylinderHeightAxis.cs | 575 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Fateblade.Haushaltsbuch.Logic.Foundation.OrchestratableDialogs.Contract;
namespace Fateblade.Haushaltsbuch.Logic.Foundation.OrchestratableDialogs.CommonUserInputDialogs.Contract.DataClasses
{
public class InfoDialogResult : IDialogResult
{
}
public class InfoDialogRequest : IDialogRequest
{
public string Info { get; set; }
}
}
| 25.705882 | 116 | 0.773455 | [
"MIT"
] | Fateblade/Haushaltsbuch | OrchestratableDialogs.CommonUserInputDialogs.Contract/DataClasses/InfoDialog.cs | 439 | 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 worklink-2018-09-25.normal.json service model.
*/
using System;
using Amazon.Runtime;
using Amazon.Util.Internal;
namespace Amazon.WorkLink
{
/// <summary>
/// Configuration for accessing Amazon WorkLink service
/// </summary>
public partial class AmazonWorkLinkConfig : ClientConfig
{
private static readonly string UserAgentString =
InternalSDKUtils.BuildUserAgentString("3.7.0.118");
private string _userAgent = UserAgentString;
/// <summary>
/// Default constructor
/// </summary>
public AmazonWorkLinkConfig()
: base(new Amazon.Runtime.Internal.DefaultConfigurationProvider(AmazonWorkLinkDefaultConfiguration.GetAllConfigurations()))
{
this.AuthenticationServiceName = "worklink";
}
/// <summary>
/// The constant used to lookup in the region hash the endpoint.
/// </summary>
public override string RegionEndpointServiceName
{
get
{
return "worklink";
}
}
/// <summary>
/// Gets the ServiceVersion property.
/// </summary>
public override string ServiceVersion
{
get
{
return "2018-09-25";
}
}
/// <summary>
/// Gets the value of UserAgent property.
/// </summary>
public override string UserAgent
{
get
{
return _userAgent;
}
}
}
} | 27.345679 | 135 | 0.599549 | [
"Apache-2.0"
] | ianb888/aws-sdk-net | sdk/src/Services/WorkLink/Generated/AmazonWorkLinkConfig.cs | 2,215 | C# |
using Abp.Application.Navigation;
using Abp.Authorization;
using Abp.Localization;
using tarea2.Authorization;
namespace tarea2.Web
{
/// <summary>
/// This class defines menus for the application.
/// It uses ABP's menu system.
/// When you add menu items here, they are automatically appear in angular application.
/// See Views/Layout/_TopMenu.cshtml file to know how to render menu.
/// </summary>
public class tarea2NavigationProvider : NavigationProvider
{
public override void SetNavigation(INavigationProviderContext context)
{
context.Manager.MainMenu
.AddItem(
new MenuItemDefinition(
PageNames.Home,
L("HomePage"),
url: "",
icon: "home",
requiresAuthentication: true
)
).AddItem(
new MenuItemDefinition(
PageNames.Tenants,
L("Tenants"),
url: "Tenants",
icon: "business",
permissionDependency: new SimplePermissionDependency(PermissionNames.Pages_Tenants)
)
).AddItem(
new MenuItemDefinition(
PageNames.Users,
L("Users"),
url: "Users",
icon: "people",
permissionDependency: new SimplePermissionDependency(PermissionNames.Pages_Users)
)
).AddItem(
new MenuItemDefinition(
PageNames.Roles,
L("Roles"),
url: "Roles",
icon: "local_offer",
permissionDependency: new SimplePermissionDependency(PermissionNames.Pages_Roles)
)
)
.AddItem(
new MenuItemDefinition(
PageNames.About,
L("About"),
url: "About",
icon: "info"
)
).AddItem( //Menu items below is just for demonstration!
new MenuItemDefinition(
"MultiLevelMenu",
L("MultiLevelMenu"),
icon: "menu"
).AddItem(
new MenuItemDefinition(
"AspNetBoilerplate",
new FixedLocalizableString("ASP.NET Boilerplate")
).AddItem(
new MenuItemDefinition(
"AspNetBoilerplateHome",
new FixedLocalizableString("Home"),
url: "https://aspnetboilerplate.com?ref=abptmpl"
)
).AddItem(
new MenuItemDefinition(
"AspNetBoilerplateTemplates",
new FixedLocalizableString("Templates"),
url: "https://aspnetboilerplate.com/Templates?ref=abptmpl"
)
).AddItem(
new MenuItemDefinition(
"AspNetBoilerplateSamples",
new FixedLocalizableString("Samples"),
url: "https://aspnetboilerplate.com/Samples?ref=abptmpl"
)
).AddItem(
new MenuItemDefinition(
"AspNetBoilerplateDocuments",
new FixedLocalizableString("Documents"),
url: "https://aspnetboilerplate.com/Pages/Documents?ref=abptmpl"
)
)
).AddItem(
new MenuItemDefinition(
"AspNetZero",
new FixedLocalizableString("ASP.NET Zero")
).AddItem(
new MenuItemDefinition(
"AspNetZeroHome",
new FixedLocalizableString("Home"),
url: "https://aspnetzero.com?ref=abptmpl"
)
).AddItem(
new MenuItemDefinition(
"AspNetZeroDescription",
new FixedLocalizableString("Description"),
url: "https://aspnetzero.com/?ref=abptmpl#description"
)
).AddItem(
new MenuItemDefinition(
"AspNetZeroFeatures",
new FixedLocalizableString("Features"),
url: "https://aspnetzero.com/?ref=abptmpl#features"
)
).AddItem(
new MenuItemDefinition(
"AspNetZeroPricing",
new FixedLocalizableString("Pricing"),
url: "https://aspnetzero.com/?ref=abptmpl#pricing"
)
).AddItem(
new MenuItemDefinition(
"AspNetZeroFaq",
new FixedLocalizableString("Faq"),
url: "https://aspnetzero.com/Faq?ref=abptmpl"
)
).AddItem(
new MenuItemDefinition(
"AspNetZeroDocuments",
new FixedLocalizableString("Documents"),
url: "https://aspnetzero.com/Documents?ref=abptmpl"
)
)
)
);
}
private static ILocalizableString L(string name)
{
return new LocalizableString(name, tarea2Consts.LocalizationSourceName);
}
}
}
| 44.847222 | 107 | 0.403685 | [
"MIT"
] | jcarlos0605/Tarea2.net | tarea2/5.7.0/src/tarea2.Web/App_Start/tarea2NavigationProvider.cs | 6,460 | C# |
using Neo.SmartContract;
using Neo.VM;
using System;
namespace Neo.Wallets
{
public class AssetDescriptor
{
public UInt160 AssetId;
public string AssetName;
public byte Decimals;
public AssetDescriptor(UInt160 asset_id)
{
byte[] script;
using (ScriptBuilder sb = new ScriptBuilder())
{
sb.EmitAppCall(asset_id, "decimals");
sb.EmitAppCall(asset_id, "name");
script = sb.ToArray();
}
ApplicationEngine engine = ApplicationEngine.Run(script, extraGAS: 3_000_000);
if (engine.State.HasFlag(VMState.FAULT)) throw new ArgumentException();
this.AssetId = asset_id;
this.AssetName = engine.ResultStack.Pop().GetString();
this.Decimals = (byte)engine.ResultStack.Pop().GetBigInteger();
}
public override string ToString()
{
return AssetName;
}
}
}
| 28.457143 | 90 | 0.575301 | [
"MIT"
] | SeppPenner/neo | neo/Wallets/AssetDescriptor.cs | 998 | C# |
using System.Collections.Generic;
using System.Text;
using Nethereum.Hex.HexConvertors.Extensions;
namespace Nethereum.Signer
{
public class EthereumMessageSigner : MessageSigner
{
public override string EcRecover(byte[] message, string signature)
{
return base.EcRecover(HashPrefixedMessage(message), signature);
}
public byte[] HashAndHashPrefixedMessage(byte[] message)
{
return HashPrefixedMessage(Hash(message));
}
public override string HashAndSign(byte[] plainMessage, EthECKey key)
{
return base.Sign(HashAndHashPrefixedMessage(plainMessage), key);
}
public byte[] HashPrefixedMessage(byte[] message)
{
var byteList = new List<byte>();
var bytePrefix = "0x19".HexToByteArray();
var textBytePrefix = Encoding.UTF8.GetBytes("Ethereum Signed Message:\n" + message.Length);
byteList.AddRange(bytePrefix);
byteList.AddRange(textBytePrefix);
byteList.AddRange(message);
return Hash(byteList.ToArray());
}
public override string Sign(byte[] message, EthECKey key)
{
return base.Sign(HashPrefixedMessage(message), key);
}
public string EncodeUTF8AndSign(string message, EthECKey key)
{
return base.Sign(HashPrefixedMessage(Encoding.UTF8.GetBytes(message)), key);
}
public string EncodeUTF8AndEcRecover(string message, string signature)
{
return EcRecover(Encoding.UTF8.GetBytes(message), signature);
}
}
} | 32.333333 | 103 | 0.633717 | [
"MIT"
] | 6ara6aka/Nethereum | src/Nethereum.Signer/EthereumMessageSigner.cs | 1,649 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: IEntityRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The interface IMuteParticipantsOperationRequestBuilder.
/// </summary>
public partial interface IMuteParticipantsOperationRequestBuilder : ICommsOperationRequestBuilder
{
/// <summary>
/// Builds the request.
/// </summary>
/// <returns>The built request.</returns>
new IMuteParticipantsOperationRequest Request();
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
new IMuteParticipantsOperationRequest Request(IEnumerable<Option> options);
}
}
| 35.694444 | 153 | 0.585214 | [
"MIT"
] | GeertVL/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Generated/requests/IMuteParticipantsOperationRequestBuilder.cs | 1,285 | C# |
using Orchard.ContentManagement;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Orchard.CRM.Core.Models
{
public class TicketMenuItemPart : ContentPart<TicketMenuItemPartRecord>
{
}
} | 20.333333 | 75 | 0.782787 | [
"MIT"
] | AccentureRapid/OrchardCollaboration | src/Orchard.Web/Modules/Orchard.CRM.Core/Models/TicketMenuItemPart.cs | 244 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class JunYueShouCardLogic : CardLogic
{
public override void Init()
{
base.Init();
this.Color = CardLogicColor.white;
this.displayName = LocalizationMgr.Instance.GetLocalizationWord("CT_N_175");
this.Desc = string.Format(LocalizationMgr.Instance.GetLocalizationWord("CT_D_175"), (this.baseDmg + this.increaseDmg * (float)base.Layers) * 100f);
}
public override void OnShowTips()
{
base.OnShowTips();
this.displayName = LocalizationMgr.Instance.GetLocalizationWord("CT_N_175");
this.Desc = string.Format(LocalizationMgr.Instance.GetLocalizationWord("CT_D_175"), (this.baseDmg + this.increaseDmg * (float)base.Layers) * 100f);
}
public override IEnumerator OnAfterAttack(CardData player, CardSlotData target)
{
base.OnAfterAttack(player, target);
if (player == this.CardData)
{
List<CardSlotData> myBattleArea = base.GetMyBattleArea();
List<CardData> list = new List<CardData>();
if (myBattleArea.IndexOf(this.CardData.CurrentCardSlotData) < myBattleArea.Count / 3 * 2)
{
CardSlotData cardSlotData = myBattleArea[myBattleArea.IndexOf(this.CardData.CurrentCardSlotData) + myBattleArea.Count / 3];
if (cardSlotData.ChildCardData != null && cardSlotData.ChildCardData.HasTag(TagMap.随从))
{
list.Add(cardSlotData.ChildCardData);
}
}
if (list.Count <= 0)
{
yield break;
}
using (List<CardData>.Enumerator enumerator = list.GetEnumerator())
{
while (enumerator.MoveNext())
{
CardData cardData = enumerator.Current;
cardData.wATK += Mathf.CeilToInt((float)cardData.ATK * (this.baseDmg + this.increaseDmg * (float)base.Layers));
}
yield break;
}
}
yield break;
}
private float baseDmg;
private float increaseDmg = 0.3f;
}
| 31.118644 | 149 | 0.724946 | [
"Apache-2.0"
] | Shadowrabbit/BigBiaDecompilation | Source/Assembly-CSharp/JunYueShouCardLogic.cs | 1,842 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace NewPlatform.Flexberry.ORM.ODataService.Tests
{
using System;
using System.Xml;
using ICSSoft.STORMNET;
// *** Start programmer edit section *** (Using statements)
// *** End programmer edit section *** (Using statements)
/// <summary>
/// Driver.
/// </summary>
// *** Start programmer edit section *** (Driver CustomAttributes)
// *** End programmer edit section *** (Driver CustomAttributes)
[AutoAltered()]
[AccessType(ICSSoft.STORMNET.AccessType.none)]
[View("AllData", new string[] {
"Name as \'Name\'",
"CarCount as \'CarCount\'",
"Documents as \'Documents\'"})]
public class Driver : ICSSoft.STORMNET.DataObject
{
private string fName;
private int fCarCount;
private bool fDocuments;
private NewPlatform.Flexberry.ORM.ODataService.Tests.DetailArrayOfCar fCar;
// *** Start programmer edit section *** (Driver CustomMembers)
// *** End programmer edit section *** (Driver CustomMembers)
/// <summary>
/// Name.
/// </summary>
// *** Start programmer edit section *** (Driver.Name CustomAttributes)
// *** End programmer edit section *** (Driver.Name CustomAttributes)
[StrLen(255)]
public virtual string Name
{
get
{
// *** Start programmer edit section *** (Driver.Name Get start)
// *** End programmer edit section *** (Driver.Name Get start)
string result = this.fName;
// *** Start programmer edit section *** (Driver.Name Get end)
// *** End programmer edit section *** (Driver.Name Get end)
return result;
}
set
{
// *** Start programmer edit section *** (Driver.Name Set start)
// *** End programmer edit section *** (Driver.Name Set start)
this.fName = value;
// *** Start programmer edit section *** (Driver.Name Set end)
// *** End programmer edit section *** (Driver.Name Set end)
}
}
/// <summary>
/// CarCount.
/// </summary>
// *** Start programmer edit section *** (Driver.CarCount CustomAttributes)
// *** End programmer edit section *** (Driver.CarCount CustomAttributes)
public virtual int CarCount
{
get
{
// *** Start programmer edit section *** (Driver.CarCount Get start)
// *** End programmer edit section *** (Driver.CarCount Get start)
int result = this.fCarCount;
// *** Start programmer edit section *** (Driver.CarCount Get end)
// *** End programmer edit section *** (Driver.CarCount Get end)
return result;
}
set
{
// *** Start programmer edit section *** (Driver.CarCount Set start)
// *** End programmer edit section *** (Driver.CarCount Set start)
this.fCarCount = value;
// *** Start programmer edit section *** (Driver.CarCount Set end)
// *** End programmer edit section *** (Driver.CarCount Set end)
}
}
/// <summary>
/// Documents.
/// </summary>
// *** Start programmer edit section *** (Driver.Documents CustomAttributes)
// *** End programmer edit section *** (Driver.Documents CustomAttributes)
public virtual bool Documents
{
get
{
// *** Start programmer edit section *** (Driver.Documents Get start)
// *** End programmer edit section *** (Driver.Documents Get start)
bool result = this.fDocuments;
// *** Start programmer edit section *** (Driver.Documents Get end)
// *** End programmer edit section *** (Driver.Documents Get end)
return result;
}
set
{
// *** Start programmer edit section *** (Driver.Documents Set start)
// *** End programmer edit section *** (Driver.Documents Set start)
this.fDocuments = value;
// *** Start programmer edit section *** (Driver.Documents Set end)
// *** End programmer edit section *** (Driver.Documents Set end)
}
}
/// <summary>
/// Driver.
/// </summary>
// *** Start programmer edit section *** (Driver.Car CustomAttributes)
// *** End programmer edit section *** (Driver.Car CustomAttributes)
public virtual NewPlatform.Flexberry.ORM.ODataService.Tests.DetailArrayOfCar Car
{
get
{
// *** Start programmer edit section *** (Driver.Car Get start)
// *** End programmer edit section *** (Driver.Car Get start)
if ((this.fCar == null))
{
this.fCar = new NewPlatform.Flexberry.ORM.ODataService.Tests.DetailArrayOfCar(this);
}
NewPlatform.Flexberry.ORM.ODataService.Tests.DetailArrayOfCar result = this.fCar;
// *** Start programmer edit section *** (Driver.Car Get end)
// *** End programmer edit section *** (Driver.Car Get end)
return result;
}
set
{
// *** Start programmer edit section *** (Driver.Car Set start)
// *** End programmer edit section *** (Driver.Car Set start)
this.fCar = value;
// *** Start programmer edit section *** (Driver.Car Set end)
// *** End programmer edit section *** (Driver.Car Set end)
}
}
/// <summary>
/// Class views container.
/// </summary>
public class Views
{
/// <summary>
/// "AllData" view.
/// </summary>
public static ICSSoft.STORMNET.View AllData
{
get
{
return ICSSoft.STORMNET.Information.GetView("AllData", typeof(NewPlatform.Flexberry.ORM.ODataService.Tests.Driver));
}
}
}
}
}
| 34.879397 | 136 | 0.50036 | [
"MIT"
] | kn1k/NewPlatform.Flexberry.ORM.ODataService | Tests/Objects/Driver.cs | 7,077 | C# |
// Copyright (c) Christof Senn. All rights reserved. See license.txt in the project root for license information.
namespace DemoStartUp
{
using System;
class Program
{
static void Main(string[] args)
{
const string host = "localhost";
const int port = 8089;
Console.WriteLine("Starting Web API service...");
using (var webApiServer = new Server.WebApiServer(port))
{
webApiServer.Open();
Console.WriteLine("Started query service.");
Console.WriteLine("Staring client demo...");
Console.WriteLine("-------------------------------------------------");
new Client.Demo(host, port).Run();
Console.WriteLine();
Console.WriteLine("-------------------------------------------------");
Console.WriteLine("Done.");
}
Console.WriteLine("Terminated Web API service. Hit enter to exit.");
Console.ReadLine();
}
}
}
| 27 | 114 | 0.483333 | [
"MIT"
] | 6bee/Remote.Linq-Samples | RemoteQueryable/10_UsingJsonSerializationOverWebApi/DemoStartUp/Program.cs | 1,082 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Ecas.Dyn365Service.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
namespace Ecas.Dyn365Service.Controllers
{
/// <summary>
/// Wrapper that executes GET (Read) on Dynamics 365 Metadata. This is to be used for querying entity attribute definition such as OptionSets or StatusReason fields.
/// </summary>
[Route("api/[controller]")]
[Authorize]
[ApiController]
public class MetadataController : ControllerBase
{
DynamicsAuthenticationSettings _dynamicsAuthenticationSettings;
public MetadataController(DynamicsAuthenticationSettings dynamicsAuthenticationSettings)
{
_dynamicsAuthenticationSettings = dynamicsAuthenticationSettings;
}
/// <summary>
/// Executes GET operations against the Dyn365 API. View https://docs.microsoft.com/en-us/powerapps/developer/common-data-service/webapi/query-metadata-web-api
/// </summary>
/// <param name="entityName">Name of the Entity where attribute resides</param>
/// <param name="optionSetName">name of the Attribute</param>
/// <returns></returns>
// GET: api/Metadata
[HttpGet]
public ActionResult<string> Get(string entityName, string optionSetName)
{
if (string.IsNullOrEmpty(entityName) || string.IsNullOrEmpty(optionSetName)) return string.Empty;
var statement = string.Empty;
if(optionSetName.ToLower() != "statuscode")
statement = $"EntityDefinitions(LogicalName='{entityName}')/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$filter=LogicalName eq '{optionSetName}'&$expand=OptionSet";
else
statement = $"EntityDefinitions(LogicalName='{entityName}')/Attributes/Microsoft.Dynamics.CRM.StatusAttributeMetadata?$select=LogicalName&$filter=LogicalName eq '{optionSetName}'&$expand=OptionSet";
var response = new Dyn365WebAPI().SendRetrieveRequestAsync(statement, true);
if (response.IsSuccessStatusCode)
{
JObject metadataInfo = JObject.Parse(response.Content.ReadAsStringAsync().Result);
Dynamics365OptionSet optionSet = new Dynamics365OptionSet
{
InternalName = metadataInfo["value"][0]["OptionSet"]["Name"].ToString(),
LogicalName = metadataInfo["value"][0]["LogicalName"].ToString(),
Options = (from o in metadataInfo["value"][0]["OptionSet"]["Options"]
select new Dynamics365OptionSetItem
{
Id = Convert.ToInt32(o["Value"]),
Label = o["Label"]["LocalizedLabels"][0]["Label"].ToString()
}).ToList()
};
return Ok(JObject.FromObject(optionSet));
}
else
return StatusCode((int)response.StatusCode,
$"Failed to Retrieve records: {response.ReasonPhrase}");
}
}
}
| 47.042857 | 216 | 0.634072 | [
"Apache-2.0"
] | arcshiftsolutions/EDUC-ECAS | web-api/Ecas.Dyn365Service/Controllers/MetadataController.cs | 3,295 | 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.
namespace Microsoft.AspNetCore.Components.WebAssembly.Http
{
/// <summary>
/// Specifies a value for the 'credentials' option on outbound HTTP requests.
/// </summary>
public enum BrowserRequestCredentials
{
/// <summary>
/// Advises the browser never to send credentials (such as cookies or HTTP auth headers).
/// </summary>
Omit,
/// <summary>
/// Advises the browser to send credentials (such as cookies or HTTP auth headers)
/// only if the target URL is on the same origin as the calling application.
/// </summary>
SameOrigin,
/// <summary>
/// Advises the browser to send credentials (such as cookies or HTTP auth headers)
/// even for cross-origin requests.
/// </summary>
Include,
}
}
| 34.517241 | 111 | 0.633367 | [
"Apache-2.0"
] | 1175169074/aspnetcore | src/Components/WebAssembly/WebAssembly/src/Http/BrowserRequestCredentials.cs | 1,001 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
namespace Bytewizer.TinyCLR.Numerics
{
public struct BigInteger : IComparable
{
//LSB on [0]
readonly uint[] data;
readonly short sign;
static readonly uint[] ONE = new uint[1] { 1 };
BigInteger(short sign, uint[] data)
{
this.sign = sign;
this.data = data;
}
public BigInteger(int value)
{
if (value == 0)
{
sign = 0;
data = null;
}
else if (value > 0)
{
sign = 1;
data = new uint[] { (uint)value };
}
else
{
sign = -1;
data = new uint[1] { (uint)-value };
}
}
public BigInteger(uint value)
{
if (value == 0)
{
sign = 0;
data = null;
}
else
{
sign = 1;
data = new uint[1] { value };
}
}
public BigInteger(long value)
{
if (value == 0)
{
sign = 0;
data = null;
}
else if (value > 0)
{
sign = 1;
uint low = (uint)value;
uint high = (uint)(value >> 32);
data = new uint[high != 0 ? 2 : 1];
data[0] = low;
if (high != 0)
data[1] = high;
}
else
{
sign = -1;
value = -value;
uint low = (uint)value;
uint high = (uint)((ulong)value >> 32);
data = new uint[high != 0 ? 2 : 1];
data[0] = low;
if (high != 0)
data[1] = high;
}
}
public BigInteger(ulong value)
{
if (value == 0)
{
sign = 0;
data = null;
}
else
{
sign = 1;
uint low = (uint)value;
uint high = (uint)(value >> 32);
data = new uint[high != 0 ? 2 : 1];
data[0] = low;
if (high != 0)
data[1] = high;
}
}
static bool Negative(byte[] v)
{
return ((v[7] & 0x80) != 0);
}
static ushort Exponent(byte[] v)
{
return (ushort)((((ushort)(v[7] & 0x7F)) << (ushort)4) | (((ushort)(v[6] & 0xF0)) >> 4));
}
static ulong Mantissa(byte[] v)
{
uint i1 = ((uint)v[0] | ((uint)v[1] << 8) | ((uint)v[2] << 16) | ((uint)v[3] << 24));
uint i2 = ((uint)v[4] | ((uint)v[5] << 8) | ((uint)(v[6] & 0xF) << 16));
return (ulong)((ulong)i1 | ((ulong)i2 << 32));
}
const int bias = 1075;
public BigInteger(double value)
{
if (double.IsNaN(value) || Double.IsInfinity(value))
throw new OverflowException();
byte[] bytes = BitConverter.GetBytes(value);
ulong mantissa = Mantissa(bytes);
if (mantissa == 0)
{
// 1.0 * 2**exp, we have a power of 2
int exponent = Exponent(bytes);
if (exponent == 0)
{
sign = 0;
data = null;
return;
}
BigInteger res = Negative(bytes) ? MinusOne : One;
res = res << (exponent - 0x3ff);
this.sign = res.sign;
this.data = res.data;
}
else
{
// 1.mantissa * 2**exp
int exponent = Exponent(bytes);
mantissa |= 0x10000000000000ul;
BigInteger res = mantissa;
res = exponent > bias ? res << (exponent - bias) : res >> (bias - exponent);
this.sign = (short)(Negative(bytes) ? -1 : 1);
this.data = res.data;
}
}
public BigInteger(float value)
: this((double)value)
{
}
public BigInteger(byte[] value)
{
if (value == null)
throw new ArgumentNullException("value");
int len = value.Length;
if (len == 0 || (len == 1 && value[0] == 0))
{
sign = 0;
data = null;
return;
}
if ((value[len - 1] & 0x80) != 0)
sign = -1;
else
sign = 1;
if (sign == 1)
{
while (value[len - 1] == 0)
{
if (--len == 0)
{
sign = 0;
data = null;
return;
}
}
int full_words, size;
full_words = size = len / 4;
if ((len & 0x3) != 0)
++size;
data = new uint[size];
int j = 0;
for (int i = 0; i < full_words; ++i)
{
data[i] = (uint)value[j++] |
(uint)(value[j++] << 8) |
(uint)(value[j++] << 16) |
(uint)(value[j++] << 24);
}
size = len & 0x3;
if (size > 0)
{
int idx = data.Length - 1;
for (int i = 0; i < size; ++i)
data[idx] |= (uint)(value[j++] << (i * 8));
}
}
else
{
int full_words, size;
full_words = size = len / 4;
if ((len & 0x3) != 0)
++size;
data = new uint[size];
uint word, borrow = 1;
ulong sub = 0;
int j = 0;
for (int i = 0; i < full_words; ++i)
{
word = (uint)value[j++] |
(uint)(value[j++] << 8) |
(uint)(value[j++] << 16) |
(uint)(value[j++] << 24);
sub = (ulong)word - borrow;
word = (uint)sub;
borrow = (uint)(sub >> 32) & 0x1u;
data[i] = ~word;
}
size = len & 0x3;
if (size > 0)
{
word = 0;
uint store_mask = 0;
for (int i = 0; i < size; ++i)
{
word |= (uint)(value[j++] << (i * 8));
store_mask = (store_mask << 8) | 0xFF;
}
sub = word - borrow;
word = (uint)sub;
borrow = (uint)(sub >> 32) & 0x1u;
if ((~word & store_mask) == 0)
data = Resize(data, data.Length - 1);
else
data[data.Length - 1] = ~word & store_mask;
}
if (borrow != 0) //FIXME I believe this can't happen, can someone write a test for it?
throw new Exception("non zero final carry");
}
}
public bool IsEven
{
get { return sign == 0 || (data[0] & 0x1) == 0; }
}
public bool IsOne
{
get { return sign == 1 && data.Length == 1 && data[0] == 1; }
}
//Gem from Hacker's Delight
//Returns the number of bits set in @x
static int PopulationCount(uint x)
{
x = x - ((x >> 1) & 0x55555555);
x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
x = (x + (x >> 4)) & 0x0F0F0F0F;
x = x + (x >> 8);
x = x + (x >> 16);
return (int)(x & 0x0000003F);
}
//Based on code by Zilong Tan on Ulib released under MIT license
//Returns the number of bits set in @x
static int PopulationCount(ulong x)
{
x -= (x >> 1) & 0x5555555555555555UL;
x = (x & 0x3333333333333333UL) + ((x >> 2) & 0x3333333333333333UL);
x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0fUL;
return (int)((x * 0x0101010101010101UL) >> 56);
}
static int LeadingZeroCount(uint value)
{
value |= value >> 1;
value |= value >> 2;
value |= value >> 4;
value |= value >> 8;
value |= value >> 16;
return 32 - PopulationCount(value); // 32 = bits in uint
}
static int LeadingZeroCount(ulong value)
{
value |= value >> 1;
value |= value >> 2;
value |= value >> 4;
value |= value >> 8;
value |= value >> 16;
value |= value >> 32;
return 64 - PopulationCount(value); // 64 = bits in ulong
}
static double BuildDouble(int sign, ulong mantissa, int exponent)
{
const int exponentBias = 1023;
const int mantissaLength = 52;
const int exponentLength = 11;
const int maxExponent = 2046;
const long mantissaMask = 0xfffffffffffffL;
const long exponentMask = 0x7ffL;
const ulong negativeMark = 0x8000000000000000uL;
if (sign == 0 || mantissa == 0)
{
return 0.0;
}
else
{
exponent += exponentBias + mantissaLength;
int offset = LeadingZeroCount(mantissa) - exponentLength;
if (exponent - offset > maxExponent)
{
return sign > 0 ? double.PositiveInfinity : double.NegativeInfinity;
}
else
{
if (offset < 0)
{
mantissa >>= -offset;
exponent += -offset;
}
else if (offset >= exponent)
{
mantissa <<= exponent - 1;
exponent = 0;
}
else
{
mantissa <<= offset;
exponent -= offset;
}
mantissa = mantissa & mantissaMask;
if ((exponent & exponentMask) == exponent)
{
unchecked
{
ulong bits = mantissa | ((ulong)exponent << mantissaLength);
if (sign < 0)
{
bits |= negativeMark;
}
return BitConverter.Int64BitsToDouble((long)bits);
}
}
else
{
return sign > 0 ? double.PositiveInfinity : double.NegativeInfinity;
}
}
}
}
public bool IsPowerOfTwo
{
get
{
bool foundBit = false;
if (sign != 1)
return false;
//This function is pop count == 1 for positive numbers
for (int i = 0; i < data.Length; ++i)
{
int p = PopulationCount(data[i]);
if (p > 0)
{
if (p > 1 || foundBit)
return false;
foundBit = true;
}
}
return foundBit;
}
}
public bool IsZero
{
get { return sign == 0; }
}
public int Sign
{
get { return sign; }
}
public static BigInteger MinusOne
{
get { return new BigInteger(-1, ONE); }
}
public static BigInteger One
{
get { return new BigInteger(1, ONE); }
}
public static BigInteger Zero
{
get { return new BigInteger(0); }
}
public static explicit operator int(BigInteger value)
{
if (value.data == null)
return 0;
if (value.data.Length > 1)
throw new OverflowException();
uint data = value.data[0];
if (value.sign == 1)
{
if (data > (uint)int.MaxValue)
throw new OverflowException();
return (int)data;
}
else if (value.sign == -1)
{
if (data > 0x80000000u)
throw new OverflowException();
return -(int)data;
}
return 0;
}
public static explicit operator uint(BigInteger value)
{
if (value.data == null)
return 0;
if (value.data.Length > 1 || value.sign == -1)
throw new OverflowException();
return value.data[0];
}
public static explicit operator short(BigInteger value)
{
int val = (int)value;
if (val < short.MinValue || val > short.MaxValue)
throw new OverflowException();
return (short)val;
}
public static explicit operator ushort(BigInteger value)
{
uint val = (uint)value;
if (val > ushort.MaxValue)
throw new OverflowException();
return (ushort)val;
}
public static explicit operator byte(BigInteger value)
{
uint val = (uint)value;
if (val > byte.MaxValue)
throw new OverflowException();
return (byte)val;
}
public static explicit operator sbyte(BigInteger value)
{
int val = (int)value;
if (val < sbyte.MinValue || val > sbyte.MaxValue)
throw new OverflowException();
return (sbyte)val;
}
public static explicit operator long(BigInteger value)
{
if (value.data == null)
return 0;
if (value.data.Length > 2)
throw new OverflowException();
uint low = value.data[0];
if (value.data.Length == 1)
{
if (value.sign == 1)
return (long)low;
long res = (long)low;
return -res;
}
uint high = value.data[1];
if (value.sign == 1)
{
if (high >= 0x80000000u)
throw new OverflowException();
return (((long)high) << 32) | low;
}
/*
We cannot represent negative numbers smaller than long.MinValue.
Those values are encoded into what look negative numbers, so negating
them produces a positive value, that's why it's safe to check for that
condition.
long.MinValue works fine since it's bigint encoding looks like a negative
number, but since long.MinValue == -long.MinValue, we're good.
*/
long result = -((((long)high) << 32) | (long)low);
if (result > 0)
throw new OverflowException();
return result;
}
public static explicit operator ulong(BigInteger value)
{
if (value.data == null)
return 0;
if (value.data.Length > 2 || value.sign == -1)
throw new OverflowException();
uint low = value.data[0];
if (value.data.Length == 1)
return low;
uint high = value.data[1];
return (((ulong)high) << 32) | low;
}
public static explicit operator double(BigInteger value)
{
if (value.data == null)
return 0.0;
switch (value.data.Length)
{
case 1:
return BuildDouble(value.sign, value.data[0], 0);
case 2:
return BuildDouble(value.sign, (ulong)value.data[1] << 32 | (ulong)value.data[0], 0);
default:
var index = value.data.Length - 1;
var word = value.data[index];
var mantissa = ((ulong)word << 32) | value.data[index - 1];
int missing = LeadingZeroCount(word) - 11; // 11 = bits in exponent
if (missing > 0)
{
// add the missing bits from the next word
mantissa = (mantissa << missing) | (value.data[index - 2] >> (32 - missing));
}
else
{
mantissa >>= -missing;
}
return BuildDouble(value.sign, mantissa, ((value.data.Length - 2) * 32) - missing);
}
}
public static explicit operator float(BigInteger value)
{
return (float)(double)value;
}
public static implicit operator BigInteger(int value)
{
return new BigInteger(value);
}
public static implicit operator BigInteger(uint value)
{
return new BigInteger(value);
}
public static implicit operator BigInteger(short value)
{
return new BigInteger(value);
}
public static implicit operator BigInteger(ushort value)
{
return new BigInteger(value);
}
public static implicit operator BigInteger(byte value)
{
return new BigInteger(value);
}
public static implicit operator BigInteger(sbyte value)
{
return new BigInteger(value);
}
public static implicit operator BigInteger(long value)
{
return new BigInteger(value);
}
public static implicit operator BigInteger(ulong value)
{
return new BigInteger(value);
}
public static explicit operator BigInteger(double value)
{
return new BigInteger(value);
}
public static explicit operator BigInteger(float value)
{
return new BigInteger(value);
}
public static BigInteger operator +(BigInteger left, BigInteger right)
{
if (left.sign == 0)
return right;
if (right.sign == 0)
return left;
if (left.sign == right.sign)
return new BigInteger(left.sign, CoreAdd(left.data, right.data));
int r = CoreCompare(left.data, right.data);
if (r == 0)
return Zero;
if (r > 0) //left > right
return new BigInteger(left.sign, CoreSub(left.data, right.data));
return new BigInteger(right.sign, CoreSub(right.data, left.data));
}
public static BigInteger operator -(BigInteger left, BigInteger right)
{
if (right.sign == 0)
return left;
if (left.sign == 0)
return new BigInteger((short)-right.sign, right.data);
if (left.sign == right.sign)
{
int r = CoreCompare(left.data, right.data);
if (r == 0)
return Zero;
if (r > 0) //left > right
return new BigInteger(left.sign, CoreSub(left.data, right.data));
return new BigInteger((short)-right.sign, CoreSub(right.data, left.data));
}
return new BigInteger(left.sign, CoreAdd(left.data, right.data));
}
public static BigInteger operator *(BigInteger left, BigInteger right)
{
if (left.sign == 0 || right.sign == 0)
return Zero;
if (left.data[0] == 1 && left.data.Length == 1)
{
if (left.sign == 1)
return right;
return new BigInteger((short)-right.sign, right.data);
}
if (right.data[0] == 1 && right.data.Length == 1)
{
if (right.sign == 1)
return left;
return new BigInteger((short)-left.sign, left.data);
}
uint[] a = left.data;
uint[] b = right.data;
uint[] res = new uint[a.Length + b.Length];
for (int i = 0; i < a.Length; ++i)
{
uint ai = a[i];
int k = i;
ulong carry = 0;
for (int j = 0; j < b.Length; ++j)
{
carry = carry + ((ulong)ai) * b[j] + res[k];
res[k++] = (uint)carry;
carry >>= 32;
}
while (carry != 0)
{
carry += res[k];
res[k++] = (uint)carry;
carry >>= 32;
}
}
int m;
for (m = res.Length - 1; m >= 0 && res[m] == 0; --m) ;
if (m < res.Length - 1)
res = Resize(res, m + 1);
return new BigInteger((short)(left.sign * right.sign), res);
}
public static BigInteger operator /(BigInteger dividend, BigInteger divisor)
{
if (divisor.sign == 0)
throw new Exception("DivideByZero");
if (dividend.sign == 0)
return dividend;
uint[] quotient;
uint[] remainder_value;
DivModUnsigned(dividend.data, divisor.data, out quotient, out remainder_value);
int i;
for (i = quotient.Length - 1; i >= 0 && quotient[i] == 0; --i) ;
if (i == -1)
return Zero;
if (i < quotient.Length - 1)
quotient = Resize(quotient, i + 1);
return new BigInteger((short)(dividend.sign * divisor.sign), quotient);
}
public static BigInteger operator %(BigInteger dividend, BigInteger divisor)
{
if (divisor.sign == 0)
throw new Exception("DivideByZero");
if (dividend.sign == 0)
return dividend;
uint[] quotient;
uint[] remainder_value;
DivModUnsigned(dividend.data, divisor.data, out quotient, out remainder_value);
int i;
for (i = remainder_value.Length - 1; i >= 0 && remainder_value[i] == 0; --i) ;
if (i == -1)
return Zero;
if (i < remainder_value.Length - 1)
remainder_value = Resize(remainder_value, i + 1);
return new BigInteger(dividend.sign, remainder_value);
}
public static BigInteger operator -(BigInteger value)
{
if (value.data == null)
return value;
return new BigInteger((short)-value.sign, value.data);
}
public static BigInteger operator +(BigInteger value)
{
return value;
}
public static BigInteger operator ++(BigInteger value)
{
if (value.data == null)
return One;
short sign = value.sign;
uint[] data = value.data;
if (data.Length == 1)
{
if (sign == -1 && data[0] == 1)
return Zero;
if (sign == 0)
return new BigInteger(1, ONE);
}
if (sign == -1)
data = CoreSub(data, 1);
else
data = CoreAdd(data, 1);
return new BigInteger(sign, data);
}
public static BigInteger operator --(BigInteger value)
{
if (value.data == null)
return MinusOne;
short sign = value.sign;
uint[] data = value.data;
if (data.Length == 1)
{
if (sign == 1 && data[0] == 1)
return Zero;
if (sign == 0)
return new BigInteger(-1, ONE);
}
if (sign == -1)
data = CoreAdd(data, 1);
else
data = CoreSub(data, 1);
return new BigInteger(sign, data);
}
public static BigInteger operator &(BigInteger left, BigInteger right)
{
if (left.sign == 0)
return left;
if (right.sign == 0)
return right;
uint[] a = left.data;
uint[] b = right.data;
int ls = left.sign;
int rs = right.sign;
bool neg_res = (ls == rs) && (ls == -1);
uint[] result = new uint[Math.Max(a.Length, b.Length)];
ulong ac = 1, bc = 1, borrow = 1;
int i;
for (i = 0; i < result.Length; ++i)
{
uint va = 0;
if (i < a.Length)
va = a[i];
if (ls == -1)
{
ac = ~va + ac;
va = (uint)ac;
ac = (uint)(ac >> 32);
}
uint vb = 0;
if (i < b.Length)
vb = b[i];
if (rs == -1)
{
bc = ~vb + bc;
vb = (uint)bc;
bc = (uint)(bc >> 32);
}
uint word = va & vb;
if (neg_res)
{
borrow = word - borrow;
word = ~(uint)borrow;
borrow = (uint)(borrow >> 32) & 0x1u;
}
result[i] = word;
}
for (i = result.Length - 1; i >= 0 && result[i] == 0; --i) ;
if (i == -1)
return Zero;
if (i < result.Length - 1)
result = Resize(result, i + 1);
return new BigInteger(neg_res ? (short)-1 : (short)1, result);
}
public static BigInteger operator |(BigInteger left, BigInteger right)
{
if (left.sign == 0)
return right;
if (right.sign == 0)
return left;
uint[] a = left.data;
uint[] b = right.data;
int ls = left.sign;
int rs = right.sign;
bool neg_res = (ls == -1) || (rs == -1);
uint[] result = new uint[Math.Max(a.Length, b.Length)];
ulong ac = 1, bc = 1, borrow = 1;
int i;
for (i = 0; i < result.Length; ++i)
{
uint va = 0;
if (i < a.Length)
va = a[i];
if (ls == -1)
{
ac = ~va + ac;
va = (uint)ac;
ac = (uint)(ac >> 32);
}
uint vb = 0;
if (i < b.Length)
vb = b[i];
if (rs == -1)
{
bc = ~vb + bc;
vb = (uint)bc;
bc = (uint)(bc >> 32);
}
uint word = va | vb;
if (neg_res)
{
borrow = word - borrow;
word = ~(uint)borrow;
borrow = (uint)(borrow >> 32) & 0x1u;
}
result[i] = word;
}
for (i = result.Length - 1; i >= 0 && result[i] == 0; --i) ;
if (i == -1)
return Zero;
if (i < result.Length - 1)
result = Resize(result, i + 1);
return new BigInteger(neg_res ? (short)-1 : (short)1, result);
}
public static BigInteger operator ^(BigInteger left, BigInteger right)
{
if (left.sign == 0)
return right;
if (right.sign == 0)
return left;
uint[] a = left.data;
uint[] b = right.data;
int ls = left.sign;
int rs = right.sign;
bool neg_res = (ls == -1) ^ (rs == -1);
uint[] result = new uint[Math.Max(a.Length, b.Length)];
ulong ac = 1, bc = 1, borrow = 1;
int i;
for (i = 0; i < result.Length; ++i)
{
uint va = 0;
if (i < a.Length)
va = a[i];
if (ls == -1)
{
ac = ~va + ac;
va = (uint)ac;
ac = (uint)(ac >> 32);
}
uint vb = 0;
if (i < b.Length)
vb = b[i];
if (rs == -1)
{
bc = ~vb + bc;
vb = (uint)bc;
bc = (uint)(bc >> 32);
}
uint word = va ^ vb;
if (neg_res)
{
borrow = word - borrow;
word = ~(uint)borrow;
borrow = (uint)(borrow >> 32) & 0x1u;
}
result[i] = word;
}
for (i = result.Length - 1; i >= 0 && result[i] == 0; --i) ;
if (i == -1)
return Zero;
if (i < result.Length - 1)
result = Resize(result, i + 1);
return new BigInteger(neg_res ? (short)-1 : (short)1, result);
}
public static BigInteger operator ~(BigInteger value)
{
if (value.data == null)
return new BigInteger(-1, ONE);
uint[] data = value.data;
int sign = value.sign;
bool neg_res = sign == 1;
uint[] result = new uint[data.Length];
ulong carry = 1, borrow = 1;
int i;
for (i = 0; i < result.Length; ++i)
{
uint word = data[i];
if (sign == -1)
{
carry = ~word + carry;
word = (uint)carry;
carry = (uint)(carry >> 32);
}
word = ~word;
if (neg_res)
{
borrow = word - borrow;
word = ~(uint)borrow;
borrow = (uint)(borrow >> 32) & 0x1u;
}
result[i] = word;
}
for (i = result.Length - 1; i >= 0 && result[i] == 0; --i) ;
if (i == -1)
return Zero;
if (i < result.Length - 1)
result = Resize(result, i + 1);
return new BigInteger(neg_res ? (short)-1 : (short)1, result);
}
//returns the 0-based index of the most significant set bit
//returns 0 if no bit is set, so extra care when using it
static int BitScanBackward(uint word)
{
for (int i = 31; i >= 0; --i)
{
uint mask = 1u << i;
if ((word & mask) == mask)
return i;
}
return 0;
}
public static BigInteger operator <<(BigInteger value, int shift)
{
if (shift == 0 || value.data == null)
return value;
if (shift < 0)
return value >> -shift;
uint[] data = value.data;
int sign = value.sign;
int topMostIdx = BitScanBackward(data[data.Length - 1]);
int bits = shift - (31 - topMostIdx);
int extra_words = (bits >> 5) + ((bits & 0x1F) != 0 ? 1 : 0);
uint[] res = new uint[data.Length + extra_words];
int idx_shift = shift >> 5;
int bit_shift = shift & 0x1F;
int carry_shift = 32 - bit_shift;
if (carry_shift == 32)
{
for (int i = 0; i < data.Length; ++i)
{
uint word = data[i];
res[i + idx_shift] |= word << bit_shift;
}
}
else
{
for (int i = 0; i < data.Length; ++i)
{
uint word = data[i];
res[i + idx_shift] |= word << bit_shift;
if (i + idx_shift + 1 < res.Length)
res[i + idx_shift + 1] = word >> carry_shift;
}
}
return new BigInteger((short)sign, res);
}
public static BigInteger operator >>(BigInteger value, int shift)
{
if (shift == 0 || value.sign == 0)
return value;
if (shift < 0)
return value << -shift;
uint[] data = value.data;
int sign = value.sign;
int topMostIdx = BitScanBackward(data[data.Length - 1]);
int idx_shift = shift >> 5;
int bit_shift = shift & 0x1F;
int extra_words = idx_shift;
if (bit_shift > topMostIdx)
++extra_words;
int size = data.Length - extra_words;
if (size <= 0)
{
if (sign == 1)
return Zero;
return new BigInteger(-1, ONE);
}
uint[] res = new uint[size];
int carry_shift = 32 - bit_shift;
if (carry_shift == 32)
{
for (int i = data.Length - 1; i >= idx_shift; --i)
{
uint word = data[i];
if (i - idx_shift < res.Length)
res[i - idx_shift] |= word >> bit_shift;
}
}
else
{
for (int i = data.Length - 1; i >= idx_shift; --i)
{
uint word = data[i];
if (i - idx_shift < res.Length)
res[i - idx_shift] |= word >> bit_shift;
if (i - idx_shift - 1 >= 0)
res[i - idx_shift - 1] = word << carry_shift;
}
}
//Round down instead of toward zero
if (sign == -1)
{
for (int i = 0; i < idx_shift; i++)
{
if (data[i] != 0u)
{
var tmp = new BigInteger((short)sign, res);
--tmp;
return tmp;
}
}
if (bit_shift > 0 && (data[idx_shift] << carry_shift) != 0u)
{
var tmp = new BigInteger((short)sign, res);
--tmp;
return tmp;
}
}
return new BigInteger((short)sign, res);
}
public static bool operator <(BigInteger left, BigInteger right)
{
return Compare(left, right) < 0;
}
public static bool operator <(BigInteger left, long right)
{
return left.CompareTo(right) < 0;
}
public static bool operator <(long left, BigInteger right)
{
return right.CompareTo(left) > 0;
}
public static bool operator <(BigInteger left, ulong right)
{
return left.CompareTo(right) < 0;
}
public static bool operator <(ulong left, BigInteger right)
{
return right.CompareTo(left) > 0;
}
public static bool operator <=(BigInteger left, BigInteger right)
{
return Compare(left, right) <= 0;
}
public static bool operator <=(BigInteger left, long right)
{
return left.CompareTo(right) <= 0;
}
public static bool operator <=(long left, BigInteger right)
{
return right.CompareTo(left) >= 0;
}
public static bool operator <=(BigInteger left, ulong right)
{
return left.CompareTo(right) <= 0;
}
public static bool operator <=(ulong left, BigInteger right)
{
return right.CompareTo(left) >= 0;
}
public static bool operator >(BigInteger left, BigInteger right)
{
return Compare(left, right) > 0;
}
public static bool operator >(BigInteger left, long right)
{
return left.CompareTo(right) > 0;
}
public static bool operator >(long left, BigInteger right)
{
return right.CompareTo(left) < 0;
}
public static bool operator >(BigInteger left, ulong right)
{
return left.CompareTo(right) > 0;
}
public static bool operator >(ulong left, BigInteger right)
{
return right.CompareTo(left) < 0;
}
public static bool operator >=(BigInteger left, BigInteger right)
{
return Compare(left, right) >= 0;
}
public static bool operator >=(BigInteger left, long right)
{
return left.CompareTo(right) >= 0;
}
public static bool operator >=(long left, BigInteger right)
{
return right.CompareTo(left) <= 0;
}
public static bool operator >=(BigInteger left, ulong right)
{
return left.CompareTo(right) >= 0;
}
public static bool operator >=(ulong left, BigInteger right)
{
return right.CompareTo(left) <= 0;
}
public static bool operator ==(BigInteger left, BigInteger right)
{
return Compare(left, right) == 0;
}
public static bool operator ==(BigInteger left, long right)
{
return left.CompareTo(right) == 0;
}
public static bool operator ==(long left, BigInteger right)
{
return right.CompareTo(left) == 0;
}
public static bool operator ==(BigInteger left, ulong right)
{
return left.CompareTo(right) == 0;
}
public static bool operator ==(ulong left, BigInteger right)
{
return right.CompareTo(left) == 0;
}
public static bool operator !=(BigInteger left, BigInteger right)
{
return Compare(left, right) != 0;
}
public static bool operator !=(BigInteger left, long right)
{
return left.CompareTo(right) != 0;
}
public static bool operator !=(long left, BigInteger right)
{
return right.CompareTo(left) != 0;
}
public static bool operator !=(BigInteger left, ulong right)
{
return left.CompareTo(right) != 0;
}
public static bool operator !=(ulong left, BigInteger right)
{
return right.CompareTo(left) != 0;
}
public override bool Equals(object obj)
{
if (!(obj is BigInteger))
return false;
return Equals((BigInteger)obj);
}
public bool Equals(BigInteger other)
{
if (sign != other.sign)
return false;
int alen = data != null ? data.Length : 0;
int blen = other.data != null ? other.data.Length : 0;
if (alen != blen)
return false;
for (int i = 0; i < alen; ++i)
{
if (data[i] != other.data[i])
return false;
}
return true;
}
public bool Equals(long other)
{
return CompareTo(other) == 0;
}
//public override string ToString ()
//{
// return ToString (10, null);
//}
//string ToStringWithPadding (string format, uint radix, IFormatProvider provider)
//{
// if (format.Length > 1) {
// int precision = Convert.ToInt32(format.Substring (1));
// string baseStr = ToString (radix, provider);
// if (baseStr.Length < precision) {
// string additional = new String ('0', precision - baseStr.Length);
// if (baseStr[0] != '-') {
// return additional + baseStr;
// } else {
// return "-" + additional + baseStr.Substring (1);
// }
// }
// return baseStr;
// }
// return ToString (radix, provider);
//}
//public string ToString (string format)
//{
// return ToString (format, null);
//}
//public string ToString (IFormatProvider provider)
//{
// return ToString (null, provider);
//}
//public string ToString (string format, IFormatProvider provider)
//{
// if (format == null || format == "")
// return ToString (10, provider);
// switch (format[0]) {
// case 'd':
// case 'D':
// case 'g':
// case 'G':
// case 'r':
// case 'R':
// return ToStringWithPadding (format, 10, provider);
// case 'x':
// case 'X':
// return ToStringWithPadding (format, 16, null);
// default:
// throw new FormatException (string.Format ("format '{0}' not implemented", format));
// }
//}
//static uint[] MakeTwoComplement (uint[] v)
//{
// uint[] res = new uint [v.Length];
// ulong carry = 1;
// for (int i = 0; i < v.Length; ++i) {
// uint word = v [i];
// carry = (ulong)~word + carry;
// word = (uint)carry;
// carry = (uint)(carry >> 32);
// res [i] = word;
// }
// uint last = res [res.Length - 1];
// int idx = FirstNonFFByte (last);
// uint mask = 0xFF;
// for (int i = 1; i < idx; ++i)
// mask = (mask << 8) | 0xFF;
// res [res.Length - 1] = last & mask;
// return res;
//}
//string ToString (uint radix, IFormatProvider provider)
//{
// const string characterSet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// if (characterSet.Length < radix)
// throw new ArgumentException ("charSet length less than radix", "characterSet");
// if (radix == 1)
// throw new ArgumentException ("There is no such thing as radix one notation", "radix");
// if (sign == 0)
// return "0";
// if (data.Length == 1 && data [0] == 1)
// return sign == 1 ? "1" : "-1";
// //List<char> digits = new List<char> (1 + data.Length * 3 / 10);
// ArrayList digits = new ArrayList(1 + data.Length * 3 / 10);
// BigInteger a;
// if (sign == 1)
// a = this;
// else {
// uint[] dt = data;
// if (radix > 10)
// dt = MakeTwoComplement (dt);
// a = new BigInteger (1, dt);
// }
// while (a != 0) {
// BigInteger rem;
// a = DivRem (a, radix, out rem);
// digits.Add (characterSet [(int) rem]);
// }
// if (sign == -1 && radix == 10) {
// NumberFormatInfo info = null;
// if (provider != null)
// info = provider.GetFormat (typeof (NumberFormatInfo)) as NumberFormatInfo;
// if (info != null) {
// string str = info.NegativeSign;
// for (int i = str.Length - 1; i >= 0; --i)
// digits.Add (str [i]);
// } else {
// digits.Add ('-');
// }
// }
// char last = (char)digits [digits.Count - 1];
// if (sign == 1 && radix > 10 && (last < '0' || last > '9'))
// digits.Add ('0');
// ((char)digits).Reverse ();
// return new String ((char[])digits.ToArray (typeof(char)));
//}
//public static BigInteger Parse (string value)
//{
// Exception ex;
// BigInteger result;
// if (!Parse (value, false, out result, out ex))
// throw ex;
// return result;
//}
//public static bool TryParse (string value, out BigInteger result)
//{
// Exception ex;
// return Parse (value, true, out result, out ex);
//}
//public static BigInteger Parse (string value, NumberStyles style)
//{
// return Parse (value, style, null);
//}
//public static BigInteger Parse (string value, IFormatProvider provider)
//{
// return Parse (value, NumberStyles.Integer, provider);
//}
//public static BigInteger Parse (
// string value, NumberStyles style, IFormatProvider provider)
//{
// Exception exc;
// BigInteger res;
// if (!Parse (value, style, provider, false, out res, out exc))
// throw exc;
// return res;
//}
//public static bool TryParse (
// string value, NumberStyles style, IFormatProvider provider,
// out BigInteger result)
//{
// Exception exc;
// if (!Parse (value, style, provider, true, out result, out exc)) {
// result = Zero;
// return false;
// }
// return true;
//}
//internal static bool Parse (string s, NumberStyles style, IFormatProvider fp, bool tryParse, out BigInteger result, out Exception exc)
//{
// result = Zero;
// exc = null;
// if (s == null) {
// if (!tryParse)
// exc = new ArgumentNullException ("s");
// return false;
// }
// if (s.Length == 0) {
// if (!tryParse)
// exc = GetFormatException ();
// return false;
// }
// NumberFormatInfo nfi = null;
// if (fp != null) {
// Type typeNFI = typeof(System.Globalization.NumberFormatInfo);
// nfi = (NumberFormatInfo)fp.GetFormat (typeNFI);
// }
// if (nfi == null)
// nfi = Thread.CurrentThread.CurrentCulture.NumberFormat;
// if (!CheckStyle (style, tryParse, ref exc))
// return false;
// bool AllowCurrencySymbol = (style & NumberStyles.AllowCurrencySymbol) != 0;
// bool AllowHexSpecifier = (style & NumberStyles.AllowHexSpecifier) != 0;
// bool AllowThousands = (style & NumberStyles.AllowThousands) != 0;
// bool AllowDecimalPoint = (style & NumberStyles.AllowDecimalPoint) != 0;
// bool AllowParentheses = (style & NumberStyles.AllowParentheses) != 0;
// bool AllowTrailingSign = (style & NumberStyles.AllowTrailingSign) != 0;
// bool AllowLeadingSign = (style & NumberStyles.AllowLeadingSign) != 0;
// bool AllowTrailingWhite = (style & NumberStyles.AllowTrailingWhite) != 0;
// bool AllowLeadingWhite = (style & NumberStyles.AllowLeadingWhite) != 0;
// bool AllowExponent = (style & NumberStyles.AllowExponent) != 0;
// int pos = 0;
// if (AllowLeadingWhite && !JumpOverWhite (ref pos, s, true, tryParse, ref exc))
// return false;
// bool foundOpenParentheses = false;
// bool negative = false;
// bool foundSign = false;
// bool foundCurrency = false;
// // Pre-number stuff
// if (AllowParentheses && s [pos] == '(') {
// foundOpenParentheses = true;
// foundSign = true;
// negative = true; // MS always make the number negative when there parentheses
// // even when NumberFormatInfo.NumberNegativePattern != 0!!!
// pos++;
// if (AllowLeadingWhite && !JumpOverWhite (ref pos, s, true, tryParse, ref exc))
// return false;
// if (s.Substring (pos, nfi.NegativeSign.Length) == nfi.NegativeSign) {
// if (!tryParse)
// exc = GetFormatException ();
// return false;
// }
// if (s.Substring (pos, nfi.PositiveSign.Length) == nfi.PositiveSign) {
// if (!tryParse)
// exc = GetFormatException ();
// return false;
// }
// }
// if (AllowLeadingSign && !foundSign) {
// // Sign + Currency
// FindSign (ref pos, s, nfi, ref foundSign, ref negative);
// if (foundSign) {
// if (AllowLeadingWhite && !JumpOverWhite (ref pos, s, true, tryParse, ref exc))
// return false;
// if (AllowCurrencySymbol) {
// FindCurrency (ref pos, s, nfi,
// ref foundCurrency);
// if (foundCurrency && AllowLeadingWhite &&
// !JumpOverWhite (ref pos, s, true, tryParse, ref exc))
// return false;
// }
// }
// }
// if (AllowCurrencySymbol && !foundCurrency) {
// // Currency + sign
// FindCurrency (ref pos, s, nfi, ref foundCurrency);
// if (foundCurrency) {
// if (AllowLeadingWhite && !JumpOverWhite (ref pos, s, true, tryParse, ref exc))
// return false;
// if (foundCurrency) {
// if (!foundSign && AllowLeadingSign) {
// FindSign (ref pos, s, nfi, ref foundSign,
// ref negative);
// if (foundSign && AllowLeadingWhite &&
// !JumpOverWhite (ref pos, s, true, tryParse, ref exc))
// return false;
// }
// }
// }
// }
// BigInteger number = Zero;
// int nDigits = 0;
// int decimalPointPos = -1;
// byte digitValue;
// char hexDigit;
// bool firstHexDigit = true;
// // Number stuff
// while (pos < s.Length) {
// if (!ValidDigit (s [pos], AllowHexSpecifier)) {
// if (AllowThousands &&
// (FindOther (ref pos, s, nfi.NumberGroupSeparator)
// || FindOther (ref pos, s, nfi.CurrencyGroupSeparator)))
// continue;
// if (AllowDecimalPoint && decimalPointPos < 0 &&
// (FindOther (ref pos, s, nfi.NumberDecimalSeparator)
// || FindOther (ref pos, s, nfi.CurrencyDecimalSeparator))) {
// decimalPointPos = nDigits;
// continue;
// }
// break;
// }
// nDigits++;
// if (AllowHexSpecifier) {
// hexDigit = s [pos++];
// if (Char.IsDigit (hexDigit))
// digitValue = (byte)(hexDigit - '0');
// else if (Char.IsLower (hexDigit))
// digitValue = (byte)(hexDigit - 'a' + 10);
// else
// digitValue = (byte)(hexDigit - 'A' + 10);
// if (firstHexDigit && (byte)digitValue >= 8)
// negative = true;
// number = number * 16 + digitValue;
// firstHexDigit = false;
// continue;
// }
// number = number * 10 + (byte)(s [pos++] - '0');
// }
// // Post number stuff
// if (nDigits == 0) {
// if (!tryParse)
// exc = GetFormatException ();
// return false;
// }
// //Signed hex value (Two's Complement)
// if (AllowHexSpecifier && negative) {
// BigInteger mask = BigInteger.Pow(16, nDigits) - 1;
// number = (number ^ mask) + 1;
// }
// int exponent = 0;
// if (AllowExponent)
// if (FindExponent (ref pos, s, ref exponent, tryParse, ref exc) && exc != null)
// return false;
// if (AllowTrailingSign && !foundSign) {
// // Sign + Currency
// FindSign (ref pos, s, nfi, ref foundSign, ref negative);
// if (foundSign && pos < s.Length) {
// if (AllowTrailingWhite && !JumpOverWhite (ref pos, s, true, tryParse, ref exc))
// return false;
// }
// }
// if (AllowCurrencySymbol && !foundCurrency) {
// if (AllowTrailingWhite && pos < s.Length && !JumpOverWhite (ref pos, s, false, tryParse, ref exc))
// return false;
// // Currency + sign
// FindCurrency (ref pos, s, nfi, ref foundCurrency);
// if (foundCurrency && pos < s.Length) {
// if (AllowTrailingWhite && !JumpOverWhite (ref pos, s, true, tryParse, ref exc))
// return false;
// if (!foundSign && AllowTrailingSign)
// FindSign (ref pos, s, nfi, ref foundSign,
// ref negative);
// }
// }
// if (AllowTrailingWhite && pos < s.Length && !JumpOverWhite (ref pos, s, false, tryParse, ref exc))
// return false;
// if (foundOpenParentheses) {
// if (pos >= s.Length || s [pos++] != ')') {
// if (!tryParse)
// exc = GetFormatException ();
// return false;
// }
// if (AllowTrailingWhite && pos < s.Length && !JumpOverWhite (ref pos, s, false, tryParse, ref exc))
// return false;
// }
// if (pos < s.Length && s [pos] != '\u0000') {
// if (!tryParse)
// exc = GetFormatException ();
// return false;
// }
// if (decimalPointPos >= 0)
// exponent = exponent - nDigits + decimalPointPos;
// if (exponent < 0) {
// //
// // Any non-zero values after decimal point are not allowed
// //
// BigInteger remainder;
// number = BigInteger.DivRem(number, BigInteger.Pow(10, -exponent), out remainder);
// if (!remainder.IsZero) {
// if (!tryParse)
// exc = new OverflowException ("Value too large or too small. exp="+exponent+" rem = " + remainder + " pow = " + BigInteger.Pow(10, -exponent));
// return false;
// }
// } else if (exponent > 0) {
// number = BigInteger.Pow(10, exponent) * number;
// }
// if (number.sign == 0)
// result = number;
// else if (negative)
// result = new BigInteger (-1, number.data);
// else
// result = new BigInteger (1, number.data);
// return true;
//}
//internal static bool CheckStyle (NumberStyles style, bool tryParse, ref Exception exc)
//{
// if ((style & NumberStyles.AllowHexSpecifier) != 0) {
// NumberStyles ne = style ^ NumberStyles.AllowHexSpecifier;
// if ((ne & NumberStyles.AllowLeadingWhite) != 0)
// ne ^= NumberStyles.AllowLeadingWhite;
// if ((ne & NumberStyles.AllowTrailingWhite) != 0)
// ne ^= NumberStyles.AllowTrailingWhite;
// if (ne != 0) {
// if (!tryParse)
// exc = new ArgumentException (
// "With AllowHexSpecifier only " +
// "AllowLeadingWhite and AllowTrailingWhite " +
// "are permitted.");
// return false;
// }
// } else if ((uint) style > (uint) NumberStyles.Any){
// if (!tryParse)
// exc = new ArgumentException ("Not a valid number style");
// return false;
// }
// return true;
//}
//internal static bool JumpOverWhite (ref int pos, string s, bool reportError, bool tryParse, ref Exception exc)
//{
// while (pos < s.Length && Char.IsWhiteSpace (s [pos]))
// pos++;
// if (reportError && pos >= s.Length) {
// if (!tryParse)
// exc = GetFormatException ();
// return false;
// }
// return true;
//}
//internal static void FindSign (ref int pos, string s, NumberFormatInfo nfi,
// ref bool foundSign, ref bool negative)
//{
// if ((pos + nfi.NegativeSign.Length) <= s.Length &&
// string.CompareOrdinal(s, pos, nfi.NegativeSign, 0, nfi.NegativeSign.Length) == 0) {
// negative = true;
// foundSign = true;
// pos += nfi.NegativeSign.Length;
// } else if ((pos + nfi.PositiveSign.Length) <= s.Length &&
// string.CompareOrdinal(s, pos, nfi.PositiveSign, 0, nfi.PositiveSign.Length) == 0) {
// negative = false;
// pos += nfi.PositiveSign.Length;
// foundSign = true;
// }
//}
//internal static void FindCurrency (ref int pos,
// string s,
// NumberFormatInfo nfi,
// ref bool foundCurrency)
//{
// if ((pos + nfi.CurrencySymbol.Length) <= s.Length &&
// s.Substring (pos, nfi.CurrencySymbol.Length) == nfi.CurrencySymbol) {
// foundCurrency = true;
// pos += nfi.CurrencySymbol.Length;
// }
//}
//internal static bool FindExponent (ref int pos, string s, ref int exponent, bool tryParse, ref Exception exc)
//{
// exponent = 0;
// if (pos >= s.Length || (s [pos] != 'e' && s[pos] != 'E')) {
// exc = null;
// return false;
// }
// var i = pos + 1;
// if (i == s.Length) {
// exc = tryParse ? null : GetFormatException ();
// return true;
// }
// bool negative = false;
// if (s [i] == '-') {
// negative = true;
// if(++i == s.Length){
// exc = tryParse ? null : GetFormatException ();
// return true;
// }
// }
// if (s [i] == '+' && ++i == s.Length) {
// exc = tryParse ? null : GetFormatException ();
// return true;
// }
// long exp = 0; // temp long value
// for (; i < s.Length; i++) {
// if (!Char.IsDigit (s [i])) {
// exc = tryParse ? null : GetFormatException ();
// return true;
// }
// // Reduce the risk of throwing an overflow exc
// exp = checked (exp * 10 - (int) (s [i] - '0'));
// if (exp < Int32.MinValue || exp > Int32.MaxValue) {
// exc = tryParse ? null : new OverflowException ("Value too large or too small.");
// return true;
// }
// }
// // exp value saved as negative
// if(!negative)
// exp = -exp;
// exc = null;
// exponent = (int)exp;
// pos = i;
// return true;
//}
//internal static bool FindOther (ref int pos, string s, string other)
//{
// if ((pos + other.Length) <= s.Length &&
// s.Substring (pos, other.Length) == other) {
// pos += other.Length;
// return true;
// }
// return false;
//}
//internal static bool ValidDigit (char e, bool allowHex)
//{
// if (allowHex)
// return Char.IsDigit (e) || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
// return Char.IsDigit (e);
//}
//static Exception GetFormatException ()
//{
// return new FormatException ("Input string was not in the correct format");
//}
//static bool ProcessTrailingWhitespace (bool tryParse, string s, int position, ref Exception exc)
//{
// int len = s.Length;
// for (int i = position; i < len; i++){
// char c = s [i];
// if (c != 0 && !Char.IsWhiteSpace (c)){
// if (!tryParse)
// exc = GetFormatException ();
// return false;
// }
// }
// return true;
//}
//static bool Parse (string s, bool tryParse, out BigInteger result, out Exception exc)
//{
// int len;
// int i, sign = 1;
// bool digits_seen = false;
// result = Zero;
// exc = null;
// if (s == null) {
// if (!tryParse)
// exc = new ArgumentNullException ("value");
// return false;
// }
// len = s.Length;
// char c;
// for (i = 0; i < len; i++){
// c = s [i];
// if (!Char.IsWhiteSpace (c))
// break;
// }
// if (i == len) {
// if (!tryParse)
// exc = GetFormatException ();
// return false;
// }
// var info = Thread.CurrentThread.CurrentCulture.NumberFormat;
// string negative = info.NegativeSign;
// string positive = info.PositiveSign;
// if (string.CompareOrdinal (s, i, positive, 0, positive.Length) == 0)
// i += positive.Length;
// else if (string.CompareOrdinal (s, i, negative, 0, negative.Length) == 0) {
// sign = -1;
// i += negative.Length;
// }
// BigInteger val = Zero;
// for (; i < len; i++){
// c = s [i];
// if (c == '\0') {
// i = len;
// continue;
// }
// if (c >= '0' && c <= '9'){
// byte d = (byte) (c - '0');
// val = val * 10 + d;
// digits_seen = true;
// } else if (!ProcessTrailingWhitespace (tryParse, s, i, ref exc))
// return false;
// }
// if (!digits_seen) {
// if (!tryParse)
// exc = GetFormatException ();
// return false;
// }
// if (val.sign == 0)
// result = val;
// else if (sign == -1)
// result = new BigInteger (-1, val.data);
// else
// result = new BigInteger (1, val.data);
// return true;
//}
public static BigInteger Min(BigInteger left, BigInteger right)
{
int ls = left.sign;
int rs = right.sign;
if (ls < rs)
return left;
if (rs < ls)
return right;
int r = CoreCompare(left.data, right.data);
if (ls == -1)
r = -r;
if (r <= 0)
return left;
return right;
}
public static BigInteger Max(BigInteger left, BigInteger right)
{
int ls = left.sign;
int rs = right.sign;
if (ls > rs)
return left;
if (rs > ls)
return right;
int r = CoreCompare(left.data, right.data);
if (ls == -1)
r = -r;
if (r >= 0)
return left;
return right;
}
public static BigInteger Abs(BigInteger value)
{
return new BigInteger((short)Math.Abs(value.sign), value.data);
}
public static BigInteger DivRem(BigInteger dividend, BigInteger divisor, out BigInteger remainder)
{
if (divisor.sign == 0)
throw new Exception("DivideByZero");
if (dividend.sign == 0)
{
remainder = dividend;
return dividend;
}
uint[] quotient;
uint[] remainder_value;
DivModUnsigned(dividend.data, divisor.data, out quotient, out remainder_value);
int i;
for (i = remainder_value.Length - 1; i >= 0 && remainder_value[i] == 0; --i) ;
if (i == -1)
{
remainder = Zero;
}
else
{
if (i < remainder_value.Length - 1)
remainder_value = Resize(remainder_value, i + 1);
remainder = new BigInteger(dividend.sign, remainder_value);
}
for (i = quotient.Length - 1; i >= 0 && quotient[i] == 0; --i) ;
if (i == -1)
return Zero;
if (i < quotient.Length - 1)
quotient = Resize(quotient, i + 1);
return new BigInteger((short)(dividend.sign * divisor.sign), quotient);
}
public static BigInteger Pow(BigInteger value, int exponent)
{
if (exponent < 0)
throw new ArgumentOutOfRangeException("exponent", "exp must be >= 0");
if (exponent == 0)
return One;
if (exponent == 1)
return value;
BigInteger result = One;
while (exponent != 0)
{
if ((exponent & 1) != 0)
result = result * value;
if (exponent == 1)
break;
value = value * value;
exponent >>= 1;
}
return result;
}
public static BigInteger ModPow(BigInteger value, BigInteger exponent, BigInteger modulus)
{
if (exponent.sign == -1)
throw new ArgumentOutOfRangeException("exponent", "power must be >= 0");
if (modulus.sign == 0)
throw new Exception("DivideByZero");
BigInteger result = One % modulus;
while (exponent.sign != 0)
{
if (!exponent.IsEven)
{
result = result * value;
result = result % modulus;
}
if (exponent.IsOne)
break;
value = value * value;
value = value % modulus;
exponent >>= 1;
}
return result;
}
public static BigInteger GreatestCommonDivisor(BigInteger left, BigInteger right)
{
if (left.sign != 0 && left.data.Length == 1 && left.data[0] == 1)
return new BigInteger(1, ONE);
if (right.sign != 0 && right.data.Length == 1 && right.data[0] == 1)
return new BigInteger(1, ONE);
if (left.IsZero)
return Abs(right);
if (right.IsZero)
return Abs(left);
BigInteger x = new BigInteger(1, left.data);
BigInteger y = new BigInteger(1, right.data);
BigInteger g = y;
while (x.data.Length > 1)
{
g = x;
x = y % x;
y = g;
}
if (x.IsZero) return g;
// TODO: should we have something here if we can convert to long?
//
// Now we can just do it with single precision. I am using the binary gcd method,
// as it should be faster.
//
uint yy = x.data[0];
uint xx = (uint)(y % yy);
int t = 0;
while (((xx | yy) & 1) == 0)
{
xx >>= 1; yy >>= 1; t++;
}
while (xx != 0)
{
while ((xx & 1) == 0) xx >>= 1;
while ((yy & 1) == 0) yy >>= 1;
if (xx >= yy)
xx = (xx - yy) >> 1;
else
yy = (yy - xx) >> 1;
}
return yy << t;
}
/*LAMESPEC Log doesn't specify to how many ulp is has to be precise
We are equilavent to MS with about 2 ULP
*/
public static double Log(BigInteger value, Double baseValue)
{
if (value.sign == -1 || baseValue == 1.0d || baseValue == -1.0d ||
baseValue == Double.NegativeInfinity || double.IsNaN(baseValue))
return double.NaN;
if (baseValue == 0.0d || baseValue == Double.PositiveInfinity)
return value.IsOne ? 0 : double.NaN;
if (value.data == null)
return double.NegativeInfinity;
int length = value.data.Length - 1;
int bitCount = -1;
for (int curBit = 31; curBit >= 0; curBit--)
{
if ((value.data[length] & (1 << curBit)) != 0)
{
bitCount = curBit + length * 32;
break;
}
}
long bitlen = bitCount;
Double c = 0, d = 1;
BigInteger testBit = One;
long tempBitlen = bitlen;
while (tempBitlen > Int32.MaxValue)
{
testBit = testBit << Int32.MaxValue;
tempBitlen -= Int32.MaxValue;
}
testBit = testBit << (int)tempBitlen;
for (long curbit = bitlen; curbit >= 0; --curbit)
{
if ((value & testBit).sign != 0)
c += d;
d *= 0.5;
testBit = testBit >> 1;
}
return (System.Math.Log(c) + System.Math.Log(2) * bitlen) / System.Math.Log(baseValue);
}
public static double Log(BigInteger value)
{
return Log(value, Math.E);
}
public static double Log10(BigInteger value)
{
return Log(value, 10);
}
public bool Equals(ulong other)
{
return CompareTo(other) == 0;
}
public override int GetHashCode()
{
uint hash = (uint)(sign * 0x01010101u);
int len = data != null ? data.Length : 0;
for (int i = 0; i < len; ++i)
hash ^= data[i];
return (int)hash;
}
public static BigInteger Add(BigInteger left, BigInteger right)
{
return left + right;
}
public static BigInteger Subtract(BigInteger left, BigInteger right)
{
return left - right;
}
public static BigInteger Multiply(BigInteger left, BigInteger right)
{
return left * right;
}
public static BigInteger Divide(BigInteger dividend, BigInteger divisor)
{
return dividend / divisor;
}
public static BigInteger Remainder(BigInteger dividend, BigInteger divisor)
{
return dividend % divisor;
}
public static BigInteger Negate(BigInteger value)
{
return -value;
}
public int CompareTo(object obj)
{
if (obj == null)
return 1;
if (!(obj is BigInteger))
return -1;
return Compare(this, (BigInteger)obj);
}
public int CompareTo(BigInteger other)
{
return Compare(this, other);
}
public int CompareTo(ulong other)
{
if (sign < 0)
return -1;
if (sign == 0)
return other == 0 ? 0 : -1;
if (data.Length > 2)
return 1;
uint high = (uint)(other >> 32);
uint low = (uint)other;
return LongCompare(low, high);
}
int LongCompare(uint low, uint high)
{
uint h = 0;
if (data.Length > 1)
h = data[1];
if (h > high)
return 1;
if (h < high)
return -1;
uint l = data[0];
if (l > low)
return 1;
if (l < low)
return -1;
return 0;
}
public int CompareTo(long other)
{
int ls = sign;
int rs = Math.Sign(other);
if (ls != rs)
return ls > rs ? 1 : -1;
if (ls == 0)
return 0;
if (data.Length > 2)
return sign;
if (other < 0)
other = -other;
uint low = (uint)other;
uint high = (uint)((ulong)other >> 32);
int r = LongCompare(low, high);
if (ls == -1)
r = -r;
return r;
}
public static int Compare(BigInteger left, BigInteger right)
{
int ls = left.sign;
int rs = right.sign;
if (ls != rs)
return ls > rs ? 1 : -1;
int r = CoreCompare(left.data, right.data);
if (ls < 0)
r = -r;
return r;
}
static int TopByte(uint x)
{
if ((x & 0xFFFF0000u) != 0)
{
if ((x & 0xFF000000u) != 0)
return 4;
return 3;
}
if ((x & 0xFF00u) != 0)
return 2;
return 1;
}
static int FirstNonFFByte(uint word)
{
if ((word & 0xFF000000u) != 0xFF000000u)
return 4;
else if ((word & 0xFF0000u) != 0xFF0000u)
return 3;
else if ((word & 0xFF00u) != 0xFF00u)
return 2;
return 1;
}
public byte[] ToByteArray()
{
if (sign == 0)
return new byte[1];
//number of bytes not counting upper word
int bytes = (data.Length - 1) * 4;
bool needExtraZero = false;
uint topWord = data[data.Length - 1];
int extra;
//if the topmost bit is set we need an extra
if (sign == 1)
{
extra = TopByte(topWord);
uint mask = 0x80u << ((extra - 1) * 8);
if ((topWord & mask) != 0)
{
needExtraZero = true;
}
}
else
{
extra = TopByte(topWord);
}
byte[] res = new byte[bytes + extra + (needExtraZero ? 1 : 0)];
if (sign == 1)
{
int j = 0;
int end = data.Length - 1;
for (int i = 0; i < end; ++i)
{
uint word = data[i];
res[j++] = (byte)word;
res[j++] = (byte)(word >> 8);
res[j++] = (byte)(word >> 16);
res[j++] = (byte)(word >> 24);
}
while (extra-- > 0)
{
res[j++] = (byte)topWord;
topWord >>= 8;
}
}
else
{
int j = 0;
int end = data.Length - 1;
uint carry = 1, word;
ulong add;
for (int i = 0; i < end; ++i)
{
word = data[i];
add = (ulong)~word + carry;
word = (uint)add;
carry = (uint)(add >> 32);
res[j++] = (byte)word;
res[j++] = (byte)(word >> 8);
res[j++] = (byte)(word >> 16);
res[j++] = (byte)(word >> 24);
}
add = (ulong)~topWord + (carry);
word = (uint)add;
carry = (uint)(add >> 32);
if (carry == 0)
{
int ex = FirstNonFFByte(word);
bool needExtra = (word & (1 << (ex * 8 - 1))) == 0;
int to = ex + (needExtra ? 1 : 0);
if (to != extra)
res = Resize(res, bytes + to);
while (ex-- > 0)
{
res[j++] = (byte)word;
word >>= 8;
}
if (needExtra)
res[j++] = 0xFF;
}
else
{
res = Resize(res, bytes + 5);
res[j++] = (byte)word;
res[j++] = (byte)(word >> 8);
res[j++] = (byte)(word >> 16);
res[j++] = (byte)(word >> 24);
res[j++] = 0xFF;
}
}
return res;
}
static byte[] Resize(byte[] v, int len)
{
byte[] res = new byte[len];
Array.Copy(v, res, Math.Min(v.Length, len));
return res;
}
static uint[] Resize(uint[] v, int len)
{
uint[] res = new uint[len];
Array.Copy(v, res, Math.Min(v.Length, len));
return res;
}
static uint[] CoreAdd(uint[] a, uint[] b)
{
if (a.Length < b.Length)
{
uint[] tmp = a;
a = b;
b = tmp;
}
int bl = a.Length;
int sl = b.Length;
uint[] res = new uint[bl];
ulong sum = 0;
int i = 0;
for (; i < sl; i++)
{
sum = sum + a[i] + b[i];
res[i] = (uint)sum;
sum >>= 32;
}
for (; i < bl; i++)
{
sum = sum + a[i];
res[i] = (uint)sum;
sum >>= 32;
}
if (sum != 0)
{
res = Resize(res, bl + 1);
res[i] = (uint)sum;
}
return res;
}
/*invariant a > b*/
static uint[] CoreSub(uint[] a, uint[] b)
{
int bl = a.Length;
int sl = b.Length;
uint[] res = new uint[bl];
ulong borrow = 0;
int i;
for (i = 0; i < sl; ++i)
{
borrow = (ulong)a[i] - b[i] - borrow;
res[i] = (uint)borrow;
borrow = (borrow >> 32) & 0x1;
}
for (; i < bl; i++)
{
borrow = (ulong)a[i] - borrow;
res[i] = (uint)borrow;
borrow = (borrow >> 32) & 0x1;
}
//remove extra zeroes
for (i = bl - 1; i >= 0 && res[i] == 0; --i) ;
if (i < bl - 1)
res = Resize(res, i + 1);
return res;
}
static uint[] CoreAdd(uint[] a, uint b)
{
int len = a.Length;
uint[] res = new uint[len];
ulong sum = b;
int i;
for (i = 0; i < len; i++)
{
sum = sum + a[i];
res[i] = (uint)sum;
sum >>= 32;
}
if (sum != 0)
{
res = Resize(res, len + 1);
res[i] = (uint)sum;
}
return res;
}
static uint[] CoreSub(uint[] a, uint b)
{
int len = a.Length;
uint[] res = new uint[len];
ulong borrow = b;
int i;
for (i = 0; i < len; i++)
{
borrow = (ulong)a[i] - borrow;
res[i] = (uint)borrow;
borrow = (borrow >> 32) & 0x1;
}
//remove extra zeroes
for (i = len - 1; i >= 0 && res[i] == 0; --i) ;
if (i < len - 1)
res = Resize(res, i + 1);
return res;
}
static int CoreCompare(uint[] a, uint[] b)
{
int al = a != null ? a.Length : 0;
int bl = b != null ? b.Length : 0;
if (al > bl)
return 1;
if (bl > al)
return -1;
for (int i = al - 1; i >= 0; --i)
{
uint ai = a[i];
uint bi = b[i];
if (ai > bi)
return 1;
if (ai < bi)
return -1;
}
return 0;
}
static int GetNormalizeShift(uint value)
{
int shift = 0;
if ((value & 0xFFFF0000) == 0) { value <<= 16; shift += 16; }
if ((value & 0xFF000000) == 0) { value <<= 8; shift += 8; }
if ((value & 0xF0000000) == 0) { value <<= 4; shift += 4; }
if ((value & 0xC0000000) == 0) { value <<= 2; shift += 2; }
if ((value & 0x80000000) == 0) { value <<= 1; shift += 1; }
return shift;
}
static void Normalize(uint[] u, int l, uint[] un, int shift)
{
uint carry = 0;
int i;
if (shift > 0)
{
int rshift = 32 - shift;
for (i = 0; i < l; i++)
{
uint ui = u[i];
un[i] = (ui << shift) | carry;
carry = ui >> rshift;
}
}
else
{
for (i = 0; i < l; i++)
{
un[i] = u[i];
}
}
while (i < un.Length)
{
un[i++] = 0;
}
if (carry != 0)
{
un[l] = carry;
}
}
static void Unnormalize(uint[] un, out uint[] r, int shift)
{
int length = un.Length;
r = new uint[length];
if (shift > 0)
{
int lshift = 32 - shift;
uint carry = 0;
for (int i = length - 1; i >= 0; i--)
{
uint uni = un[i];
r[i] = (uni >> shift) | carry;
carry = (uni << lshift);
}
}
else
{
for (int i = 0; i < length; i++)
{
r[i] = un[i];
}
}
}
const ulong Base = 0x100000000;
static void DivModUnsigned(uint[] u, uint[] v, out uint[] q, out uint[] r)
{
int m = u.Length;
int n = v.Length;
if (n <= 1)
{
// Divide by single digit
//
ulong rem = 0;
uint v0 = v[0];
q = new uint[m];
r = new uint[1];
for (int j = m - 1; j >= 0; j--)
{
rem *= Base;
rem += u[j];
ulong div = rem / v0;
rem -= div * v0;
q[j] = (uint)div;
}
r[0] = (uint)rem;
}
else if (m >= n)
{
int shift = GetNormalizeShift(v[n - 1]);
uint[] un = new uint[m + 1];
uint[] vn = new uint[n];
Normalize(u, m, un, shift);
Normalize(v, n, vn, shift);
q = new uint[m - n + 1];
r = null;
// Main division loop
//
for (int j = m - n; j >= 0; j--)
{
ulong rr, qq;
int i;
rr = Base * un[j + n] + un[j + n - 1];
qq = rr / vn[n - 1];
rr -= qq * vn[n - 1];
for (; ; )
{
// Estimate too big ?
//
if ((qq >= Base) || (qq * vn[n - 2] > (rr * Base + un[j + n - 2])))
{
qq--;
rr += (ulong)vn[n - 1];
if (rr < Base)
continue;
}
break;
}
// Multiply and subtract
//
long b = 0;
long t = 0;
for (i = 0; i < n; i++)
{
ulong p = vn[i] * qq;
t = (long)un[i + j] - (long)(uint)p - b;
un[i + j] = (uint)t;
p >>= 32;
t >>= 32;
b = (long)p - t;
}
t = (long)un[j + n] - b;
un[j + n] = (uint)t;
// Store the calculated value
//
q[j] = (uint)qq;
// Add back vn[0..n] to un[j..j+n]
//
if (t < 0)
{
q[j]--;
ulong c = 0;
for (i = 0; i < n; i++)
{
c = (ulong)vn[i] + un[j + i] + c;
un[j + i] = (uint)c;
c >>= 32;
}
c += (ulong)un[j + n];
un[j + n] = (uint)c;
}
}
Unnormalize(un, out r, shift);
}
else
{
q = new uint[] { 0 };
r = u;
}
}
}
}
| 29.528055 | 156 | 0.409984 | [
"MIT"
] | bytewizer/runtime | src/Bytewizer.TinyCLR.Numerics/Numerics/BigInteger.cs | 85,779 | C# |
using Dictionary.Domain.Abstracts;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Dictionary.Data.Entities
{
public class Meaning : DBaseEntity
{
public Meaning()
{
WordTypes = new HashSet<MeaningWordType>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Int64 Id { get; set; }
public int WordId { get; set; }
[Required]
public string MeaningText { get; set; }
public bool isVerb { get; set; } = false;
public ICollection<MeaningWordType> WordTypes { get; set; }
public override DBaseEntity Copy()
{
return this.MemberwiseClone() as Meaning;
}
}
}
| 24.794118 | 68 | 0.626335 | [
"MIT"
] | metekoroglu/Dictionary | Dictionary.Data/Entities/Meaning.cs | 845 | C# |
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;
namespace HappyTesting.Editor {
internal static partial class Generator {
static readonly object parallellLock = new();
[MenuItem("Assets/HappyTesting/Generate TestCode Template")]
public static void GenerateTestTemplate() {
// Selectionがら対象取得
if (!ContainsScriptInSelection(out var texts)) {
Debug.LogWarning("selection is not C# script");
return;
}
var destDir = GetOutputPathFromDialog();
if (string.IsNullOrEmpty(destDir)) {
return;
}
// コードの生成
var scripts = texts.Select(x => x.text).ToArray();
List<(string code, string fileName)> generated = new();
Parallel.ForEach(scripts, script => {
var param = LoadEditModeTestGenerateParam(script);
var fullText = GetEditModeTestFullText(param);
lock (parallellLock) {
generated.Add((fullText, $"{param.testClassName}.cs"));
}
}
);
Debug.Log(string.Join(",", generated.Select(x => x.fileName)));
GenerateScriptAsset(destDir, generated);
}
[MenuItem("Assets/HappyTesting/Generate Interface TestMock")]
public static void GenerateTestMock() {
// Selectionがら対象取得
if (!ContainsScriptInSelection(out var texts)) {
Debug.LogWarning("selection is not C# script");
}
var destDir = GetOutputPathFromDialog();
if (string.IsNullOrEmpty(destDir)) {
return;
}
// コードの生成
var scripts = texts.Select(x => x.text).ToArray();
List<(string code, string fileName)> generated = new();
Parallel.ForEach(scripts, script => {
var param = LoadInterfaceMockGenerateParam(script);
var fullText = GetInterfaceTestMockFullText(param);
lock (parallellLock) {
generated.Add((fullText, $"{param.className}.cs"));
}
}
);
GenerateScriptAsset(destDir, generated);
}
static bool ContainsScriptInSelection(out TextAsset[] scripts) {
var textAssets = Selection.GetFiltered(typeof(TextAsset), SelectionMode.TopLevel);
if (textAssets == null || textAssets.Length == 0) {
scripts = default;
return false;
}
scripts = textAssets
.Where(x => Path.GetExtension(AssetDatabase.GetAssetPath(x)) == ".cs")
.Cast<TextAsset>()
.ToArray();
return scripts is { Length: > 0 };
}
static string GetOutputPathFromDialog() {
return EditorUtility.SaveFolderPanel("select destination", Application.dataPath, "");
}
static void GenerateScriptAsset(string saveTo, List<(string code, string fileName)> generated) {
foreach (var (code, fileName) in generated) {
var saveFullPath = Path.Combine(saveTo, fileName);
File.WriteAllText(saveFullPath, code);
}
AssetDatabase.Refresh();
}
}
}
| 39.363636 | 104 | 0.550231 | [
"MIT"
] | naninunenoy/HappyTesting | Assets/HappyTesting/Editor/Generator.cs | 3,512 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace PTSharp
{
class MC
{
public static T[] Concat<T>(params T[][] arrays)
{
// return (from array in arrays from arr in array select arr).ToArray();
var result = new T[arrays.Sum(a => a.Length)];
int offset = 0;
for (int x = 0; x < arrays.Length; x++)
{
arrays[x].CopyTo(result, offset);
offset += arrays[x].Length;
}
return result;
}
internal static Mesh NewSDFMesh(SDF sdf, Box box, double step)
{
var min = box.Min;
var size = box.Size();
var nx = (int)Math.Ceiling(size.X / step);
var ny = (int)Math.Ceiling(size.Y / step);
var nz = (int)Math.Ceiling(size.Z / step);
var sx = size.X / nx;
var sy = size.Y / ny;
var sz = size.Z / nz;
List<Triangle> triangles = new List<Triangle>();
for (int x = 0; x < nx - 1; x++)
{
for(int y = 0; y < ny - 1; y++)
{
for(int z = 0; z < nz - 1; z++)
{
(var x0, var y0, var z0) = ((double)x * sx + min.X, (double)y * sy + min.Y, (double)z * sz + min.Z);
(var x1, var y1, var z1) = (x0 + sx, y0 + sy, z0 + sz);
var p = new Vector[8] {
new Vector( x0, y0, z0),
new Vector( x1, y0, z0),
new Vector( x1, y1, z0),
new Vector( x0, y1, z0),
new Vector( x0, y0, z1),
new Vector( x1, y0, z1),
new Vector( x1, y1, z1),
new Vector( x0, y1, z1)
};
double[] v = new double[8];
for(int i = 0; i < 8; i++)
{
v[i] = sdf.Evaluate(p[i]);
}
if (mcPolygonize(p, v, 0) == null)
{
continue;
} else
{
triangles.AddRange(mcPolygonize(p, v, 0));
}
}
}
}
return Mesh.NewMesh(triangles.ToArray());
}
static Triangle[] mcPolygonize(Vector[] p, double[] v, double x)
{
int index = 0;
for (int i = 0; i < 8; i++)
{
if (v[i] < x)
{
index |= 1 << Convert.ToUInt16(i);
}
}
if (edgetable[index] == 0)
{
return null;
}
Vector[] points = new Vector[12];
for (int i = 0; i < 12; i++)
{
int bit = 1 << Convert.ToUInt16(i);
if ((edgetable[index] & bit) != 0)
{
int a = pairTable[i][0];
int b = pairTable[i][1];
points[i] = mcInterpolate(p[a], p[b], v[a], v[b], x);
}
}
var table = triangleTable[index];
var count = table.Length / 3;
Triangle[] result = new Triangle[count];
for (int i = 0; i < count; i++)
{
Triangle triangle = new Triangle();
triangle.V3 = points[table[i * 3 + 0]];
triangle.V2 = points[table[i * 3 + 1]];
triangle.V1 = points[table[i * 3 + 2]];
triangle.FixNormals();
result[i] = triangle;
}
return result;
}
static Vector mcInterpolate(Vector p1, Vector p2, double v1, double v2, double x)
{
if (Math.Abs(x - v1) < Util.EPS)
return p1;
if (Math.Abs(x - v2) < Util.EPS)
return p2;
if (Math.Abs(v1 - v2) < Util.EPS)
return p1;
var t = (x - v1) / (v2 - v1);
return new Vector(p1.X + t * (p2.X - p1.X), p1.Y + t * (p2.Y - p1.Y), p1.Z + t * (p2.Z - p1.Z));
}
static int[][] pairTable = {
new int[] {0, 1}, new int[] {1, 2}, new int[] {2, 3}, new int[] {3, 0},
new int[] {4, 5}, new int[] {5, 6}, new int[] {6, 7}, new int[] {7, 4},
new int[] {0, 4}, new int[] {1, 5}, new int[] {2, 6}, new int[] {3, 7}
};
static int[] edgetable =
{
0x0000, 0x0109, 0x0203, 0x030a, 0x0406, 0x050f, 0x0605, 0x070c,
0x080c, 0x0905, 0x0a0f, 0x0b06, 0x0c0a, 0x0d03, 0x0e09, 0x0f00,
0x0190, 0x0099, 0x0393, 0x029a, 0x0596, 0x049f, 0x0795, 0x069c,
0x099c, 0x0895, 0x0b9f, 0x0a96, 0x0d9a, 0x0c93, 0x0f99, 0x0e90,
0x0230, 0x0339, 0x0033, 0x013a, 0x0636, 0x073f, 0x0435, 0x053c,
0x0a3c, 0x0b35, 0x083f, 0x0936, 0x0e3a, 0x0f33, 0x0c39, 0x0d30,
0x03a0, 0x02a9, 0x01a3, 0x00aa, 0x07a6, 0x06af, 0x05a5, 0x04ac,
0x0bac, 0x0aa5, 0x09af, 0x08a6, 0x0faa, 0x0ea3, 0x0da9, 0x0ca0,
0x0460, 0x0569, 0x0663, 0x076a, 0x0066, 0x016f, 0x0265, 0x036c,
0x0c6c, 0x0d65, 0x0e6f, 0x0f66, 0x086a, 0x0963, 0x0a69, 0x0b60,
0x05f0, 0x04f9, 0x07f3, 0x06fa, 0x01f6, 0x00ff, 0x03f5, 0x02fc,
0x0dfc, 0x0cf5, 0x0fff, 0x0ef6, 0x09fa, 0x08f3, 0x0bf9, 0x0af0,
0x0650, 0x0759, 0x0453, 0x055a, 0x0256, 0x035f, 0x0055, 0x015c,
0x0e5c, 0x0f55, 0x0c5f, 0x0d56, 0x0a5a, 0x0b53, 0x0859, 0x0950,
0x07c0, 0x06c9, 0x05c3, 0x04ca, 0x03c6, 0x02cf, 0x01c5, 0x00cc,
0x0fcc, 0x0ec5, 0x0dcf, 0x0cc6, 0x0bca, 0x0ac3, 0x09c9, 0x08c0,
0x08c0, 0x09c9, 0x0ac3, 0x0bca, 0x0cc6, 0x0dcf, 0x0ec5, 0x0fcc,
0x00cc, 0x01c5, 0x02cf, 0x03c6, 0x04ca, 0x05c3, 0x06c9, 0x07c0,
0x0950, 0x0859, 0x0b53, 0x0a5a, 0x0d56, 0x0c5f, 0x0f55, 0x0e5c,
0x015c, 0x0055, 0x035f, 0x0256, 0x055a, 0x0453, 0x0759, 0x0650,
0x0af0, 0x0bf9, 0x08f3, 0x09fa, 0x0ef6, 0x0fff, 0x0cf5, 0x0dfc,
0x02fc, 0x03f5, 0x00ff, 0x01f6, 0x06fa, 0x07f3, 0x04f9, 0x05f0,
0x0b60, 0x0a69, 0x0963, 0x086a, 0x0f66, 0x0e6f, 0x0d65, 0x0c6c,
0x036c, 0x0265, 0x016f, 0x0066, 0x076a, 0x0663, 0x0569, 0x0460,
0x0ca0, 0x0da9, 0x0ea3, 0x0faa, 0x08a6, 0x09af, 0x0aa5, 0x0bac,
0x04ac, 0x05a5, 0x06af, 0x07a6, 0x00aa, 0x01a3, 0x02a9, 0x03a0,
0x0d30, 0x0c39, 0x0f33, 0x0e3a, 0x0936, 0x083f, 0x0b35, 0x0a3c,
0x053c, 0x0435, 0x073f, 0x0636, 0x013a, 0x0033, 0x0339, 0x0230,
0x0e90, 0x0f99, 0x0c93, 0x0d9a, 0x0a96, 0x0b9f, 0x0895, 0x099c,
0x069c, 0x0795, 0x049f, 0x0596, 0x029a, 0x0393, 0x0099, 0x0190,
0x0f00, 0x0e09, 0x0d03, 0x0c0a, 0x0b06, 0x0a0f, 0x0905, 0x080c,
0x070c, 0x0605, 0x050f, 0x0406, 0x030a, 0x0203, 0x0109, 0x0000
};
static int[][] triangleTable = new int[][]
{
new int[] {},
new int[] {0, 8, 3},
new int[] {0, 1, 9},
new int[] {1, 8, 3, 9, 8, 1},
new int[] {1, 2, 10},
new int[] {0, 8, 3, 1, 2, 10},
new int[] {9, 2, 10, 0, 2, 9},
new int[] {2, 8, 3, 2, 10, 8, 10, 9, 8},
new int[] {3, 11, 2},
new int[] {0, 11, 2, 8, 11, 0},
new int[] {1, 9, 0, 2, 3, 11},
new int[] {1, 11, 2, 1, 9, 11, 9, 8, 11},
new int[] {3, 10, 1, 11, 10, 3},
new int[] {0, 10, 1, 0, 8, 10, 8, 11, 10},
new int[] {3, 9, 0, 3, 11, 9, 11, 10, 9},
new int[] {9, 8, 10, 10, 8, 11},
new int[] {4, 7, 8},
new int[] {4, 3, 0, 7, 3, 4},
new int[] {0, 1, 9, 8, 4, 7},
new int[] {4, 1, 9, 4, 7, 1, 7, 3, 1},
new int[] {1, 2, 10, 8, 4, 7},
new int[] {3, 4, 7, 3, 0, 4, 1, 2, 10},
new int[] {9, 2, 10, 9, 0, 2, 8, 4, 7},
new int[] {2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4},
new int[] {8, 4, 7, 3, 11, 2},
new int[] {11, 4, 7, 11, 2, 4, 2, 0, 4},
new int[] {9, 0, 1, 8, 4, 7, 2, 3, 11},
new int[] {4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1},
new int[] {3, 10, 1, 3, 11, 10, 7, 8, 4},
new int[] {1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4},
new int[] {4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3},
new int[] {4, 7, 11, 4, 11, 9, 9, 11, 10},
new int[] {9, 5, 4},
new int[] {9, 5, 4, 0, 8, 3},
new int[] {0, 5, 4, 1, 5, 0},
new int[] {8, 5, 4, 8, 3, 5, 3, 1, 5},
new int[] {1, 2, 10, 9, 5, 4},
new int[] {3, 0, 8, 1, 2, 10, 4, 9, 5},
new int[] {5, 2, 10, 5, 4, 2, 4, 0, 2},
new int[] {2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8},
new int[] {9, 5, 4, 2, 3, 11},
new int[] {0, 11, 2, 0, 8, 11, 4, 9, 5},
new int[] {0, 5, 4, 0, 1, 5, 2, 3, 11},
new int[] {2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5},
new int[] {10, 3, 11, 10, 1, 3, 9, 5, 4},
new int[] {4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10},
new int[] {5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3},
new int[] {5, 4, 8, 5, 8, 10, 10, 8, 11},
new int[] {9, 7, 8, 5, 7, 9},
new int[] {9, 3, 0, 9, 5, 3, 5, 7, 3},
new int[] {0, 7, 8, 0, 1, 7, 1, 5, 7},
new int[] {1, 5, 3, 3, 5, 7},
new int[] {9, 7, 8, 9, 5, 7, 10, 1, 2},
new int[] {10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3},
new int[] {8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2},
new int[] {2, 10, 5, 2, 5, 3, 3, 5, 7},
new int[] {7, 9, 5, 7, 8, 9, 3, 11, 2},
new int[] {9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11},
new int[] {2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7},
new int[] {11, 2, 1, 11, 1, 7, 7, 1, 5},
new int[] {9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11},
new int[] {5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0},
new int[] {11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0},
new int[] {11, 10, 5, 7, 11, 5},
new int[] {10, 6, 5},
new int[] {0, 8, 3, 5, 10, 6},
new int[] {9, 0, 1, 5, 10, 6},
new int[] {1, 8, 3, 1, 9, 8, 5, 10, 6},
new int[] {1, 6, 5, 2, 6, 1},
new int[] {1, 6, 5, 1, 2, 6, 3, 0, 8},
new int[] {9, 6, 5, 9, 0, 6, 0, 2, 6},
new int[] {5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8},
new int[] {2, 3, 11, 10, 6, 5},
new int[] {11, 0, 8, 11, 2, 0, 10, 6, 5},
new int[] {0, 1, 9, 2, 3, 11, 5, 10, 6},
new int[] {5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11},
new int[] {6, 3, 11, 6, 5, 3, 5, 1, 3},
new int[] {0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6},
new int[] {3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9},
new int[] {6, 5, 9, 6, 9, 11, 11, 9, 8},
new int[] {5, 10, 6, 4, 7, 8},
new int[] {4, 3, 0, 4, 7, 3, 6, 5, 10},
new int[] {1, 9, 0, 5, 10, 6, 8, 4, 7},
new int[] {10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4},
new int[] {6, 1, 2, 6, 5, 1, 4, 7, 8},
new int[] {1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7},
new int[] {8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6},
new int[] {7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9},
new int[] {3, 11, 2, 7, 8, 4, 10, 6, 5},
new int[] {5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11},
new int[] {0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6},
new int[] {9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6},
new int[] {8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6},
new int[] {5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11},
new int[] {0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7},
new int[] {6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9},
new int[] {10, 4, 9, 6, 4, 10},
new int[] {4, 10, 6, 4, 9, 10, 0, 8, 3},
new int[] {10, 0, 1, 10, 6, 0, 6, 4, 0},
new int[] {8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10},
new int[] {1, 4, 9, 1, 2, 4, 2, 6, 4},
new int[] {3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4},
new int[] {0, 2, 4, 4, 2, 6},
new int[] {8, 3, 2, 8, 2, 4, 4, 2, 6},
new int[] {10, 4, 9, 10, 6, 4, 11, 2, 3},
new int[] {0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6},
new int[] {3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10},
new int[] {6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1},
new int[] {9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3},
new int[] {8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1},
new int[] {3, 11, 6, 3, 6, 0, 0, 6, 4},
new int[] {6, 4, 8, 11, 6, 8},
new int[] {7, 10, 6, 7, 8, 10, 8, 9, 10},
new int[] {0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10},
new int[] {10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0},
new int[] {10, 6, 7, 10, 7, 1, 1, 7, 3},
new int[] {1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7},
new int[] {2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9},
new int[] {7, 8, 0, 7, 0, 6, 6, 0, 2},
new int[] {7, 3, 2, 6, 7, 2},
new int[] {2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7},
new int[] {2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7},
new int[] {1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11},
new int[] {11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1},
new int[] {8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6},
new int[] {0, 9, 1, 11, 6, 7},
new int[] {7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0},
new int[] {7, 11, 6},
new int[] {7, 6, 11},
new int[] {3, 0, 8, 11, 7, 6},
new int[] {0, 1, 9, 11, 7, 6},
new int[] {8, 1, 9, 8, 3, 1, 11, 7, 6},
new int[] {10, 1, 2, 6, 11, 7},
new int[] {1, 2, 10, 3, 0, 8, 6, 11, 7},
new int[] {2, 9, 0, 2, 10, 9, 6, 11, 7},
new int[] {6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8},
new int[] {7, 2, 3, 6, 2, 7},
new int[] {7, 0, 8, 7, 6, 0, 6, 2, 0},
new int[] {2, 7, 6, 2, 3, 7, 0, 1, 9},
new int[] {1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6},
new int[] {10, 7, 6, 10, 1, 7, 1, 3, 7},
new int[] {10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8},
new int[] {0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7},
new int[] {7, 6, 10, 7, 10, 8, 8, 10, 9},
new int[] {6, 8, 4, 11, 8, 6},
new int[] {3, 6, 11, 3, 0, 6, 0, 4, 6},
new int[] {8, 6, 11, 8, 4, 6, 9, 0, 1},
new int[] {9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6},
new int[] {6, 8, 4, 6, 11, 8, 2, 10, 1},
new int[] {1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6},
new int[] {4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9},
new int[] {10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3},
new int[] {8, 2, 3, 8, 4, 2, 4, 6, 2},
new int[] {0, 4, 2, 4, 6, 2},
new int[] {1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8},
new int[] {1, 9, 4, 1, 4, 2, 2, 4, 6},
new int[] {8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1},
new int[] {10, 1, 0, 10, 0, 6, 6, 0, 4},
new int[] {4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3},
new int[] {10, 9, 4, 6, 10, 4},
new int[] {4, 9, 5, 7, 6, 11},
new int[] {0, 8, 3, 4, 9, 5, 11, 7, 6},
new int[] {5, 0, 1, 5, 4, 0, 7, 6, 11},
new int[] {11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5},
new int[] {9, 5, 4, 10, 1, 2, 7, 6, 11},
new int[] {6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5},
new int[] {7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2},
new int[] {3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6},
new int[] {7, 2, 3, 7, 6, 2, 5, 4, 9},
new int[] {9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7},
new int[] {3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0},
new int[] {6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8},
new int[] {9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7},
new int[] {1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4},
new int[] {4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10},
new int[] {7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10},
new int[] {6, 9, 5, 6, 11, 9, 11, 8, 9},
new int[] {3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5},
new int[] {0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11},
new int[] {6, 11, 3, 6, 3, 5, 5, 3, 1},
new int[] {1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6},
new int[] {0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10},
new int[] {11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5},
new int[] {6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3},
new int[] {5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2},
new int[] {9, 5, 6, 9, 6, 0, 0, 6, 2},
new int[] {1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8},
new int[] {1, 5, 6, 2, 1, 6},
new int[] {1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6},
new int[] {10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0},
new int[] {0, 3, 8, 5, 6, 10},
new int[] {10, 5, 6},
new int[] {11, 5, 10, 7, 5, 11},
new int[] {11, 5, 10, 11, 7, 5, 8, 3, 0},
new int[] {5, 11, 7, 5, 10, 11, 1, 9, 0},
new int[] {10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1},
new int[] {11, 1, 2, 11, 7, 1, 7, 5, 1},
new int[] {0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11},
new int[] {9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7},
new int[] {7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2},
new int[] {2, 5, 10, 2, 3, 5, 3, 7, 5},
new int[] {8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5},
new int[] {9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2},
new int[] {9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2},
new int[] {1, 3, 5, 3, 7, 5},
new int[] {0, 8, 7, 0, 7, 1, 1, 7, 5},
new int[] {9, 0, 3, 9, 3, 5, 5, 3, 7},
new int[] {9, 8, 7, 5, 9, 7},
new int[] {5, 8, 4, 5, 10, 8, 10, 11, 8},
new int[] {5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0},
new int[] {0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5},
new int[] {10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4},
new int[] {2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8},
new int[] {0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11},
new int[] {0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5},
new int[] {9, 4, 5, 2, 11, 3},
new int[] {2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4},
new int[] {5, 10, 2, 5, 2, 4, 4, 2, 0},
new int[] {3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9},
new int[] {5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2},
new int[] {8, 4, 5, 8, 5, 3, 3, 5, 1},
new int[] {0, 4, 5, 1, 0, 5},
new int[] {8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5},
new int[] {9, 4, 5},
new int[] {4, 11, 7, 4, 9, 11, 9, 10, 11},
new int[] {0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11},
new int[] {1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11},
new int[] {3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4},
new int[] {4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2},
new int[] {9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3},
new int[] {11, 7, 4, 11, 4, 2, 2, 4, 0},
new int[] {11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4},
new int[] {2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9},
new int[] {9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7},
new int[] {3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10},
new int[] {1, 10, 2, 8, 7, 4},
new int[] {4, 9, 1, 4, 1, 7, 7, 1, 3},
new int[] {4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1},
new int[] {4, 0, 3, 7, 4, 3},
new int[] {4, 8, 7},
new int[] {9, 10, 8, 10, 11, 8},
new int[] {3, 0, 9, 3, 9, 11, 11, 9, 10},
new int[] {0, 1, 10, 0, 10, 8, 8, 10, 11},
new int[] {3, 1, 10, 11, 3, 10},
new int[] {1, 2, 11, 1, 11, 9, 9, 11, 8},
new int[] {3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9},
new int[] {0, 2, 11, 8, 0, 11},
new int[] {3, 2, 11},
new int[] {2, 3, 8, 2, 8, 10, 10, 8, 9},
new int[] {9, 10, 2, 0, 9, 2},
new int[] {2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8},
new int[] {1, 10, 2},
new int[] {1, 3, 8, 9, 1, 8},
new int[] {0, 9, 1},
new int[] {0, 3, 8},
new int[] {}
};
}
}
| 50.675234 | 125 | 0.354742 | [
"MIT"
] | xfischer/PTSharp | MC.cs | 21,689 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using ILRuntime.CLR.TypeSystem;
using ILRuntime.Mono.Cecil.Pdb;
using ILRuntime.Reflection;
using ILRuntime.Runtime.Enviorment;
using ILRuntime.Runtime.Generated;
using ILRuntime.Runtime.Intepreter;
using LitJson;
using UnityEngine;
using AppDomain = ILRuntime.Runtime.Enviorment.AppDomain;
namespace QFramework
{
public static class ILRuntimeHelper
{
public static AppDomain AppDomain { get; private set; }
public static bool IsRunning { get; private set; }
static private MemoryStream msDll = null;
static private MemoryStream msPdb = null;
public static void LoadHotfix(byte[] dllBytes, byte[] pdbBytes = null, bool isRegisterBindings = true)
{
//
IsRunning = true;
//
AppDomain = new AppDomain();
msDll = new MemoryStream(dllBytes);
if (pdbBytes != null)
msPdb = new MemoryStream(pdbBytes);
AppDomain.LoadAssembly(msDll, msPdb, new PdbReaderProvider());
//绑定的初始化
//ada绑定
//是否注册各种binding
if (isRegisterBindings)
{
CLRBindings.Initialize(AppDomain);
CLRManualBindings.Initialize(AppDomain);
// ILRuntime.Runtime.Generated.PreCLRBuilding.Initialize(AppDomain);
}
ILRuntimeRedirectHelper.RegisterMethodRedirection(AppDomain);
ILRuntimeDelegateHelper.RegisterDelegate(AppDomain);
ILRuntimeValueTypeBinderHelper.Register(AppDomain);
if (Application.isEditor)
{
AppDomain.DebugService.StartDebugService(56000);
}
}
private static Dictionary<string,Type> hotfixType = null;
public static IEnumerable<Type> GetHotfixTypes()
{
if (hotfixType == null)
{
hotfixType = new Dictionary<string, Type>();
foreach (var v in AppDomain.LoadedTypes)
{
hotfixType.Add(v.Key,v.Value.ReflectionType);
}
}
return hotfixType.Values;
}
public static Type GetCLRType(object obj)
{
//如果是继承了主项目的热更的类型
if (obj is CrossBindingAdaptorType adaptor)
{
return adaptor.ILInstance.Type.ReflectionType;
}
//如果是热更的类型
if (obj is ILTypeInstance ilInstance)
{
return ilInstance.Type.ReflectionType;
}
return obj.GetType();
}
public static Type GetCLRType(Type type)
{
if (type is ILRuntimeType runtimeType)
return runtimeType.ILType.ReflectionType;
if (type is ILRuntimeWrapperType wrapperType)
return wrapperType.RealType;
return type;
}
public static Type GetCLRType(this IType type)
{
if (type is CLRType clrType)
{
return clrType.TypeForCLR;
}
return type.ReflectionType;
}
public static Type GetType(string name)
{
if (hotfixType == null)
GetHotfixTypes();
return hotfixType.TryGetValue(name, out var type) ? type : null;
}
public static void Close()
{
if (msDll != null)
{
msDll.Dispose();
}
if (msPdb != null)
{
msPdb.Dispose();
}
}
}
} | 29.440945 | 110 | 0.548007 | [
"MIT"
] | yzx4036/QFramework | Unity2019ILRuntime/Assets/QFramework/ILRuntime/Runtime/Framework/ScriptHelper/ILRuntimeHelper.cs | 3,815 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Moq;
using Newtonsoft.Json.Linq;
using NuGet.Common;
using NuGet.Configuration;
using NuGet.Protocol;
using NuGet.Protocol.Core.Types;
using NuGet.Protocol.Plugins;
using NuGet.Versioning;
namespace NuGet.Credentials.Test
{
internal sealed class TestExpectation
{
internal IEnumerable<OperationClaim> OperationClaims { get; }
public string OperationClaimsSourceRepository { get; }
public JObject ServiceIndex { get; }
public ConnectionOptions ClientConnectionOptions { get; }
public SemanticVersion PluginVersion { get; }
public Uri Uri { get; }
public string AuthenticationUsername { get; }
public string AuthenticationPassword { get; }
public bool Success { get; }
public string ProxyUsername { get; }
public string ProxyPassword { get; }
public bool PluginLaunched { get; }
public bool CanShowDialog { get; }
internal TestExpectation(
string serviceIndexJson,
string sourceUri,
IEnumerable<OperationClaim> operationClaims,
ConnectionOptions connectionOptions,
SemanticVersion pluginVersion,
Uri uri,
string authenticationUsername,
string authenticationPassword,
bool success,
string proxyUsername = null,
string proxyPassword = null,
bool pluginLaunched = true,
bool canShowDialog = true
)
{
var serviceIndex = string.IsNullOrEmpty(serviceIndexJson)
? null : new ServiceIndexResourceV3(JObject.Parse(serviceIndexJson), DateTime.UtcNow);
OperationClaims = operationClaims;
OperationClaimsSourceRepository = sourceUri;
ClientConnectionOptions = connectionOptions;
PluginVersion = pluginVersion;
Uri = uri;
AuthenticationUsername = authenticationUsername;
AuthenticationPassword = authenticationPassword;
Success = success;
ProxyPassword = proxyPassword;
ProxyUsername = proxyUsername;
PluginLaunched = pluginLaunched;
CanShowDialog = canShowDialog;
}
}
internal sealed class PluginManagerMock : IDisposable
{
private readonly Mock<IConnection> _connection;
private readonly TestExpectation _expectations;
private readonly Mock<IPluginFactory> _factory;
private readonly Mock<IPlugin> _plugin;
private readonly Mock<IPluginDiscoverer> _pluginDiscoverer;
private readonly Mock<IEnvironmentVariableReader> _reader;
internal PluginManager PluginManager { get; }
private string _pluginFilePath;
internal PluginManagerMock(
string pluginFilePath,
PluginFileState pluginFileState,
TestExpectation expectations)
{
_pluginFilePath = pluginFilePath;
_expectations = expectations;
_reader = new Mock<IEnvironmentVariableReader>(MockBehavior.Strict);
EnsureAllEnvironmentVariablesAreCalled(pluginFilePath);
_pluginDiscoverer = new Mock<IPluginDiscoverer>(MockBehavior.Strict);
EnsureDiscovererIsCalled(pluginFilePath, pluginFileState);
_connection = new Mock<IConnection>(MockBehavior.Strict);
EnsureBasicPluginSetupCalls();
_plugin = new Mock<IPlugin>(MockBehavior.Strict);
EnsurePluginSetupCalls();
_factory = new Mock<IPluginFactory>(MockBehavior.Strict);
EnsureFactorySetupCalls(pluginFilePath);
// Setup connection
_connection.SetupGet(x => x.Options)
.Returns(expectations.ClientConnectionOptions);
_connection.SetupGet(x => x.ProtocolVersion)
.Returns(expectations.PluginVersion);
// Setup expectations
_connection.Setup(x => x.SendRequestAndReceiveResponseAsync<GetOperationClaimsRequest, GetOperationClaimsResponse>(
It.Is<MessageMethod>(m => m == MessageMethod.GetOperationClaims),
It.Is<GetOperationClaimsRequest>(
g => g.PackageSourceRepository == expectations.OperationClaimsSourceRepository),
It.IsAny<CancellationToken>()))
.ReturnsAsync(new GetOperationClaimsResponse(expectations.OperationClaims.ToArray()));
if (_expectations.Success)
{
_connection.Setup(x => x.SendRequestAndReceiveResponseAsync<SetLogLevelRequest, SetLogLevelResponse>(
It.Is<MessageMethod>(m => m == MessageMethod.SetLogLevel),
It.IsAny<SetLogLevelRequest>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(new SetLogLevelResponse(MessageResponseCode.Success));
}
if (expectations.ProxyUsername != null && expectations.ProxyPassword != null)
{
_connection.Setup(x => x.SendRequestAndReceiveResponseAsync<SetCredentialsRequest, SetCredentialsResponse>(
It.Is<MessageMethod>(m => m == MessageMethod.SetCredentials),
It.Is<SetCredentialsRequest>(e => e.PackageSourceRepository.Equals(expectations.Uri.AbsolutePath) && e.Password == null && e.Username == null && e.ProxyPassword.Equals(expectations.ProxyPassword) && e.ProxyUsername.Equals(expectations.ProxyUsername)),
It.IsAny<CancellationToken>()))
.ReturnsAsync(new SetCredentialsResponse(MessageResponseCode.Success));
}
if (_expectations.Success)
{
_connection.Setup(x => x.SendRequestAndReceiveResponseAsync<GetAuthenticationCredentialsRequest, GetAuthenticationCredentialsResponse>(
It.Is<MessageMethod>(m => m == MessageMethod.GetAuthenticationCredentials),
It.Is<GetAuthenticationCredentialsRequest>(e => e.Uri.Equals(expectations.Uri) && e.CanShowDialog.Equals(expectations.CanShowDialog)),
It.IsAny<CancellationToken>()))
.ReturnsAsync(new GetAuthenticationCredentialsResponse(expectations.AuthenticationUsername, expectations.AuthenticationPassword, null, null, MessageResponseCode.Success));
}
PluginManager = new PluginManager(
_reader.Object,
new Lazy<IPluginDiscoverer>(() => _pluginDiscoverer.Object),
(TimeSpan idleTimeout) => _factory.Object);
}
public void Dispose()
{
LocalResourceUtils.DeleteDirectoryTree(
Path.Combine(
SettingsUtility.GetPluginsCacheFolder(),
CachingUtility.RemoveInvalidFileNameChars(CachingUtility.ComputeHash(_pluginFilePath))),
new List<string>());
PluginManager.Dispose();
GC.SuppressFinalize(this);
_reader.Verify();
_pluginDiscoverer.Verify();
if (_expectations.PluginLaunched)
{
_connection.Verify(x => x.SendRequestAndReceiveResponseAsync<GetOperationClaimsRequest, GetOperationClaimsResponse>(
It.Is<MessageMethod>(m => m == MessageMethod.GetOperationClaims),
It.Is<GetOperationClaimsRequest>(
g => g.PackageSourceRepository == null), // The source repository should be null in the context of credential plugins
It.IsAny<CancellationToken>()), Times.Once());
if (_expectations.Success)
{
_connection.Verify(x => x.SendRequestAndReceiveResponseAsync<GetAuthenticationCredentialsRequest, GetAuthenticationCredentialsResponse>(
It.Is<MessageMethod>(m => m == MessageMethod.GetAuthenticationCredentials),
It.IsAny<GetAuthenticationCredentialsRequest>(),
It.IsAny<CancellationToken>()), Times.Once());
}
if (_expectations.ProxyUsername != null && _expectations.ProxyPassword != null)
{
_connection.Verify(x => x.SendRequestAndReceiveResponseAsync<SetCredentialsRequest, SetCredentialsResponse>(
It.Is<MessageMethod>(m => m == MessageMethod.SetCredentials),
It.Is<SetCredentialsRequest>(e => e.PackageSourceRepository.Equals(_expectations.Uri.AbsolutePath) && e.Password == null && e.Username == null && e.ProxyPassword.Equals(_expectations.ProxyPassword) && e.ProxyUsername.Equals(_expectations.ProxyUsername)),
It.IsAny<CancellationToken>()),
Times.Once());
}
}
_connection.Verify();
_plugin.Verify();
_factory.Verify();
}
private void EnsureAllEnvironmentVariablesAreCalled(string pluginFilePath)
{
_reader.Setup(x => x.GetEnvironmentVariable(
It.Is<string>(value => value == CredentialTestConstants.PluginPathsEnvironmentVariable)))
.Returns(pluginFilePath);
_reader.Setup(x => x.GetEnvironmentVariable(
It.Is<string>(value => value == CredentialTestConstants.PluginRequestTimeoutEnvironmentVariable)))
.Returns("RequestTimeout");
_reader.Setup(x => x.GetEnvironmentVariable(
It.Is<string>(value => value == CredentialTestConstants.PluginIdleTimeoutEnvironmentVariable)))
.Returns("IdleTimeout");
_reader.Setup(x => x.GetEnvironmentVariable(
It.Is<string>(value => value == CredentialTestConstants.PluginHandshakeTimeoutEnvironmentVariable)))
.Returns("HandshakeTimeout");
}
private void EnsureDiscovererIsCalled(string pluginFilePath, PluginFileState pluginFileState)
{
_pluginDiscoverer.Setup(x => x.Dispose());
_pluginDiscoverer.Setup(x => x.DiscoverAsync(It.IsAny<CancellationToken>()))
.ReturnsAsync(new[]
{
new PluginDiscoveryResult(new PluginFile(pluginFilePath, new Lazy<PluginFileState>(() => pluginFileState)))
});
}
private void EnsureBasicPluginSetupCalls()
{
_connection.Setup(x => x.Dispose());
_connection.Setup(x => x.SendRequestAndReceiveResponseAsync<MonitorNuGetProcessExitRequest, MonitorNuGetProcessExitResponse>(
It.Is<MessageMethod>(m => m == MessageMethod.MonitorNuGetProcessExit),
It.IsNotNull<MonitorNuGetProcessExitRequest>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(new MonitorNuGetProcessExitResponse(MessageResponseCode.Success));
_connection.Setup(x => x.SendRequestAndReceiveResponseAsync<InitializeRequest, InitializeResponse>(
It.Is<MessageMethod>(m => m == MessageMethod.Initialize),
It.IsNotNull<InitializeRequest>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(new InitializeResponse(MessageResponseCode.Success));
_connection.Setup(x => x.MessageDispatcher.RequestHandlers.AddOrUpdate(
It.Is<MessageMethod>(m => m == MessageMethod.Log),
It.IsAny<Func<IRequestHandler>>(),
It.IsAny<Func<IRequestHandler, IRequestHandler>>()));
}
private void EnsurePluginSetupCalls()
{
_plugin.Setup(x => x.Dispose());
_plugin.SetupGet(x => x.Connection)
.Returns(_connection.Object);
_plugin.SetupGet(x => x.Id)
.Returns("id");
}
private void EnsureFactorySetupCalls(string pluginFilePath)
{
_factory.Setup(x => x.Dispose());
_factory.Setup(x => x.GetOrCreateAsync(
It.Is<string>(p => p == pluginFilePath),
It.IsNotNull<IEnumerable<string>>(),
It.IsNotNull<IRequestHandlers>(),
It.IsNotNull<ConnectionOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(_plugin.Object);
}
}
} | 47.773234 | 278 | 0.618862 | [
"Apache-2.0"
] | BdDsl/NuGet.Client | test/NuGet.Core.Tests/NuGet.Credentials.Test/PluginManagerMock.cs | 12,851 | C# |
//
// Copyright 2020 Google LLC
//
// 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 Google.Apis.Util;
using Google.Solutions.IapDesktop.Application.Services.Adapters;
using Google.Solutions.IapDesktop.Application.Services.SecureConnect;
using Google.Solutions.IapDesktop.Application.Settings;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
namespace Google.Solutions.IapDesktop.Application.Services.Settings
{
/// <summary>
/// Registry-backed repository for app settings.
/// </summary>
public class ApplicationSettingsRepository : SettingsRepositoryBase<ApplicationSettings>
{
private readonly RegistryKey machinePolicyKey;
private readonly RegistryKey userPolicyKey;
public ApplicationSettingsRepository(
RegistryKey settingsKey,
RegistryKey machinePolicyKey,
RegistryKey userPolicyKey) : base(settingsKey)
{
Utilities.ThrowIfNull(settingsKey, nameof(settingsKey));
this.machinePolicyKey = machinePolicyKey;
this.userPolicyKey = userPolicyKey;
}
protected override ApplicationSettings LoadSettings(RegistryKey key)
=> ApplicationSettings.FromKey(
key,
this.machinePolicyKey,
this.userPolicyKey);
public bool IsPolicyPresent
=> this.machinePolicyKey != null || this.userPolicyKey != null;
}
public class ApplicationSettings : IRegistrySettingsCollection
{
public const char FullScreenDevicesSeparator = ',';
public RegistryBoolSetting IsMainWindowMaximized { get; private set; }
public RegistryDwordSetting MainWindowHeight { get; private set; }
public RegistryDwordSetting MainWindowWidth { get; private set; }
public RegistryBoolSetting IsUpdateCheckEnabled { get; private set; }
public RegistryQwordSetting LastUpdateCheck { get; private set; }
public RegistryBoolSetting IsPreviewFeatureSetEnabled { get; private set; }
public RegistryStringSetting ProxyUrl { get; private set; }
public RegistryStringSetting ProxyPacUrl { get; private set; }
public RegistryStringSetting ProxyUsername { get; private set; }
public RegistrySecureStringSetting ProxyPassword { get; private set; }
public RegistryBoolSetting IsDeviceCertificateAuthenticationEnabled { get; private set; }
public RegistryStringSetting FullScreenDevices { get; private set; }
public RegistryEnumSetting<OperatingSystems> IncludeOperatingSystems { get; private set; }
public RegistryStringSetting DeviceCertificateSelector { get; private set; }
public IEnumerable<ISetting> Settings => new ISetting[]
{
this.IsMainWindowMaximized,
this.MainWindowHeight,
this.MainWindowWidth,
this.IsUpdateCheckEnabled,
this.LastUpdateCheck,
this.IsUpdateCheckEnabled,
this.ProxyUrl,
this.ProxyPacUrl,
this.ProxyUsername,
this.ProxyPassword,
this.IsDeviceCertificateAuthenticationEnabled,
this.FullScreenDevices,
this.IncludeOperatingSystems,
this.DeviceCertificateSelector
};
private ApplicationSettings()
{ }
public static ApplicationSettings FromKey(
RegistryKey settingsKey,
RegistryKey machinePolicyKey,
RegistryKey userPolicyKey)
{
return new ApplicationSettings()
{
//
// Settings that can be overriden by policy.
//
// NB. Default values must be kept consistent with the
// ADMX policy templates!
// NB. Machine policies override user policies, and
// user policies override settings.
//
IsPreviewFeatureSetEnabled = RegistryBoolSetting.FromKey(
"IsPreviewFeatureSetEnabled",
"IsPreviewFeatureSetEnabled",
null,
null,
false,
settingsKey)
.ApplyPolicy(userPolicyKey)
.ApplyPolicy(machinePolicyKey),
IsUpdateCheckEnabled = RegistryBoolSetting.FromKey(
"IsUpdateCheckEnabled",
"IsUpdateCheckEnabled",
null,
null,
true,
settingsKey)
.ApplyPolicy(userPolicyKey)
.ApplyPolicy(machinePolicyKey),
IsDeviceCertificateAuthenticationEnabled = RegistryBoolSetting.FromKey(
"IsDeviceCertificateAuthenticationEnabled",
"IsDeviceCertificateAuthenticationEnabled",
null,
null,
false,
settingsKey)
.ApplyPolicy(userPolicyKey)
.ApplyPolicy(machinePolicyKey),
ProxyUrl = RegistryStringSetting.FromKey(
"ProxyUrl",
"ProxyUrl",
null,
null,
null,
settingsKey,
url => url == null || Uri.TryCreate(url, UriKind.Absolute, out Uri _))
.ApplyPolicy(userPolicyKey)
.ApplyPolicy(machinePolicyKey),
ProxyPacUrl = RegistryStringSetting.FromKey(
"ProxyPacUrl",
"ProxyPacUrl",
null,
null,
null,
settingsKey,
url => url == null || Uri.TryCreate(url, UriKind.Absolute, out Uri _))
.ApplyPolicy(userPolicyKey)
.ApplyPolicy(machinePolicyKey),
DeviceCertificateSelector = RegistryStringSetting.FromKey(
"DeviceCertificateSelector",
"DeviceCertificateSelector",
null,
null,
SecureConnectEnrollment.DefaultDeviceCertificateSelector,
settingsKey,
selector => selector == null || ChromeCertificateSelector.TryParse(selector, out var _))
.ApplyPolicy(userPolicyKey)
.ApplyPolicy(machinePolicyKey), // TODO: extend ADMX
//
// User preferences. These cannot be overriden by policy.
//
IsMainWindowMaximized = RegistryBoolSetting.FromKey(
"IsMainWindowMaximized",
"IsMainWindowMaximized",
null,
null,
false,
settingsKey),
MainWindowHeight = RegistryDwordSetting.FromKey(
"MainWindowHeight",
"MainWindowHeight",
null,
null,
0,
settingsKey,
0,
ushort.MaxValue),
MainWindowWidth = RegistryDwordSetting.FromKey(
"WindowWidth",
"WindowWidth",
null,
null,
0,
settingsKey,
0,
ushort.MaxValue),
LastUpdateCheck = RegistryQwordSetting.FromKey(
"LastUpdateCheck",
"LastUpdateCheck",
null,
null,
0,
settingsKey,
0,
long.MaxValue),
ProxyUsername = RegistryStringSetting.FromKey(
"ProxyUsername",
"ProxyUsername",
null,
null,
null,
settingsKey,
_ => true),
ProxyPassword = RegistrySecureStringSetting.FromKey(
"ProxyPassword",
"ProxyPassword",
null,
null,
settingsKey,
DataProtectionScope.CurrentUser),
FullScreenDevices = RegistryStringSetting.FromKey(
"FullScreenDevices",
"FullScreenDevices",
null,
null,
null,
settingsKey,
_ => true),
IncludeOperatingSystems = RegistryEnumSetting<OperatingSystems>.FromKey(
"IncludeOperatingSystems",
"IncludeOperatingSystems",
null,
null,
OperatingSystems.Windows | OperatingSystems.Linux,
settingsKey)
};
}
}
}
| 38.861004 | 112 | 0.539096 | [
"Apache-2.0"
] | bluPhy/iap-desktop | sources/Google.Solutions.IapDesktop.Application/Services/Settings/ApplicationSettingsRepository.cs | 10,067 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
namespace Contoso.Branding.CustomCSSWeb
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
}
}
} | 21.375 | 68 | 0.719298 | [
"Apache-2.0"
] | AKrasheninnikov/PnP | Samples/Branding.CustomCSS/Branding.CustomCSSWeb/Global.asax.cs | 344 | C# |
using System;
namespace Open_Lab_04._01
{
class Program
{
public static bool DoubleLetters(string str)
{
for (var i = 0; i < str.Length -1; i++)
{
if (str[i] == str[i + 1])
{
return true;
}
}
return false;
}
static void Main(string[] args)
{
string enter = Console.ReadLine();
Console.WriteLine(DoubleLetters(enter));
}
}
}
| 19.555556 | 52 | 0.416667 | [
"MIT"
] | matejslovak/Open-Lab-04.01 | Open-Lab-04.01/Program.cs | 530 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Machine.UrlStrong.Translation.Model;
namespace Machine.UrlStrong.Translation.Parsing
{
public class ParseResultBuilder : IParseListener
{
int _currentLineNumber;
string _currentLine;
string _namespace = "";
string _className = "Urls";
List<ParsedUrl> _urls = new List<ParsedUrl>();
List<string> _namespaces = new List<string>();
List<ParseError> _errors = new List<ParseError>();
public void BeginLine(int lineNumber, string line)
{
_currentLine = line;
_currentLineNumber = lineNumber;
}
public void AddError(string error)
{
var parseError = new ParseError(_currentLineNumber, _currentLine, error);
_errors.Add(parseError);
}
public void OnUrl(IEnumerable<string> verbs, string url, string hash, string comment)
{
var parsedVerbs = ParseVerbs(verbs);
var parsedUrlParts = ParseUrl(url);
_urls.Add(new ParsedUrl(parsedVerbs, parsedUrlParts, hash, comment));
}
static IEnumerable<ParsedUrlPart> ParseUrl(string url)
{
List<ParsedUrlPart> parts = new List<ParsedUrlPart>();
foreach (var part in url.Split(new [] {'/'}, StringSplitOptions.RemoveEmptyEntries))
{
parts.Add(new ParsedUrlPart(part));
}
return parts;
}
IEnumerable<HttpVerbs> ParseVerbs(IEnumerable<string> verbs)
{
if (verbs.Contains("*"))
{
return Enum.GetValues(typeof(HttpVerbs)).Cast<HttpVerbs>();
}
List<HttpVerbs> parsedVerbs = new List<HttpVerbs>();
foreach (var verb in verbs)
{
try
{
HttpVerbs parsedVerb = (HttpVerbs)Enum.Parse(typeof(HttpVerbs), verb, true);
parsedVerbs.Add(parsedVerb);
}
catch (ArgumentException)
{
AddError(String.Format("Unknown verb: {0}, try one of these: {1}", verb,
String.Join(", ", Enum.GetNames(typeof(HttpVerbs)).Select(x => x.ToUpper()).ToArray())));
}
}
return parsedVerbs;
}
public void OnUsingNamespace(string @namespace)
{
_namespaces.Add(@namespace);
}
public void OnNamespace(string value)
{
if (!String.IsNullOrEmpty(_namespace))
{
throw new Exception("You can only have one namespace per url file.");
}
_namespace = value;
}
public void OnClassName(string value)
{
if (!String.IsNullOrEmpty(_className))
{
throw new Exception("You can only have one class per url file.");
}
_namespace = value;
}
public ParseResult GetResult()
{
var urlConfig = new UrlStrongModel(_urls, _namespaces, _namespace, _className);
return new ParseResult(urlConfig, _errors);
}
}
public class ParseError
{
readonly int _lineNumber;
readonly string _line;
readonly string _error;
public ParseError(int lineNumber, string line, string error)
{
_lineNumber = lineNumber;
_line = line;
_error = error;
}
}
}
| 26.409836 | 102 | 0.612973 | [
"MIT"
] | machine/machine.urlstrong | Source/Machine.UrlStrong.Translation/Parsing/ParseResultBuilder.cs | 3,224 | C# |
// Copyright © 2017 - 2018 Chocolatey Software, Inc
// Copyright © 2011 - 2017 RealDimensions Software, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace chocolatey.tests.integration.scenarios
{
using System.Collections.Generic;
using System.Linq;
using bdddoc.core;
using chocolatey.infrastructure.app;
using chocolatey.infrastructure.app.commands;
using chocolatey.infrastructure.app.configuration;
using chocolatey.infrastructure.app.services;
using chocolatey.infrastructure.results;
using NuGet;
using Should;
public class ListScenarios
{
public abstract class ScenariosBase : TinySpec
{
protected IList<PackageResult> Results;
protected ChocolateyConfiguration Configuration;
protected IChocolateyPackageService Service;
public override void Context()
{
Configuration = Scenario.list();
Scenario.reset(Configuration);
Scenario.add_packages_to_source_location(Configuration, Configuration.Input + "*" + Constants.PackageExtension);
Scenario.add_packages_to_source_location(Configuration, "installpackage*" + Constants.PackageExtension);
Scenario.install_package(Configuration, "installpackage", "1.0.0");
Scenario.install_package(Configuration, "upgradepackage", "1.0.0");
Service = NUnitSetup.Container.GetInstance<IChocolateyPackageService>();
}
}
[Concern(typeof(ChocolateyListCommand))]
public class when_searching_packages_with_no_filter_happy_path : ScenariosBase
{
public override void Because()
{
MockLogger.reset();
Results = Service.list_run(Configuration).ToList();
}
[Fact]
public void should_list_available_packages_only_once()
{
MockLogger.contains_message_count("upgradepackage").ShouldEqual(1);
}
[Fact]
public void should_contain_packages_and_versions_with_a_space_between_them()
{
MockLogger.contains_message("upgradepackage 1.1.0").ShouldBeTrue();
}
[Fact]
public void should_not_contain_packages_and_versions_with_a_pipe_between_them()
{
MockLogger.contains_message("upgradepackage|1.1.0").ShouldBeFalse();
}
[Fact]
public void should_contain_a_summary()
{
MockLogger.contains_message("packages found").ShouldBeTrue();
}
[Fact]
public void should_contain_debugging_messages()
{
MockLogger.contains_message("Searching for package information", LogLevel.Debug).ShouldBeTrue();
MockLogger.contains_message("Running list with the following filter", LogLevel.Debug).ShouldBeTrue();
MockLogger.contains_message("Start of List", LogLevel.Debug).ShouldBeTrue();
MockLogger.contains_message("End of List", LogLevel.Debug).ShouldBeTrue();
}
}
[Concern(typeof(ChocolateyListCommand))]
public class when_searching_for_a_particular_package : ScenariosBase
{
public override void Context()
{
base.Context();
Configuration.Input = Configuration.PackageNames = "upgradepackage";
}
public override void Because()
{
MockLogger.reset();
Results = Service.list_run(Configuration).ToList();
}
[Fact]
public void should_contain_packages_and_versions_with_a_space_between_them()
{
MockLogger.contains_message("upgradepackage 1.1.0").ShouldBeTrue();
}
[Fact]
public void should_not_contain_packages_that_do_not_match()
{
MockLogger.contains_message("installpackage").ShouldBeFalse();
}
[Fact]
public void should_contain_a_summary()
{
MockLogger.contains_message("packages found").ShouldBeTrue();
}
[Fact]
public void should_contain_debugging_messages()
{
MockLogger.contains_message("Searching for package information", LogLevel.Debug).ShouldBeTrue();
MockLogger.contains_message("Running list with the following filter", LogLevel.Debug).ShouldBeTrue();
MockLogger.contains_message("Start of List", LogLevel.Debug).ShouldBeTrue();
MockLogger.contains_message("End of List", LogLevel.Debug).ShouldBeTrue();
}
}
[Concern(typeof(ChocolateyListCommand))]
public class when_searching_all_available_packages : ScenariosBase
{
public override void Context()
{
base.Context();
Configuration.AllVersions = true;
}
public override void Because()
{
MockLogger.reset();
Results = Service.list_run(Configuration).ToList();
}
[Fact]
public void should_list_available_packages_as_many_times_as_they_show_on_the_feed()
{
MockLogger.contains_message_count("upgradepackage").ShouldNotEqual(0);
MockLogger.contains_message_count("upgradepackage").ShouldNotEqual(1);
}
[Fact]
public void should_contain_packages_and_versions_with_a_space_between_them()
{
MockLogger.contains_message("upgradepackage 1.1.0").ShouldBeTrue();
}
[Fact]
public void should_not_contain_packages_and_versions_with_a_pipe_between_them()
{
MockLogger.contains_message("upgradepackage|1.1.0").ShouldBeFalse();
}
[Fact]
public void should_contain_a_summary()
{
MockLogger.contains_message("packages found").ShouldBeTrue();
}
[Fact]
public void should_contain_debugging_messages()
{
MockLogger.contains_message("Searching for package information", LogLevel.Debug).ShouldBeTrue();
MockLogger.contains_message("Running list with the following filter", LogLevel.Debug).ShouldBeTrue();
MockLogger.contains_message("Start of List", LogLevel.Debug).ShouldBeTrue();
MockLogger.contains_message("End of List", LogLevel.Debug).ShouldBeTrue();
}
}
[Concern(typeof(ChocolateyListCommand))]
public class when_searching_packages_with_verbose : ScenariosBase
{
public override void Context()
{
base.Context();
Configuration.Verbose = true;
}
public override void Because()
{
MockLogger.reset();
Results = Service.list_run(Configuration).ToList();
}
[Fact]
public void should_contain_packages_and_versions_with_a_space_between_them()
{
MockLogger.contains_message("upgradepackage 1.1.0").ShouldBeTrue();
}
[Fact]
public void should_contain_description()
{
MockLogger.contains_message("Description: ").ShouldBeTrue();
}
[Fact]
public void should_contain_tags()
{
MockLogger.contains_message("Tags: ").ShouldBeTrue();
}
[Fact]
public void should_contain_download_counts()
{
MockLogger.contains_message("Number of Downloads: ").ShouldBeTrue();
}
[Fact]
public void should_not_contain_packages_and_versions_with_a_pipe_between_them()
{
MockLogger.contains_message("upgradepackage|1.1.0").ShouldBeFalse();
}
[Fact]
public void should_contain_a_summary()
{
MockLogger.contains_message("packages found").ShouldBeTrue();
}
[Fact]
public void should_contain_debugging_messages()
{
MockLogger.contains_message("Searching for package information", LogLevel.Debug).ShouldBeTrue();
MockLogger.contains_message("Running list with the following filter", LogLevel.Debug).ShouldBeTrue();
MockLogger.contains_message("Start of List", LogLevel.Debug).ShouldBeTrue();
MockLogger.contains_message("End of List", LogLevel.Debug).ShouldBeTrue();
}
}
[Concern(typeof(ChocolateyListCommand))]
public class when_listing_local_packages : ScenariosBase
{
public override void Context()
{
base.Context();
Configuration.ListCommand.LocalOnly = true;
Configuration.Sources = ApplicationParameters.PackagesLocation;
}
public override void Because()
{
MockLogger.reset();
Results = Service.list_run(Configuration).ToList();
}
[Fact]
public void should_contain_packages_and_versions_with_a_space_between_them()
{
MockLogger.contains_message("upgradepackage 1.0.0").ShouldBeTrue();
}
[Fact]
public void should_not_contain_packages_and_versions_with_a_pipe_between_them()
{
MockLogger.contains_message("upgradepackage|1.0.0").ShouldBeFalse();
}
[Fact]
public void should_contain_a_summary()
{
MockLogger.contains_message("packages installed").ShouldBeTrue();
}
[Fact]
public void should_contain_debugging_messages()
{
MockLogger.contains_message("Searching for package information", LogLevel.Debug).ShouldBeTrue();
MockLogger.contains_message("Running list with the following filter", LogLevel.Debug).ShouldBeTrue();
MockLogger.contains_message("Start of List", LogLevel.Debug).ShouldBeTrue();
MockLogger.contains_message("End of List", LogLevel.Debug).ShouldBeTrue();
}
}
[Concern(typeof(ChocolateyListCommand))]
public class when_listing_local_packages_with_id_only : ScenariosBase
{
public override void Context()
{
base.Context();
Configuration.ListCommand.LocalOnly = true;
Configuration.ListCommand.IdOnly = true;
Configuration.Sources = ApplicationParameters.PackagesLocation;
}
public override void Because()
{
MockLogger.reset();
Results = Service.list_run(Configuration).ToList();
}
[Fact]
public void should_contain_package_name()
{
MockLogger.contains_message("upgradepackage").ShouldBeTrue();
}
[Fact]
public void should_not_contain_any_version_number()
{
MockLogger.contains_message(".0").ShouldBeFalse();
}
}
[Concern(typeof(ChocolateyListCommand))]
public class when_listing_local_packages_limiting_output : ScenariosBase
{
public override void Context()
{
base.Context();
Configuration.ListCommand.LocalOnly = true;
Configuration.Sources = ApplicationParameters.PackagesLocation;
Configuration.RegularOutput = false;
}
public override void Because()
{
MockLogger.reset();
Results = Service.list_run(Configuration).ToList();
}
[Fact]
public void should_contain_packages_and_versions_with_a_pipe_between_them()
{
MockLogger.contains_message("upgradepackage|1.0.0").ShouldBeTrue();
}
[Fact]
public void should_only_have_messages_related_to_package_information()
{
var count = MockLogger.Messages.SelectMany(messageLevel => messageLevel.Value.or_empty_list_if_null()).Count();
count.ShouldEqual(2);
}
[Fact]
public void should_not_contain_packages_and_versions_with_a_space_between_them()
{
MockLogger.contains_message("upgradepackage 1.0.0").ShouldBeFalse();
}
[Fact]
public void should_not_contain_a_summary()
{
MockLogger.contains_message("packages installed").ShouldBeFalse();
}
[Fact]
public void should_not_contain_debugging_messages()
{
MockLogger.contains_message("Searching for package information", LogLevel.Debug).ShouldBeFalse();
MockLogger.contains_message("Running list with the following filter", LogLevel.Debug).ShouldBeFalse();
MockLogger.contains_message("Start of List", LogLevel.Debug).ShouldBeFalse();
MockLogger.contains_message("End of List", LogLevel.Debug).ShouldBeFalse();
}
}
[Concern(typeof(ChocolateyListCommand))]
public class when_listing_local_packages_limiting_output_with_id_only : ScenariosBase
{
public override void Context()
{
base.Context();
Configuration.ListCommand.LocalOnly = true;
Configuration.ListCommand.IdOnly = true;
Configuration.Sources = ApplicationParameters.PackagesLocation;
Configuration.RegularOutput = false;
}
public override void Because()
{
MockLogger.reset();
Results = Service.list_run(Configuration).ToList();
}
[Fact]
public void should_contain_packages_id()
{
MockLogger.contains_message("upgradepackage").ShouldBeTrue();
}
[Fact]
public void should_not_contain_any_version_number()
{
MockLogger.contains_message(".0").ShouldBeFalse();
}
[Fact]
public void should_not_contain_pipe()
{
MockLogger.contains_message("|").ShouldBeFalse();
}
}
[Concern(typeof(ChocolateyListCommand))]
public class when_listing_packages_with_no_sources_enabled : ScenariosBase
{
public override void Context()
{
base.Context();
Configuration.Sources = null;
}
public override void Because()
{
MockLogger.reset();
Results = Service.list_run(Configuration).ToList();
}
[Fact]
public void should_have_no_sources_enabled_result()
{
MockLogger.contains_message("Unable to search for packages when there are no sources enabled for", LogLevel.Error).ShouldBeTrue();
}
[Fact]
public void should_not_list_any_packages()
{
Results.Count().ShouldEqual(0);
}
}
[Concern(typeof(ChocolateyListCommand))]
public class when_searching_for_an_exact_package : ScenariosBase
{
public override void Context()
{
Configuration = Scenario.list();
Scenario.reset(Configuration);
Scenario.add_packages_to_source_location(Configuration, "exactpackage*" + Constants.PackageExtension);
Service = NUnitSetup.Container.GetInstance<IChocolateyPackageService>();
Configuration.ListCommand.Exact = true;
Configuration.Input = Configuration.PackageNames = "exactpackage";
}
public override void Because()
{
MockLogger.reset();
Results = Service.list_run(Configuration).ToList();
}
[Fact]
public void should_contain_packages_and_versions_with_a_space_between_them()
{
MockLogger.contains_message("exactpackage 1.0.0").ShouldBeTrue();
}
[Fact]
public void should_not_contain_packages_that_do_not_match()
{
MockLogger.contains_message("exactpackage.dontfind").ShouldBeFalse();
}
[Fact]
public void should_contain_a_summary()
{
MockLogger.contains_message("packages found").ShouldBeTrue();
}
[Fact]
public void should_contain_debugging_messages()
{
MockLogger.contains_message("Searching for package information", LogLevel.Debug).ShouldBeTrue();
MockLogger.contains_message("Running list with the following filter", LogLevel.Debug).ShouldBeTrue();
MockLogger.contains_message("Start of List", LogLevel.Debug).ShouldBeTrue();
MockLogger.contains_message("End of List", LogLevel.Debug).ShouldBeTrue();
}
}
}
}
| 38.297959 | 147 | 0.569807 | [
"Apache-2.0"
] | FranklinYu/choco | src/chocolatey.tests.integration/scenarios/ListScenarios.cs | 18,770 | C# |
using AutoMapper;
using HC.WeChat.QuestionOptions;
using HC.WeChat.QuestionOptions.Dtos;
namespace HC.WeChat.QuestionOptions.Mapper
{
/// <summary>
/// 配置QuestionOption的AutoMapper
/// </summary>
internal static class QuestionOptionMapper
{
public static void CreateMappings(IMapperConfigurationExpression configuration)
{
configuration.CreateMap <QuestionOption,QuestionOptionListDto>();
configuration.CreateMap <QuestionOptionListDto,QuestionOption>();
configuration.CreateMap <QuestionOptionEditDto,QuestionOption>();
configuration.CreateMap <QuestionOption,QuestionOptionEditDto>();
}
}
}
| 27.36 | 87 | 0.722222 | [
"MIT"
] | DonaldTdz/GAWeChat | aspnet-core/src/HC.WeChat.Application/QuestionOptions/Mapper/QuestionOptionMapper.cs | 690 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using RestAPIWithASPNET.Business;
using RestAPIWithASPNET.Business.Implementations;
using RestAPIWithASPNET.Model.Context;
using RestAPIWithASPNET.Repository.Implementations;
using RestAPIWithASPNET.Repository.Implementations.Generic;
using Serilog;
using System;
using System.Collections.Generic;
namespace RestAPIWithASPNET
{
public class Startup
{
public IWebHostEnvironment Environment { get; }
public Startup(IConfiguration configuration, IWebHostEnvironment environment)
{
Environment = environment;
Configuration = configuration;
Log.Logger = new LoggerConfiguration()
.WriteTo
.Console()
.CreateLogger();
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var connection = Configuration["MySQLConnection:MySQLConnectionString"];
if(Environment.IsDevelopment())
{
MigrateDatabase(connection);
}
services.AddControllers();
services.AddApiVersioning()
;
services.AddDbContext<MySQLContext>(options => options.UseMySql(connection));
services.AddScoped<IPersonBusiness, PersonBusinessImpl>();
services.AddScoped<IBookBusiness, BookBusinessImpl>();
services.AddScoped(typeof(IRepository<>), typeof(GenericRepository<>));
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "RestAPIWithASPNET", Version = "v1" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "RestAPIWithASPNET v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
private void MigrateDatabase(string connection)
{
try
{
var evolveConnection = new MySql.Data.MySqlClient.MySqlConnection(connection);
var evolve = new Evolve.Evolve(evolveConnection, msg => Log.Information(msg))
{
Locations = new List<string> { "db/migrations", "db/dataset" },
IsEraseDisabled = true
};
evolve.Migrate();
}
catch (Exception ex)
{
Log.Error("Database migration failed", ex);
throw;
}
}
}
}
| 31.962264 | 109 | 0.603011 | [
"Apache-2.0"
] | murillo120/RestAPIWithASPNET | RestAPIWithASPNET/RestAPIWithASPNET/Startup.cs | 3,388 | C# |
// Copyright (c) 2018 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
// Licensed under MIT licence. See License.txt in the project root for license information.
using AutoMapper;
using GenericBizRunner;
using Microsoft.EntityFrameworkCore;
using TestBizLayer.BizDTOs;
namespace Tests.DTOs
{
public class ServiceLayerBizOutDto : GenericActionFromBizDto<BizDataOut, ServiceLayerBizOutDto>
{
public string Output { get; set; }
public bool SetupSecondaryOutputDataCalled { get; private set; }
public bool CopyFromBizDataCalled { get; private set; }
protected internal override void SetupSecondaryOutputData(DbContext db)
{
SetupSecondaryOutputDataCalled = true;
base.SetupSecondaryOutputData(db);
}
protected internal override ServiceLayerBizOutDto CopyFromBizData(DbContext db, IMapper mapper,
BizDataOut source)
{
var result = base.CopyFromBizData(db, mapper, source);
result.CopyFromBizDataCalled = true;
return result;
}
}
} | 34.8125 | 103 | 0.697487 | [
"MIT"
] | Anapher/EfCore.GenericBizRunner | Tests/DTOs/ServiceLayerBizOutDto.cs | 1,116 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/Audioclient.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
using static TerraFX.Interop.Windows;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="IAudioAmbisonicsControl" /> struct.</summary>
public static unsafe partial class IAudioAmbisonicsControlTests
{
/// <summary>Validates that the <see cref="Guid" /> of the <see cref="IAudioAmbisonicsControl" /> struct is correct.</summary>
[Test]
public static void GuidOfTest()
{
Assert.That(typeof(IAudioAmbisonicsControl).GUID, Is.EqualTo(IID_IAudioAmbisonicsControl));
}
/// <summary>Validates that the <see cref="IAudioAmbisonicsControl" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<IAudioAmbisonicsControl>(), Is.EqualTo(sizeof(IAudioAmbisonicsControl)));
}
/// <summary>Validates that the <see cref="IAudioAmbisonicsControl" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(IAudioAmbisonicsControl).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="IAudioAmbisonicsControl" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(IAudioAmbisonicsControl), Is.EqualTo(8));
}
else
{
Assert.That(sizeof(IAudioAmbisonicsControl), Is.EqualTo(4));
}
}
}
}
| 38.826923 | 145 | 0.653294 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | tests/Interop/Windows/um/Audioclient/IAudioAmbisonicsControlTests.cs | 2,021 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace SoccerDataBinding.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
[global::System.Configuration.DefaultSettingValueAttribute("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Labuser18\\Desktop\\me" +
"\\SoccerDataBinding\\SoccerDataBinding\\SoccerPlayers.mdf;Integrated Security=True")]
public string ConnectionStrings {
get {
return ((string)(this["ConnectionStrings"]));
}
}
}
}
| 46.105263 | 157 | 0.626142 | [
"Unlicense"
] | gkhachatryan/WPF_XAML_Examples | SoccerDataBinding/SoccerDataBinding/Properties/Settings.Designer.cs | 1,754 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoFixture.NUnit3;
using FluentAssertions;
using Moq;
using NUnit.Framework;
using SFA.DAS.EmployerDemand.Application.CourseDemand.Services;
using SFA.DAS.EmployerDemand.Domain.Interfaces;
using SFA.DAS.Testing.AutoFixture;
namespace SFA.DAS.EmployerDemand.Application.UnitTests.CourseDemand.Services
{
public class WhenGettingEmployerDemandsThatHaveNotBeenMet
{
[Test, RecursiveMoqAutoData]
public async Task Then_The_Repository_Is_Called_And_Demands_Not_Met_After_Inputted_Days_Returned(
uint ageOfDemand,
List<Domain.Entities.CourseDemand> demands,
[Frozen] Mock<ICourseDemandRepository> repository,
CourseDemandService service)
{
//Arrange
repository
.Setup(x => x.GetCourseDemandsWithNoProviderInterest(ageOfDemand))
.ReturnsAsync(demands);
//Act
var actual = await service.GetUnmetEmployerDemands(ageOfDemand);
//Assert
actual.Should().BeEquivalentTo(demands.Select(c=>(Domain.Models.CourseDemand)c).ToList());
}
}
} | 35.285714 | 105 | 0.691498 | [
"MIT"
] | SkillsFundingAgency/das-employerdemand-api | src/SFA.DAS.EmployerDemand.Application.UnitTests/CourseDemand/Services/WhenGettingEmployerDemandsThatHaveNotBeenMet.cs | 1,235 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OPA.Statistics
{
/// <summary>
/// Analysis of Covariance
/// The implementation is based on ANCOVA tutorial at http://vassarstats.net/textbook/ch17pt1.html
///
/// For a regression model (x_i, y_i):
/// y_i = grand_mean_y + group_effect_j + beta * (x_i - mean_x_ij) + epsilon,
/// where
/// i is the sample index,
/// j is the group index,
/// epsilon ~ N(0, sigma^2)
/// grand_mean_y is the mean of y_i, for all i
/// mean_x_ij is the mean of x_i, for i belonging to group j
///
/// We can then write:
/// y_i - beta * (x_i - mean_x_ij) = grand_mean_y + group_effect_j + epsilon
/// If we let: Y_i = y_i - beta * (x_i - mean_x_ij)
/// Then we have a ANOVA: Y_i = grand_mean_y + group_effect_j + epsilon
/// </summary>
public class ANCOVA
{
public double SSTy; //sum of squares total for y
public double SSTx; //sum of squares total for x
public double SSBGy; //sum of squares between groups for y
public double SSBGx; //sum of squares between groups for x
public double SSWGy; //sum of squares within group for y
public double SSWGx; // sum of squares within group for x
public double SCT; //covariance total between x and y
public double SCWG; //sum of coveriance within groups between x and y
public double rT; //correlation total between x and y
public double rWG; //correlation within group between x and y
public double SSTy_adj; //adjusted SSTy with the effect of x removed : SST(y - b * x)
public double SSWGy_adj; //adjusted SSWGy with the effect of x removed : SSWG(y - b * x)
public double SSBGy_adj; //adjusted SSBGy with the effect of x removed : SSBG(y - b * x)
public int dfT; //total degree of freedom
public int dfBG; // between group degree of freedom;
public int dfWG; // within group degree of freedom
public double MSBGy_adj; //mean of squares between group for adjusted
public double MSWGy_adj; //mean of squares within group for adjusted
public Dictionary<int, double> MeanWithinGroups_x = new Dictionary<int, double>(); //the mean x within each group
public Dictionary<int, double> MeanWithinGroups_y = new Dictionary<int, double>(); //the mean y within each group
/// <summary>
/// The values of the intercept in each regression model
/// y = b * x + intercept[j], where j is the group id
/// </summary>
public Dictionary<int, double> Intercepts = new Dictionary<int, double>();
/// <summary>
/// The values of the slope, b, in each regression model
/// y = b * x + intercept[j], where j is the group id
/// </summary>
public double Slope;
public double F; // the F critic value, which is = SSBGy_adj / SSWGy_adj (i.e. the F critic for y - b * x
public bool RejectH0; //H_0 : y - b * x is independent of group category
public double pValue; // p-value = P(observation for y-b*x deviates between groups | H_0 is true) where H_0 : y - b * x is independent of group category
public string Summary
{
get
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("Means Within Group:");
sb.AppendLine("X\tY\tGroupId");
foreach (int groupId in MeanWithinGroups_x.Keys)
{
double mean_x = MeanWithinGroups_x[groupId];
double mean_y = MeanWithinGroups_y[groupId];
sb.AppendFormat("{0:0.00}\t{1:0.00}\t{2}\r\n", mean_x, mean_y, groupId);
}
sb.AppendLine();
sb.AppendLine("Y:");
sb.AppendFormat("SST(y) = {0:0.00}\r\n", SSTy);
sb.AppendFormat("SSwg(y) = {0:0.00}\r\n", SSWGy);
sb.AppendFormat("SSbg(y) = {0:0.00}\r\n", SSBGy);
sb.AppendLine();
sb.AppendLine("X:");
sb.AppendFormat("SST(x) = {0:0.00}\r\n", SSTx);
sb.AppendFormat("SSwg(x) = {0:0.00}\r\n", SSWGx);
sb.AppendLine();
sb.AppendLine("Convariance:");
sb.AppendFormat("SCT = {0:0.00}\r\n", SCT);
sb.AppendFormat("SCwg = {0:0.00}\r\n", SCWG);
sb.AppendLine();
sb.AppendLine("Correlation:");
sb.AppendFormat("r_T = {0:0.00}\r\n", rT);
sb.AppendFormat("r_wg = {0:0.00}\r\n", rWG);
sb.AppendLine();
sb.AppendLine("y_adj = y - b * x");
sb.AppendLine();
sb.AppendLine("Y_adj:");
sb.AppendFormat("SST(y_adj) = {0:0.00}\r\n", SSTy_adj);
sb.AppendFormat("SSwg(y_adj) = {0:0.00}\r\n", SSWGy_adj);
sb.AppendFormat("SSbg(y_adj) = {0:0.00}\r\n", SSBGy_adj);
sb.AppendLine();
sb.AppendLine("Regression Model");
sb.AppendLine("Intercept(GroupId)\tSlope\tGroupId");
foreach (int groupId in Intercepts.Keys)
{
sb.AppendFormat("{0:0.00}\t\t\t{1:0.00}\t{2}\r\n", Intercepts[groupId], Slope, groupId);
}
sb.AppendLine();
sb.AppendLine("ANOVA on y_adj:");
sb.AppendFormat("df_bg = {0:0.00}\r\n", dfBG);
sb.AppendFormat("df_wg = {0:0.00}\r\n", dfWG);
sb.AppendFormat("MS_bg(y_adj) = {0:0.00}\r\n", MSBGy_adj);
sb.AppendFormat("MS_wg(y_adj) = {0:0.00}\r\n", MSWGy_adj);
sb.AppendFormat("F_crit = {0:0.00}\r\n", F);
sb.AppendFormat("p-value = {0:0.00}\r\n", pValue);
sb.AppendFormat("Reject H_0: {0} => {1}", RejectH0, RejectH0 ? "y_adj does have group effect" : "y_adj does not have group effect");
return sb.ToString();
}
}
/// <summary>
/// Suppose the regression is given by y = b * x + intercept[j], where j is the group id (in other words, b is the fixed effect, intercept is the random effect)
/// Run the ANCOVA which calculates the following:
/// 1. the slope, b, of y = b * x + intercept[j]
/// 2. the intercept, of y = b * x + intercept[j]
/// </summary>
/// <param name="x">data for the predictor variable</param>
/// <param name="y">data for the response variable</param>
/// <param name="grpCat">group id for each (x, y)</param>
/// <param name="output">the result of ANCOVA</param>
/// <param name="significance_level">alpha for the hypothesis testing, in which H_0 : y - b * x is independent of group category</param>
public static void RunANCOVA(double[] x, double[] y, int[] grpCat, out ANCOVA output, double significance_level = 0.05)
{
output = new ANCOVA();
Dictionary<int, List<double>> groupped_x = new Dictionary<int, List<double>>();
Dictionary<int, List<double>> groupped_y = new Dictionary<int, List<double>>();
int N = x.Length;
for (int i = 0; i < N; ++i)
{
int grpId = grpCat[i];
double xVal = x[i];
double yVal = y[i];
List<double> group_x = null;
List<double> group_y = null;
if (groupped_x.ContainsKey(grpId))
{
group_x = groupped_x[grpId];
}
else
{
group_x = new List<double>();
groupped_x[grpId] = group_x;
}
if (groupped_y.ContainsKey(grpId))
{
group_y = groupped_y[grpId];
}
else
{
group_y = new List<double>();
groupped_y[grpId] = group_y;
}
group_x.Add(xVal);
group_y.Add(yVal);
}
double grand_mean_x;
double grand_mean_y;
output.SSTx = GetSST(x, out grand_mean_x);
output.SSTy = GetSST(y, out grand_mean_y);
output.SSBGx = GetSSG(groupped_x, grand_mean_x);
output.SSBGy = GetSSG(groupped_y, grand_mean_y);
output.SSWGy = output.SSTy - output.SSBGy;
output.SSWGx = output.SSTx - output.SSBGx;
output.SCT = GetCovariance(x, y);
output.SCWG = GetCovarianceWithinGroup(groupped_x, groupped_y);
output.rT = output.SCT / System.Math.Sqrt(output.SSTx * output.SSTy);
output.rWG = output.SCWG / System.Math.Sqrt(output.SSWGx * output.SSWGy);
output.SSTy_adj = output.SSTy - System.Math.Pow(output.SCT, 2) / output.SSTx;
output.SSWGy_adj = output.SSWGy - System.Math.Pow(output.SCWG, 2) / output.SSWGx;
output.SSBGy_adj = output.SSTy_adj - output.SSWGy_adj;
output.dfT = N - 2;
output.dfBG = groupped_x.Count - 1;
output.dfWG = N - groupped_x.Count - 1;
output.MSBGy_adj = output.SSBGy_adj / output.dfBG;
output.MSWGy_adj = output.SSWGy_adj / output.dfWG;
output.Slope = output.SCWG / output.SSWGx;
output.MeanWithinGroups_x = GetMeanWithinGroup(groupped_x);
output.MeanWithinGroups_y = GetMeanWithinGroup(groupped_y);
output.Intercepts = GetIntercepts(output.MeanWithinGroups_x, output.MeanWithinGroups_y, grand_mean_x, output.Slope);
output.F = output.MSBGy_adj / output.MSWGy_adj;
try
{
output.pValue = 1 - FDistribution.GetPercentile(output.F, output.dfBG, output.dfWG);
}
catch
{
}
output.RejectH0 = output.pValue < significance_level;
}
public static Dictionary<int, double> GetIntercepts(Dictionary<int, double> mean_x_within_group, Dictionary<int, double> mean_y_within_group, double grand_mean_x, double b)
{
Dictionary<int, double> intercepts = new Dictionary<int, double>();
foreach (int grpId in mean_x_within_group.Keys)
{
double mean_x = mean_x_within_group[grpId];
double mean_y = mean_y_within_group[grpId];
intercepts[grpId] = mean_y - b * (mean_x - grand_mean_x);
}
return intercepts;
}
/// <summary>
/// Return the sum of squares total
///
/// SST measures the total variability in the response variable
/// </summary>
/// <param name="totalSample">all the data points in the sample containing all classes</param>
/// <param name="grand_mean">The mean of all the data points in the sample containing all classes</param>
/// <returns>The sum of squares total, which measures p=o--i9i9</returns>
public static double GetSST(double[] totalSample, out double grand_mean)
{
grand_mean = Mean.GetMean(totalSample);
double SST = 0;
int n = totalSample.Length;
for (int i = 0; i < n; ++i)
{
double yd = totalSample[i] - grand_mean;
SST += yd * yd;
}
return SST;
}
/// <summary>
/// Return the sum of squares group (SSG)
///
/// SSG measures the variability between groups
/// This is also known as explained variablity: deviation of group mean from overral mean, weighted by sample size
/// </summary>
/// <param name="groupedSample">The sample groupped based on the classes</param>
/// <returns></returns>
public static double GetSSG(Dictionary<int, List<double>> groupedSample, double grand_mean)
{
double SSG = 0;
foreach (int grpId in groupedSample.Keys)
{
List<double> group = groupedSample[grpId];
double group_mean = Mean.GetMean(group);
double group_size = group.Count;
SSG += group_size * (group_mean - grand_mean) * (group_mean - grand_mean);
}
return SSG;
}
public static double GetCovariance(double[] x, double[] y)
{
double sum_xy = 0;
double sum_x = 0;
double sum_y = 0;
int N = x.Length;
for (int i = 0; i < N; ++i)
{
sum_xy += x[i] * y[i];
sum_x += x[i];
sum_y += y[i];
}
return sum_xy - (sum_x * sum_y) / N;
}
public static double GetCovarianceWithinGroup(Dictionary<int, List<double>> groupped_x, Dictionary<int, List<double>> groupped_y)
{
double SCG = 0;
foreach (int grpId in groupped_x.Keys)
{
List<double> group_x = groupped_x[grpId];
List<double> group_y = groupped_y[grpId];
double SC_grp = GetCovariance(group_x, group_y);
SCG += SC_grp;
}
return SCG;
}
public static double GetCovariance(List<double> x, List<double> y)
{
double sum_xy = 0;
double sum_x = 0;
double sum_y = 0;
int N = x.Count;
for (int i = 0; i < N; ++i)
{
sum_xy += x[i] * y[i];
sum_x += x[i];
sum_y += y[i];
}
return sum_xy - (sum_x * sum_y) / N;
}
public static Dictionary<int, double> GetMeanWithinGroup(Dictionary<int, List<double>> groupSample)
{
Dictionary<int, double> means = new Dictionary<int, double>();
foreach (int grpId in groupSample.Keys)
{
means[grpId] = Mean.GetMean(groupSample[grpId]);
}
return means;
}
}
}
| 40.30791 | 180 | 0.540052 | [
"MIT"
] | chen0040/cs-optimization-physical-algorithms | cs-optimization-physical-algorithms/Statistics/ANCOVA.cs | 14,269 | 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("FlowEngine")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FlowEngine")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[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("a67db8f5-7240-4c50-85c3-b4c7bba60dd5")]
// 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")]
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config")]
| 37.641026 | 84 | 0.746594 | [
"MIT"
] | vincentnacar02/FlowEngine | FlowEngine/Properties/AssemblyInfo.cs | 1,471 | C# |
using dict = System.Collections.Generic.Dictionary<string, string>;
using list = System.Collections.Generic.List<string>;
namespace Plivo.XML
{
public class W : PlivoElement
{
public W(string body, dict parameters)
: base(body, parameters)
{
Nestables = new list() {
"Break",
"Emphasis",
"Phoneme",
"Prosody",
"SayAs",
"Sub"
};
ValidAttributes = new list()
{
"role",
};
addAttributes();
}
}
} | 24.038462 | 67 | 0.4448 | [
"MIT"
] | loki-NK/plivo-dotnet | src/Plivo/XML/W.cs | 625 | C# |
using System;
using System.Threading.Tasks;
namespace EzBus.Core.Middlewares
{
internal class HandleErrorMessageMiddleware : IPreMiddleware
{
private readonly IBroker broker;
private readonly IAddressConfig addressConfig;
private BasicMessage bm;
public HandleErrorMessageMiddleware(IBroker broker, IAddressConfig addressConfig)
{
this.broker = broker ?? throw new ArgumentNullException(nameof(broker));
this.addressConfig = addressConfig ?? throw new ArgumentNullException(nameof(addressConfig));
}
public async Task Invoke(MiddlewareContext context, Func<Task> next)
{
bm = context.BasicMessage;
await next();
}
public async Task OnError(Exception ex)
{
if (bm == null) throw new Exception("Message is null!", ex);
bm.BodyStream.Position = 0;
var level = 0;
while (ex != null)
{
var headerName = $"EzBus.ErrorMessage L{level}";
var value = $"{DateTime.UtcNow}: {ex.Message}";
bm.AddHeader(headerName, value);
ex = ex.InnerException;
level++;
}
await broker.Send(addressConfig.ErrorAddress, bm);
}
}
} | 30.930233 | 105 | 0.585714 | [
"MIT"
] | Zapote/EzBus | EzBus.Core/Middlewares/HandleErrorMessageMiddleware.cs | 1,332 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Web.V20200901
{
public static class GetWebAppPremierAddOnSlot
{
/// <summary>
/// Premier add-on.
/// </summary>
public static Task<GetWebAppPremierAddOnSlotResult> InvokeAsync(GetWebAppPremierAddOnSlotArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetWebAppPremierAddOnSlotResult>("azure-nextgen:web/v20200901:getWebAppPremierAddOnSlot", args ?? new GetWebAppPremierAddOnSlotArgs(), options.WithVersion());
}
public sealed class GetWebAppPremierAddOnSlotArgs : Pulumi.InvokeArgs
{
/// <summary>
/// Name of the app.
/// </summary>
[Input("name", required: true)]
public string Name { get; set; } = null!;
/// <summary>
/// Add-on name.
/// </summary>
[Input("premierAddOnName", required: true)]
public string PremierAddOnName { get; set; } = null!;
/// <summary>
/// Name of the resource group to which the resource belongs.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
/// <summary>
/// Name of the deployment slot. If a slot is not specified, the API will get the named add-on for the production slot.
/// </summary>
[Input("slot", required: true)]
public string Slot { get; set; } = null!;
public GetWebAppPremierAddOnSlotArgs()
{
}
}
[OutputType]
public sealed class GetWebAppPremierAddOnSlotResult
{
/// <summary>
/// Resource Id.
/// </summary>
public readonly string Id;
/// <summary>
/// Kind of resource.
/// </summary>
public readonly string? Kind;
/// <summary>
/// Resource Location.
/// </summary>
public readonly string Location;
/// <summary>
/// Premier add on Marketplace offer.
/// </summary>
public readonly string? MarketplaceOffer;
/// <summary>
/// Premier add on Marketplace publisher.
/// </summary>
public readonly string? MarketplacePublisher;
/// <summary>
/// Resource Name.
/// </summary>
public readonly string Name;
/// <summary>
/// Premier add on Product.
/// </summary>
public readonly string? Product;
/// <summary>
/// Premier add on SKU.
/// </summary>
public readonly string? Sku;
/// <summary>
/// The system metadata relating to this resource.
/// </summary>
public readonly Outputs.SystemDataResponse SystemData;
/// <summary>
/// Resource tags.
/// </summary>
public readonly ImmutableDictionary<string, string>? Tags;
/// <summary>
/// Resource type.
/// </summary>
public readonly string Type;
/// <summary>
/// Premier add on Vendor.
/// </summary>
public readonly string? Vendor;
[OutputConstructor]
private GetWebAppPremierAddOnSlotResult(
string id,
string? kind,
string location,
string? marketplaceOffer,
string? marketplacePublisher,
string name,
string? product,
string? sku,
Outputs.SystemDataResponse systemData,
ImmutableDictionary<string, string>? tags,
string type,
string? vendor)
{
Id = id;
Kind = kind;
Location = location;
MarketplaceOffer = marketplaceOffer;
MarketplacePublisher = marketplacePublisher;
Name = name;
Product = product;
Sku = sku;
SystemData = systemData;
Tags = tags;
Type = type;
Vendor = vendor;
}
}
}
| 29.333333 | 212 | 0.562384 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Web/V20200901/GetWebAppPremierAddOnSlot.cs | 4,312 | C# |
namespace Microsoft.Maui.Controls.Shapes
{
public sealed partial class RoundRectangle : Shape
{
public RoundRectangle() : base()
{
Aspect = Stretch.Fill;
}
public static readonly BindableProperty CornerRadiusProperty =
BindableProperty.Create(nameof(CornerRadius), typeof(CornerRadius), typeof(RoundRectangle), new CornerRadius());
public CornerRadius CornerRadius
{
set { SetValue(CornerRadiusProperty, value); }
get { return (CornerRadius)GetValue(CornerRadiusProperty); }
}
}
} | 26.947368 | 115 | 0.75 | [
"MIT"
] | 10088/maui | src/Controls/src/Core/Shapes/RoundRectangle.cs | 514 | C# |
using System;
using ImgurAPIClient;
namespace ImgurAlbumDownloader {
class Program {
static void Main(string[] args) {
Console.WriteLine("Imgur Album Downloader");
Console.WriteLine("Copyright (c) 2018 Alex Ingram");
Console.WriteLine("");
if (args.Length == 0) {
Console.WriteLine("Usage: ImgurAlbumDownloader.exe url1 [url2 url3 ...]");
Environment.Exit(0);
}
ImgurClient Client = new ImgurClient("6b33eb78c24c603");
foreach (string s in args) {
Client.Download(s);
}
}
}
}
| 21.791667 | 78 | 0.674952 | [
"MIT"
] | ReimuHakurei/ImgurAlbumDownloader | Program.cs | 525 | C# |
#nullable enable
using System;
using Microsoft.Maui.Graphics;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Shapes;
using WDoubleCollection = Microsoft.UI.Xaml.Media.DoubleCollection;
using WPenLineCap = Microsoft.UI.Xaml.Media.PenLineCap;
using WPenLineJoin = Microsoft.UI.Xaml.Media.PenLineJoin;
namespace Microsoft.Maui.Handlers
{
public class ContentPanel : Panel
{
internal Func<double, double, Size>? CrossPlatformMeasure { get; set; }
internal Func<Graphics.Rectangle, Size>? CrossPlatformArrange { get; set; }
protected override Windows.Foundation.Size MeasureOverride(Windows.Foundation.Size availableSize)
{
if (CrossPlatformMeasure == null)
{
return base.MeasureOverride(availableSize);
}
var measure = CrossPlatformMeasure(availableSize.Width, availableSize.Height);
return measure.ToNative();
}
protected override Windows.Foundation.Size ArrangeOverride(Windows.Foundation.Size finalSize)
{
if (CrossPlatformArrange == null)
{
return base.ArrangeOverride(finalSize);
}
var width = finalSize.Width;
var height = finalSize.Height;
var actual = CrossPlatformArrange(new Graphics.Rectangle(0, 0, width, height));
return new Windows.Foundation.Size(actual.Width, actual.Height);
}
public ContentPanel()
{
_borderPath = new Path();
EnsureBorderPath();
SizeChanged += ContentPanelSizeChanged;
}
private void ContentPanelSizeChanged(object sender, UI.Xaml.SizeChangedEventArgs e)
{
UpdatePath();
}
internal void EnsureBorderPath()
{
if (!Children.Contains(_borderPath))
{
Children.Add(_borderPath);
}
}
readonly Path? _borderPath;
IShape? _borderShape;
public void UpdateBackground(Paint? background)
{
if (_borderPath == null)
return;
_borderPath.Fill = background?.ToNative();
_borderPath.Visibility = background != null ? UI.Xaml.Visibility.Visible : UI.Xaml.Visibility.Collapsed;
}
public void UpdateStroke(Paint borderBrush)
{
if (_borderPath == null)
return;
_borderPath.Stroke = borderBrush.ToNative();
}
public void UpdateStrokeThickness(double borderWidth)
{
if (_borderPath == null)
return;
_borderPath.StrokeThickness = borderWidth;
}
public void UpdateStrokeDashPattern(float[]? borderDashArray)
{
if (_borderPath == null)
return;
if (_borderPath.StrokeDashArray != null)
_borderPath.StrokeDashArray.Clear();
if (borderDashArray != null && borderDashArray.Length > 0)
{
if (_borderPath.StrokeDashArray == null)
_borderPath.StrokeDashArray = new WDoubleCollection();
double[] array = new double[borderDashArray.Length];
borderDashArray.CopyTo(array, 0);
foreach (double value in array)
{
_borderPath.StrokeDashArray.Add(value);
}
}
}
public void UpdateBorderShape(IShape borderShape)
{
_borderShape = borderShape;
UpdatePath();
}
public void UpdateBorderDashOffset(double borderDashOffset)
{
if (_borderPath == null)
return;
_borderPath.StrokeDashOffset = borderDashOffset;
}
public void UpdateStrokeMiterLimit(double strokeMiterLimit)
{
if (_borderPath == null)
return;
_borderPath.StrokeMiterLimit = strokeMiterLimit;
}
public void UpdateStrokeLineCap(LineCap strokeLineCap)
{
if (_borderPath == null)
return;
WPenLineCap wLineCap = WPenLineCap.Flat;
switch (strokeLineCap)
{
case LineCap.Butt:
wLineCap = WPenLineCap.Flat;
break;
case LineCap.Square:
wLineCap = WPenLineCap.Square;
break;
case LineCap.Round:
wLineCap = WPenLineCap.Round;
break;
}
_borderPath.StrokeStartLineCap = _borderPath.StrokeEndLineCap = wLineCap;
}
public void UpdateStrokeLineJoin(LineJoin strokeLineJoin)
{
if (_borderPath == null)
return;
WPenLineJoin wLineJoin = WPenLineJoin.Miter;
switch (strokeLineJoin)
{
case LineJoin.Miter:
wLineJoin = WPenLineJoin.Miter;
break;
case LineJoin.Bevel:
wLineJoin = WPenLineJoin.Bevel;
break;
case LineJoin.Round:
wLineJoin = WPenLineJoin.Round;
break;
}
_borderPath.StrokeLineJoin = wLineJoin;
}
void UpdatePath()
{
if (_borderShape == null)
return;
var strokeThickness = _borderPath?.StrokeThickness ?? 0;
var width = ActualWidth;
var height = ActualHeight;
if (width <= 0 || height <= 0)
return;
var pathSize = new Graphics.Rectangle(0, 0, width + strokeThickness, height + strokeThickness);
var shapePath = _borderShape.PathForBounds(pathSize);
var geometry = shapePath.AsPathGeometry();
if (_borderPath != null)
{
_borderPath.Data = geometry;
_borderPath.RenderTransform = new TranslateTransform() { X = -(strokeThickness/2), Y = -(strokeThickness/2) };
}
}
}
}
| 23.12381 | 114 | 0.705725 | [
"MIT"
] | davidbuckleyni/maui | src/Core/src/Platform/Windows/ContentPanel.cs | 4,858 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text.RegularExpressions;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// “空白页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234238 上有介绍
namespace BK20
{
/// <summary>
/// 可用于自身或导航至 Frame 内部的空白页。
/// </summary>
public sealed partial class LoginPage : Page
{
public LoginPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
l_txt_email.Text = SettingHelper.Get_Email();
}
private void btn_Login_Click(object sender, RoutedEventArgs e)
{
if (l_txt_email.Text.Length==0||l_txt_password.Password.Length==0)
{
messShow.Show("(#`O′),檢查下你的輸入!", 3000);
return;
}
Login(l_txt_email.Text, l_txt_password.Password);
}
private async void Login(string email,string password)
{
try
{
pr_Load.Visibility = Visibility.Visible;
LoginM lm = new LoginM()
{
email=email,
password=password
};
string results = await WebClientClass.PostResults_Login(new Uri("https://picaapi.picacomic.com/auth/sign-in"),JsonConvert.SerializeObject(lm));
LoginModel re = JsonConvert.DeserializeObject<LoginModel>(results);
if (re.code==200)
{
SettingHelper.Set_Authorization(re.data.token);
SettingHelper.Set_Email(email);
SettingHelper.Set_Password(password);
this.Frame.Navigate(typeof(MainPage));
}
else
{
messShow.Show(re.message,3000);
}
}
catch (Exception ex)
{
if (ex.HResult == -2147012867)
{
messShow.Show("檢查你的網絡連接!", 3000);
}
else
{
messShow.Show("登錄失敗了,檢查下你的輸入?", 3000);
}
}
finally
{
pr_Load.Visibility = Visibility.Collapsed;
}
}
private async void Sign(string email, string password,string name,string date,string gender)
{
try
{
pr_Load.Visibility = Visibility.Visible;
SignM lm = new SignM()
{
email = email,
password = password,
birthday=date,
name=name,
gender=gender
};
string results = await WebClientClass.PostResults_Login(new Uri("https://picaapi.picacomic.com/auth/register"), JsonConvert.SerializeObject(lm));
LoginModel re = JsonConvert.DeserializeObject<LoginModel>(results);
if (re.code == 200)
{
SettingHelper.Set_Email(email);
SettingHelper.Set_Password(password);
p_Login.Visibility = Visibility.Visible;
p_Sign.Visibility = Visibility.Collapsed;
l_txt_email.Text = SettingHelper.Get_Email();
l_txt_password.Password = SettingHelper.Get_Password();
Login(l_txt_email.Text, l_txt_password.Password);
}
else
{
messShow.Show(re.message, 3000);
pr_Load.Visibility = Visibility.Collapsed;
}
}
catch (Exception ex)
{
pr_Load.Visibility = Visibility.Collapsed;
if (ex.HResult == -2147012867)
{
messShow.Show("檢查你的網絡連接!", 3000);
}
else
{
messShow.Show("注冊失敗了,换个邮箱或挂個VPN試試?", 3000);
}
}
}
private void btn_Sign_Click(object sender, RoutedEventArgs e)
{
if (s_txt_email.Text.Length == 0 || s_txt_password.Password.Length == 0 || s_txt_password_a.Password.Length == 0||s_txt_name.Text.Length==0||s_date.Date==null)
{
messShow.Show("(#`O′),檢查下你的輸入!", 3000);
return;
}
if (!Regex.IsMatch(s_txt_email.Text,@".*?@.*?\..*?"))
{
messShow.Show("郵箱輸入格式錯誤", 3000);
return;
}
if ((DateTime.Now.Year - s_date.Date.Year) < 18)
{
messShow.Show("未滿18的小朋友不適合用這應用哦!", 3000);
return;
}
if (s_txt_password.Password.Length<8)
{
messShow.Show("密碼太短了,至少要8位", 3000);
return;
}
if (s_txt_password.Password!=s_txt_password_a.Password)
{
messShow.Show("兩次密碼不一致", 3000);
return;
}
Sign(s_txt_email.Text, s_txt_password.Password, s_txt_name.Text, s_date.Date.Date.ToString("yyyy-MM-dd"), "bot");
}
private void btn_GoSign_Click(object sender, RoutedEventArgs e)
{
p_Login.Visibility = Visibility.Collapsed;
p_Sign.Visibility = Visibility.Visible;
p_Find_Password.Visibility = Visibility.Collapsed;
p_Resend_activation.Visibility = Visibility.Collapsed;
}
private void btn_GoLogin_Click(object sender, RoutedEventArgs e)
{
p_Login.Visibility = Visibility.Visible;
p_Sign.Visibility = Visibility.Collapsed;
p_Find_Password.Visibility = Visibility.Collapsed;
p_Resend_activation.Visibility = Visibility.Collapsed;
}
private void btn_SendEmail_Click(object sender, RoutedEventArgs e)
{
if (r_txt_email.Text.Length==0)
{
messShow.Show("(#`O′),檢查下你的輸入!", 3000);
return;
}
SendEmail(r_txt_email.Text);
}
private async void SendEmail(string email)
{
try
{
pr_Load.Visibility = Visibility.Visible;
SignM lm = new SignM()
{
email = email,
};
string results = await WebClientClass.PostResults_Login(new Uri("https://picaapi.picacomic.com/auth/resend-activation"), JsonConvert.SerializeObject(lm));
LoginModel re = JsonConvert.DeserializeObject<LoginModel>(results);
if (re.code == 200)
{
messShow.Show("已發送", 3000);
}
else
{
messShow.Show(re.message, 3000);
pr_Load.Visibility = Visibility.Collapsed;
}
}
catch (Exception ex)
{
pr_Load.Visibility = Visibility.Collapsed;
if (ex.HResult == -2147012867)
{
messShow.Show("檢查你的網絡連接!", 3000);
}
else
{
messShow.Show("發送失敗了,挂個VPN試試?", 3000);
}
}
}
private async void FindPassword(string email)
{
try
{
pr_Load.Visibility = Visibility.Visible;
SignM lm = new SignM()
{
email = email,
};
string results = await WebClientClass.PostResults_Login(new Uri(" https://picaapi.picacomic.com/auth/forgot-password"), JsonConvert.SerializeObject(lm));
LoginModel re = JsonConvert.DeserializeObject<LoginModel>(results);
if (re.code == 200)
{
messShow.Show("已發送", 3000);
}
else
{
messShow.Show(re.message, 3000);
pr_Load.Visibility = Visibility.Collapsed;
}
}
catch (Exception ex)
{
pr_Load.Visibility = Visibility.Collapsed;
if (ex.HResult == -2147012867)
{
messShow.Show("檢查你的網絡連接!", 3000);
}
else
{
messShow.Show("發送失敗了,挂個VPN試試?", 3000);
}
}
}
private void btn_SendEmail_f_Click(object sender, RoutedEventArgs e)
{
if (f_txt_email.Text.Length == 0)
{
messShow.Show("(#`O′),檢查下你的輸入!", 3000);
return;
}
FindPassword(f_txt_email.Text);
}
private void btn_findp_Click(object sender, RoutedEventArgs e)
{
p_Login.Visibility = Visibility.Collapsed;
p_Sign.Visibility = Visibility.Collapsed;
p_Find_Password.Visibility = Visibility.Visible;
p_Resend_activation.Visibility = Visibility.Collapsed;
}
private void btn_sende_Click(object sender, RoutedEventArgs e)
{
p_Login.Visibility = Visibility.Collapsed;
p_Sign.Visibility = Visibility.Collapsed;
p_Find_Password.Visibility = Visibility.Collapsed;
p_Resend_activation.Visibility = Visibility.Visible;
}
}
public class EmailM
{
public string email { get; set; }
}
public class LoginM
{
public string email { get; set; }
public string password { get; set; }
}
public class SignM
{
public string email { get; set; }
public string password { get; set; }
public string birthday { get; set; }
public string gender { get; set; }
public string name { get; set; }
}
public class LoginModel
{
public int code { get; set; }
public string message { get; set; }
public LoginModel data { get; set; }
public string token { get; set; }
}
}
| 33.467085 | 171 | 0.500468 | [
"MIT"
] | creeperlv/PikaComic-UWP | BK20/LoginPage.xaml.cs | 11,082 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Text.Json;
using Azure.Core;
using Azure.ResourceManager.Storage.Models;
namespace Azure.ResourceManager.Storage
{
public partial class FileServiceData : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("properties");
writer.WriteStartObject();
if (Optional.IsDefined(Cors))
{
writer.WritePropertyName("cors");
writer.WriteObjectValue(Cors);
}
if (Optional.IsDefined(ShareDeleteRetentionPolicy))
{
writer.WritePropertyName("shareDeleteRetentionPolicy");
writer.WriteObjectValue(ShareDeleteRetentionPolicy);
}
if (Optional.IsDefined(ProtocolSettings))
{
writer.WritePropertyName("protocolSettings");
writer.WriteObjectValue(ProtocolSettings);
}
writer.WriteEndObject();
writer.WriteEndObject();
}
internal static FileServiceData DeserializeFileServiceData(JsonElement element)
{
Optional<Sku> sku = default;
ResourceIdentifier id = default;
string name = default;
ResourceType type = default;
Optional<CorsRules> cors = default;
Optional<DeleteRetentionPolicy> shareDeleteRetentionPolicy = default;
Optional<ProtocolSettings> protocolSettings = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("sku"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
sku = Sku.DeserializeSku(property.Value);
continue;
}
if (property.NameEquals("id"))
{
id = new ResourceIdentifier(property.Value.GetString());
continue;
}
if (property.NameEquals("name"))
{
name = property.Value.GetString();
continue;
}
if (property.NameEquals("type"))
{
type = property.Value.GetString();
continue;
}
if (property.NameEquals("properties"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
foreach (var property0 in property.Value.EnumerateObject())
{
if (property0.NameEquals("cors"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
cors = CorsRules.DeserializeCorsRules(property0.Value);
continue;
}
if (property0.NameEquals("shareDeleteRetentionPolicy"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
shareDeleteRetentionPolicy = DeleteRetentionPolicy.DeserializeDeleteRetentionPolicy(property0.Value);
continue;
}
if (property0.NameEquals("protocolSettings"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
protocolSettings = ProtocolSettings.DeserializeProtocolSettings(property0.Value);
continue;
}
}
continue;
}
}
return new FileServiceData(id, name, type, sku.Value, cors.Value, shareDeleteRetentionPolicy.Value, protocolSettings.Value);
}
}
}
| 39.821138 | 136 | 0.475909 | [
"MIT"
] | AhmedLeithy/azure-sdk-for-net | sdk/storage/Azure.ResourceManager.Storage/src/Generated/Models/FileServiceData.Serialization.cs | 4,898 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace DesafioCast.Models
{
public class usuario
{
[Key]
public int Id { get; set; }
[Required(ErrorMessage = "O campo Nome é obrigatório.")]
public string nomeusuario { get; set; }
[Required(ErrorMessage = "O campo senha é obrigatório.")]
public string senha { get; set; }
}
} | 23.7 | 65 | 0.654008 | [
"MIT"
] | andersonbellini/desafio | DesafioCast/DesafioCast/Models/usuario.cs | 480 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ModelHashingPublicSetReadOnlyDictionaryOfNullableParent.cs" company="OBeautifulCode">
// Copyright (c) OBeautifulCode 2018. All rights reserved.
// </copyright>
// <auto-generated>
// Sourced from OBeautifulCode.CodeGen.ModelObject.Test.CodeGeneratorTest
// </auto-generated>
// --------------------------------------------------------------------------------------------------------------------
namespace OBeautifulCode.CodeGen.ModelObject.Test
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using FakeItEasy;
using OBeautifulCode.Assertion.Recipes;
using OBeautifulCode.CodeAnalysis.Recipes;
using OBeautifulCode.Equality.Recipes;
using OBeautifulCode.Type;
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = ObcSuppressBecause.CA1711_IdentifiersShouldNotHaveIncorrectSuffix_TypeNameAddedAsSuffixForTestsWhereTypeIsPrimaryConcern)]
public abstract partial class ModelHashingPublicSetReadOnlyDictionaryOfNullableParent : IHashableViaCodeGen
{
[SuppressMessage("Microsoft.Design", "CA1002: DoNotExposeGenericLists")]
[SuppressMessage("Microsoft.Naming", "CA1720: IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public IReadOnlyDictionary<bool?, bool?> ParentReadOnlyDictionaryInterfaceOfNullableBoolProperty { get; set; }
[SuppressMessage("Microsoft.Design", "CA1002: DoNotExposeGenericLists")]
[SuppressMessage("Microsoft.Naming", "CA1720: IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public IReadOnlyDictionary<int?, int?> ParentReadOnlyDictionaryInterfaceOfNullableIntProperty { get; set; }
[SuppressMessage("Microsoft.Design", "CA1002: DoNotExposeGenericLists")]
[SuppressMessage("Microsoft.Naming", "CA1720: IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public IReadOnlyDictionary<Guid?, Guid?> ParentReadOnlyDictionaryInterfaceOfNullableGuidProperty { get; set; }
[SuppressMessage("Microsoft.Design", "CA1002: DoNotExposeGenericLists")]
[SuppressMessage("Microsoft.Naming", "CA1720: IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public IReadOnlyDictionary<CustomEnum?, CustomEnum?> ParentReadOnlyDictionaryInterfaceOfNullableCustomEnumProperty { get; set; }
[SuppressMessage("Microsoft.Design", "CA1002: DoNotExposeGenericLists")]
[SuppressMessage("Microsoft.Naming", "CA1720: IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public IReadOnlyDictionary<CustomFlagsEnum?, CustomFlagsEnum?> ParentReadOnlyDictionaryInterfaceOfNullableCustomFlagsEnumProperty { get; set; }
}
} | 65.68254 | 229 | 0.730788 | [
"MIT"
] | OBeautifulCode/OBeautifulCode.CodeGen | OBeautifulCode.CodeGen.ModelObject.Test/Models/Scripted/Hashing/PublicSet/ReadOnlyDictionaryOfNullable/ModelHashingPublicSetReadOnlyDictionaryOfNullableParent.cs | 4,140 | C# |
using MLAPI;
using UnityEngine;
namespace HelloWorld
{
public class HelloWorldManager : MonoBehaviour
{
void OnGUI()
{
GUILayout.BeginArea(new rect(10, 10, 300, 300));
if (!NetworkManager.Singletion.IsClient && !NetworkManager.Singletion.IsServer)
{
StartButtons();
}
else
{
StatusLables();
SubmitNewPosition();
}
GUILayout.EndArea();
}
static void StartButtons()
{
if (GUILayout.Button("Host")) NetworkManager.Singletion.StartHost();
if (GUILayout.Button("Client")) NetworkManager.Singletion.StartClient();
if (GUILayout.Button("Server")) NetworkManager.Singletion.StartServer();
}
static void StatusLables()
{
var mode = NetworkManager.Singletion.InHost ?
"Host" : NetworkManager.Singletion.IsServer ? "Server" : "Client";
GUILayout.Label("Transport: " +
NetworkManager.Singletion.NetworkConfig.NetworkTransport.GetType().Name);
GUILayout.Label("Mode: " + mode);
}
static void SubmitNewPosition()
{
if (GUILayout.Button(NetworkManager.Singletion.IsServer ? "Move" : "Request Position Change"))
{
if (NetworkManager.Singletion.ConnectedClients.TryGetValue(NetworkManager.Singletion.LocalClientId,
out var networkedClient))
{
var player = networkedClient.PlayerObjects.GetComponent<HelloWorldPlayer>();
if (player)
{
player.Move()
}
}
}
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
}
| 29.028571 | 115 | 0.513287 | [
"MIT"
] | chom-cracker/Unity-Multiplayer-Tutorials | Assets/Tutorials/ConnectionApproval/Scripts/HelloWorldManager.cs | 2,032 | C# |
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
#if STRIDE_GRAPHICS_API_DIRECT3D12
using System.Collections.Generic;
using SharpDX.Direct3D12;
namespace Stride.Graphics
{
public partial struct CompiledCommandList
{
internal CommandList Builder;
internal GraphicsCommandList NativeCommandList;
internal CommandAllocator NativeCommandAllocator;
internal List<DescriptorHeap> SrvHeaps;
internal List<DescriptorHeap> SamplerHeaps;
internal List<GraphicsResource> StagingResources;
}
}
#endif
| 38.45 | 163 | 0.762029 | [
"MIT"
] | Alan-love/xenko | sources/engine/Stride.Graphics/Direct3D12/CompiledCommandList.Direct3D12.cs | 769 | C# |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTests.Schemas.StructurePropertyTests
{
[TestClass]
public class StructurePropertyGetGuidValueTests : UnitTests
{
[TestMethod]
public void GetIdValue_WhenGuidOnFirstLevel_ReturnsGuid()
{
var expected = Guid.Parse("4217F3B7-6DEB-4DFA-B195-D111C1297988");
var item = new GuidOnRoot { Value = expected };
var property = StructurePropertyTestFactory.GetPropertyByPath<GuidOnRoot>("Value");
var actual = property.GetValue(item);
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void GetIdValue_WhenNullableGuidOnFirstLevel_ReturnsGuid()
{
var expected = Guid.Parse("4217F3B7-6DEB-4DFA-B195-D111C1297988");
var item = new NullableGuidOnRoot { Value = expected };
var property = StructurePropertyTestFactory.GetPropertyByPath<NullableGuidOnRoot>("Value");
var actual = property.GetValue(item);
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void GetIdValue_WhenNullAssignedNullableGuidOnFirstLevel_ReturnsNull()
{
var item = new NullableGuidOnRoot { Value = null };
var property = StructurePropertyTestFactory.GetPropertyByPath<NullableGuidOnRoot>("Value");
var actual = property.GetValue(item);
Assert.IsNull(actual);
}
private class GuidOnRoot
{
public Guid Value { get; set; }
}
private class NullableGuidOnRoot
{
public Guid? Value { get; set; }
}
private class Container
{
public GuidOnRoot GuidOnRootItem { get; set; }
}
}
} | 31.474576 | 103 | 0.613893 | [
"MIT"
] | apetrut/structurizer | src/tests/UnitTests/Schemas/StructurePropertyTests/StructurePropertyGetGuidValueTests.cs | 1,859 | C# |
/*
* Copyright 2012 The Netty Project
*
* The Netty Project 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.
*
* Copyright (c) 2020 The Dotnetty-Span-Fork Project (cuteant@outlook.com)
*
* https://github.com/cuteant/dotnetty-span-fork
*
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
using System;
using System.Buffers;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using DotNetty.Common;
namespace DotNetty.Buffers
{
unsafe partial class ArrayPooledUnsafeDirectByteBuffer : ArrayPooledByteBuffer
{
static readonly ThreadLocalPool<ArrayPooledUnsafeDirectByteBuffer> Recycler = new ThreadLocalPool<ArrayPooledUnsafeDirectByteBuffer>(handle => new ArrayPooledUnsafeDirectByteBuffer(handle, 0));
internal static ArrayPooledUnsafeDirectByteBuffer NewInstance(ArrayPooledByteBufferAllocator allocator, ArrayPool<byte> arrayPool, byte[] buffer, int length, int maxCapacity)
{
var buf = Recycler.Take();
buf.Reuse(allocator, arrayPool, buffer, length, maxCapacity);
return buf;
}
internal ArrayPooledUnsafeDirectByteBuffer(ThreadLocalPool.Handle recyclerHandle, int maxCapacity)
: base(recyclerHandle, maxCapacity)
{
}
public sealed override bool IsDirect => true;
protected internal sealed override byte _GetByte(int index) => Memory[index];
protected internal sealed override void _SetByte(int index, int value) => Memory[index] = unchecked((byte)value);
protected internal sealed override short _GetShort(int index)
{
fixed (byte* addr = &Addr(index))
return UnsafeByteBufferUtil.GetShort(addr);
}
protected internal sealed override short _GetShortLE(int index)
{
fixed (byte* addr = &Addr(index))
return UnsafeByteBufferUtil.GetShortLE(addr);
}
protected internal sealed override int _GetUnsignedMedium(int index)
{
fixed (byte* addr = &Addr(index))
return UnsafeByteBufferUtil.GetUnsignedMedium(addr);
}
protected internal sealed override int _GetUnsignedMediumLE(int index)
{
fixed (byte* addr = &Addr(index))
return UnsafeByteBufferUtil.GetUnsignedMediumLE(addr);
}
protected internal sealed override int _GetInt(int index)
{
fixed (byte* addr = &Addr(index))
return UnsafeByteBufferUtil.GetInt(addr);
}
protected internal sealed override int _GetIntLE(int index)
{
fixed (byte* addr = &Addr(index))
return UnsafeByteBufferUtil.GetIntLE(addr);
}
protected internal sealed override long _GetLong(int index)
{
fixed (byte* addr = &Addr(index))
return UnsafeByteBufferUtil.GetLong(addr);
}
protected internal sealed override long _GetLongLE(int index)
{
fixed (byte* addr = &Addr(index))
return UnsafeByteBufferUtil.GetLongLE(addr);
}
public sealed override IByteBuffer GetBytes(int index, IByteBuffer dst, int dstIndex, int length)
{
if (dst is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dst); }
CheckDstIndex(index, length, dstIndex, dst.Capacity);
fixed (byte* addr = &Addr(index))
{
UnsafeByteBufferUtil.GetBytes(this, addr, index, dst, dstIndex, length);
return this;
}
}
public sealed override IByteBuffer GetBytes(int index, byte[] dst, int dstIndex, int length)
{
if (dst is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dst); }
CheckDstIndex(index, length, dstIndex, dst.Length);
fixed (byte* addr = &Addr(index))
{
UnsafeByteBufferUtil.GetBytes(addr, dst, dstIndex, length);
return this;
}
}
protected internal sealed override void _SetShort(int index, int value)
{
fixed (byte* addr = &Addr(index))
UnsafeByteBufferUtil.SetShort(addr, value);
}
protected internal sealed override void _SetShortLE(int index, int value)
{
fixed (byte* addr = &Addr(index))
UnsafeByteBufferUtil.SetShortLE(addr, value);
}
protected internal sealed override void _SetMedium(int index, int value)
{
fixed (byte* addr = &Addr(index))
UnsafeByteBufferUtil.SetMedium(addr, value);
}
protected internal sealed override void _SetMediumLE(int index, int value)
{
fixed (byte* addr = &Addr(index))
UnsafeByteBufferUtil.SetMediumLE(addr, value);
}
protected internal sealed override void _SetInt(int index, int value)
{
fixed (byte* addr = &Addr(index))
UnsafeByteBufferUtil.SetInt(addr, value);
}
protected internal sealed override void _SetIntLE(int index, int value)
{
fixed (byte* addr = &Addr(index))
UnsafeByteBufferUtil.SetIntLE(addr, value);
}
protected internal sealed override void _SetLong(int index, long value)
{
fixed (byte* addr = &Addr(index))
UnsafeByteBufferUtil.SetLong(addr, value);
}
protected internal sealed override void _SetLongLE(int index, long value)
{
fixed (byte* addr = &Addr(index))
UnsafeByteBufferUtil.SetLongLE(addr, value);
}
public sealed override IByteBuffer SetBytes(int index, IByteBuffer src, int srcIndex, int length)
{
if (src is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.src); }
CheckSrcIndex(index, length, srcIndex, src.Capacity);
if (0u >= (uint)length) { return this; }
fixed (byte* addr = &Addr(index))
{
UnsafeByteBufferUtil.SetBytes(this, addr, index, src, srcIndex, length);
return this;
}
}
public sealed override IByteBuffer SetBytes(int index, byte[] src, int srcIndex, int length)
{
if (src is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.src); }
CheckSrcIndex(index, length, srcIndex, src.Length);
if (0u >= (uint)length) { return this; }
fixed (byte* addr = &Addr(index))
{
UnsafeByteBufferUtil.SetBytes(addr, src, srcIndex, length);
return this;
}
}
public sealed override IByteBuffer GetBytes(int index, Stream output, int length)
{
if (output is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.output); }
CheckIndex(index, length);
//fixed (byte* addr = &Addr(index))
//{
// UnsafeByteBufferUtil.GetBytes(this, addr, index, output, length);
// return this;
//}
// UnsafeByteBufferUtil.GetBytes 多一遍内存拷贝,最终还是调用 stream.write,没啥必要
#if NETCOREAPP || NETSTANDARD_2_0_GREATER
output.Write(new ReadOnlySpan<byte>(Memory, index, length));
#else
output.Write(Memory, index, length);
#endif
return this;
}
public sealed override Task<int> SetBytesAsync(int index, Stream src, int length, CancellationToken cancellationToken)
{
if (src is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.src); }
CheckIndex(index, length);
//int read;
//fixed (byte* addr = &Addr(index))
//{
// read = UnsafeByteBufferUtil.SetBytes(this, addr, index, src, length);
// return Task.FromResult(read);
//}
int readTotal = 0;
int read;
do
{
#if NETCOREAPP || NETSTANDARD_2_0_GREATER
read = src.Read(new Span<byte>(Memory, index + readTotal, length - readTotal));
#else
read = src.Read(Memory, index + readTotal, length - readTotal);
#endif
readTotal += read;
}
while (read > 0 && readTotal < length);
return Task.FromResult(readTotal);
}
public sealed override IByteBuffer Copy(int index, int length)
{
CheckIndex(index, length);
fixed (byte* addr = &Addr(index))
return UnsafeByteBufferUtil.Copy(this, addr, index, length);
}
[MethodImpl(InlineMethod.AggressiveOptimization)]
ref byte Addr(int index) => ref Memory[index];
public sealed override IByteBuffer SetZero(int index, int length)
{
CheckIndex(index, length);
fixed (byte* addr = &Addr(index))
{
UnsafeByteBufferUtil.SetZero(addr, length);
return this;
}
}
public sealed override IByteBuffer WriteZero(int length)
{
if (0u >= (uint)length) { return this; }
_ = EnsureWritable(length);
int wIndex = WriterIndex;
CheckIndex0(wIndex, length);
fixed (byte* addr = &Addr(wIndex))
{
UnsafeByteBufferUtil.SetZero(addr, length);
}
_ = SetWriterIndex(wIndex + length);
return this;
}
}
}
| 36.657143 | 201 | 0.602786 | [
"MIT"
] | maksimkim/SpanNetty | src/DotNetty.Buffers/ArrayPooledUnsafeDirectByteBuffer.cs | 10,304 | C# |
using UnityEngine;
using UnityEngine.UI;
public class AttributesUI : MonoBehaviour {
private bool activated;
void Update()
{
if (activated != UIManager.Instance.ActiveAttributesUI)
{
ToggleUIActive();
}
}
public void ToggleUIActive()
{
activated = !activated;
transform.GetChild(0).gameObject.SetActive(activated);
GetComponent<Image>().color = new Color(0f, 0f, 0f, activated ? 1f : 0f);
}
}
| 21.130435 | 81 | 0.611111 | [
"MIT"
] | DominikaBogusz/Evilmine | Assets/Scripts/UI/AttributesUI.cs | 488 | C# |
using ApsiyonProject.Application.App.Common.Interfaces.Dtos.Flats;
using ApsiyonProject.Application.App.Common.Interfaces.Services.Flats;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ApsiyonProject.Infrastructure.Controllers.Flats
{
[Route("api/[controller]")]
[ApiController]
public class FlatTypeApiController : ControllerBase
{
private readonly IFlatTypeCrudService _flatTypeCrudService;
public FlatTypeApiController(IFlatTypeCrudService flatTypeCrudService)
{
_flatTypeCrudService = flatTypeCrudService;
}
[HttpPost("AddFlatType")]
public async Task<int> AddFlatTypeAsync(FlatTypeDto flatTypeDto)
{
return await _flatTypeCrudService.CreateFlatTypeAsync(flatTypeDto);
}
[HttpGet("GetFlatTypeById")]
public async Task<FlatTypeDto> GetFlatTypeByIdAsync(Guid id)
{
return await _flatTypeCrudService.GetFlatTypeByIdAsync(id);
}
[HttpGet("GetListFlatType")]
public async Task<List<FlatTypeDto>> GetListFlatTypeAsync()
{
return await _flatTypeCrudService.GetListFlatTypeAsync();
}
}
}
| 30.674419 | 79 | 0.705838 | [
"MIT"
] | emretuna01/ApsiyonProject | ApsiyonProject.Infrastructure/Controllers/Flats/FlatTypeApiController.cs | 1,321 | C# |
using System.Management.Automation;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Publishing;
using SharePointPnP.PowerShell.CmdletHelpAttributes;
using SharePointPnP.PowerShell.Commands.Base.PipeBinds;
namespace SharePointPnP.PowerShell.Commands.Publishing
{
[Cmdlet(VerbsCommon.Get, "PnPPublishingImageRendition")]
[CmdletHelp("Returns all image renditions or if Identity is specified a specific one",
Category = CmdletHelpCategory.Publishing,
OutputType = typeof(ImageRendition),
OutputTypeLink = "https://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.publishing.imagerendition.aspx")]
[CmdletExample(
Code = @"PS:> Get-PnPPublishingImageRendition",
Remarks = @"Returns all Image Renditions",
SortOrder = 1)]
[CmdletExample(
Code = @"PS:> Get-PnPPublishingImageRendition -Identity ""Test""",
Remarks = @"Returns the image rendition named ""Test""",
SortOrder = 2)]
[CmdletExample(
Code = @"PS:> Get-PnPPublishingImageRendition -Identity 2",
Remarks = @"Returns the image rendition where its id equals 2",
SortOrder = 3)]
public class GetPublishingImageRendition : SPOWebCmdlet
{
[Parameter(Mandatory = false, HelpMessage = "Id or name of an existing image rendition", Position = 0, ValueFromPipeline = true)]
public ImageRenditionPipeBind Identity;
protected override void ExecuteCmdlet()
{
if (MyInvocation.BoundParameters.ContainsKey("Identity"))
{
WriteObject(Identity.GetImageRendition(SelectedWeb));
}
else
{
WriteObject(SelectedWeb.GetPublishingImageRenditions(), true);
}
}
}
}
| 40.931818 | 137 | 0.676846 | [
"MIT"
] | phrueegsegger/PnP-PowerShell | Commands/Publishing/GetPublishingImageRendition.cs | 1,803 | C# |
using Informapp.InformSystem.WebApi.Client.Decorators;
using Informapp.InformSystem.IntegrationTool.Core.Loggers;
using System.Threading;
using System.Threading.Tasks;
namespace Informapp.InformSystem.IntegrationTool.Core.Uploaders
{
/// <summary>
/// Decorator class for <see cref="IUploader{TCommand}"/> to log upload has started
/// </summary>
/// <typeparam name="TCommand">Type of command</typeparam>
public class LogUploaderDecorator<TCommand> : Decorator<IUploader<TCommand>>,
IUploader<TCommand>
where TCommand : class, IUploadCommand
{
private readonly IUploader<TCommand> _uploader;
private readonly IApplicationLogger _logger;
/// <summary>
/// Initializes a new instance of the <see cref="LogUploaderDecorator{TCommand}"/> class
/// </summary>
/// <param name="uploader">Injected uploader</param>
/// <param name="logger">Injected application logger</param>
public LogUploaderDecorator(
IUploader<TCommand> uploader,
IApplicationLogger logger) : base(uploader)
{
Argument.NotNull(uploader, nameof(uploader));
Argument.NotNull(logger, nameof(logger));
_uploader = uploader;
_logger = logger;
}
/// <summary>
/// Logs upload has started and continues with uploading
/// </summary>
/// <param name="command">The command</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns>Upload continues</returns>
public Task<IUploadResult> Upload(TCommand command, CancellationToken cancellationToken)
{
Argument.NotNull(command, nameof(command));
if (_logger.IsInfoEnabled == true)
{
_logger.InfoFormat("Uploading {0}", command.Path);
}
return _uploader.Upload(command, cancellationToken);
}
}
}
| 34.912281 | 96 | 0.633668 | [
"MIT"
] | InformappNL/informapp-api-dotnet-client | src/IntegrationTool.Core/Uploaders/LogUploaderDecorator.T1.cs | 1,992 | 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 license-manager-2018-08-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Net;
using Amazon.LicenseManager.Model;
using Amazon.LicenseManager.Model.Internal.MarshallTransformations;
using Amazon.LicenseManager.Internal;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.LicenseManager
{
/// <summary>
/// Implementation for accessing LicenseManager
///
/// AWS License Manager
/// <para>
/// AWS License Manager makes it easier to manage licenses from software vendors across
/// multiple AWS accounts and on-premises servers.
/// </para>
/// </summary>
public partial class AmazonLicenseManagerClient : AmazonServiceClient, IAmazonLicenseManager
{
private static IServiceMetadata serviceMetadata = new AmazonLicenseManagerMetadata();
#region Constructors
/// <summary>
/// Constructs AmazonLicenseManagerClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
public AmazonLicenseManagerClient()
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonLicenseManagerConfig()) { }
/// <summary>
/// Constructs AmazonLicenseManagerClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="region">The region to connect.</param>
public AmazonLicenseManagerClient(RegionEndpoint region)
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonLicenseManagerConfig{RegionEndpoint = region}) { }
/// <summary>
/// Constructs AmazonLicenseManagerClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="config">The AmazonLicenseManagerClient Configuration Object</param>
public AmazonLicenseManagerClient(AmazonLicenseManagerConfig config)
: base(FallbackCredentialsFactory.GetCredentials(), config) { }
/// <summary>
/// Constructs AmazonLicenseManagerClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonLicenseManagerClient(AWSCredentials credentials)
: this(credentials, new AmazonLicenseManagerConfig())
{
}
/// <summary>
/// Constructs AmazonLicenseManagerClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonLicenseManagerClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonLicenseManagerConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonLicenseManagerClient with AWS Credentials and an
/// AmazonLicenseManagerClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonLicenseManagerClient Configuration Object</param>
public AmazonLicenseManagerClient(AWSCredentials credentials, AmazonLicenseManagerConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonLicenseManagerClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonLicenseManagerClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonLicenseManagerConfig())
{
}
/// <summary>
/// Constructs AmazonLicenseManagerClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonLicenseManagerClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonLicenseManagerConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonLicenseManagerClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonLicenseManagerClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonLicenseManagerClient Configuration Object</param>
public AmazonLicenseManagerClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonLicenseManagerConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonLicenseManagerClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonLicenseManagerClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonLicenseManagerConfig())
{
}
/// <summary>
/// Constructs AmazonLicenseManagerClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonLicenseManagerClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonLicenseManagerConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonLicenseManagerClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonLicenseManagerClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonLicenseManagerClient Configuration Object</param>
public AmazonLicenseManagerClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonLicenseManagerConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
{
}
#endregion
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
/// <summary>
/// Capture metadata for the service.
/// </summary>
protected override IServiceMetadata ServiceMetadata
{
get
{
return serviceMetadata;
}
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region AcceptGrant
/// <summary>
/// Accepts the specified grant.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the AcceptGrant service method.</param>
///
/// <returns>The response from the AcceptGrant service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ResourceLimitExceededException">
/// Your resource limits have been exceeded.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ValidationException">
/// The provided input is not valid. Try your request again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/AcceptGrant">REST API Reference for AcceptGrant Operation</seealso>
public virtual AcceptGrantResponse AcceptGrant(AcceptGrantRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = AcceptGrantRequestMarshaller.Instance;
options.ResponseUnmarshaller = AcceptGrantResponseUnmarshaller.Instance;
return Invoke<AcceptGrantResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the AcceptGrant operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the AcceptGrant operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndAcceptGrant
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/AcceptGrant">REST API Reference for AcceptGrant Operation</seealso>
public virtual IAsyncResult BeginAcceptGrant(AcceptGrantRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = AcceptGrantRequestMarshaller.Instance;
options.ResponseUnmarshaller = AcceptGrantResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the AcceptGrant operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginAcceptGrant.</param>
///
/// <returns>Returns a AcceptGrantResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/AcceptGrant">REST API Reference for AcceptGrant Operation</seealso>
public virtual AcceptGrantResponse EndAcceptGrant(IAsyncResult asyncResult)
{
return EndInvoke<AcceptGrantResponse>(asyncResult);
}
#endregion
#region CheckInLicense
/// <summary>
/// Checks in the specified license. Check in a license when it is no longer in use.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CheckInLicense service method.</param>
///
/// <returns>The response from the CheckInLicense service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ConflictException">
/// There was a conflict processing the request. Try your request again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ResourceNotFoundException">
/// The resource cannot be found.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ValidationException">
/// The provided input is not valid. Try your request again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CheckInLicense">REST API Reference for CheckInLicense Operation</seealso>
public virtual CheckInLicenseResponse CheckInLicense(CheckInLicenseRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CheckInLicenseRequestMarshaller.Instance;
options.ResponseUnmarshaller = CheckInLicenseResponseUnmarshaller.Instance;
return Invoke<CheckInLicenseResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the CheckInLicense operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CheckInLicense operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCheckInLicense
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CheckInLicense">REST API Reference for CheckInLicense Operation</seealso>
public virtual IAsyncResult BeginCheckInLicense(CheckInLicenseRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = CheckInLicenseRequestMarshaller.Instance;
options.ResponseUnmarshaller = CheckInLicenseResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the CheckInLicense operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCheckInLicense.</param>
///
/// <returns>Returns a CheckInLicenseResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CheckInLicense">REST API Reference for CheckInLicense Operation</seealso>
public virtual CheckInLicenseResponse EndCheckInLicense(IAsyncResult asyncResult)
{
return EndInvoke<CheckInLicenseResponse>(asyncResult);
}
#endregion
#region CheckoutBorrowLicense
/// <summary>
/// Checks out the specified license for offline use.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CheckoutBorrowLicense service method.</param>
///
/// <returns>The response from the CheckoutBorrowLicense service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.EntitlementNotAllowedException">
/// The entitlement is not allowed.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.NoEntitlementsAllowedException">
/// There are no entitlements found for this license, or the entitlement maximum count
/// is reached.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RedirectException">
/// This is not the correct Region for the resource. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ResourceNotFoundException">
/// The resource cannot be found.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.UnsupportedDigitalSignatureMethodException">
/// The digital signature method is unsupported. Try your request again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ValidationException">
/// The provided input is not valid. Try your request again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CheckoutBorrowLicense">REST API Reference for CheckoutBorrowLicense Operation</seealso>
public virtual CheckoutBorrowLicenseResponse CheckoutBorrowLicense(CheckoutBorrowLicenseRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CheckoutBorrowLicenseRequestMarshaller.Instance;
options.ResponseUnmarshaller = CheckoutBorrowLicenseResponseUnmarshaller.Instance;
return Invoke<CheckoutBorrowLicenseResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the CheckoutBorrowLicense operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CheckoutBorrowLicense operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCheckoutBorrowLicense
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CheckoutBorrowLicense">REST API Reference for CheckoutBorrowLicense Operation</seealso>
public virtual IAsyncResult BeginCheckoutBorrowLicense(CheckoutBorrowLicenseRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = CheckoutBorrowLicenseRequestMarshaller.Instance;
options.ResponseUnmarshaller = CheckoutBorrowLicenseResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the CheckoutBorrowLicense operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCheckoutBorrowLicense.</param>
///
/// <returns>Returns a CheckoutBorrowLicenseResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CheckoutBorrowLicense">REST API Reference for CheckoutBorrowLicense Operation</seealso>
public virtual CheckoutBorrowLicenseResponse EndCheckoutBorrowLicense(IAsyncResult asyncResult)
{
return EndInvoke<CheckoutBorrowLicenseResponse>(asyncResult);
}
#endregion
#region CheckoutLicense
/// <summary>
/// Checks out the specified license.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CheckoutLicense service method.</param>
///
/// <returns>The response from the CheckoutLicense service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.NoEntitlementsAllowedException">
/// There are no entitlements found for this license, or the entitlement maximum count
/// is reached.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RedirectException">
/// This is not the correct Region for the resource. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ResourceNotFoundException">
/// The resource cannot be found.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.UnsupportedDigitalSignatureMethodException">
/// The digital signature method is unsupported. Try your request again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ValidationException">
/// The provided input is not valid. Try your request again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CheckoutLicense">REST API Reference for CheckoutLicense Operation</seealso>
public virtual CheckoutLicenseResponse CheckoutLicense(CheckoutLicenseRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CheckoutLicenseRequestMarshaller.Instance;
options.ResponseUnmarshaller = CheckoutLicenseResponseUnmarshaller.Instance;
return Invoke<CheckoutLicenseResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the CheckoutLicense operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CheckoutLicense operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCheckoutLicense
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CheckoutLicense">REST API Reference for CheckoutLicense Operation</seealso>
public virtual IAsyncResult BeginCheckoutLicense(CheckoutLicenseRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = CheckoutLicenseRequestMarshaller.Instance;
options.ResponseUnmarshaller = CheckoutLicenseResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the CheckoutLicense operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCheckoutLicense.</param>
///
/// <returns>Returns a CheckoutLicenseResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CheckoutLicense">REST API Reference for CheckoutLicense Operation</seealso>
public virtual CheckoutLicenseResponse EndCheckoutLicense(IAsyncResult asyncResult)
{
return EndInvoke<CheckoutLicenseResponse>(asyncResult);
}
#endregion
#region CreateGrant
/// <summary>
/// Creates a grant for the specified license. A grant shares the use of license entitlements
/// with specific AWS accounts.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateGrant service method.</param>
///
/// <returns>The response from the CreateGrant service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ResourceLimitExceededException">
/// Your resource limits have been exceeded.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ValidationException">
/// The provided input is not valid. Try your request again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CreateGrant">REST API Reference for CreateGrant Operation</seealso>
public virtual CreateGrantResponse CreateGrant(CreateGrantRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateGrantRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateGrantResponseUnmarshaller.Instance;
return Invoke<CreateGrantResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateGrant operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateGrant operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateGrant
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CreateGrant">REST API Reference for CreateGrant Operation</seealso>
public virtual IAsyncResult BeginCreateGrant(CreateGrantRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateGrantRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateGrantResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the CreateGrant operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateGrant.</param>
///
/// <returns>Returns a CreateGrantResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CreateGrant">REST API Reference for CreateGrant Operation</seealso>
public virtual CreateGrantResponse EndCreateGrant(IAsyncResult asyncResult)
{
return EndInvoke<CreateGrantResponse>(asyncResult);
}
#endregion
#region CreateGrantVersion
/// <summary>
/// Creates a new version of the specified grant.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateGrantVersion service method.</param>
///
/// <returns>The response from the CreateGrantVersion service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ResourceLimitExceededException">
/// Your resource limits have been exceeded.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ValidationException">
/// The provided input is not valid. Try your request again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CreateGrantVersion">REST API Reference for CreateGrantVersion Operation</seealso>
public virtual CreateGrantVersionResponse CreateGrantVersion(CreateGrantVersionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateGrantVersionRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateGrantVersionResponseUnmarshaller.Instance;
return Invoke<CreateGrantVersionResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateGrantVersion operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateGrantVersion operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateGrantVersion
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CreateGrantVersion">REST API Reference for CreateGrantVersion Operation</seealso>
public virtual IAsyncResult BeginCreateGrantVersion(CreateGrantVersionRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateGrantVersionRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateGrantVersionResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the CreateGrantVersion operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateGrantVersion.</param>
///
/// <returns>Returns a CreateGrantVersionResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CreateGrantVersion">REST API Reference for CreateGrantVersion Operation</seealso>
public virtual CreateGrantVersionResponse EndCreateGrantVersion(IAsyncResult asyncResult)
{
return EndInvoke<CreateGrantVersionResponse>(asyncResult);
}
#endregion
#region CreateLicense
/// <summary>
/// Creates a license.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateLicense service method.</param>
///
/// <returns>The response from the CreateLicense service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RedirectException">
/// This is not the correct Region for the resource. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ValidationException">
/// The provided input is not valid. Try your request again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CreateLicense">REST API Reference for CreateLicense Operation</seealso>
public virtual CreateLicenseResponse CreateLicense(CreateLicenseRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateLicenseRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateLicenseResponseUnmarshaller.Instance;
return Invoke<CreateLicenseResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateLicense operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateLicense operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateLicense
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CreateLicense">REST API Reference for CreateLicense Operation</seealso>
public virtual IAsyncResult BeginCreateLicense(CreateLicenseRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateLicenseRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateLicenseResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the CreateLicense operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateLicense.</param>
///
/// <returns>Returns a CreateLicenseResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CreateLicense">REST API Reference for CreateLicense Operation</seealso>
public virtual CreateLicenseResponse EndCreateLicense(IAsyncResult asyncResult)
{
return EndInvoke<CreateLicenseResponse>(asyncResult);
}
#endregion
#region CreateLicenseConfiguration
/// <summary>
/// Creates a license configuration.
///
///
/// <para>
/// A license configuration is an abstraction of a customer license agreement that can
/// be consumed and enforced by License Manager. Components include specifications for
/// the license type (licensing by instance, socket, CPU, or vCPU), allowed tenancy (shared
/// tenancy, Dedicated Instance, Dedicated Host, or all of these), license affinity to
/// host (how long a license must be associated with a host), and the number of licenses
/// purchased and used.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateLicenseConfiguration service method.</param>
///
/// <returns>The response from the CreateLicenseConfiguration service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ResourceLimitExceededException">
/// Your resource limits have been exceeded.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CreateLicenseConfiguration">REST API Reference for CreateLicenseConfiguration Operation</seealso>
public virtual CreateLicenseConfigurationResponse CreateLicenseConfiguration(CreateLicenseConfigurationRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateLicenseConfigurationRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateLicenseConfigurationResponseUnmarshaller.Instance;
return Invoke<CreateLicenseConfigurationResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateLicenseConfiguration operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateLicenseConfiguration operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateLicenseConfiguration
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CreateLicenseConfiguration">REST API Reference for CreateLicenseConfiguration Operation</seealso>
public virtual IAsyncResult BeginCreateLicenseConfiguration(CreateLicenseConfigurationRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateLicenseConfigurationRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateLicenseConfigurationResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the CreateLicenseConfiguration operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateLicenseConfiguration.</param>
///
/// <returns>Returns a CreateLicenseConfigurationResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CreateLicenseConfiguration">REST API Reference for CreateLicenseConfiguration Operation</seealso>
public virtual CreateLicenseConfigurationResponse EndCreateLicenseConfiguration(IAsyncResult asyncResult)
{
return EndInvoke<CreateLicenseConfigurationResponse>(asyncResult);
}
#endregion
#region CreateLicenseManagerReportGenerator
/// <summary>
/// Creates a new report generator.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateLicenseManagerReportGenerator service method.</param>
///
/// <returns>The response from the CreateLicenseManagerReportGenerator service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ResourceLimitExceededException">
/// Your resource limits have been exceeded.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ResourceNotFoundException">
/// The resource cannot be found.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ValidationException">
/// The provided input is not valid. Try your request again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CreateLicenseManagerReportGenerator">REST API Reference for CreateLicenseManagerReportGenerator Operation</seealso>
public virtual CreateLicenseManagerReportGeneratorResponse CreateLicenseManagerReportGenerator(CreateLicenseManagerReportGeneratorRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateLicenseManagerReportGeneratorRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateLicenseManagerReportGeneratorResponseUnmarshaller.Instance;
return Invoke<CreateLicenseManagerReportGeneratorResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateLicenseManagerReportGenerator operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateLicenseManagerReportGenerator operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateLicenseManagerReportGenerator
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CreateLicenseManagerReportGenerator">REST API Reference for CreateLicenseManagerReportGenerator Operation</seealso>
public virtual IAsyncResult BeginCreateLicenseManagerReportGenerator(CreateLicenseManagerReportGeneratorRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateLicenseManagerReportGeneratorRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateLicenseManagerReportGeneratorResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the CreateLicenseManagerReportGenerator operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateLicenseManagerReportGenerator.</param>
///
/// <returns>Returns a CreateLicenseManagerReportGeneratorResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CreateLicenseManagerReportGenerator">REST API Reference for CreateLicenseManagerReportGenerator Operation</seealso>
public virtual CreateLicenseManagerReportGeneratorResponse EndCreateLicenseManagerReportGenerator(IAsyncResult asyncResult)
{
return EndInvoke<CreateLicenseManagerReportGeneratorResponse>(asyncResult);
}
#endregion
#region CreateLicenseVersion
/// <summary>
/// Creates a new version of the specified license.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateLicenseVersion service method.</param>
///
/// <returns>The response from the CreateLicenseVersion service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ConflictException">
/// There was a conflict processing the request. Try your request again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RedirectException">
/// This is not the correct Region for the resource. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ResourceNotFoundException">
/// The resource cannot be found.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ValidationException">
/// The provided input is not valid. Try your request again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CreateLicenseVersion">REST API Reference for CreateLicenseVersion Operation</seealso>
public virtual CreateLicenseVersionResponse CreateLicenseVersion(CreateLicenseVersionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateLicenseVersionRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateLicenseVersionResponseUnmarshaller.Instance;
return Invoke<CreateLicenseVersionResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateLicenseVersion operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateLicenseVersion operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateLicenseVersion
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CreateLicenseVersion">REST API Reference for CreateLicenseVersion Operation</seealso>
public virtual IAsyncResult BeginCreateLicenseVersion(CreateLicenseVersionRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateLicenseVersionRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateLicenseVersionResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the CreateLicenseVersion operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateLicenseVersion.</param>
///
/// <returns>Returns a CreateLicenseVersionResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CreateLicenseVersion">REST API Reference for CreateLicenseVersion Operation</seealso>
public virtual CreateLicenseVersionResponse EndCreateLicenseVersion(IAsyncResult asyncResult)
{
return EndInvoke<CreateLicenseVersionResponse>(asyncResult);
}
#endregion
#region CreateToken
/// <summary>
/// Creates a long-lived token.
///
///
/// <para>
/// A refresh token is a JWT token used to get an access token. With an access token,
/// you can call AssumeRoleWithWebIdentity to get role credentials that you can use to
/// call License Manager to manage the specified license.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateToken service method.</param>
///
/// <returns>The response from the CreateToken service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RedirectException">
/// This is not the correct Region for the resource. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ResourceLimitExceededException">
/// Your resource limits have been exceeded.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ResourceNotFoundException">
/// The resource cannot be found.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ValidationException">
/// The provided input is not valid. Try your request again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CreateToken">REST API Reference for CreateToken Operation</seealso>
public virtual CreateTokenResponse CreateToken(CreateTokenRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateTokenRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateTokenResponseUnmarshaller.Instance;
return Invoke<CreateTokenResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateToken operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateToken operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateToken
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CreateToken">REST API Reference for CreateToken Operation</seealso>
public virtual IAsyncResult BeginCreateToken(CreateTokenRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateTokenRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateTokenResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the CreateToken operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateToken.</param>
///
/// <returns>Returns a CreateTokenResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CreateToken">REST API Reference for CreateToken Operation</seealso>
public virtual CreateTokenResponse EndCreateToken(IAsyncResult asyncResult)
{
return EndInvoke<CreateTokenResponse>(asyncResult);
}
#endregion
#region DeleteGrant
/// <summary>
/// Deletes the specified grant.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteGrant service method.</param>
///
/// <returns>The response from the DeleteGrant service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ResourceLimitExceededException">
/// Your resource limits have been exceeded.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ValidationException">
/// The provided input is not valid. Try your request again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/DeleteGrant">REST API Reference for DeleteGrant Operation</seealso>
public virtual DeleteGrantResponse DeleteGrant(DeleteGrantRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteGrantRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteGrantResponseUnmarshaller.Instance;
return Invoke<DeleteGrantResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteGrant operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteGrant operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteGrant
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/DeleteGrant">REST API Reference for DeleteGrant Operation</seealso>
public virtual IAsyncResult BeginDeleteGrant(DeleteGrantRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteGrantRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteGrantResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DeleteGrant operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteGrant.</param>
///
/// <returns>Returns a DeleteGrantResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/DeleteGrant">REST API Reference for DeleteGrant Operation</seealso>
public virtual DeleteGrantResponse EndDeleteGrant(IAsyncResult asyncResult)
{
return EndInvoke<DeleteGrantResponse>(asyncResult);
}
#endregion
#region DeleteLicense
/// <summary>
/// Deletes the specified license.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteLicense service method.</param>
///
/// <returns>The response from the DeleteLicense service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ConflictException">
/// There was a conflict processing the request. Try your request again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RedirectException">
/// This is not the correct Region for the resource. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ValidationException">
/// The provided input is not valid. Try your request again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/DeleteLicense">REST API Reference for DeleteLicense Operation</seealso>
public virtual DeleteLicenseResponse DeleteLicense(DeleteLicenseRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteLicenseRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteLicenseResponseUnmarshaller.Instance;
return Invoke<DeleteLicenseResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteLicense operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteLicense operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteLicense
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/DeleteLicense">REST API Reference for DeleteLicense Operation</seealso>
public virtual IAsyncResult BeginDeleteLicense(DeleteLicenseRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteLicenseRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteLicenseResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DeleteLicense operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteLicense.</param>
///
/// <returns>Returns a DeleteLicenseResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/DeleteLicense">REST API Reference for DeleteLicense Operation</seealso>
public virtual DeleteLicenseResponse EndDeleteLicense(IAsyncResult asyncResult)
{
return EndInvoke<DeleteLicenseResponse>(asyncResult);
}
#endregion
#region DeleteLicenseConfiguration
/// <summary>
/// Deletes the specified license configuration.
///
///
/// <para>
/// You cannot delete a license configuration that is in use.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteLicenseConfiguration service method.</param>
///
/// <returns>The response from the DeleteLicenseConfiguration service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/DeleteLicenseConfiguration">REST API Reference for DeleteLicenseConfiguration Operation</seealso>
public virtual DeleteLicenseConfigurationResponse DeleteLicenseConfiguration(DeleteLicenseConfigurationRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteLicenseConfigurationRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteLicenseConfigurationResponseUnmarshaller.Instance;
return Invoke<DeleteLicenseConfigurationResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteLicenseConfiguration operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteLicenseConfiguration operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteLicenseConfiguration
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/DeleteLicenseConfiguration">REST API Reference for DeleteLicenseConfiguration Operation</seealso>
public virtual IAsyncResult BeginDeleteLicenseConfiguration(DeleteLicenseConfigurationRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteLicenseConfigurationRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteLicenseConfigurationResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DeleteLicenseConfiguration operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteLicenseConfiguration.</param>
///
/// <returns>Returns a DeleteLicenseConfigurationResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/DeleteLicenseConfiguration">REST API Reference for DeleteLicenseConfiguration Operation</seealso>
public virtual DeleteLicenseConfigurationResponse EndDeleteLicenseConfiguration(IAsyncResult asyncResult)
{
return EndInvoke<DeleteLicenseConfigurationResponse>(asyncResult);
}
#endregion
#region DeleteLicenseManagerReportGenerator
/// <summary>
/// Delete an existing report generator.
///
///
/// <para>
/// This action deletes the report generator, which stops it from generating future reports
/// and cannot be reversed. However, the previous reports from this generator will remain
/// in your S3 bucket.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteLicenseManagerReportGenerator service method.</param>
///
/// <returns>The response from the DeleteLicenseManagerReportGenerator service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ResourceLimitExceededException">
/// Your resource limits have been exceeded.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ResourceNotFoundException">
/// The resource cannot be found.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ValidationException">
/// The provided input is not valid. Try your request again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/DeleteLicenseManagerReportGenerator">REST API Reference for DeleteLicenseManagerReportGenerator Operation</seealso>
public virtual DeleteLicenseManagerReportGeneratorResponse DeleteLicenseManagerReportGenerator(DeleteLicenseManagerReportGeneratorRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteLicenseManagerReportGeneratorRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteLicenseManagerReportGeneratorResponseUnmarshaller.Instance;
return Invoke<DeleteLicenseManagerReportGeneratorResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteLicenseManagerReportGenerator operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteLicenseManagerReportGenerator operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteLicenseManagerReportGenerator
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/DeleteLicenseManagerReportGenerator">REST API Reference for DeleteLicenseManagerReportGenerator Operation</seealso>
public virtual IAsyncResult BeginDeleteLicenseManagerReportGenerator(DeleteLicenseManagerReportGeneratorRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteLicenseManagerReportGeneratorRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteLicenseManagerReportGeneratorResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DeleteLicenseManagerReportGenerator operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteLicenseManagerReportGenerator.</param>
///
/// <returns>Returns a DeleteLicenseManagerReportGeneratorResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/DeleteLicenseManagerReportGenerator">REST API Reference for DeleteLicenseManagerReportGenerator Operation</seealso>
public virtual DeleteLicenseManagerReportGeneratorResponse EndDeleteLicenseManagerReportGenerator(IAsyncResult asyncResult)
{
return EndInvoke<DeleteLicenseManagerReportGeneratorResponse>(asyncResult);
}
#endregion
#region DeleteToken
/// <summary>
/// Deletes the specified token. Must be called in the license home Region.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteToken service method.</param>
///
/// <returns>The response from the DeleteToken service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RedirectException">
/// This is not the correct Region for the resource. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ResourceNotFoundException">
/// The resource cannot be found.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ValidationException">
/// The provided input is not valid. Try your request again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/DeleteToken">REST API Reference for DeleteToken Operation</seealso>
public virtual DeleteTokenResponse DeleteToken(DeleteTokenRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteTokenRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteTokenResponseUnmarshaller.Instance;
return Invoke<DeleteTokenResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteToken operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteToken operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteToken
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/DeleteToken">REST API Reference for DeleteToken Operation</seealso>
public virtual IAsyncResult BeginDeleteToken(DeleteTokenRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteTokenRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteTokenResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DeleteToken operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteToken.</param>
///
/// <returns>Returns a DeleteTokenResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/DeleteToken">REST API Reference for DeleteToken Operation</seealso>
public virtual DeleteTokenResponse EndDeleteToken(IAsyncResult asyncResult)
{
return EndInvoke<DeleteTokenResponse>(asyncResult);
}
#endregion
#region ExtendLicenseConsumption
/// <summary>
/// Extends the expiration date for license consumption.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ExtendLicenseConsumption service method.</param>
///
/// <returns>The response from the ExtendLicenseConsumption service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ResourceNotFoundException">
/// The resource cannot be found.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ValidationException">
/// The provided input is not valid. Try your request again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ExtendLicenseConsumption">REST API Reference for ExtendLicenseConsumption Operation</seealso>
public virtual ExtendLicenseConsumptionResponse ExtendLicenseConsumption(ExtendLicenseConsumptionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ExtendLicenseConsumptionRequestMarshaller.Instance;
options.ResponseUnmarshaller = ExtendLicenseConsumptionResponseUnmarshaller.Instance;
return Invoke<ExtendLicenseConsumptionResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ExtendLicenseConsumption operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ExtendLicenseConsumption operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndExtendLicenseConsumption
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ExtendLicenseConsumption">REST API Reference for ExtendLicenseConsumption Operation</seealso>
public virtual IAsyncResult BeginExtendLicenseConsumption(ExtendLicenseConsumptionRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ExtendLicenseConsumptionRequestMarshaller.Instance;
options.ResponseUnmarshaller = ExtendLicenseConsumptionResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ExtendLicenseConsumption operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginExtendLicenseConsumption.</param>
///
/// <returns>Returns a ExtendLicenseConsumptionResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ExtendLicenseConsumption">REST API Reference for ExtendLicenseConsumption Operation</seealso>
public virtual ExtendLicenseConsumptionResponse EndExtendLicenseConsumption(IAsyncResult asyncResult)
{
return EndInvoke<ExtendLicenseConsumptionResponse>(asyncResult);
}
#endregion
#region GetAccessToken
/// <summary>
/// Gets a temporary access token to use with AssumeRoleWithWebIdentity. Access tokens
/// are valid for one hour.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetAccessToken service method.</param>
///
/// <returns>The response from the GetAccessToken service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ValidationException">
/// The provided input is not valid. Try your request again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/GetAccessToken">REST API Reference for GetAccessToken Operation</seealso>
public virtual GetAccessTokenResponse GetAccessToken(GetAccessTokenRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetAccessTokenRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetAccessTokenResponseUnmarshaller.Instance;
return Invoke<GetAccessTokenResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the GetAccessToken operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetAccessToken operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetAccessToken
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/GetAccessToken">REST API Reference for GetAccessToken Operation</seealso>
public virtual IAsyncResult BeginGetAccessToken(GetAccessTokenRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetAccessTokenRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetAccessTokenResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the GetAccessToken operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetAccessToken.</param>
///
/// <returns>Returns a GetAccessTokenResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/GetAccessToken">REST API Reference for GetAccessToken Operation</seealso>
public virtual GetAccessTokenResponse EndGetAccessToken(IAsyncResult asyncResult)
{
return EndInvoke<GetAccessTokenResponse>(asyncResult);
}
#endregion
#region GetGrant
/// <summary>
/// Gets detailed information about the specified grant.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetGrant service method.</param>
///
/// <returns>The response from the GetGrant service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ResourceLimitExceededException">
/// Your resource limits have been exceeded.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ValidationException">
/// The provided input is not valid. Try your request again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/GetGrant">REST API Reference for GetGrant Operation</seealso>
public virtual GetGrantResponse GetGrant(GetGrantRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetGrantRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetGrantResponseUnmarshaller.Instance;
return Invoke<GetGrantResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the GetGrant operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetGrant operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetGrant
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/GetGrant">REST API Reference for GetGrant Operation</seealso>
public virtual IAsyncResult BeginGetGrant(GetGrantRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetGrantRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetGrantResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the GetGrant operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetGrant.</param>
///
/// <returns>Returns a GetGrantResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/GetGrant">REST API Reference for GetGrant Operation</seealso>
public virtual GetGrantResponse EndGetGrant(IAsyncResult asyncResult)
{
return EndInvoke<GetGrantResponse>(asyncResult);
}
#endregion
#region GetLicense
/// <summary>
/// Gets detailed information about the specified license.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetLicense service method.</param>
///
/// <returns>The response from the GetLicense service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ValidationException">
/// The provided input is not valid. Try your request again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/GetLicense">REST API Reference for GetLicense Operation</seealso>
public virtual GetLicenseResponse GetLicense(GetLicenseRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetLicenseRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetLicenseResponseUnmarshaller.Instance;
return Invoke<GetLicenseResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the GetLicense operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetLicense operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetLicense
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/GetLicense">REST API Reference for GetLicense Operation</seealso>
public virtual IAsyncResult BeginGetLicense(GetLicenseRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetLicenseRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetLicenseResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the GetLicense operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetLicense.</param>
///
/// <returns>Returns a GetLicenseResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/GetLicense">REST API Reference for GetLicense Operation</seealso>
public virtual GetLicenseResponse EndGetLicense(IAsyncResult asyncResult)
{
return EndInvoke<GetLicenseResponse>(asyncResult);
}
#endregion
#region GetLicenseConfiguration
/// <summary>
/// Gets detailed information about the specified license configuration.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetLicenseConfiguration service method.</param>
///
/// <returns>The response from the GetLicenseConfiguration service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/GetLicenseConfiguration">REST API Reference for GetLicenseConfiguration Operation</seealso>
public virtual GetLicenseConfigurationResponse GetLicenseConfiguration(GetLicenseConfigurationRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetLicenseConfigurationRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetLicenseConfigurationResponseUnmarshaller.Instance;
return Invoke<GetLicenseConfigurationResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the GetLicenseConfiguration operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetLicenseConfiguration operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetLicenseConfiguration
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/GetLicenseConfiguration">REST API Reference for GetLicenseConfiguration Operation</seealso>
public virtual IAsyncResult BeginGetLicenseConfiguration(GetLicenseConfigurationRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetLicenseConfigurationRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetLicenseConfigurationResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the GetLicenseConfiguration operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetLicenseConfiguration.</param>
///
/// <returns>Returns a GetLicenseConfigurationResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/GetLicenseConfiguration">REST API Reference for GetLicenseConfiguration Operation</seealso>
public virtual GetLicenseConfigurationResponse EndGetLicenseConfiguration(IAsyncResult asyncResult)
{
return EndInvoke<GetLicenseConfigurationResponse>(asyncResult);
}
#endregion
#region GetLicenseManagerReportGenerator
/// <summary>
/// Gets information on the specified report generator.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetLicenseManagerReportGenerator service method.</param>
///
/// <returns>The response from the GetLicenseManagerReportGenerator service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ResourceLimitExceededException">
/// Your resource limits have been exceeded.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ResourceNotFoundException">
/// The resource cannot be found.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ValidationException">
/// The provided input is not valid. Try your request again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/GetLicenseManagerReportGenerator">REST API Reference for GetLicenseManagerReportGenerator Operation</seealso>
public virtual GetLicenseManagerReportGeneratorResponse GetLicenseManagerReportGenerator(GetLicenseManagerReportGeneratorRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetLicenseManagerReportGeneratorRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetLicenseManagerReportGeneratorResponseUnmarshaller.Instance;
return Invoke<GetLicenseManagerReportGeneratorResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the GetLicenseManagerReportGenerator operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetLicenseManagerReportGenerator operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetLicenseManagerReportGenerator
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/GetLicenseManagerReportGenerator">REST API Reference for GetLicenseManagerReportGenerator Operation</seealso>
public virtual IAsyncResult BeginGetLicenseManagerReportGenerator(GetLicenseManagerReportGeneratorRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetLicenseManagerReportGeneratorRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetLicenseManagerReportGeneratorResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the GetLicenseManagerReportGenerator operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetLicenseManagerReportGenerator.</param>
///
/// <returns>Returns a GetLicenseManagerReportGeneratorResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/GetLicenseManagerReportGenerator">REST API Reference for GetLicenseManagerReportGenerator Operation</seealso>
public virtual GetLicenseManagerReportGeneratorResponse EndGetLicenseManagerReportGenerator(IAsyncResult asyncResult)
{
return EndInvoke<GetLicenseManagerReportGeneratorResponse>(asyncResult);
}
#endregion
#region GetLicenseUsage
/// <summary>
/// Gets detailed information about the usage of the specified license.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetLicenseUsage service method.</param>
///
/// <returns>The response from the GetLicenseUsage service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ValidationException">
/// The provided input is not valid. Try your request again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/GetLicenseUsage">REST API Reference for GetLicenseUsage Operation</seealso>
public virtual GetLicenseUsageResponse GetLicenseUsage(GetLicenseUsageRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetLicenseUsageRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetLicenseUsageResponseUnmarshaller.Instance;
return Invoke<GetLicenseUsageResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the GetLicenseUsage operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetLicenseUsage operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetLicenseUsage
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/GetLicenseUsage">REST API Reference for GetLicenseUsage Operation</seealso>
public virtual IAsyncResult BeginGetLicenseUsage(GetLicenseUsageRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetLicenseUsageRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetLicenseUsageResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the GetLicenseUsage operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetLicenseUsage.</param>
///
/// <returns>Returns a GetLicenseUsageResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/GetLicenseUsage">REST API Reference for GetLicenseUsage Operation</seealso>
public virtual GetLicenseUsageResponse EndGetLicenseUsage(IAsyncResult asyncResult)
{
return EndInvoke<GetLicenseUsageResponse>(asyncResult);
}
#endregion
#region GetServiceSettings
/// <summary>
/// Gets the License Manager settings for the current Region.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetServiceSettings service method.</param>
///
/// <returns>The response from the GetServiceSettings service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/GetServiceSettings">REST API Reference for GetServiceSettings Operation</seealso>
public virtual GetServiceSettingsResponse GetServiceSettings(GetServiceSettingsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetServiceSettingsRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetServiceSettingsResponseUnmarshaller.Instance;
return Invoke<GetServiceSettingsResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the GetServiceSettings operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetServiceSettings operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetServiceSettings
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/GetServiceSettings">REST API Reference for GetServiceSettings Operation</seealso>
public virtual IAsyncResult BeginGetServiceSettings(GetServiceSettingsRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetServiceSettingsRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetServiceSettingsResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the GetServiceSettings operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetServiceSettings.</param>
///
/// <returns>Returns a GetServiceSettingsResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/GetServiceSettings">REST API Reference for GetServiceSettings Operation</seealso>
public virtual GetServiceSettingsResponse EndGetServiceSettings(IAsyncResult asyncResult)
{
return EndInvoke<GetServiceSettingsResponse>(asyncResult);
}
#endregion
#region ListAssociationsForLicenseConfiguration
/// <summary>
/// Lists the resource associations for the specified license configuration.
///
///
/// <para>
/// Resource associations need not consume licenses from a license configuration. For
/// example, an AMI or a stopped instance might not consume a license (depending on the
/// license rules).
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListAssociationsForLicenseConfiguration service method.</param>
///
/// <returns>The response from the ListAssociationsForLicenseConfiguration service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.FilterLimitExceededException">
/// The request uses too many filters or too many filter values.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListAssociationsForLicenseConfiguration">REST API Reference for ListAssociationsForLicenseConfiguration Operation</seealso>
public virtual ListAssociationsForLicenseConfigurationResponse ListAssociationsForLicenseConfiguration(ListAssociationsForLicenseConfigurationRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListAssociationsForLicenseConfigurationRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListAssociationsForLicenseConfigurationResponseUnmarshaller.Instance;
return Invoke<ListAssociationsForLicenseConfigurationResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListAssociationsForLicenseConfiguration operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListAssociationsForLicenseConfiguration operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListAssociationsForLicenseConfiguration
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListAssociationsForLicenseConfiguration">REST API Reference for ListAssociationsForLicenseConfiguration Operation</seealso>
public virtual IAsyncResult BeginListAssociationsForLicenseConfiguration(ListAssociationsForLicenseConfigurationRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListAssociationsForLicenseConfigurationRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListAssociationsForLicenseConfigurationResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListAssociationsForLicenseConfiguration operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListAssociationsForLicenseConfiguration.</param>
///
/// <returns>Returns a ListAssociationsForLicenseConfigurationResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListAssociationsForLicenseConfiguration">REST API Reference for ListAssociationsForLicenseConfiguration Operation</seealso>
public virtual ListAssociationsForLicenseConfigurationResponse EndListAssociationsForLicenseConfiguration(IAsyncResult asyncResult)
{
return EndInvoke<ListAssociationsForLicenseConfigurationResponse>(asyncResult);
}
#endregion
#region ListDistributedGrants
/// <summary>
/// Lists the grants distributed for the specified license.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListDistributedGrants service method.</param>
///
/// <returns>The response from the ListDistributedGrants service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ResourceLimitExceededException">
/// Your resource limits have been exceeded.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ValidationException">
/// The provided input is not valid. Try your request again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListDistributedGrants">REST API Reference for ListDistributedGrants Operation</seealso>
public virtual ListDistributedGrantsResponse ListDistributedGrants(ListDistributedGrantsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListDistributedGrantsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListDistributedGrantsResponseUnmarshaller.Instance;
return Invoke<ListDistributedGrantsResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListDistributedGrants operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListDistributedGrants operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListDistributedGrants
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListDistributedGrants">REST API Reference for ListDistributedGrants Operation</seealso>
public virtual IAsyncResult BeginListDistributedGrants(ListDistributedGrantsRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListDistributedGrantsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListDistributedGrantsResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListDistributedGrants operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListDistributedGrants.</param>
///
/// <returns>Returns a ListDistributedGrantsResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListDistributedGrants">REST API Reference for ListDistributedGrants Operation</seealso>
public virtual ListDistributedGrantsResponse EndListDistributedGrants(IAsyncResult asyncResult)
{
return EndInvoke<ListDistributedGrantsResponse>(asyncResult);
}
#endregion
#region ListFailuresForLicenseConfigurationOperations
/// <summary>
/// Lists the license configuration operations that failed.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListFailuresForLicenseConfigurationOperations service method.</param>
///
/// <returns>The response from the ListFailuresForLicenseConfigurationOperations service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListFailuresForLicenseConfigurationOperations">REST API Reference for ListFailuresForLicenseConfigurationOperations Operation</seealso>
public virtual ListFailuresForLicenseConfigurationOperationsResponse ListFailuresForLicenseConfigurationOperations(ListFailuresForLicenseConfigurationOperationsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListFailuresForLicenseConfigurationOperationsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListFailuresForLicenseConfigurationOperationsResponseUnmarshaller.Instance;
return Invoke<ListFailuresForLicenseConfigurationOperationsResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListFailuresForLicenseConfigurationOperations operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListFailuresForLicenseConfigurationOperations operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListFailuresForLicenseConfigurationOperations
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListFailuresForLicenseConfigurationOperations">REST API Reference for ListFailuresForLicenseConfigurationOperations Operation</seealso>
public virtual IAsyncResult BeginListFailuresForLicenseConfigurationOperations(ListFailuresForLicenseConfigurationOperationsRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListFailuresForLicenseConfigurationOperationsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListFailuresForLicenseConfigurationOperationsResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListFailuresForLicenseConfigurationOperations operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListFailuresForLicenseConfigurationOperations.</param>
///
/// <returns>Returns a ListFailuresForLicenseConfigurationOperationsResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListFailuresForLicenseConfigurationOperations">REST API Reference for ListFailuresForLicenseConfigurationOperations Operation</seealso>
public virtual ListFailuresForLicenseConfigurationOperationsResponse EndListFailuresForLicenseConfigurationOperations(IAsyncResult asyncResult)
{
return EndInvoke<ListFailuresForLicenseConfigurationOperationsResponse>(asyncResult);
}
#endregion
#region ListLicenseConfigurations
/// <summary>
/// Lists the license configurations for your account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListLicenseConfigurations service method.</param>
///
/// <returns>The response from the ListLicenseConfigurations service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.FilterLimitExceededException">
/// The request uses too many filters or too many filter values.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListLicenseConfigurations">REST API Reference for ListLicenseConfigurations Operation</seealso>
public virtual ListLicenseConfigurationsResponse ListLicenseConfigurations(ListLicenseConfigurationsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListLicenseConfigurationsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListLicenseConfigurationsResponseUnmarshaller.Instance;
return Invoke<ListLicenseConfigurationsResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListLicenseConfigurations operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListLicenseConfigurations operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListLicenseConfigurations
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListLicenseConfigurations">REST API Reference for ListLicenseConfigurations Operation</seealso>
public virtual IAsyncResult BeginListLicenseConfigurations(ListLicenseConfigurationsRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListLicenseConfigurationsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListLicenseConfigurationsResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListLicenseConfigurations operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListLicenseConfigurations.</param>
///
/// <returns>Returns a ListLicenseConfigurationsResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListLicenseConfigurations">REST API Reference for ListLicenseConfigurations Operation</seealso>
public virtual ListLicenseConfigurationsResponse EndListLicenseConfigurations(IAsyncResult asyncResult)
{
return EndInvoke<ListLicenseConfigurationsResponse>(asyncResult);
}
#endregion
#region ListLicenseManagerReportGenerators
/// <summary>
/// Lists the report generators for your account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListLicenseManagerReportGenerators service method.</param>
///
/// <returns>The response from the ListLicenseManagerReportGenerators service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ResourceLimitExceededException">
/// Your resource limits have been exceeded.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ResourceNotFoundException">
/// The resource cannot be found.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ValidationException">
/// The provided input is not valid. Try your request again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListLicenseManagerReportGenerators">REST API Reference for ListLicenseManagerReportGenerators Operation</seealso>
public virtual ListLicenseManagerReportGeneratorsResponse ListLicenseManagerReportGenerators(ListLicenseManagerReportGeneratorsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListLicenseManagerReportGeneratorsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListLicenseManagerReportGeneratorsResponseUnmarshaller.Instance;
return Invoke<ListLicenseManagerReportGeneratorsResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListLicenseManagerReportGenerators operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListLicenseManagerReportGenerators operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListLicenseManagerReportGenerators
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListLicenseManagerReportGenerators">REST API Reference for ListLicenseManagerReportGenerators Operation</seealso>
public virtual IAsyncResult BeginListLicenseManagerReportGenerators(ListLicenseManagerReportGeneratorsRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListLicenseManagerReportGeneratorsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListLicenseManagerReportGeneratorsResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListLicenseManagerReportGenerators operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListLicenseManagerReportGenerators.</param>
///
/// <returns>Returns a ListLicenseManagerReportGeneratorsResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListLicenseManagerReportGenerators">REST API Reference for ListLicenseManagerReportGenerators Operation</seealso>
public virtual ListLicenseManagerReportGeneratorsResponse EndListLicenseManagerReportGenerators(IAsyncResult asyncResult)
{
return EndInvoke<ListLicenseManagerReportGeneratorsResponse>(asyncResult);
}
#endregion
#region ListLicenses
/// <summary>
/// Lists the licenses for your account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListLicenses service method.</param>
///
/// <returns>The response from the ListLicenses service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ValidationException">
/// The provided input is not valid. Try your request again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListLicenses">REST API Reference for ListLicenses Operation</seealso>
public virtual ListLicensesResponse ListLicenses(ListLicensesRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListLicensesRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListLicensesResponseUnmarshaller.Instance;
return Invoke<ListLicensesResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListLicenses operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListLicenses operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListLicenses
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListLicenses">REST API Reference for ListLicenses Operation</seealso>
public virtual IAsyncResult BeginListLicenses(ListLicensesRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListLicensesRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListLicensesResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListLicenses operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListLicenses.</param>
///
/// <returns>Returns a ListLicensesResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListLicenses">REST API Reference for ListLicenses Operation</seealso>
public virtual ListLicensesResponse EndListLicenses(IAsyncResult asyncResult)
{
return EndInvoke<ListLicensesResponse>(asyncResult);
}
#endregion
#region ListLicenseSpecificationsForResource
/// <summary>
/// Describes the license configurations for the specified resource.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListLicenseSpecificationsForResource service method.</param>
///
/// <returns>The response from the ListLicenseSpecificationsForResource service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListLicenseSpecificationsForResource">REST API Reference for ListLicenseSpecificationsForResource Operation</seealso>
public virtual ListLicenseSpecificationsForResourceResponse ListLicenseSpecificationsForResource(ListLicenseSpecificationsForResourceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListLicenseSpecificationsForResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListLicenseSpecificationsForResourceResponseUnmarshaller.Instance;
return Invoke<ListLicenseSpecificationsForResourceResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListLicenseSpecificationsForResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListLicenseSpecificationsForResource operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListLicenseSpecificationsForResource
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListLicenseSpecificationsForResource">REST API Reference for ListLicenseSpecificationsForResource Operation</seealso>
public virtual IAsyncResult BeginListLicenseSpecificationsForResource(ListLicenseSpecificationsForResourceRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListLicenseSpecificationsForResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListLicenseSpecificationsForResourceResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListLicenseSpecificationsForResource operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListLicenseSpecificationsForResource.</param>
///
/// <returns>Returns a ListLicenseSpecificationsForResourceResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListLicenseSpecificationsForResource">REST API Reference for ListLicenseSpecificationsForResource Operation</seealso>
public virtual ListLicenseSpecificationsForResourceResponse EndListLicenseSpecificationsForResource(IAsyncResult asyncResult)
{
return EndInvoke<ListLicenseSpecificationsForResourceResponse>(asyncResult);
}
#endregion
#region ListLicenseVersions
/// <summary>
/// Lists all versions of the specified license.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListLicenseVersions service method.</param>
///
/// <returns>The response from the ListLicenseVersions service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListLicenseVersions">REST API Reference for ListLicenseVersions Operation</seealso>
public virtual ListLicenseVersionsResponse ListLicenseVersions(ListLicenseVersionsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListLicenseVersionsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListLicenseVersionsResponseUnmarshaller.Instance;
return Invoke<ListLicenseVersionsResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListLicenseVersions operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListLicenseVersions operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListLicenseVersions
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListLicenseVersions">REST API Reference for ListLicenseVersions Operation</seealso>
public virtual IAsyncResult BeginListLicenseVersions(ListLicenseVersionsRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListLicenseVersionsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListLicenseVersionsResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListLicenseVersions operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListLicenseVersions.</param>
///
/// <returns>Returns a ListLicenseVersionsResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListLicenseVersions">REST API Reference for ListLicenseVersions Operation</seealso>
public virtual ListLicenseVersionsResponse EndListLicenseVersions(IAsyncResult asyncResult)
{
return EndInvoke<ListLicenseVersionsResponse>(asyncResult);
}
#endregion
#region ListReceivedGrants
/// <summary>
/// Lists grants that are received but not accepted.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListReceivedGrants service method.</param>
///
/// <returns>The response from the ListReceivedGrants service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ResourceLimitExceededException">
/// Your resource limits have been exceeded.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ValidationException">
/// The provided input is not valid. Try your request again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListReceivedGrants">REST API Reference for ListReceivedGrants Operation</seealso>
public virtual ListReceivedGrantsResponse ListReceivedGrants(ListReceivedGrantsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListReceivedGrantsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListReceivedGrantsResponseUnmarshaller.Instance;
return Invoke<ListReceivedGrantsResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListReceivedGrants operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListReceivedGrants operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListReceivedGrants
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListReceivedGrants">REST API Reference for ListReceivedGrants Operation</seealso>
public virtual IAsyncResult BeginListReceivedGrants(ListReceivedGrantsRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListReceivedGrantsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListReceivedGrantsResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListReceivedGrants operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListReceivedGrants.</param>
///
/// <returns>Returns a ListReceivedGrantsResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListReceivedGrants">REST API Reference for ListReceivedGrants Operation</seealso>
public virtual ListReceivedGrantsResponse EndListReceivedGrants(IAsyncResult asyncResult)
{
return EndInvoke<ListReceivedGrantsResponse>(asyncResult);
}
#endregion
#region ListReceivedLicenses
/// <summary>
/// Lists received licenses.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListReceivedLicenses service method.</param>
///
/// <returns>The response from the ListReceivedLicenses service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ResourceLimitExceededException">
/// Your resource limits have been exceeded.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ValidationException">
/// The provided input is not valid. Try your request again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListReceivedLicenses">REST API Reference for ListReceivedLicenses Operation</seealso>
public virtual ListReceivedLicensesResponse ListReceivedLicenses(ListReceivedLicensesRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListReceivedLicensesRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListReceivedLicensesResponseUnmarshaller.Instance;
return Invoke<ListReceivedLicensesResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListReceivedLicenses operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListReceivedLicenses operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListReceivedLicenses
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListReceivedLicenses">REST API Reference for ListReceivedLicenses Operation</seealso>
public virtual IAsyncResult BeginListReceivedLicenses(ListReceivedLicensesRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListReceivedLicensesRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListReceivedLicensesResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListReceivedLicenses operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListReceivedLicenses.</param>
///
/// <returns>Returns a ListReceivedLicensesResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListReceivedLicenses">REST API Reference for ListReceivedLicenses Operation</seealso>
public virtual ListReceivedLicensesResponse EndListReceivedLicenses(IAsyncResult asyncResult)
{
return EndInvoke<ListReceivedLicensesResponse>(asyncResult);
}
#endregion
#region ListResourceInventory
/// <summary>
/// Lists resources managed using Systems Manager inventory.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListResourceInventory service method.</param>
///
/// <returns>The response from the ListResourceInventory service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.FailedDependencyException">
/// A dependency required to run the API is missing.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.FilterLimitExceededException">
/// The request uses too many filters or too many filter values.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListResourceInventory">REST API Reference for ListResourceInventory Operation</seealso>
public virtual ListResourceInventoryResponse ListResourceInventory(ListResourceInventoryRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListResourceInventoryRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListResourceInventoryResponseUnmarshaller.Instance;
return Invoke<ListResourceInventoryResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListResourceInventory operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListResourceInventory operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListResourceInventory
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListResourceInventory">REST API Reference for ListResourceInventory Operation</seealso>
public virtual IAsyncResult BeginListResourceInventory(ListResourceInventoryRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListResourceInventoryRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListResourceInventoryResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListResourceInventory operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListResourceInventory.</param>
///
/// <returns>Returns a ListResourceInventoryResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListResourceInventory">REST API Reference for ListResourceInventory Operation</seealso>
public virtual ListResourceInventoryResponse EndListResourceInventory(IAsyncResult asyncResult)
{
return EndInvoke<ListResourceInventoryResponse>(asyncResult);
}
#endregion
#region ListTagsForResource
/// <summary>
/// Lists the tags for the specified license configuration.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListTagsForResource service method.</param>
///
/// <returns>The response from the ListTagsForResource service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso>
public virtual ListTagsForResourceResponse ListTagsForResource(ListTagsForResourceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListTagsForResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListTagsForResourceResponseUnmarshaller.Instance;
return Invoke<ListTagsForResourceResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListTagsForResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListTagsForResource operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListTagsForResource
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso>
public virtual IAsyncResult BeginListTagsForResource(ListTagsForResourceRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListTagsForResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListTagsForResourceResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListTagsForResource operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListTagsForResource.</param>
///
/// <returns>Returns a ListTagsForResourceResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso>
public virtual ListTagsForResourceResponse EndListTagsForResource(IAsyncResult asyncResult)
{
return EndInvoke<ListTagsForResourceResponse>(asyncResult);
}
#endregion
#region ListTokens
/// <summary>
/// Lists your tokens.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListTokens service method.</param>
///
/// <returns>The response from the ListTokens service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ValidationException">
/// The provided input is not valid. Try your request again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListTokens">REST API Reference for ListTokens Operation</seealso>
public virtual ListTokensResponse ListTokens(ListTokensRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListTokensRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListTokensResponseUnmarshaller.Instance;
return Invoke<ListTokensResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListTokens operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListTokens operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListTokens
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListTokens">REST API Reference for ListTokens Operation</seealso>
public virtual IAsyncResult BeginListTokens(ListTokensRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListTokensRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListTokensResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListTokens operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListTokens.</param>
///
/// <returns>Returns a ListTokensResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListTokens">REST API Reference for ListTokens Operation</seealso>
public virtual ListTokensResponse EndListTokens(IAsyncResult asyncResult)
{
return EndInvoke<ListTokensResponse>(asyncResult);
}
#endregion
#region ListUsageForLicenseConfiguration
/// <summary>
/// Lists all license usage records for a license configuration, displaying license consumption
/// details by resource at a selected point in time. Use this action to audit the current
/// license consumption for any license inventory and configuration.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListUsageForLicenseConfiguration service method.</param>
///
/// <returns>The response from the ListUsageForLicenseConfiguration service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.FilterLimitExceededException">
/// The request uses too many filters or too many filter values.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListUsageForLicenseConfiguration">REST API Reference for ListUsageForLicenseConfiguration Operation</seealso>
public virtual ListUsageForLicenseConfigurationResponse ListUsageForLicenseConfiguration(ListUsageForLicenseConfigurationRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListUsageForLicenseConfigurationRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListUsageForLicenseConfigurationResponseUnmarshaller.Instance;
return Invoke<ListUsageForLicenseConfigurationResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListUsageForLicenseConfiguration operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListUsageForLicenseConfiguration operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListUsageForLicenseConfiguration
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListUsageForLicenseConfiguration">REST API Reference for ListUsageForLicenseConfiguration Operation</seealso>
public virtual IAsyncResult BeginListUsageForLicenseConfiguration(ListUsageForLicenseConfigurationRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListUsageForLicenseConfigurationRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListUsageForLicenseConfigurationResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListUsageForLicenseConfiguration operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListUsageForLicenseConfiguration.</param>
///
/// <returns>Returns a ListUsageForLicenseConfigurationResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/ListUsageForLicenseConfiguration">REST API Reference for ListUsageForLicenseConfiguration Operation</seealso>
public virtual ListUsageForLicenseConfigurationResponse EndListUsageForLicenseConfiguration(IAsyncResult asyncResult)
{
return EndInvoke<ListUsageForLicenseConfigurationResponse>(asyncResult);
}
#endregion
#region RejectGrant
/// <summary>
/// Rejects the specified grant.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RejectGrant service method.</param>
///
/// <returns>The response from the RejectGrant service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ResourceLimitExceededException">
/// Your resource limits have been exceeded.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ValidationException">
/// The provided input is not valid. Try your request again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/RejectGrant">REST API Reference for RejectGrant Operation</seealso>
public virtual RejectGrantResponse RejectGrant(RejectGrantRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = RejectGrantRequestMarshaller.Instance;
options.ResponseUnmarshaller = RejectGrantResponseUnmarshaller.Instance;
return Invoke<RejectGrantResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the RejectGrant operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the RejectGrant operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndRejectGrant
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/RejectGrant">REST API Reference for RejectGrant Operation</seealso>
public virtual IAsyncResult BeginRejectGrant(RejectGrantRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = RejectGrantRequestMarshaller.Instance;
options.ResponseUnmarshaller = RejectGrantResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the RejectGrant operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginRejectGrant.</param>
///
/// <returns>Returns a RejectGrantResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/RejectGrant">REST API Reference for RejectGrant Operation</seealso>
public virtual RejectGrantResponse EndRejectGrant(IAsyncResult asyncResult)
{
return EndInvoke<RejectGrantResponse>(asyncResult);
}
#endregion
#region TagResource
/// <summary>
/// Adds the specified tags to the specified license configuration.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the TagResource service method.</param>
///
/// <returns>The response from the TagResource service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/TagResource">REST API Reference for TagResource Operation</seealso>
public virtual TagResourceResponse TagResource(TagResourceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = TagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = TagResourceResponseUnmarshaller.Instance;
return Invoke<TagResourceResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the TagResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the TagResource operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndTagResource
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/TagResource">REST API Reference for TagResource Operation</seealso>
public virtual IAsyncResult BeginTagResource(TagResourceRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = TagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = TagResourceResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the TagResource operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginTagResource.</param>
///
/// <returns>Returns a TagResourceResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/TagResource">REST API Reference for TagResource Operation</seealso>
public virtual TagResourceResponse EndTagResource(IAsyncResult asyncResult)
{
return EndInvoke<TagResourceResponse>(asyncResult);
}
#endregion
#region UntagResource
/// <summary>
/// Removes the specified tags from the specified license configuration.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UntagResource service method.</param>
///
/// <returns>The response from the UntagResource service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/UntagResource">REST API Reference for UntagResource Operation</seealso>
public virtual UntagResourceResponse UntagResource(UntagResourceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UntagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = UntagResourceResponseUnmarshaller.Instance;
return Invoke<UntagResourceResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the UntagResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UntagResource operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUntagResource
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/UntagResource">REST API Reference for UntagResource Operation</seealso>
public virtual IAsyncResult BeginUntagResource(UntagResourceRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = UntagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = UntagResourceResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the UntagResource operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUntagResource.</param>
///
/// <returns>Returns a UntagResourceResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/UntagResource">REST API Reference for UntagResource Operation</seealso>
public virtual UntagResourceResponse EndUntagResource(IAsyncResult asyncResult)
{
return EndInvoke<UntagResourceResponse>(asyncResult);
}
#endregion
#region UpdateLicenseConfiguration
/// <summary>
/// Modifies the attributes of an existing license configuration.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateLicenseConfiguration service method.</param>
///
/// <returns>The response from the UpdateLicenseConfiguration service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ResourceLimitExceededException">
/// Your resource limits have been exceeded.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/UpdateLicenseConfiguration">REST API Reference for UpdateLicenseConfiguration Operation</seealso>
public virtual UpdateLicenseConfigurationResponse UpdateLicenseConfiguration(UpdateLicenseConfigurationRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateLicenseConfigurationRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateLicenseConfigurationResponseUnmarshaller.Instance;
return Invoke<UpdateLicenseConfigurationResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the UpdateLicenseConfiguration operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateLicenseConfiguration operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUpdateLicenseConfiguration
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/UpdateLicenseConfiguration">REST API Reference for UpdateLicenseConfiguration Operation</seealso>
public virtual IAsyncResult BeginUpdateLicenseConfiguration(UpdateLicenseConfigurationRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateLicenseConfigurationRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateLicenseConfigurationResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the UpdateLicenseConfiguration operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateLicenseConfiguration.</param>
///
/// <returns>Returns a UpdateLicenseConfigurationResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/UpdateLicenseConfiguration">REST API Reference for UpdateLicenseConfiguration Operation</seealso>
public virtual UpdateLicenseConfigurationResponse EndUpdateLicenseConfiguration(IAsyncResult asyncResult)
{
return EndInvoke<UpdateLicenseConfigurationResponse>(asyncResult);
}
#endregion
#region UpdateLicenseManagerReportGenerator
/// <summary>
/// Updates a report generator.
///
///
/// <para>
/// After you make changes to a report generator, it will start generating new reports
/// within 60 minutes of being updated.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateLicenseManagerReportGenerator service method.</param>
///
/// <returns>The response from the UpdateLicenseManagerReportGenerator service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ResourceLimitExceededException">
/// Your resource limits have been exceeded.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ResourceNotFoundException">
/// The resource cannot be found.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ValidationException">
/// The provided input is not valid. Try your request again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/UpdateLicenseManagerReportGenerator">REST API Reference for UpdateLicenseManagerReportGenerator Operation</seealso>
public virtual UpdateLicenseManagerReportGeneratorResponse UpdateLicenseManagerReportGenerator(UpdateLicenseManagerReportGeneratorRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateLicenseManagerReportGeneratorRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateLicenseManagerReportGeneratorResponseUnmarshaller.Instance;
return Invoke<UpdateLicenseManagerReportGeneratorResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the UpdateLicenseManagerReportGenerator operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateLicenseManagerReportGenerator operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUpdateLicenseManagerReportGenerator
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/UpdateLicenseManagerReportGenerator">REST API Reference for UpdateLicenseManagerReportGenerator Operation</seealso>
public virtual IAsyncResult BeginUpdateLicenseManagerReportGenerator(UpdateLicenseManagerReportGeneratorRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateLicenseManagerReportGeneratorRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateLicenseManagerReportGeneratorResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the UpdateLicenseManagerReportGenerator operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateLicenseManagerReportGenerator.</param>
///
/// <returns>Returns a UpdateLicenseManagerReportGeneratorResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/UpdateLicenseManagerReportGenerator">REST API Reference for UpdateLicenseManagerReportGenerator Operation</seealso>
public virtual UpdateLicenseManagerReportGeneratorResponse EndUpdateLicenseManagerReportGenerator(IAsyncResult asyncResult)
{
return EndInvoke<UpdateLicenseManagerReportGeneratorResponse>(asyncResult);
}
#endregion
#region UpdateLicenseSpecificationsForResource
/// <summary>
/// Adds or removes the specified license configurations for the specified AWS resource.
///
///
/// <para>
/// You can update the license specifications of AMIs, instances, and hosts. You cannot
/// update the license specifications for launch templates and AWS CloudFormation templates,
/// as they send license configurations to the operation that creates the resource.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateLicenseSpecificationsForResource service method.</param>
///
/// <returns>The response from the UpdateLicenseSpecificationsForResource service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidResourceStateException">
/// License Manager cannot allocate a license to a resource because of its state.
///
///
/// <para>
/// For example, you cannot allocate a license to an instance in the process of shutting
/// down.
/// </para>
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.LicenseUsageException">
/// You do not have enough licenses available to support a new resource launch.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/UpdateLicenseSpecificationsForResource">REST API Reference for UpdateLicenseSpecificationsForResource Operation</seealso>
public virtual UpdateLicenseSpecificationsForResourceResponse UpdateLicenseSpecificationsForResource(UpdateLicenseSpecificationsForResourceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateLicenseSpecificationsForResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateLicenseSpecificationsForResourceResponseUnmarshaller.Instance;
return Invoke<UpdateLicenseSpecificationsForResourceResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the UpdateLicenseSpecificationsForResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateLicenseSpecificationsForResource operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUpdateLicenseSpecificationsForResource
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/UpdateLicenseSpecificationsForResource">REST API Reference for UpdateLicenseSpecificationsForResource Operation</seealso>
public virtual IAsyncResult BeginUpdateLicenseSpecificationsForResource(UpdateLicenseSpecificationsForResourceRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateLicenseSpecificationsForResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateLicenseSpecificationsForResourceResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the UpdateLicenseSpecificationsForResource operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateLicenseSpecificationsForResource.</param>
///
/// <returns>Returns a UpdateLicenseSpecificationsForResourceResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/UpdateLicenseSpecificationsForResource">REST API Reference for UpdateLicenseSpecificationsForResource Operation</seealso>
public virtual UpdateLicenseSpecificationsForResourceResponse EndUpdateLicenseSpecificationsForResource(IAsyncResult asyncResult)
{
return EndInvoke<UpdateLicenseSpecificationsForResourceResponse>(asyncResult);
}
#endregion
#region UpdateServiceSettings
/// <summary>
/// Updates License Manager settings for the current Region.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateServiceSettings service method.</param>
///
/// <returns>The response from the UpdateServiceSettings service method, as returned by LicenseManager.</returns>
/// <exception cref="Amazon.LicenseManager.Model.AccessDeniedException">
/// Access to resource denied.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.AuthorizationException">
/// The AWS user account does not have permission to perform the action. Check the IAM
/// policy associated with this account.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.InvalidParameterValueException">
/// One or more parameter values are not valid.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.RateLimitExceededException">
/// Too many requests have been submitted. Try again after a brief wait.
/// </exception>
/// <exception cref="Amazon.LicenseManager.Model.ServerInternalException">
/// The server experienced an internal error. Try again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/UpdateServiceSettings">REST API Reference for UpdateServiceSettings Operation</seealso>
public virtual UpdateServiceSettingsResponse UpdateServiceSettings(UpdateServiceSettingsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateServiceSettingsRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateServiceSettingsResponseUnmarshaller.Instance;
return Invoke<UpdateServiceSettingsResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the UpdateServiceSettings operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateServiceSettings operation on AmazonLicenseManagerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUpdateServiceSettings
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/UpdateServiceSettings">REST API Reference for UpdateServiceSettings Operation</seealso>
public virtual IAsyncResult BeginUpdateServiceSettings(UpdateServiceSettingsRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateServiceSettingsRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateServiceSettingsResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the UpdateServiceSettings operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateServiceSettings.</param>
///
/// <returns>Returns a UpdateServiceSettingsResult from LicenseManager.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/UpdateServiceSettings">REST API Reference for UpdateServiceSettings Operation</seealso>
public virtual UpdateServiceSettingsResponse EndUpdateServiceSettings(IAsyncResult asyncResult)
{
return EndInvoke<UpdateServiceSettingsResponse>(asyncResult);
}
#endregion
}
} | 58.743317 | 228 | 0.684773 | [
"Apache-2.0"
] | nechemiaseif/aws-sdk-net | sdk/src/Services/LicenseManager/Generated/_bcl35/AmazonLicenseManagerClient.cs | 215,353 | C# |
using System;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace TrainingCenter.QuadraticEquationBenchmark
{
class Program
{
static void Main()
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("ru-RU");
const int equationCount = 45*1000*1000;
Console.WriteLine("Решаем квадратные уравнения: {0:N0}", equationCount);
Console.WriteLine();
BenchmarkWithoutThreads(equationCount);
Console.WriteLine();
BenchmarkWithThreads(equationCount, 2);
BenchmarkWithThreads(equationCount, 3);
BenchmarkWithThreads(equationCount, 4);
Console.WriteLine();
#region ThreadPriority.Highest
//BenchmarkWithThreads(equationCount, 2, ThreadPriority.Highest);
//BenchmarkWithThreads(equationCount, 3, ThreadPriority.Highest);
//BenchmarkWithThreads(equationCount, 4, ThreadPriority.Highest);
//Console.WriteLine();
#endregion
#region Parallel.For
//Console.Write("Время на решение с помощью Parallel.ForEach: ");
//Stopwatch watch = Stopwatch.StartNew();
//var equations = (new RandomCoeffEnumerator()).Take(equationCount);
//Parallel.ForEach(
// equations,
// new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount },
// eq => { Equation tempEq = eq; Solve(ref tempEq); }
//);
//watch.Stop();
//Console.WriteLine("{0:F4} сек.", watch.Elapsed.TotalSeconds);
#endregion
}
/// <summary>
/// Замеряет и выводит на экран время потраченное на решение уравнений без использования потоков
/// </summary>
/// <param name="equationCount">Количество уравнений которые необходимо решить</param>
//private static void BenchmarkWithoutThreads(Equation[] equations)
private static void BenchmarkWithoutThreads(int equationCount)
{
Console.Write("Время на решение без потоков: ");
var coeffEnumerator = new RandomCoeffEnumerator().GetEnumerator();
Stopwatch watch = Stopwatch.StartNew();
for (int i = 0; i < equationCount; i++)
{
coeffEnumerator.MoveNext();
Equation eq = coeffEnumerator.Current;
Solve(ref eq);
}
watch.Stop();
Console.WriteLine("{0:F4} сек.", watch.Elapsed.TotalSeconds);
}
/// <summary>
/// Замеряет и выводит на экран время потраченное на решение уравнений с использованием потоков
/// </summary>
/// <param name="totalEquationCount">Общее количество уравнений которые необходимо решить. Делится между потоками</param>
/// <param name="threadCount">Кол-во потоков которые следует использовать для параллельного решения уравнений</param>
/// <param name="priority">Приоритет потока</param>
private static void BenchmarkWithThreads(int totalEquationCount, int threadCount, ThreadPriority priority = ThreadPriority.Normal)
{
if (totalEquationCount % threadCount != 0) throw new Exception();
Console.Write("Время на решение с потоками: ");
int itemsPerThread = totalEquationCount / threadCount; // Кол-во уравнений для каждого потока
Stopwatch watch = Stopwatch.StartNew();
Thread[] solveThreads = new Thread[threadCount];
for (int i = 0, offset = 0; i < solveThreads.Length; i++, offset += itemsPerThread)
{
solveThreads[i] = new Thread(SolveThread)
{
Name = String.Format("Решатель уравнений #{0}", i + 1),
Priority = priority
};
solveThreads[i].Start(itemsPerThread);
}
foreach (Thread solveThread in solveThreads)
{
solveThread.Join();
}
watch.Stop();
Console.WriteLine("{0:F4} сек. Кол-во потоков: {1}. Приоритет: {2}", watch.Elapsed.TotalSeconds, threadCount, PriorityToString(priority));
}
static string PriorityToString(ThreadPriority priority)
{
switch (priority)
{
case ThreadPriority.Lowest:
return "Самый низкий";
case ThreadPriority.BelowNormal:
return "Ниже нормального";
case ThreadPriority.Normal:
return "Нормальный";
case ThreadPriority.AboveNormal:
return "Выше нормального";
case ThreadPriority.Highest:
return "Самый высокий";
default:
return priority.ToString();
}
}
/// <summary>
/// Решение квадратного уравнения с двумя коэффециентами
/// </summary>
/// <param name="equation"></param>
static void Solve(ref Equation equation)
{
if (equation.B > 0 || equation.B < 0)
{
double d = equation.B*equation.B; // Дискриминант
double sqrt_d = Math.Sqrt(d);
double a2 = 2*equation.A;
equation.Solution1 = (sqrt_d - equation.B)/a2;
equation.Solution2 = (-equation.B - sqrt_d)/a2;
}
else
{
equation.Solution1 = equation.Solution2 = -equation.B/(2*equation.A);
}
}
static void SolveThread(object data)
{
int equationCount = (int)data;
var coeffEnumerator = new RandomCoeffEnumerator().GetEnumerator();
for (int i = 0; i < equationCount; i++)
{
coeffEnumerator.MoveNext();
Equation eq = coeffEnumerator.Current;
Solve(ref eq);
}
}
}
}
| 38.528302 | 150 | 0.566275 | [
"MIT"
] | bazile/Training | CSharp/L08-S02-Threads/ThreadsDemo-06.QuadraticEquationBenchmark/Program.cs | 6,774 | C# |
using WebGL;
namespace THREE
{
public class CubeGeometry : Geometry
{
public readonly double width;
public readonly double height;
public readonly double depth;
public readonly int widthSegments;
public readonly int heightSegments;
public readonly int depthSegments;
public CubeGeometry(double width, double height, double depth,
int widthSegments = 1, int heightSegments = 1, int depthSegments = 1)
{
this.width = width;
this.height = height;
this.depth = depth;
this.widthSegments = widthSegments;
this.heightSegments = heightSegments;
this.depthSegments = depthSegments;
var width_half = this.width / 2;
var height_half = this.height / 2;
var depth_half = this.depth / 2;
buildPlane('z', 'y', - 1, - 1, this.depth, this.height, width_half, 0);
buildPlane('z', 'y', 1, - 1, this.depth, this.height, - width_half, 1);
buildPlane('x', 'z', 1, 1, this.width, this.depth, height_half, 2);
buildPlane('x', 'z', 1, - 1, this.width, this.depth, - height_half, 3);
buildPlane('x', 'y', 1, - 1, this.width, this.height, depth_half, 4);
buildPlane('x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5);
computeCentroids();
mergeVertices();
}
private void buildPlane(char u, char v, double udir, double vdir, double width, double height, double depth, int materialIndex)
{
var w = 'x';
int ix;
int iy;
var gridX = widthSegments;
var gridY = heightSegments;
var width_half = width / 2;
var height_half = height / 2;
var offset = vertices.length;
if ((u == 'x' && v == 'y') || (u == 'y' && v == 'x'))
{
w = 'z';
}
else if ((u == 'x' && v == 'z') || (u == 'z' && v == 'x'))
{
w = 'y';
gridY = depthSegments;
}
else if ((u == 'z' && v == 'y') || (u == 'y' && v == 'z'))
{
w = 'x';
gridX = depthSegments;
}
var gridX1 = gridX + 1;
var gridY1 = gridY + 1;
var segment_width = width / gridX;
var segment_height = height / gridY;
var normal = new Vector3();
normal[w] = depth > 0 ? 1 : - 1;
for (iy = 0; iy < gridY1; iy++)
{
for (ix = 0; ix < gridX1; ix++)
{
var vector = new Vector3();
vector[u] = (ix * segment_width - width_half) * udir;
vector[v] = (iy * segment_height - height_half) * vdir;
vector[w] = depth;
vertices.push(vector);
}
}
for (iy = 0; iy < gridY; iy++)
{
for (ix = 0; ix < gridX; ix++)
{
var a = ix + gridX1 * iy;
var b = ix + gridX1 * (iy + 1);
var c = (ix + 1) + gridX1 * (iy + 1);
var d = (ix + 1) + gridX1 * iy;
var face = new Face4(a + offset, b + offset, c + offset, d + offset);
face.normal.copy(normal);
face.vertexNormals.push(normal.clone(), normal.clone(), normal.clone(), normal.clone());
face.materialIndex = materialIndex;
faces.push(face);
faceVertexUvs[0].push(new JSArray(
new Vector2(ix / (double)gridX, 1 - iy / (double)gridY),
new Vector2(ix / (double)gridX, 1 - (iy + 1) / (double)gridY),
new Vector2((ix + 1) / (double)gridX, 1 - (iy + 1) / (double)gridY),
new Vector2((ix + 1) / (double)gridX, 1 - iy / (double)gridY)));
}
}
}
}
}
| 29.464286 | 129 | 0.558182 | [
"Apache-2.0"
] | jdarc/webgl.net | THREE/Extras/Geometries/CubeGeometry.cs | 3,302 | C# |
// Copyright (c) Autofac Project. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Diagnostics;
using Autofac.Diagnostics;
namespace Autofac;
/// <summary>
/// Extensions to the container to provide convenience methods for tracing.
/// </summary>
public static class ContainerExtensions
{
/// <summary>
/// Subscribes a diagnostic tracer to Autofac events.
/// </summary>
/// <param name="container">The container with the diagnostics to which you want to subscribe.</param>
/// <param name="tracer">A diagnostic tracer that will be subscribed to the lifetime scope's diagnostic source.</param>
/// <remarks>
/// <para>
/// This is a convenience method that attaches the <paramref name="tracer"/> to the
/// <see cref="DiagnosticListener"/> associated with the <paramref name="container"/>. If you
/// have an event listener that isn't a <see cref="DiagnosticTracerBase"/> you can
/// use standard <see cref="DiagnosticListener"/> semantics to subscribe to the events
/// with your custom listener.
/// </para>
/// </remarks>
public static void SubscribeToDiagnostics(this IContainer container, DiagnosticTracerBase tracer)
{
if (container is null)
{
throw new ArgumentNullException(nameof(container));
}
if (tracer is null)
{
throw new ArgumentNullException(nameof(tracer));
}
container.DiagnosticSource.Subscribe(tracer, tracer.IsEnabled);
}
/// <summary>
/// Subscribes a diagnostic tracer to Autofac events.
/// </summary>
/// <typeparam name="T">
/// The type of diagnostic tracer that will be subscribed to the lifetime scope's diagnostic source.
/// </typeparam>
/// <param name="container">The container with the diagnostics to which you want to subscribe.</param>
/// <returns>
/// The diagnostic tracer that was created and attached to the diagnostic source. Use
/// this instance to enable or disable the messages that should be handled.
/// </returns>
/// <remarks>
/// <para>
/// This is a convenience method that attaches a tracer to the
/// <see cref="DiagnosticListener"/> associated with the <paramref name="container"/>. If you
/// have an event listener that isn't a <see cref="DiagnosticTracerBase"/> you can
/// use standard <see cref="DiagnosticListener"/> semantics to subscribe to the events
/// with your custom listener.
/// </para>
/// </remarks>
public static T SubscribeToDiagnostics<T>(this IContainer container)
where T : DiagnosticTracerBase, new()
{
if (container is null)
{
throw new ArgumentNullException(nameof(container));
}
var tracer = new T();
container.SubscribeToDiagnostics(tracer);
return tracer;
}
}
| 38.657895 | 123 | 0.663376 | [
"MIT"
] | rcdailey/Autofac | src/Autofac/ContainerExtensions.cs | 2,940 | C# |
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
using System.ComponentModel;
namespace WeifenLuo.WinFormsUI.Docking
{
public class InertButton : Button
{
private enum RepeatClickStatus
{
Disabled,
Started,
Repeating,
Stopped
}
private class RepeatClickEventArgs : EventArgs
{
private static RepeatClickEventArgs _empty;
static RepeatClickEventArgs()
{
_empty = new RepeatClickEventArgs();
}
public new static RepeatClickEventArgs Empty
{
get { return _empty; }
}
}
private IContainer components = new Container();
private int m_borderWidth = 1;
private bool m_mouseOver = false;
private bool m_mouseCapture = false;
private bool m_isPopup = false;
private Image m_imageEnabled = null;
private Image m_imageDisabled = null;
private int m_imageIndexEnabled = -1;
private int m_imageIndexDisabled = -1;
private bool m_monochrom = true;
private ToolTip m_toolTip = null;
private string m_toolTipText = "";
private Color m_borderColor = Color.Empty;
public InertButton()
{
InternalConstruct(null, null);
}
public InertButton(Image imageEnabled)
{
InternalConstruct(imageEnabled, null);
}
public InertButton(Image imageEnabled, Image imageDisabled)
{
InternalConstruct(imageEnabled, imageDisabled);
}
private void InternalConstruct(Image imageEnabled, Image imageDisabled)
{
// Remember parameters
ImageEnabled = imageEnabled;
ImageDisabled = imageDisabled;
// Prevent drawing flicker by blitting from memory in WM_PAINT
SetStyle(ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
// Prevent base class from trying to generate double click events and
// so testing clicks against the double click time and rectangle. Getting
// rid of this allows the user to press then release button very quickly.
//SetStyle(ControlStyles.StandardDoubleClick, false);
// Should not be allowed to select this control
SetStyle(ControlStyles.Selectable, false);
m_timer = new Timer();
m_timer.Enabled = false;
m_timer.Tick += new EventHandler(Timer_Tick);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
components.Dispose();
}
base.Dispose(disposing);
}
public Color BorderColor
{
get { return m_borderColor; }
set
{
if (m_borderColor != value)
{
m_borderColor = value;
Invalidate();
}
}
}
private bool ShouldSerializeBorderColor()
{
return (m_borderColor != Color.Empty);
}
public int BorderWidth
{
get { return m_borderWidth; }
set
{
if (value < 1)
value = 1;
if (m_borderWidth != value)
{
m_borderWidth = value;
Invalidate();
}
}
}
public Image ImageEnabled
{
get
{
if (m_imageEnabled != null)
return m_imageEnabled;
try
{
if (ImageList == null || ImageIndexEnabled == -1)
return null;
else
return ImageList.Images[m_imageIndexEnabled];
}
catch
{
return null;
}
}
set
{
if (m_imageEnabled != value)
{
m_imageEnabled = value;
Invalidate();
}
}
}
private bool ShouldSerializeImageEnabled()
{
return (m_imageEnabled != null);
}
public Image ImageDisabled
{
get
{
if (m_imageDisabled != null)
return m_imageDisabled;
try
{
if (ImageList == null || ImageIndexDisabled == -1)
return null;
else
return ImageList.Images[m_imageIndexDisabled];
}
catch
{
return null;
}
}
set
{
if (m_imageDisabled != value)
{
m_imageDisabled = value;
Invalidate();
}
}
}
public int ImageIndexEnabled
{
get { return m_imageIndexEnabled; }
set
{
if (m_imageIndexEnabled != value)
{
m_imageIndexEnabled = value;
Invalidate();
}
}
}
public int ImageIndexDisabled
{
get { return m_imageIndexDisabled; }
set
{
if (m_imageIndexDisabled != value)
{
m_imageIndexDisabled = value;
Invalidate();
}
}
}
public bool IsPopup
{
get { return m_isPopup; }
set
{
if (m_isPopup != value)
{
m_isPopup = value;
Invalidate();
}
}
}
public bool Monochrome
{
get { return m_monochrom; }
set
{
if (value != m_monochrom)
{
m_monochrom = value;
Invalidate();
}
}
}
public bool RepeatClick
{
get { return (ClickStatus != RepeatClickStatus.Disabled); }
set { ClickStatus = RepeatClickStatus.Stopped; }
}
private RepeatClickStatus m_clickStatus = RepeatClickStatus.Disabled;
private RepeatClickStatus ClickStatus
{
get { return m_clickStatus; }
set
{
if (m_clickStatus == value)
return;
m_clickStatus = value;
if (ClickStatus == RepeatClickStatus.Started)
{
Timer.Interval = RepeatClickDelay;
Timer.Enabled = true;
}
else if (ClickStatus == RepeatClickStatus.Repeating)
Timer.Interval = RepeatClickInterval;
else
Timer.Enabled = false;
}
}
private int m_repeatClickDelay = 500;
public int RepeatClickDelay
{
get { return m_repeatClickDelay; }
set { m_repeatClickDelay = value; }
}
private int m_repeatClickInterval = 100;
public int RepeatClickInterval
{
get { return m_repeatClickInterval; }
set { m_repeatClickInterval = value; }
}
private Timer m_timer;
private Timer Timer
{
get { return m_timer; }
}
public string ToolTipText
{
get { return m_toolTipText; }
set
{
if (m_toolTipText != value)
{
if (m_toolTip == null)
m_toolTip = new ToolTip(this.components);
m_toolTipText = value;
m_toolTip.SetToolTip(this, value);
}
}
}
private void Timer_Tick(object sender, EventArgs e)
{
if (m_mouseCapture && m_mouseOver)
OnClick(RepeatClickEventArgs.Empty);
if (ClickStatus == RepeatClickStatus.Started)
ClickStatus = RepeatClickStatus.Repeating;
}
/// <exclude/>
protected override void OnMouseDown(MouseEventArgs mevent)
{
base.OnMouseDown(mevent);
if (mevent.Button != MouseButtons.Left)
return;
if (m_mouseCapture == false || m_mouseOver == false)
{
m_mouseCapture = true;
m_mouseOver = true;
//Redraw to show button state
Invalidate();
}
if (RepeatClick)
{
OnClick(RepeatClickEventArgs.Empty);
ClickStatus = RepeatClickStatus.Started;
}
}
/// <exclude/>
protected override void OnClick(EventArgs e)
{
if (RepeatClick && !(e is RepeatClickEventArgs))
return;
base.OnClick (e);
}
/// <exclude/>
protected override void OnMouseUp(MouseEventArgs mevent)
{
base.OnMouseUp(mevent);
if (mevent.Button != MouseButtons.Left)
return;
if (m_mouseOver == true || m_mouseCapture == true)
{
m_mouseOver = false;
m_mouseCapture = false;
// Redraw to show button state
Invalidate();
}
if (RepeatClick)
ClickStatus = RepeatClickStatus.Stopped;
}
/// <exclude/>
protected override void OnMouseMove(MouseEventArgs mevent)
{
base.OnMouseMove(mevent);
// Is mouse point inside our client rectangle
bool over = this.ClientRectangle.Contains(new Point(mevent.X, mevent.Y));
// If entering the button area or leaving the button area...
if (over != m_mouseOver)
{
// Update state
m_mouseOver = over;
// Redraw to show button state
Invalidate();
}
}
/// <exclude/>
protected override void OnMouseEnter(EventArgs e)
{
// Update state to reflect mouse over the button area
if (!m_mouseOver)
{
m_mouseOver = true;
// Redraw to show button state
Invalidate();
}
base.OnMouseEnter(e);
}
/// <exclude/>
protected override void OnMouseLeave(EventArgs e)
{
// Update state to reflect mouse not over the button area
if (m_mouseOver)
{
m_mouseOver = false;
// Redraw to show button state
Invalidate();
}
base.OnMouseLeave(e);
}
/// <exclude/>
protected override void OnPaint(PaintEventArgs pevent)
{
base.OnPaint(pevent);
DrawBackground(pevent.Graphics);
DrawImage(pevent.Graphics);
DrawText(pevent.Graphics);
DrawBorder(pevent.Graphics);
}
private void DrawBackground(Graphics g)
{
using (SolidBrush brush = new SolidBrush(BackColor))
{
g.FillRectangle(brush, ClientRectangle);
}
}
private void DrawImage(Graphics g)
{
Image image = this.Enabled ? ImageEnabled : ((ImageDisabled != null) ? ImageDisabled : ImageEnabled);
ImageAttributes imageAttr = null;
if (null == image)
return;
if (m_monochrom)
{
imageAttr = new ImageAttributes();
// transform the monochrom image
// white -> BackColor
// black -> ForeColor
ColorMap[] colorMap = new ColorMap[2];
colorMap[0] = new ColorMap();
colorMap[0].OldColor = Color.White;
colorMap[0].NewColor = this.BackColor;
colorMap[1] = new ColorMap();
colorMap[1].OldColor = Color.Black;
colorMap[1].NewColor = this.ForeColor;
imageAttr.SetRemapTable(colorMap);
}
Rectangle rect = new Rectangle(0, 0, image.Width, image.Height);
if ((!Enabled) && (null == ImageDisabled))
{
using (Bitmap bitmapMono = new Bitmap(image, ClientRectangle.Size))
{
if (imageAttr != null)
{
using (Graphics gMono = Graphics.FromImage(bitmapMono))
{
gMono.DrawImage(image, new Point[3] { new Point(0, 0), new Point(image.Width - 1, 0), new Point(0, image.Height - 1) }, rect, GraphicsUnit.Pixel, imageAttr);
}
}
ControlPaint.DrawImageDisabled(g, bitmapMono, 0, 0, this.BackColor);
}
}
else
{
// Three points provided are upper-left, upper-right and
// lower-left of the destination parallelogram.
Point[] pts = new Point[3];
pts[0].X = (Enabled && m_mouseOver && m_mouseCapture) ? 1 : 0;
pts[0].Y = (Enabled && m_mouseOver && m_mouseCapture) ? 1 : 0;
pts[1].X = pts[0].X + ClientRectangle.Width;
pts[1].Y = pts[0].Y;
pts[2].X = pts[0].X;
pts[2].Y = pts[1].Y + ClientRectangle.Height;
if (imageAttr == null)
g.DrawImage(image, pts, rect, GraphicsUnit.Pixel);
else
g.DrawImage(image, pts, rect, GraphicsUnit.Pixel, imageAttr);
}
}
private void DrawText(Graphics g)
{
if (Text == string.Empty)
return;
Rectangle rect = ClientRectangle;
rect.X += BorderWidth;
rect.Y += BorderWidth;
rect.Width -= 2 * BorderWidth;
rect.Height -= 2 * BorderWidth;
StringFormat stringFormat = new StringFormat();
if (TextAlign == ContentAlignment.TopLeft)
{
stringFormat.Alignment = StringAlignment.Near;
stringFormat.LineAlignment = StringAlignment.Near;
}
else if (TextAlign == ContentAlignment.TopCenter)
{
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Near;
}
else if (TextAlign == ContentAlignment.TopRight)
{
stringFormat.Alignment = StringAlignment.Far;
stringFormat.LineAlignment = StringAlignment.Near;
}
else if (TextAlign == ContentAlignment.MiddleLeft)
{
stringFormat.Alignment = StringAlignment.Near;
stringFormat.LineAlignment = StringAlignment.Center;
}
else if (TextAlign == ContentAlignment.MiddleCenter)
{
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Center;
}
else if (TextAlign == ContentAlignment.MiddleRight)
{
stringFormat.Alignment = StringAlignment.Far;
stringFormat.LineAlignment = StringAlignment.Center;
}
else if (TextAlign == ContentAlignment.BottomLeft)
{
stringFormat.Alignment = StringAlignment.Near;
stringFormat.LineAlignment = StringAlignment.Far;
}
else if (TextAlign == ContentAlignment.BottomCenter)
{
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Far;
}
else if (TextAlign == ContentAlignment.BottomRight)
{
stringFormat.Alignment = StringAlignment.Far;
stringFormat.LineAlignment = StringAlignment.Far;
}
using (Brush brush = new SolidBrush(ForeColor))
{
g.DrawString(Text, Font, brush, rect, stringFormat);
}
}
private void DrawBorder(Graphics g)
{
ButtonBorderStyle bs;
// Decide on the type of border to draw around image
if (!this.Enabled)
bs = IsPopup ? ButtonBorderStyle.Outset : ButtonBorderStyle.Solid;
else if (m_mouseOver && m_mouseCapture)
bs = ButtonBorderStyle.Inset;
else if (IsPopup || m_mouseOver)
bs = ButtonBorderStyle.Outset;
else
bs = ButtonBorderStyle.Solid;
Color colorLeftTop;
Color colorRightBottom;
if (bs == ButtonBorderStyle.Solid)
{
colorLeftTop = this.BackColor;
colorRightBottom = this.BackColor;
}
else if (bs == ButtonBorderStyle.Outset)
{
colorLeftTop = m_borderColor.IsEmpty ? this.BackColor : m_borderColor;
colorRightBottom = this.BackColor;
}
else
{
colorLeftTop = this.BackColor;
colorRightBottom = m_borderColor.IsEmpty ? this.BackColor : m_borderColor;
}
ControlPaint.DrawBorder(g, this.ClientRectangle,
colorLeftTop, m_borderWidth, bs,
colorLeftTop, m_borderWidth, bs,
colorRightBottom, m_borderWidth, bs,
colorRightBottom, m_borderWidth, bs);
}
/// <exclude/>
protected override void OnEnabledChanged(EventArgs e)
{
base.OnEnabledChanged(e);
if (Enabled == false)
{
m_mouseOver = false;
m_mouseCapture = false;
if (RepeatClick && ClickStatus != RepeatClickStatus.Stopped)
ClickStatus = RepeatClickStatus.Stopped;
}
Invalidate();
}
}
} | 31.806139 | 186 | 0.465106 | [
"MIT"
] | LJunJoy/NetworkDesigner | WinFormsUI/Docking/InertButton.cs | 19,070 | C# |
using OpenQA.Selenium;
using RuriLib.Functions.Files;
using RuriLib.LS;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Windows.Media;
namespace RuriLib
{
/// <summary>
/// The available ways to address an element.
/// </summary>
public enum ElementLocator
{
/// <summary>The id of the element.</summary>
Id,
/// <summary>The class of the element.</summary>
Class,
/// <summary>The name of the element.</summary>
Name,
/// <summary>The tag of the element.</summary>
Tag,
/// <summary>The CSS selector of the element.</summary>
Selector,
/// <summary>The xpath of the element.</summary>
XPath
}
/// <summary>
/// The actions that can be performed on an element.
/// </summary>
public enum ElementAction
{
/// <summary>Clears the text of an input element.</summary>
Clear,
/// <summary>Sends keystrokes to an input element.</summary>
SendKeys,
/// <summary>Types keystrokes into an input element with random delays between each keystroke, like a human would.</summary>
SendKeysHuman,
/// <summary>Clicks an element.</summary>
Click,
/// <summary>Submits a form element.</summary>
Submit,
/// <summary>Gets the text inside an element.</summary>
GetText,
/// <summary>Gets a given attribute of an element.</summary>
GetAttribute,
/// <summary>Checks if the element is currently displayed on the page.</summary>
IsDisplayed,
/// <summary>Checks if the element is enabled on the page.</summary>
IsEnabled,
/// <summary>Checks if the element is selected.</summary>
IsSelected,
/// <summary>Retrieves the X coordinate of the top-left corner of the element.</summary>
LocationX,
/// <summary>Retrieves the Y coordinate of the top-left corner of the element.</summary>
LocationY,
/// <summary>Retrieves the width of the element.</summary>
SizeX,
/// <summary>Retrieves the height of the element.</summary>
SizeY,
/// <summary>Takes a screenshot of the element.</summary>
Screenshot,
/// <summary>Switches to the iframe element.</summary>
SwitchToFrame,
/// <summary>Waits until the element appears in the DOM (up to a specified timeout).</summary>
WaitForElement
}
/// <summary>
/// A block that can perform an action on an element inside an HTML page.
/// </summary>
public class SBlockElementAction : BlockBase
{
private ElementLocator locator = ElementLocator.Id;
/// <summary>The element locator.</summary>
public ElementLocator Locator { get { return locator; } set { locator = value; OnPropertyChanged(); } }
private string elementString = "";
/// <summary>The value of the locator.</summary>
public string ElementString { get { return elementString; } set { elementString = value; OnPropertyChanged(); } }
private int elementIndex = 0;
/// <summary>The index of the element in case the locator matches more than one.</summary>
public int ElementIndex { get { return elementIndex; } set { elementIndex = value; OnPropertyChanged(); } }
private ElementAction action = ElementAction.Clear;
/// <summary>The action to be performed on the element.</summary>
public ElementAction Action { get { return action; } set { action = value; OnPropertyChanged(); } }
private string input = "";
/// <summary>The input data.</summary>
public string Input { get { return input; } set { input = value; OnPropertyChanged(); } }
private string outputVariable = "";
/// <summary>The name of the output variable.</summary>
public string OutputVariable { get { return outputVariable; } set { outputVariable = value; OnPropertyChanged(); } }
private bool isCapture = false;
/// <summary>Whether the output variable should be marked for Capture.</summary>
public bool IsCapture { get { return isCapture; } set { isCapture = value; OnPropertyChanged(); } }
private bool recursive = false;
/// <summary>Whether the GetText and GetAttribute actions should be executed on all the elements matched by the locator and return a list of values.</summary>
public bool Recursive { get { return recursive; } set { recursive = value; OnPropertyChanged(); } }
/// <summary>
/// Creates an element action block.
/// </summary>
public SBlockElementAction()
{
Label = "ELEMENT ACTION";
}
/// <inheritdoc />
public override BlockBase FromLS(string line)
{
// Trim the line
var input = line.Trim();
// Parse the label
if (input.StartsWith("#"))
Label = LineParser.ParseLabel(ref input);
/*
* Syntax:
* ELEMENTACTION ID "id" 0 RECURSIVE? ACTION ["INPUT"] [-> VAR/CAP "OUTPUT"]
* */
Locator = (ElementLocator)LineParser.ParseEnum(ref input, "LOCATOR", typeof(ElementLocator));
ElementString = LineParser.ParseLiteral(ref input, "STRING");
if (LineParser.Lookahead(ref input) == TokenType.Boolean)
LineParser.SetBool(ref input, this);
else if (LineParser.Lookahead(ref input) == TokenType.Integer)
ElementIndex = LineParser.ParseInt(ref input, "INDEX");
Action = (ElementAction)LineParser.ParseEnum(ref input, "ACTION", typeof(ElementAction));
if (input == "") return this;
if (LineParser.Lookahead(ref input) == TokenType.Literal)
Input = LineParser.ParseLiteral(ref input, "INPUT");
// Try to parse the arrow, otherwise just return the block as is with default var name and var / cap choice
if (LineParser.ParseToken(ref input, TokenType.Arrow, false) == "")
return this;
// Parse the VAR / CAP
try
{
var varType = LineParser.ParseToken(ref input, TokenType.Parameter, true);
if (varType.ToUpper() == "VAR" || varType.ToUpper() == "CAP")
IsCapture = varType.ToUpper() == "CAP";
}
catch { throw new ArgumentException("Invalid or missing variable type"); }
// Parse the variable/capture name
try { OutputVariable = LineParser.ParseToken(ref input, TokenType.Literal, true); }
catch { throw new ArgumentException("Variable name not specified"); }
return this;
}
/// <inheritdoc />
public override string ToLS(bool indent = true)
{
var writer = new BlockWriter(GetType(), indent, Disabled);
writer
.Label(Label)
.Token("ELEMENTACTION")
.Token(Locator)
.Literal(ElementString);
if (Recursive) writer.Boolean(Recursive, "Recursive");
else if (ElementIndex != 0) writer.Integer(ElementIndex, "ElementIndex");
writer
.Indent()
.Token(Action)
.Literal(Input, "Input");
if (!writer.CheckDefault(OutputVariable, "OutputVariable"))
{
writer
.Arrow()
.Token(IsCapture ? "CAP" : "VAR")
.Literal(OutputVariable);
}
return writer.ToString();
}
/// <inheritdoc />
public override void Process(BotData data)
{
base.Process(data);
if (data.Driver == null)
{
data.Log(new LogEntry("Open a browser first!", Colors.White));
throw new Exception("Browser not open");
}
// Find the element
IWebElement element = null;
ReadOnlyCollection<IWebElement> elements = null;
try
{
if(action != ElementAction.WaitForElement)
{
elements = FindElements(data);
element = elements[elementIndex];
}
}
catch { data.Log(new LogEntry("Cannot find element on the page", Colors.White)); }
List<string> outputs = new List<string>();
try
{
switch (action)
{
case ElementAction.Clear:
element.Clear();
break;
case ElementAction.SendKeys:
element.SendKeys(ReplaceValues(input, data));
break;
case ElementAction.Click:
element.Click();
UpdateSeleniumData(data);
break;
case ElementAction.Submit:
element.Submit();
UpdateSeleniumData(data);
break;
case ElementAction.GetText:
if (recursive) foreach (var elem in elements) outputs.Add(elem.Text);
else outputs.Add(element.Text);
break;
case ElementAction.GetAttribute:
if (recursive) foreach (var elem in elements) outputs.Add(elem.GetAttribute(ReplaceValues(input, data)));
else outputs.Add(element.GetAttribute(ReplaceValues(input, data)));
break;
case ElementAction.IsDisplayed:
outputs.Add(element.Displayed.ToString());
break;
case ElementAction.IsEnabled:
outputs.Add(element.Enabled.ToString());
break;
case ElementAction.IsSelected:
outputs.Add(element.Selected.ToString());
break;
case ElementAction.LocationX:
outputs.Add(element.Location.X.ToString());
break;
case ElementAction.LocationY:
outputs.Add(element.Location.Y.ToString());
break;
case ElementAction.SizeX:
outputs.Add(element.Size.Width.ToString());
break;
case ElementAction.SizeY:
outputs.Add(element.Size.Height.ToString());
break;
case ElementAction.Screenshot:
var image = GetElementScreenShot(data.Driver, element);
Files.SaveScreenshot(image, data);
break;
case ElementAction.SwitchToFrame:
data.Driver.SwitchTo().Frame(element);
break;
case ElementAction.WaitForElement:
var ms = 0; // Currently waited milliseconds
var max = 10000;
try { max = int.Parse(input) * 1000; } catch { }// Max ms to wait
var found = false;
while(ms < max)
{
try
{
elements = FindElements(data);
element = elements[0];
found = true;
break;
}
catch { ms += 200; Thread.Sleep(200); }
}
if (!found) { data.Log(new LogEntry("Timeout while waiting for element", Colors.White)); }
break;
case ElementAction.SendKeysHuman:
var toSend = ReplaceValues(input, data);
var rand = new Random();
foreach(char c in toSend) {
element.SendKeys(c.ToString());
Thread.Sleep(rand.Next(100, 300));
}
break;
}
}
catch { data.Log(new LogEntry("Cannot execute action on the element", Colors.White)); }
data.Log(new LogEntry(string.Format("Executed action {0} on the element with input {1}", action, ReplaceValues(input, data)), Colors.White));
if (outputs.Count != 0)
{
InsertVariables(data, isCapture, recursive, outputs, outputVariable, "", "", false, true);
}
}
/// <summary>
/// Screenshots an element on the page.
/// </summary>
/// <param name="driver">The selenium driver</param>
/// <param name="element">The element to screenshot</param>
/// <returns>The bitmap screenshot of the element</returns>
public static Bitmap GetElementScreenShot(IWebDriver driver, IWebElement element)
{
Screenshot sc = ((ITakesScreenshot)driver).GetScreenshot();
var img = Image.FromStream(new MemoryStream(sc.AsByteArray)) as Bitmap;
return img.Clone(new Rectangle(element.Location, element.Size), img.PixelFormat);
}
private ReadOnlyCollection<IWebElement> FindElements(BotData data)
{
switch (locator)
{
case ElementLocator.Id:
return data.Driver.FindElements(By.Id(ReplaceValues(elementString, data)));
case ElementLocator.Class:
return data.Driver.FindElements(By.ClassName(ReplaceValues(elementString, data)));
case ElementLocator.Name:
return data.Driver.FindElements(By.Name(ReplaceValues(elementString, data)));
case ElementLocator.Tag:
return data.Driver.FindElements(By.TagName(ReplaceValues(elementString, data)));
case ElementLocator.Selector:
return data.Driver.FindElements(By.CssSelector(ReplaceValues(elementString, data)));
case ElementLocator.XPath:
return data.Driver.FindElements(By.XPath(ReplaceValues(elementString, data)));
default:
return null;
}
}
}
}
| 38.023077 | 166 | 0.533684 | [
"MIT"
] | Area51Crew/OB-M2-Browning | RuriLib/Blocks/SBlockElementAction.cs | 14,831 | C# |
//
// UnityOSC - Open Sound Control interface for the Unity3d game engine
//
// Copyright (c) 2012 Jorge Garcia Martin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.Net;
using UnityEngine;
#if NETFX_CORE
using Windows.Networking;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
#else
using System.Net.Sockets;
#endif
namespace UnityOSC
{
/// <summary>
/// Dispatches OSC messages to the specified destination address and port.
/// </summary>
public class OSCClient
{
#region Constructors
public OSCClient (IPAddress address, int port)
{
_ipAddress = address;
_port = port;
Connect();
}
#endregion
#region Member Variables
private IPAddress _ipAddress;
private int _port;
#if NETFX_CORE
DatagramSocket socket;
HostName _hostname;
#else
private UdpClient _udpClient;
#endif
#endregion
#region Properties
public IPAddress ClientIPAddress
{
get
{
return _ipAddress;
}
}
public int Port
{
get
{
return _port;
}
}
#endregion
#region Methods
/// <summary>
/// Connects the client to a given remote address and port.
/// </summary>
public void Connect()
{
#if NETFX_CORE
Debug.Log("OSCClient Connect start...");
_hostname = new HostName(_ipAddress.ToString());
socket = new DatagramSocket();
Debug.Log("exit start:"+_ipAddress.ToString());
#else
if(_udpClient != null) Close();
_udpClient = new UdpClient();
try
{
_udpClient.Connect(_ipAddress, _port);
}
catch
{
throw new Exception(String.Format("Can't create client at IP address {0} and port {1}.", _ipAddress,_port));
}
#endif
}
public void Flush() {
#if NETFX_CORE
//socket.Flush();
#else
if (_udpClient != null) {
//_udpClient.Client.SetSocketOption(SocketOptionLevel.Udp, SocketOptionName.DontLinger, true );
}
#endif
}
/// <summary>
/// Closes the client.
/// </summary>
public void Close()
{
#if NETFX_CORE
socket.Dispose();
Debug.Log("OSC CLIENT UWP CLOSE");
#else
_udpClient.Close();
_udpClient = null;
#endif
}
/// <summary>
/// Sends an OSC packet to the defined destination and address of the client.
/// </summary>
/// <param name="packet">
/// A <see cref="OSCPacket"/>
/// </param>
#if NETFX_CORE
public async void Send(OSCPacket packet)
{
byte[] data = packet.BinaryData;
//Debug.Log("OSCCLIENT-SEND:" + System.Text.Encoding.ASCII.GetString(data));
using (var writer = new DataWriter(await socket.GetOutputStreamAsync(_hostname, _port.ToString()))){
try
{
writer.WriteBytes(data);
await writer.StoreAsync();
}
catch
{
throw new Exception(String.Format("Can't send OSC packet to client {0} : {1}:Length{2}", _ipAddress, _port,data.Length));
}
}
}
#else
public void Send(OSCPacket packet)
{
byte[] data = packet.BinaryData;
try
{
_udpClient.Send(data, data.Length);
}
catch
{
throw new Exception(String.Format("Can't send OSC packet to client {0} : {1}", _ipAddress, _port));
}
}
#endif
#endregion
}
}
| 23.892655 | 126 | 0.672736 | [
"MIT"
] | hku-ect/UnityVRStarterkit | Assets/UnityOSC-Toolkit/Scripts/OSC/OSCClient.cs | 4,229 | C# |
using Sharpen;
namespace android.net
{
[Sharpen.NakedStub]
public class DhcpInfo
{
}
}
| 9.2 | 22 | 0.717391 | [
"Apache-2.0"
] | Conceptengineai/XobotOS | android/generated/android/net/DhcpInfo.cs | 92 | C# |
using System;
using System.Collections.Generic;
using UnityEngine;
namespace VaporNetworking
{
public class ServerModule : MonoBehaviour
{
/// <summary>
/// Other servermodules this one is dependant on
/// </summary>
private readonly List<Type> dependencies = new List<Type>();
/// <summary>
/// Returns a list of module types this module depends on.
/// </summary>
public IEnumerable<Type> Dependencies
{
get { return dependencies; }
}
public UDPServer Server { get; set; }
/// <summary>
/// Called by master server when module should be started
/// </summary>
/// <param name="manager"></param>
public virtual void Initialize(UDPServer server)
{
}
/// <summary>
/// Called when the manager unloads all the modules.
/// </summary>
/// <param name="manager"></param>
public virtual void Unload(UDPServer server)
{
}
/// <summary>
/// Adds a dependency to the list. Should be called in awake method of a module.
/// </summary>
/// <typeparam name="T"></typeparam>
public void AddDependency<T>()
{
dependencies.Add(typeof(T));
}
}
} | 26.490196 | 92 | 0.541081 | [
"MIT"
] | Tyrant117/Vapor-Networking | Runtime/Server/ServerModule.cs | 1,353 | C# |
using System;
using System.Collections;
using UnityEngine;
namespace App.Scripts.TransitionScene
{
public class Fade
{
private IFade fade;
public Fade(IFade fade)
{
this.fade = fade;
fade.Range = cutoutRange;
}
private float cutoutRange;
//
// private void OnValidate()
// {
// Init();
// fade.Range = cutoutRange;
// }
private IEnumerator FadeoutCoroutine(float time, Action action)
{
var endTime = Time.timeSinceLevelLoad + time * (cutoutRange);
var endFrame = new WaitForEndOfFrame();
while (endTime >= Time.timeSinceLevelLoad)
{
fade.Range = cutoutRange = (endTime - Time.timeSinceLevelLoad) / time;
yield return endFrame;
}
fade.Range = cutoutRange = 0;
action?.Invoke();
}
private IEnumerator FadeinCoroutine(float time, Action action)
{
var endTime = Time.timeSinceLevelLoad + time * (1 - cutoutRange);
var endFrame = new WaitForEndOfFrame();
while (endTime >= Time.timeSinceLevelLoad)
{
fade.Range = cutoutRange = 1 - ((endTime - Time.timeSinceLevelLoad) / time);
yield return endFrame;
}
fade.Range = cutoutRange = 1;
action?.Invoke();
}
public Coroutine FadeOut(float time, Action action)
{
CoroutineHandler.StaticStopAllCoroutine();
return CoroutineHandler.StartStaticCoroutine(FadeoutCoroutine(time, action));
}
public Coroutine FadeIn(float time, Action action)
{
CoroutineHandler.StaticStopAllCoroutine();
return CoroutineHandler.StartStaticCoroutine(FadeinCoroutine(time, action));
}
public Coroutine FadeOut(float time) => FadeOut(time, null);
public Coroutine FadeIn(float time) => FadeIn(time, null);
}
} | 23.828571 | 80 | 0.697842 | [
"MIT"
] | eyedropsP/UnityPractice | UnityPractices/Assets/TransitionScene/Fade.cs | 1,670 | C# |
// This file is part of Silk.NET.
//
// You may modify and distribute Silk.NET under the terms
// of the MIT license. See the LICENSE file for details.
using System;
using Silk.NET.Core.Attributes;
#pragma warning disable 1591
namespace Silk.NET.SDL
{
[NativeName("AnonymousName", "__AnonymousEnum_SDL_video_L1019_C9")]
[NativeName("Name", "SDL_HitTestResult")]
public enum HitTestResult : int
{
[NativeName("Name", "SDL_HITTEST_NORMAL")]
HittestNormal = 0x0,
[NativeName("Name", "SDL_HITTEST_DRAGGABLE")]
HittestDraggable = 0x1,
[NativeName("Name", "SDL_HITTEST_RESIZE_TOPLEFT")]
HittestResizeTopleft = 0x2,
[NativeName("Name", "SDL_HITTEST_RESIZE_TOP")]
HittestResizeTop = 0x3,
[NativeName("Name", "SDL_HITTEST_RESIZE_TOPRIGHT")]
HittestResizeTopright = 0x4,
[NativeName("Name", "SDL_HITTEST_RESIZE_RIGHT")]
HittestResizeRight = 0x5,
[NativeName("Name", "SDL_HITTEST_RESIZE_BOTTOMRIGHT")]
HittestResizeBottomright = 0x6,
[NativeName("Name", "SDL_HITTEST_RESIZE_BOTTOM")]
HittestResizeBottom = 0x7,
[NativeName("Name", "SDL_HITTEST_RESIZE_BOTTOMLEFT")]
HittestResizeBottomleft = 0x8,
[NativeName("Name", "SDL_HITTEST_RESIZE_LEFT")]
HittestResizeLeft = 0x9,
}
}
| 33.675 | 71 | 0.672606 | [
"MIT"
] | ThomasMiz/Silk.NET | src/Windowing/Silk.NET.SDL/Enums/HitTestResult.gen.cs | 1,347 | 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("HttpServer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("HttpServer")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2012")]
[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("d68bd1a3-d890-4bca-8289-b24b6365bca4")]
// 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")]
| 39.108108 | 85 | 0.729095 | [
"Unlicense"
] | IDWMaster/OpenServer | HttpServer/Properties/AssemblyInfo.cs | 1,450 | C# |
using System;
using System.Collections.Generic;
namespace SKIT.FlurlHttpClient.Wechat.TenpayV3.Models
{
/// <summary>
/// <para>表示 [POST] /payscore/partner/permissions/terminate 接口的响应。</para>
/// </summary>
public class TerminatePayScorePartnerPermissionsByOpenIdResponse : TerminatePayScorePartnerPermissionsByAuthorizationCodeResponse
{
}
}
| 28.384615 | 133 | 0.758808 | [
"MIT"
] | KimMeng2015/DotNetCore.SKIT.FlurlHttpClient.Wechat | src/SKIT.FlurlHttpClient.Wechat.TenpayV3/Models/PayScorePartnerPermissions/TerminatePayScorePartnerPermissionsByOpenIdResponse.cs | 387 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Rectangle_of_10_x_10_Stars
{
class Program
{
static void Main(string[] args)
{
int num = int.Parse(Console.ReadLine());
for (int i = 0; i < num; i++)
{
for (int j = 0; j < num; j++)
{
Console.Write('*');
}
Console.WriteLine();
}
}
}
}
| 20.461538 | 52 | 0.468045 | [
"MIT"
] | 1ooIL40/FundamentalsRepo | new project 02.18/Rectangle of 10 x 10 Stars/Rectangle of 10 x 10 Stars/Program.cs | 534 | C# |
namespace MLSoftware.OTA
{
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "4.2.0.31")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://www.opentravel.org/OTA/2003/05")]
public enum GuaranteeTypeGuaranteeType
{
/// <remarks/>
GuaranteeRequired,
/// <remarks/>
None,
/// <remarks/>
[System.Xml.Serialization.XmlEnumAttribute("CC/DC/Voucher")]
CCDCVoucher,
/// <remarks/>
Profile,
/// <remarks/>
Deposit,
/// <remarks/>
PrePay,
/// <remarks/>
DepositRequired,
}
} | 24.064516 | 118 | 0.534853 | [
"MIT"
] | Franklin89/OTA-Library | src/OTA-Library/GuaranteeTypeGuaranteeType.cs | 746 | C# |
using System;
using Wbs.Everdigm.BLL;
using Wbs.Everdigm.Database;
namespace Wbs.Everdigm.Web
{
/// <summary>
/// 用户信息管理基类
/// </summary>
public class BaseAccountPage : BaseBLLPage
{
protected override void Page_Load(object sender, EventArgs e)
{
base.Page_Load(sender, e);
if (HasSessionLose)
{
ShowNotification("../default.aspx", "Your session has expired, please login again.", false, true);
}
}
protected DepartmentBLL DepartmentInstance { get { return new DepartmentBLL(); } }
protected RoleBLL RoleInstance { get { return new RoleBLL(); } }
/// <summary>
/// 更新用户信息
/// </summary>
/// <param name="obj"></param>
protected void Update(TB_Account obj)
{
AccountInstance.Update(f => f.id == obj.id, action =>
{
action.Delete = obj.Delete;
action.Answer = obj.Answer;
action.Code = obj.Code;
action.Department = obj.Department;
action.Email = obj.Email;
action.LandlineNumber = obj.LandlineNumber;
action.LastLoginIp = obj.LastLoginIp;
action.LastLoginTime = obj.LastLoginTime;
action.Locked = obj.Locked;
action.LoginTimes = obj.LoginTimes;
action.Name = obj.Name;
action.Password = obj.Password;
action.Phone = obj.Phone;
action.Question = obj.Question;
action.RegisterTime = obj.RegisterTime;
action.Role = obj.Role;
});
}
}
} | 34.2 | 114 | 0.532164 | [
"Apache-2.0"
] | wanbangsoftware/Everdigm | Wbs.Everdigm.Web/Wbs.Everdigm.Web/classes/BaseAccountPage.cs | 1,740 | C# |
// Working Files List
// Visual Studio extension tool window that shows a selectable list of files
// that are open in the editor
// Copyright © 2016 Anthony Fung
// 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.Windows.Input;
namespace WorkingFilesList.ToolWindow.ViewModel.Command
{
public class OpenOptionsPage : ICommand
{
#pragma warning disable 67
// ICommand interface member is only used by XAML
public event EventHandler CanExecuteChanged;
#pragma warning restore 67
public event EventHandler OptionsPageRequested;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
OptionsPageRequested?.Invoke(this, EventArgs.Empty);
}
}
}
| 31.186047 | 76 | 0.705444 | [
"Apache-2.0"
] | Ant-f/WorkingFilesList | Solution/WorkingFilesList.ToolWindow/ViewModel/Command/OpenOptionsPage.cs | 1,344 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Todo.Dto
{
public class AccountDto
{
public string Account { get; set; }
public string Password { get; set; }
}
}
| 17.928571 | 44 | 0.669323 | [
"MIT"
] | a975409/Todo | Todo/Dto/AccountDto.cs | 253 | C# |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// 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.Drawing;
using System.Linq;
using System.Text;
using Gallio.Common.Splash.Internal;
using MbUnit.Framework;
namespace Gallio.Common.Splash.Tests
{
public class SplashDocumentTest
{
[Test]
public void Constructor_CreatesAnEmptyDocument()
{
var document = new SplashDocument();
Assert.Multiple(() =>
{
Assert.AreEqual(0, document.CharCount);
Assert.AreEqual(1, document.ParagraphCount);
Assert.AreEqual(1, document.StyleCount);
Assert.AreEqual(0, document.ObjectCount);
Assert.AreEqual(0, document.RunCount);
Assert.AreEqual("", document.ToString());
});
}
[Test]
public void Clear_EmptiesTheDocumentAndRaisesEvent()
{
var document = new SplashDocument();
document.AppendText("some text...");
bool documentClearedEventRaised = false;
document.DocumentCleared += (sender, e) => documentClearedEventRaised = true;
document.Clear();
Assert.Multiple(() =>
{
Assert.AreEqual(0, document.CharCount);
Assert.AreEqual(1, document.ParagraphCount);
Assert.AreEqual(1, document.StyleCount);
Assert.AreEqual(0, document.ObjectCount);
Assert.AreEqual(0, document.RunCount);
Assert.AreEqual("", document.ToString());
Assert.IsTrue(documentClearedEventRaised);
});
}
[Test]
public void GetTextRange_WhenStartIndexNegative_Throws()
{
var document = new SplashDocument();
document.AppendText("some text...");
Assert.Throws<ArgumentOutOfRangeException>(() => document.GetTextRange(-1, 1));
}
[Test]
public void GetTextRange_WhenLengthNegative_Throws()
{
var document = new SplashDocument();
document.AppendText("some text...");
Assert.Throws<ArgumentOutOfRangeException>(() => document.GetTextRange(0, -1));
}
[Test]
public void GetTextRange_WhenStartIndexPlusLengthExceedsDocument_Throws()
{
var document = new SplashDocument();
document.AppendText("some text...");
Assert.Throws<ArgumentOutOfRangeException>(() => document.GetTextRange(10, 3));
}
[Test]
[Row(0, 12)]
[Row(10, 2)]
[Row(0, 4)]
[Row(3, 7)]
public void GetTextRange_WhenRangeValid_ReturnsRange(int startIndex, int length)
{
var document = new SplashDocument();
document.AppendText("some text...");
Assert.AreEqual("some text...".Substring(startIndex, length), document.GetTextRange(startIndex, length));
}
[Test]
public void BeginStyle_WhenStyleIsNull_Throws()
{
var document = new SplashDocument();
Assert.Throws<ArgumentNullException>(() => document.BeginStyle(null));
}
[Test]
public void EndStyle_WhenOnlyDefaultStyleOnStack_Throws()
{
var document = new SplashDocument();
Assert.Throws<InvalidOperationException>(() => document.EndStyle());
}
[Test]
public void BeginStyleAndEndStyle_PushAndPopStylesOnStack()
{
var document = new SplashDocument();
var style1 = new StyleBuilder() { Color = Color.Red }.ToStyle();
var style2 = new StyleBuilder() { Color = Color.Green }.ToStyle();
var style3 = new StyleBuilder() { Color = Color.Blue }.ToStyle();
Assert.AreEqual(Style.Default, document.CurrentStyle);
document.BeginStyle(style1);
Assert.AreEqual(style1, document.CurrentStyle);
document.EndStyle();
Assert.AreEqual(Style.Default, document.CurrentStyle);
using (document.BeginStyle(style2))
{
Assert.AreEqual(style2, document.CurrentStyle);
using (document.BeginStyle(style3))
{
Assert.AreEqual(style3, document.CurrentStyle);
}
Assert.AreEqual(style2, document.CurrentStyle);
}
Assert.AreEqual(Style.Default, document.CurrentStyle);
}
[Test]
public void BeginStyle_CoalescesEqualStyles()
{
var document = new SplashDocument();
var style = new StyleBuilder().ToStyle(); // equal to default style
document.BeginStyle(style);
Assert.AreSame(Style.Default, document.CurrentStyle);
document.EndStyle();
Assert.AreSame(Style.Default, document.CurrentStyle);
}
[Test]
public void GetStyleAtIndex_WhenIndexNegative_Throws()
{
var document = new SplashDocument();
document.AppendText("some text...");
Assert.Throws<ArgumentOutOfRangeException>(() => document.GetStyleAtIndex(-1));
}
[Test]
public void GetStyleAtIndex_WhenIndexBeyondDocument_Throws()
{
var document = new SplashDocument();
document.AppendText("some text...");
Assert.Throws<ArgumentOutOfRangeException>(() => document.GetStyleAtIndex(12));
}
[Test]
public void GetStyleAtIndex_WhenIndexValid_ReturnsStyleAtIndex()
{
var document = new SplashDocument();
var style = new StyleBuilder() { Color = Color.Red }.ToStyle();
document.AppendText("some ");
using (document.BeginStyle(style))
document.AppendText("text");
document.AppendText("...");
Assert.Multiple(() =>
{
for (int i = 0; i < 5; i++)
Assert.AreEqual(Style.Default, document.GetStyleAtIndex(i));
for (int i = 5; i < 9; i++)
Assert.AreEqual(style, document.GetStyleAtIndex(i));
for (int i = 9; i < 12; i++)
Assert.AreEqual(Style.Default, document.GetStyleAtIndex(i));
});
}
[Test]
public void EndAnnotation_WhenNoCurrentAnnotation_Throws()
{
var document = new SplashDocument();
var key = new Key<string>("href");
// 1st case: no annotation table exists
Assert.Throws<InvalidOperationException>(() => document.EndAnnotation(key));
// 2nd case: annotation table exists but there is no current annotation
document.BeginAnnotation(key, "value");
document.EndAnnotation(key);
Assert.Throws<InvalidOperationException>(() => document.EndAnnotation(key));
}
[Test]
public void BeginAnnotationAndEndAnnotation_PushAndPopAnnotationsOnStack()
{
var document = new SplashDocument();
var key = new Key<string>("href");
string value;
Assert.IsFalse(document.TryGetCurrentAnnotation(key, out value));
Assert.IsNull(value);
document.BeginAnnotation(key, "a");
Assert.IsTrue(document.TryGetCurrentAnnotation(key, out value));
Assert.AreEqual("a", value);
document.EndAnnotation(key);
Assert.IsFalse(document.TryGetCurrentAnnotation(key, out value));
Assert.IsNull(value);
using (document.BeginAnnotation(key, "b"))
{
Assert.IsTrue(document.TryGetCurrentAnnotation(key, out value));
Assert.AreEqual("b", value);
using (document.BeginAnnotation(key, "c"))
{
Assert.IsTrue(document.TryGetCurrentAnnotation(key, out value));
Assert.AreEqual("c", value);
}
Assert.IsTrue(document.TryGetCurrentAnnotation(key, out value));
Assert.AreEqual("b", value);
}
Assert.IsFalse(document.TryGetCurrentAnnotation(key, out value));
Assert.IsNull(value);
}
[Test]
public void TryGetAnnotationAtIndex_WhenIndexNegative_Throws()
{
var document = new SplashDocument();
var key = new Key<string>("href");
string value;
document.AppendText("some text...");
Assert.Throws<ArgumentOutOfRangeException>(() => document.TryGetAnnotationAtIndex(key, -1, out value));
}
[Test]
public void TryGetAnnotationAtIndex_WhenIndexBeyondDocument_Throws()
{
var document = new SplashDocument();
var key = new Key<string>("href");
string value;
document.AppendText("some text...");
Assert.Throws<ArgumentOutOfRangeException>(() => document.TryGetAnnotationAtIndex(key, 12, out value));
}
[Test]
public void TryGetAnnotationAtIndex_WhenIndexValidAndNoAnnotations_ReturnsFalse()
{
var document = new SplashDocument();
var key = new Key<string>("href");
document.AppendText("foo");
string value;
Assert.IsFalse(document.TryGetAnnotationAtIndex(key, 0, out value));
Assert.IsNull(value);
}
[Test]
public void TryGetAnnotationAtIndex_WhenIndexValidAndAtLeastOneAnnotation_ReturnsAnnotationAtIndex()
{
var document = new SplashDocument();
var key = new Key<string>("href");
// begin/end an empty block of annotations, these will get stripped out
document.BeginAnnotation(key, "empty");
document.BeginAnnotation(key, "empty2");
document.EndAnnotation(key);
document.EndAnnotation(key);
// add some unannotated text
document.AppendText("some ");
// add some annotated text
using (document.BeginAnnotation(key, "a"))
{
document.AppendText("text ");
using (document.BeginAnnotation(key, "b"))
document.AppendText("more");
}
// add some unannotated text
document.AppendText("...");
// begin another empty annotation at the end, should have no effect on current text
document.BeginAnnotation(key, "trailer");
Assert.Multiple(() =>
{
string value;
for (int i = 0; i < 5; i++)
{
Assert.IsFalse(document.TryGetAnnotationAtIndex(key, i, out value));
Assert.IsNull(value);
}
for (int i = 5; i < 10; i++)
{
Assert.IsTrue(document.TryGetAnnotationAtIndex(key, i, out value));
Assert.AreEqual("a", value);
}
for (int i = 10; i < 14; i++)
{
Assert.IsTrue(document.TryGetAnnotationAtIndex(key, i, out value));
Assert.AreEqual("b", value);
}
for (int i = 14; i < 17; i++)
{
Assert.IsFalse(document.TryGetAnnotationAtIndex(key, i, out value));
Assert.IsNull(value);
}
});
}
[Test]
public void GetObjectAtIndex_WhenIndexNegative_Throws()
{
var document = new SplashDocument();
document.AppendText("some text...");
Assert.Throws<ArgumentOutOfRangeException>(() => document.GetObjectAtIndex(-1));
}
[Test]
public void GetObjectAtIndex_WhenIndexBeyondDocument_Throws()
{
var document = new SplashDocument();
document.AppendText("some text...");
Assert.Throws<ArgumentOutOfRangeException>(() => document.GetObjectAtIndex(12));
}
[Test]
public void GetObjectAtIndex_WhenIndexValid_ReturnsEmbeddedObject()
{
var document = new SplashDocument();
var obj = new EmbeddedImage(new Bitmap(16, 16));
document.AppendText("obj");
document.AppendObject(obj);
document.AppendText("...");
Assert.Multiple(() =>
{
for (int i = 0; i < 3; i++)
Assert.IsNull(document.GetObjectAtIndex(i));
Assert.AreEqual(obj, document.GetObjectAtIndex(3));
for (int i = 4; i < 7; i++)
Assert.IsNull(document.GetObjectAtIndex(i));
});
}
[Test]
public void AppendText_WhenTextIsNull_Throws()
{
var document = new SplashDocument();
Assert.Throws<ArgumentNullException>(() => document.AppendText(null));
}
[Test]
public void AppendObject_WhenObjectIsNull_Throws()
{
var document = new SplashDocument();
Assert.Throws<ArgumentNullException>(() => document.AppendObject(null));
}
[Test]
public unsafe void AppendStuff()
{
var style1 = new StyleBuilder() { Color = Color.Red }.ToStyle();
var style2 = new StyleBuilder() { LeftMargin = 10, RightMargin = 10 }.ToStyle();
var style3 = new StyleBuilder() { Font = SystemFonts.SmallCaptionFont, Color = Color.Blue }.ToStyle();
var embeddedObject = new EmbeddedImage(new Bitmap(16, 16));
var document = new SplashDocument();
var changedParagraphIndices = new List<int>();
document.ParagraphChanged += (sender, e) => changedParagraphIndices.Add(e.ParagraphIndex);
using (document.BeginStyle(style1))
document.AppendText("Some text, lalala.\nMore text.");
using (document.BeginStyle(style2))
{
document.AppendText("Tab\t.\n");
document.AppendText("\0\r"); // these control characters will be discarded
using (document.BeginStyle(style3))
{
document.AppendLine();
document.AppendText(""); // to verify that no change event is raised for empty text
}
document.AppendText("(");
document.AppendObject(embeddedObject);
document.AppendText(")");
}
Assert.Multiple(() =>
{
// Check char content.
Assert.AreEqual("Some text, lalala.\nMore text.Tab\t.\n\n( )", document.ToString());
// Check style table.
Assert.AreEqual(4, document.StyleCount);
Assert.AreEqual(Style.Default, document.LookupStyle(0));
Assert.AreEqual(style1, document.LookupStyle(1));
Assert.AreEqual(style2, document.LookupStyle(2));
Assert.AreEqual(style3, document.LookupStyle(3));
// Check object table.
Assert.AreEqual(1, document.ObjectCount);
Assert.AreEqual(embeddedObject, document.LookupObject(0));
// Check paragraph table.
Assert.AreEqual(4, document.ParagraphCount);
Paragraph* paragraphs = document.GetParagraphZero();
Assert.AreEqual(0, paragraphs[0].CharIndex); // "Some text, lalala.\n"
Assert.AreEqual(19, paragraphs[0].CharCount);
Assert.AreEqual(0, paragraphs[0].RunIndex);
Assert.AreEqual(1, paragraphs[0].RunCount);
Assert.AreEqual(19, paragraphs[1].CharIndex); // "More text.Tab\t.\n"
Assert.AreEqual(16, paragraphs[1].CharCount);
Assert.AreEqual(1, paragraphs[1].RunIndex);
Assert.AreEqual(4, paragraphs[1].RunCount);
Assert.AreEqual(35, paragraphs[2].CharIndex); // "\n"
Assert.AreEqual(1, paragraphs[2].CharCount);
Assert.AreEqual(5, paragraphs[2].RunIndex);
Assert.AreEqual(1, paragraphs[2].RunCount);
Assert.AreEqual(36, paragraphs[3].CharIndex); // "( )"
Assert.AreEqual(3, paragraphs[3].CharCount);
Assert.AreEqual(6, paragraphs[3].RunIndex);
Assert.AreEqual(3, paragraphs[3].RunCount);
// Check run table.
Assert.AreEqual(9, document.RunCount);
Run* runs = document.GetRunZero();
Assert.AreEqual(RunKind.Text, runs[0].RunKind); // "Some text, lalala.\n"
Assert.AreEqual(19, runs[0].CharCount);
Assert.AreEqual(1, runs[0].StyleIndex);
Assert.AreEqual(RunKind.Text, runs[1].RunKind); // "More text."
Assert.AreEqual(10, runs[1].CharCount);
Assert.AreEqual(1, runs[1].StyleIndex);
Assert.AreEqual(RunKind.Text, runs[2].RunKind); // "Tab"
Assert.AreEqual(3, runs[2].CharCount);
Assert.AreEqual(2, runs[2].StyleIndex);
Assert.AreEqual(RunKind.Tab, runs[3].RunKind); // "\t"
Assert.AreEqual(1, runs[3].CharCount);
Assert.AreEqual(2, runs[3].StyleIndex);
Assert.AreEqual(RunKind.Text, runs[4].RunKind); // ".\n"
Assert.AreEqual(2, runs[4].CharCount);
Assert.AreEqual(2, runs[4].StyleIndex);
Assert.AreEqual(RunKind.Text, runs[5].RunKind); // "\n"
Assert.AreEqual(1, runs[5].CharCount);
Assert.AreEqual(3, runs[5].StyleIndex);
Assert.AreEqual(RunKind.Text, runs[6].RunKind); // "("
Assert.AreEqual(1, runs[6].CharCount);
Assert.AreEqual(2, runs[6].StyleIndex);
Assert.AreEqual(RunKind.Object, runs[7].RunKind); // "("
Assert.AreEqual(1, runs[7].CharCount);
Assert.AreEqual(2, runs[7].StyleIndex);
Assert.AreEqual(0, runs[7].ObjectIndex);
Assert.AreEqual(RunKind.Text, runs[8].RunKind); // ")"
Assert.AreEqual(1, runs[8].CharCount);
Assert.AreEqual(2, runs[8].StyleIndex);
// Check that paragraph changed notifications were raised as needed.
Assert.AreElementsEqual(new[] { 0, 1, 2, 2, 3, 3, 3 }, changedParagraphIndices);
});
}
[Test]
[Row(SplashDocument.MaxCharsPerRun)]
[Row(SplashDocument.MaxCharsPerRun + 1)]
[Row(SplashDocument.MaxCharsPerRun * 2)]
[Row(SplashDocument.MaxCharsPerRun * 2 + 1)]
public unsafe void AppendText_WhenRunIsExtremelyLong_SplitsRun(int length)
{
var document = new SplashDocument();
var content = new string(' ', length);
document.AppendText(content);
Assert.Multiple(() =>
{
// Check char content.
Assert.AreEqual(content, document.ToString());
// Check paragraph table.
Assert.AreEqual(1, document.ParagraphCount);
Paragraph* paragraphs = document.GetParagraphZero();
int expectedRuns = (length + SplashDocument.MaxCharsPerRun - 1) / SplashDocument.MaxCharsPerRun;
Assert.AreEqual(0, paragraphs[0].CharIndex);
Assert.AreEqual(length, paragraphs[0].CharCount);
Assert.AreEqual(0, paragraphs[0].RunIndex);
Assert.AreEqual(expectedRuns, paragraphs[0].RunCount);
// Check run table.
Assert.AreEqual(expectedRuns, document.RunCount);
Run* runs = document.GetRunZero();
for (int i = 0; i < expectedRuns; i++)
{
Assert.AreEqual(RunKind.Text, runs[i].RunKind);
Assert.AreEqual(Math.Min(length, SplashDocument.MaxCharsPerRun), runs[i].CharCount);
Assert.AreEqual(0, runs[i].StyleIndex);
length -= SplashDocument.MaxCharsPerRun;
}
});
}
}
}
| 37.549822 | 117 | 0.559447 | [
"ECL-2.0",
"Apache-2.0"
] | citizenmatt/gallio | src/Common/Gallio.Common.Splash.Tests/SplashDocumentTest.cs | 21,103 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace SamuraiApp.Data
{
public class SamuraiContextNoTracking : SamuraiContext
{
public SamuraiContextNoTracking()
{
base.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
}
}
}
| 22.666667 | 88 | 0.732843 | [
"Apache-2.0"
] | sansindia85/EFCore6 | InteractEFCoreData/SamuraiApp/SamuraiApp.Data/SamuraiContextNoTracking.cs | 410 | C# |
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using HandlebarsDotNet.ObjectDescriptors;
using HandlebarsDotNet.PathStructure;
using HandlebarsDotNet.Runtime;
namespace HandlebarsDotNet
{
public readonly struct Context
{
private readonly DeferredValue<BindingContext, ObjectDescriptor> _descriptor;
public readonly object Value;
public Context(BindingContext context)
{
Value = context.Value;
_descriptor = context.Descriptor;
}
public Context(BindingContext context, object value)
{
Value = value;
_descriptor = context.Descriptor;
}
public IEnumerable<ChainSegment> Properties =>
_descriptor.Value
.GetProperties(_descriptor.Value, Value)
.OfType<object>()
.Select(o => ChainSegment.Create(o));
public object this[ChainSegment segment] =>
_descriptor.Value.MemberAccessor.TryGetValue(Value, segment, out var value)
? value
: null;
public T GetValue<T>(ChainSegment segment)
{
if (!_descriptor.Value.MemberAccessor.TryGetValue(Value, segment, out var obj)) return default;
if (obj is T value) return value;
var converter = TypeDescriptor.GetConverter(obj.GetType());
return (T) converter.ConvertTo(obj, typeof(T));
}
}
} | 31.229167 | 107 | 0.621081 | [
"MIT"
] | Andrea-MariaDB-2/Handlebars.Net | source/Handlebars/Context.cs | 1,499 | C# |
namespace UblTr.Common
{
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
[System.Xml.Serialization.XmlRootAttribute("CurrentStatus", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2", IsNullable = false)]
public partial class StatusType
{
private ConditionCodeType conditionCodeField;
private ReferenceDateType referenceDateField;
private ReferenceTimeType referenceTimeField;
private DescriptionType[] descriptionField;
private StatusReasonCodeType statusReasonCodeField;
private StatusReasonType[] statusReasonField;
private SequenceIDType sequenceIDField;
private TextType2[] textField;
private IndicationIndicatorType indicationIndicatorField;
private PercentType1 percentField;
private ReliabilityPercentType reliabilityPercentField;
private ConditionType1[] conditionField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public ConditionCodeType ConditionCode
{
get
{
return this.conditionCodeField;
}
set
{
this.conditionCodeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public ReferenceDateType ReferenceDate
{
get
{
return this.referenceDateField;
}
set
{
this.referenceDateField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public ReferenceTimeType ReferenceTime
{
get
{
return this.referenceTimeField;
}
set
{
this.referenceTimeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Description", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public DescriptionType[] Description
{
get
{
return this.descriptionField;
}
set
{
this.descriptionField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public StatusReasonCodeType StatusReasonCode
{
get
{
return this.statusReasonCodeField;
}
set
{
this.statusReasonCodeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("StatusReason", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public StatusReasonType[] StatusReason
{
get
{
return this.statusReasonField;
}
set
{
this.statusReasonField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public SequenceIDType SequenceID
{
get
{
return this.sequenceIDField;
}
set
{
this.sequenceIDField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Text", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public TextType2[] Text
{
get
{
return this.textField;
}
set
{
this.textField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IndicationIndicatorType IndicationIndicator
{
get
{
return this.indicationIndicatorField;
}
set
{
this.indicationIndicatorField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public PercentType1 Percent
{
get
{
return this.percentField;
}
set
{
this.percentField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public ReliabilityPercentType ReliabilityPercent
{
get
{
return this.reliabilityPercentField;
}
set
{
this.reliabilityPercentField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Condition")]
public ConditionType1[] Condition
{
get
{
return this.conditionField;
}
set
{
this.conditionField = value;
}
}
}
} | 30.27451 | 172 | 0.558776 | [
"MIT"
] | canyener/Ubl-Tr | Ubl-Tr/Common/CommonAggregateComponents/StatusType.cs | 6,176 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.Media.Devices
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
#endif
public enum ColorTemperaturePreset
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
Auto,
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
Manual,
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
Cloudy,
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
Daylight,
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
Flash,
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
Fluorescent,
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
Tungsten,
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
Candlelight,
#endif
}
#endif
}
| 27.052632 | 63 | 0.680934 | [
"Apache-2.0"
] | 06needhamt/uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Media.Devices/ColorTemperaturePreset.cs | 1,028 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.NetCore.Analyzers.Security
{
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class DoNotCallDangerousMethodsInDeserialization : DiagnosticAnalyzer
{
internal const string DiagnosticId = "CA5360";
private static readonly LocalizableString s_Title = new LocalizableResourceString(
nameof(MicrosoftNetCoreAnalyzersResources.DoNotCallDangerousMethodsInDeserialization),
MicrosoftNetCoreAnalyzersResources.ResourceManager,
typeof(MicrosoftNetCoreAnalyzersResources));
private static readonly LocalizableString s_Message = new LocalizableResourceString(
nameof(MicrosoftNetCoreAnalyzersResources.DoNotCallDangerousMethodsInDeserializationMessage),
MicrosoftNetCoreAnalyzersResources.ResourceManager,
typeof(MicrosoftNetCoreAnalyzersResources));
private static readonly LocalizableString s_Description = new LocalizableResourceString(
nameof(MicrosoftNetCoreAnalyzersResources.DoNotCallDangerousMethodsInDeserializationDescription),
MicrosoftNetCoreAnalyzersResources.ResourceManager,
typeof(MicrosoftNetCoreAnalyzersResources));
private ImmutableArray<(string, string[])> DangerousCallable = ImmutableArray.Create<(string, string[])>
(
(WellKnownTypeNames.SystemIOFileFullName, new[] { "WriteAllBytes", "WriteAllLines", "WriteAllText", "Copy", "Move", "AppendAllLines", "AppendAllText", "AppendText", "Delete" }),
(WellKnownTypeNames.SystemIODirectory, new[] { "Delete" }),
(WellKnownTypeNames.SystemIOFileInfo, new[] { "Delete" }),
(WellKnownTypeNames.SystemIODirectoryInfo, new[] { "Delete" }),
(WellKnownTypeNames.SystemIOLogLogStore, new[] { "Delete" }),
(WellKnownTypeNames.SystemReflectionAssemblyFullName, new[] { "GetLoadedModules", "Load", "LoadFile", "LoadFrom", "LoadModule", "LoadWithPartialName", "ReflectionOnlyLoad", "ReflectionOnlyLoadFrom", "UnsafeLoadFrom" })
);
internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(
DiagnosticId,
s_Title,
s_Message,
DiagnosticCategory.Security,
DiagnosticHelpers.DefaultDiagnosticSeverity,
isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX,
description: s_Description,
helpLinkUri: null,
customTags: WellKnownDiagnosticTags.Telemetry);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public sealed override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
// Security analyzer - analyze and report diagnostics on generated code.
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
context.RegisterCompilationStartAction(
(CompilationStartAnalysisContext compilationStartAnalysisContext) =>
{
var compilation = compilationStartAnalysisContext.Compilation;
var wellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(compilation);
if (!wellKnownTypeProvider.TryGetOrCreateTypeByMetadataName(
WellKnownTypeNames.SystemSerializableAttribute,
out INamedTypeSymbol? serializableAttributeTypeSymbol))
{
return;
}
var dangerousMethodSymbolsBuilder = ImmutableHashSet.CreateBuilder<IMethodSymbol>();
foreach (var (typeName, methodNames) in DangerousCallable)
{
if (!wellKnownTypeProvider.TryGetOrCreateTypeByMetadataName(
typeName,
out INamedTypeSymbol? typeSymbol))
{
continue;
}
foreach (var methodName in methodNames)
{
dangerousMethodSymbolsBuilder.UnionWith(
typeSymbol.GetMembers()
.OfType<IMethodSymbol>()
.Where(
s => s.Name == methodName));
}
}
if (!dangerousMethodSymbolsBuilder.Any())
{
return;
}
var dangerousMethodSymbols = dangerousMethodSymbolsBuilder.ToImmutableHashSet();
var attributeTypeSymbolsBuilder = ImmutableArray.CreateBuilder<INamedTypeSymbol>();
if (wellKnownTypeProvider.TryGetOrCreateTypeByMetadataName(
WellKnownTypeNames.SystemRuntimeSerializationOnDeserializingAttribute,
out INamedTypeSymbol? onDeserializingAttributeTypeSymbol))
{
attributeTypeSymbolsBuilder.Add(onDeserializingAttributeTypeSymbol);
}
if (wellKnownTypeProvider.TryGetOrCreateTypeByMetadataName(
WellKnownTypeNames.SystemRuntimeSerializationOnDeserializedAttribute,
out INamedTypeSymbol? onDeserializedAttributeTypeSymbol))
{
attributeTypeSymbolsBuilder.Add(onDeserializedAttributeTypeSymbol);
}
var attributeTypeSymbols = attributeTypeSymbolsBuilder.ToImmutable();
if (!wellKnownTypeProvider.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationStreamingContext, out INamedTypeSymbol? streamingContextTypeSymbol) ||
!wellKnownTypeProvider.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationIDeserializationCallback, out INamedTypeSymbol? IDeserializationCallbackTypeSymbol))
{
return;
}
// A dictionary from method symbol to set of methods invoked by it directly.
// The bool value in the sub ConcurrentDictionary is not used, use ConcurrentDictionary rather than HashSet just for the concurrency security.
var callGraph = new ConcurrentDictionary<ISymbol, ConcurrentDictionary<ISymbol, bool>>();
compilationStartAnalysisContext.RegisterOperationBlockStartAction(
(OperationBlockStartAnalysisContext operationBlockStartAnalysisContext) =>
{
var owningSymbol = operationBlockStartAnalysisContext.OwningSymbol;
ConcurrentDictionary<ISymbol, bool> calledMethods;
if (owningSymbol is IMethodSymbol methodSymbol ||
(owningSymbol is IFieldSymbol fieldSymbol &&
fieldSymbol.Type.TypeKind == TypeKind.Delegate))
{
// Delegate member could be added already, so use GetOrAdd().
calledMethods = callGraph.GetOrAdd(owningSymbol, new ConcurrentDictionary<ISymbol, bool>());
}
else
{
return;
}
operationBlockStartAnalysisContext.RegisterOperationAction(operationContext =>
{
ISymbol? calledSymbol = null;
ITypeSymbol? possibleDelegateSymbol = null;
switch (operationContext.Operation)
{
case IInvocationOperation invocationOperation:
calledSymbol = invocationOperation.TargetMethod.OriginalDefinition;
possibleDelegateSymbol = calledSymbol.ContainingType; // Invoke().
break;
case IFieldReferenceOperation fieldReferenceOperation:
var fieldSymbol = (IFieldSymbol)fieldReferenceOperation.Field;
possibleDelegateSymbol = fieldSymbol.Type; // Delegate field.
if (possibleDelegateSymbol.TypeKind != TypeKind.Delegate)
{
return;
}
else
{
calledSymbol = fieldSymbol;
}
break;
default:
throw new NotImplementedException();
}
calledMethods.TryAdd(calledSymbol, true);
if (!calledSymbol.IsInSource() ||
calledSymbol.ContainingType.TypeKind == TypeKind.Interface ||
calledSymbol.IsAbstract ||
possibleDelegateSymbol.TypeKind == TypeKind.Delegate)
{
callGraph.TryAdd(calledSymbol, new ConcurrentDictionary<ISymbol, bool>());
}
}, OperationKind.Invocation, OperationKind.FieldReference);
});
compilationStartAnalysisContext.RegisterCompilationEndAction(
(CompilationAnalysisContext compilationAnalysisContext) =>
{
var visited = new HashSet<ISymbol>();
var results = new Dictionary<ISymbol, HashSet<ISymbol>>();
foreach (var methodSymbol in callGraph.Keys.OfType<IMethodSymbol>())
{
// Determine if the method is called automatically when an object is deserialized.
// This includes methods with OnDeserializing attribute, method with OnDeserialized attribute, deserialization callbacks as well as cleanup/dispose calls.
var flagSerializable = methodSymbol.ContainingType.HasAttribute(serializableAttributeTypeSymbol);
var parameters = methodSymbol.GetParameters();
var flagHasDeserializeAttributes = attributeTypeSymbols.Length != 0
&& attributeTypeSymbols.Any(s => methodSymbol.HasAttribute(s))
&& parameters.Length == 1
&& parameters[0].Type.Equals(streamingContextTypeSymbol);
var flagImplementOnDeserializationMethod = methodSymbol.IsOnDeserializationImplementation(IDeserializationCallbackTypeSymbol);
var flagImplementDisposeMethod = methodSymbol.IsDisposeImplementation(compilation);
var flagIsFinalizer = methodSymbol.IsFinalizer();
if (!flagSerializable || !flagHasDeserializeAttributes && !flagImplementOnDeserializationMethod && !flagImplementDisposeMethod && !flagIsFinalizer)
{
continue;
}
FindCalledDangerousMethod(methodSymbol, visited, results);
foreach (var result in results[methodSymbol])
{
compilationAnalysisContext.ReportDiagnostic(
methodSymbol.CreateDiagnostic(
Rule,
methodSymbol.ContainingType.Name,
methodSymbol.MetadataName,
result.MetadataName));
}
}
});
// <summary>
// Analyze the method to find all the dangerous method it calls.
// </summary>
// <param name="methodSymbol">The symbol of the method to be analyzed</param>
// <param name="visited">All the method has been analyzed</param>
// <param name="results">The result is organized by <method to be analyzed, dangerous method it calls></param>
void FindCalledDangerousMethod(ISymbol methodSymbol, HashSet<ISymbol> visited, Dictionary<ISymbol, HashSet<ISymbol>> results)
{
if (visited.Add(methodSymbol))
{
results.Add(methodSymbol, new HashSet<ISymbol>());
if (!callGraph.TryGetValue(methodSymbol, out var calledMethods))
{
Debug.Fail(methodSymbol.Name + " was not found in callGraph");
return;
}
foreach (var child in calledMethods.Keys)
{
if (dangerousMethodSymbols.Contains(child))
{
results[methodSymbol].Add(child);
}
FindCalledDangerousMethod(child, visited, results);
if (results.TryGetValue(child, out var result))
{
results[methodSymbol].UnionWith(result);
}
else
{
Debug.Fail(child.Name + " was not found in results");
}
}
}
}
});
}
}
}
| 55.626812 | 234 | 0.531492 | [
"Apache-2.0"
] | edespong/roslyn-analyzers | src/Microsoft.NetCore.Analyzers/Core/Security/DoNotCallDangerousMethodsInDeserialization.cs | 15,353 | C# |
// Licensed to the Mixcore Foundation under one or more agreements.
// The Mixcore Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Mix.Cms.Lib.Models.Cms;
using Mix.Cms.Lib.Services;
using Mix.Cms.Lib.ViewModels.MixPositions;
using Mix.Domain.Core.ViewModels;
using Newtonsoft.Json.Linq;
using System;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace Mix.Cms.Api.Controllers.v1
{
[Produces("application/json")]
[Route("api/v1/{culture}/menu")]
public class ApiMenuController :
BaseGenericApiController<MixCmsContext, MixPosition>
{
public ApiMenuController(MixCmsContext context, IMemoryCache memoryCache, Microsoft.AspNetCore.SignalR.IHubContext<Hub.PortalHub> hubContext) : base(context, memoryCache, hubContext)
{
}
#region Get
// GET api/menu/id
[HttpGet, HttpOptions]
[Route("delete/{id}")]
public async Task<RepositoryResponse<MixPosition>> DeleteAsync(int id)
{
return await base.DeleteAsync<DeleteViewModel>(
model => model.Id == id, true);
}
// GET api/menus/id
[HttpGet, HttpOptions]
[Route("details/{id}/{viewType}")]
[Route("details/{viewType}")]
public async Task<ActionResult<JObject>> Details(string viewType, int? id)
{
string msg = string.Empty;
switch (viewType)
{
case "portal":
if (id.HasValue)
{
Expression<Func<MixPosition, bool>> predicate = model => model.Id == id;
var portalResult = await base.GetSingleAsync<UpdateViewModel>($"{viewType}_{id}", predicate);
return Ok(JObject.FromObject(portalResult));
}
else
{
var model = new MixPosition()
{
Status = MixService.GetConfig<int>("DefaultStatus")
,
Priority = UpdateViewModel.Repository.Max(a => a.Priority).Data + 1
};
RepositoryResponse<UpdateViewModel> result = await base.GetSingleAsync<UpdateViewModel>($"{viewType}_default", null, model);
return Ok(JObject.FromObject(result));
}
default:
if (id.HasValue)
{
Expression<Func<MixPosition, bool>> predicate = model => model.Id == id;
var result = await base.GetSingleAsync<ReadViewModel>($"{viewType}_{id}", predicate);
return Ok(JObject.FromObject(result));
}
else
{
var model = new MixPosition()
{
Status = MixService.GetConfig<int>("DefaultStatus")
,
Priority = ReadViewModel.Repository.Max(a => a.Priority).Data + 1
};
RepositoryResponse<ReadViewModel> result = await base.GetSingleAsync<ReadViewModel>($"{viewType}_default", null, model);
return Ok(JObject.FromObject(result));
}
}
}
#endregion Get
#region Post
// POST api/menu
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "SuperAdmin, Admin")]
[HttpPost, HttpOptions]
[Route("save")]
public async Task<RepositoryResponse<UpdateViewModel>> Save([FromBody]UpdateViewModel data)
{
if (data != null)
{
data.Specificulture = _lang;
var result = await base.SaveAsync<UpdateViewModel>(data, true);
if (result.IsSucceed)
{
MixService.LoadFromDatabase();
MixService.SaveSettings();
}
return result;
}
return new RepositoryResponse<UpdateViewModel>() { Status = 501 };
}
// GET api/menu
[HttpPost, HttpOptions]
[Route("list")]
public async Task<ActionResult<JObject>> GetList(
[FromBody] RequestPaging request)
{
ParseRequestPagingDate(request);
Expression<Func<MixPosition, bool>> predicate = model =>
string.IsNullOrWhiteSpace(request.Keyword)
|| (model.Description.Contains(request.Keyword)
);
string key = $"{request.Key}_{request.PageSize}_{request.PageIndex}";
switch (request.Key)
{
case "portal":
var portalResult = await base.GetListAsync<UpdateViewModel>(key, request, predicate);
return Ok(JObject.FromObject(portalResult));
default:
var listItemResult = await base.GetListAsync<ReadViewModel>(key, request, predicate);
return JObject.FromObject(listItemResult);
}
}
#endregion Post
}
}
| 38.416667 | 190 | 0.543022 | [
"MIT"
] | robinson/mix.core | src/Mix.Cms.Api/Controllers/v1/ApiMenuController.cs | 5,534 | C# |
using NetOffice.Attributes;
namespace NetOffice.WordApi.Enums
{
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
/// </summary>
///<remarks> MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff845050.aspx </remarks>
[SupportByVersion("Word", 9, 10, 11, 12, 14, 15, 16)]
[EntityType(EntityType.IsEnum)]
public enum WdTabLeader
{
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>0</remarks>
[SupportByVersion("Word", 9, 10, 11, 12, 14, 15, 16)]
wdTabLeaderSpaces = 0,
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>1</remarks>
[SupportByVersion("Word", 9, 10, 11, 12, 14, 15, 16)]
wdTabLeaderDots = 1,
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>2</remarks>
[SupportByVersion("Word", 9, 10, 11, 12, 14, 15, 16)]
wdTabLeaderDashes = 2,
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>3</remarks>
[SupportByVersion("Word", 9, 10, 11, 12, 14, 15, 16)]
wdTabLeaderLines = 3,
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>4</remarks>
[SupportByVersion("Word", 9, 10, 11, 12, 14, 15, 16)]
wdTabLeaderHeavy = 4,
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>5</remarks>
[SupportByVersion("Word", 9, 10, 11, 12, 14, 15, 16)]
wdTabLeaderMiddleDot = 5
}
} | 33.407407 | 121 | 0.525499 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | ehsan2022002/VirastarE | Office/Word/Enums/WdTabLeader.cs | 1,806 | C# |
using SimpleAccounting.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SimpleAccounting.Repository
{
/// <summary>
/// this is for creating tables
/// </summary>
public interface ISimpleAccountingContext
{
IDbSet<AccountingCompanyDetail> AccountingCompanyDetails { get; set; }
IDbSet<AccountingCustomer> AccountingCustomers { get; set; }
IDbSet<AccountingOption> AccountingOptions { get; set; }
IDbSet<AccountingProduct> AccountingProducts { get; set; }
IDbSet<AccountingPurchaseInvoice> AccountingPurchaseInvoices { get; set; }
IDbSet<AccountingPurchaseInvoiceDetail> AccountingPurchaseInvoiceDetails { get; set; }
IDbSet<AccountingPurchaseOrder> AccountingPurchaseOrders { get; set; }
IDbSet<AccountingPurchaseOrderDetail> AccountingPurchaseOrderDetail { get; set; }
//IDbSet<AccountingPurchaseQuotation> AccountingPurchaseQuotations { get; set; }
IDbSet<AccountingSalesInvoice> AccountingSalesInvoices { get; set; }
IDbSet<AccountingSalesInvoiceDetail> AccountingSalesInvoiceDetails { get; set; }
IDbSet<AccountingSalesOrder> AccountingSalesOrder { get; set; }
IDbSet<AccountingSalesOrderDetail> AccountingSalesOrderDetails { get; set; }
//IDbSet<AccountingSalesQuotation> AccountingSalesQuotations { get; set; }
IDbSet<AccountingSupplier> AccountingSuppliers { get; set; }
DbSet<TEntity> Set<TEntity>() where TEntity : class;
DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
int SaveChanges();
}
public class SimpleAccountingContext : DbContext, ISimpleAccountingContext
{
public SimpleAccountingContext() : base("name=MyConnectionString")
{
}
public static SimpleAccountingContext Create()
{
return new SimpleAccountingContext();
}
public IDbSet<AccountingCompanyDetail> AccountingCompanyDetails
{
get;
set;
}
public IDbSet<AccountingCustomer> AccountingCustomers
{
get;
set;
}
public IDbSet<AccountingOption> AccountingOptions
{
get;
set;
}
public IDbSet<AccountingPurchaseInvoice> AccountingPurchaseInvoices
{
get;
set;
}
public IDbSet<AccountingPurchaseOrder> AccountingPurchaseOrders
{
get;
set;
}
/* public IDbSet<AccountingPurchaseQuotation> AccountingPurchaseQuotations
{
get;
set;
}*/
public IDbSet<AccountingProduct> AccountingProducts
{
get;
set;
}
public IDbSet<AccountingSalesInvoice> AccountingSalesInvoices
{
get;
set;
}
public IDbSet<AccountingSalesOrder> AccountingSalesOrder
{
get;
set;
}
public IDbSet<AccountingSupplier> AccountingSuppliers
{
get;
set;
}
public IDbSet<AccountingPurchaseInvoiceDetail> AccountingPurchaseInvoiceDetails
{
get;
set;
}
public IDbSet<AccountingPurchaseOrderDetail> AccountingPurchaseOrderDetail
{
get;
set;
}
public IDbSet<AccountingSalesInvoiceDetail> AccountingSalesInvoiceDetails
{
get;
set;
}
public IDbSet<AccountingSalesOrderDetail> AccountingSalesOrderDetails
{
get;
set;
}
/* public IDbSet<AccountingSalesQuotation> AccountingSalesQuotations
{
get;
set;
}*/
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
base.OnModelCreating(modelBuilder);
#region<--Table AccountingCompany-->
modelBuilder.Entity<AccountingCompanyDetail>()
.ToTable("AccountingCompanyDetails")
.HasKey(c => c.CompanyId);
modelBuilder.Entity<AccountingCompanyDetail>()
.Property(c => c.CompanyName)
.HasColumnName("CompanyName")
.HasColumnType("varchar")
.HasMaxLength(200)
.IsRequired();
modelBuilder.Entity<AccountingCompanyDetail>()
.Property(c => c.CompanyRegno)
.HasColumnName("Registrationno")
.HasColumnType("int")
.IsRequired();
modelBuilder.Entity<AccountingCompanyDetail>()
.Property(c => c.CompanyTelephone)
.HasColumnName("Telephoneno")
.HasColumnType("nvarchar")
.HasMaxLength(15)
.IsRequired();
modelBuilder.Entity<AccountingCompanyDetail>()
.Property(c => c.CompanyEmail)
.HasColumnName("Email")
.HasColumnType("varchar")
.HasMaxLength(30)
.IsRequired();
modelBuilder.Entity<AccountingCompanyDetail>()
.Property(c => c.FinancialYrStartDate)
.HasColumnName("StartDate")
.HasColumnType("date")
.IsOptional();
modelBuilder.Entity<AccountingCompanyDetail>()
.Property(c => c.CompanyLogo)
.HasColumnName("LogoImage")
.HasColumnType("Image")
.IsOptional();
modelBuilder.Entity<AccountingCompanyDetail>()
.Property(c => c.SoftwareSerialNo)
.HasColumnName("Serialno")
.HasColumnType("varchar")
.IsOptional();
modelBuilder.Entity<AccountingCompanyDetail>()
.Property(c => c.BilltoLine1)
.HasColumnName("BillAddressLine1")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingCompanyDetail>()
.Property(c => c.BilltoLine2)
.HasColumnName("BillAddressLine2")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsOptional();
modelBuilder.Entity<AccountingCompanyDetail>()
.Property(c => c.BilltoCity)
.HasColumnName("BillCity")
.HasColumnType("varchar")
.HasMaxLength(20)
.IsRequired();
modelBuilder.Entity<AccountingCompanyDetail>()
.Property(c => c.BilltoState)
.HasColumnName("BillState")
.HasColumnType("varchar")
.HasMaxLength(20)
.IsRequired();
modelBuilder.Entity<AccountingCompanyDetail>()
.Property(c => c.BilltoCountry)
.HasColumnName("BillCountry")
.HasColumnType("varchar")
.HasMaxLength(20)
.IsRequired();
modelBuilder.Entity<AccountingCompanyDetail>()
.Property(c => c.BilltoPostalCode)
.HasColumnName("BillPostalCode")
.HasColumnType("varchar")
.HasMaxLength(10)
.IsRequired();
modelBuilder.Entity<AccountingCompanyDetail>()
.Property(c => c.ShiptoLine1)
.HasColumnName("ShipAddressLine1")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingCompanyDetail>()
.Property(c => c.ShiptoLine2)
.HasColumnName("ShipAddressLine2")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingCompanyDetail>()
.Property(c => c.ShiptoCity)
.HasColumnName("ShipCity")
.HasColumnType("varchar")
.HasMaxLength(20)
.IsRequired();
modelBuilder.Entity<AccountingCompanyDetail>()
.Property(c => c.ShiptoState)
.HasColumnName("ShipState")
.HasColumnType("varchar")
.HasMaxLength(20)
.IsRequired();
modelBuilder.Entity<AccountingCompanyDetail>()
.Property(c => c.ShiptoCountry)
.HasColumnName("ShipCountry")
.HasColumnType("varchar")
.HasMaxLength(20)
.IsRequired();
modelBuilder.Entity<AccountingCompanyDetail>()
.Property(c => c.ShiptoPostalCode)
.HasColumnName("ShipPostalCode")
.HasColumnType("varchar")
.HasMaxLength(10)
.IsRequired();
#endregion
#region<--Table AccountingCustomer-->
modelBuilder.Entity<AccountingCustomer>()
.ToTable("AccountingCustomer")
.HasKey(c => c.CustomerId);
modelBuilder.Entity<AccountingCustomer>()
.Property(c => c.CustomerName)
.HasColumnType("varchar")
.HasColumnName("Name")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingCustomer>()
.Property(c => c.CustomerInActive)
.HasColumnName("Active")
.HasColumnType("bit");
modelBuilder.Entity<AccountingCustomer>()
.Property(c => c.CustomerCompanyRegno)
.HasColumnName("Registrationno")
.HasColumnType("int")
.IsOptional();
modelBuilder.Entity<AccountingCustomer>()
.Property(c => c.CustomerBalanceAmt)
.HasColumnName("BalanceAmt")
.HasColumnType("money")
.IsOptional();
modelBuilder.Entity<AccountingCustomer>()
.Property(c => c.CustomerType)
.HasColumnType("varchar")
.HasColumnName("CustomerType")
.HasMaxLength(20)
.IsRequired();
modelBuilder.Entity<AccountingCustomer>()
.Property(c => c.Salesman)
.HasColumnName("SalesMan")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingCustomer>()
.Property(c => c.CustomerTelephone)
.HasColumnName("Telephoneno")
.HasColumnType("varchar")
.HasMaxLength(15)
.IsRequired();
modelBuilder.Entity<AccountingCustomer>()
.Property(c => c.CustomerFax)
.HasColumnName("Fax")
.HasColumnType("varchar")
.HasMaxLength(20)
.IsOptional();
modelBuilder.Entity<AccountingCustomer>()
.Property(c => c.CustomerEmail)
.HasColumnName("Email")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingCustomer>()
.Property(c => c.CustomerContactPerson)
.HasColumnType("varchar")
.HasColumnName("ContactPerson")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingCustomer>()
.Property(c => c.CustomerRemarks)
.HasColumnName("Remarks")
.HasColumnType("varchar")
.HasMaxLength(200)
.IsRequired();
modelBuilder.Entity<AccountingCustomer>()
.Property(c => c.CustomerBilltoLine1)
.HasColumnName("BillAddressLine1")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingCustomer>()
.Property(c => c.CustomerBilltoLine2)
.HasColumnName("BillAddressLine2")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsOptional();
modelBuilder.Entity<AccountingCustomer>()
.Property(c => c.CustomerBilltoCity)
.HasColumnName("BillCity")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingCustomer>()
.Property(c => c.CustomerBilltoState)
.HasColumnName("BillState")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingCustomer>()
.Property(c => c.CustomerBilltoCountry)
.HasColumnName("BillCountry")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingCustomer>()
.Property(c => c.CustomerBilltoPostalCode)
.HasColumnType("varchar")
.HasColumnName("BillPostalCode")
.HasMaxLength(20)
.IsRequired();
modelBuilder.Entity<AccountingCustomer>()
.Property(c => c.CustomerShiptoLine1)
.HasColumnType("varchar")
.HasColumnName("ShipAddressLine1")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingCustomer>()
.Property(c => c.CustomerShiptoLine2)
.HasColumnName("ShipAddressLine2")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsOptional();
modelBuilder.Entity<AccountingCustomer>()
.Property(c => c.CustomerShiptoCity)
.HasColumnName("ShipCity")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingCustomer>()
.Property(c => c.CustomerShiptoState)
.HasColumnType("varchar")
.HasColumnName("ShipState")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingCustomer>()
.Property(c => c.CustomerShiptoCountry)
.HasColumnType("varchar")
.HasColumnName("ShipCountry")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingCustomer>()
.Property(c => c.CustomerShiptoPostalCode)
.HasColumnType("varchar")
.HasColumnName("ShipPostalCode")
.HasMaxLength(20)
.IsRequired();
#endregion
#region<--Table AccountingSupplier-->
modelBuilder.Entity<AccountingSupplier>()
.ToTable("AccountingSupplier")
.HasKey(c => c.SupplierId);
modelBuilder.Entity<AccountingSupplier>()
.Property(c => c.SupplierName)
.HasColumnType("varchar")
.HasColumnName("Name")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingSupplier>()
.Property(c => c.SupplierInActive)
.HasColumnName("Active")
.HasColumnType("bit");
modelBuilder.Entity<AccountingSupplier>()
.Property(c => c.SupplierCompanyRegno)
.HasColumnName("Registrationno")
.HasColumnType("int")
.IsOptional();
modelBuilder.Entity<AccountingSupplier>()
.Property(c => c.SupplierBalanceAmt)
.HasColumnName("BalanceAmt")
.HasColumnType("money")
.IsOptional();
modelBuilder.Entity<AccountingSupplier>()
.Property(c => c.SupplierTelephone)
.HasColumnName("Telephoneno")
.HasColumnType("varchar")
.HasMaxLength(15)
.IsRequired();
modelBuilder.Entity<AccountingSupplier>()
.Property(c => c.SupplierFax)
.HasColumnName("Fax")
.HasColumnType("varchar")
.HasMaxLength(20)
.IsOptional();
modelBuilder.Entity<AccountingSupplier>()
.Property(c => c.SupplierEmail)
.HasColumnName("Email")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingSupplier>()
.Property(c => c.SupplierContactPerson)
.HasColumnType("varchar")
.HasColumnName("ContactPerson")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingSupplier>()
.Property(c => c.SupplierRemarks)
.HasColumnName("Remarks")
.HasColumnType("varchar")
.HasMaxLength(200)
.IsRequired();
modelBuilder.Entity<AccountingSupplier>()
.Property(c => c.SupplierBilltoLine1)
.HasColumnName("BillAddressLine1")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingSupplier>()
.Property(c => c.SupplierBilltoLine2)
.HasColumnName("BillAddressLine2")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsOptional();
modelBuilder.Entity<AccountingSupplier>()
.Property(c => c.SupplierBilltoCity)
.HasColumnName("BillCity")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingSupplier>()
.Property(c => c.SupplierBilltoState)
.HasColumnName("BillState")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingSupplier>()
.Property(c => c.SupplierBilltoCountry)
.HasColumnName("BillCountry")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingSupplier>()
.Property(c => c.SupplierBilltoPostalCode)
.HasColumnType("varchar")
.HasColumnName("BillPostalCode")
.HasMaxLength(20)
.IsRequired();
modelBuilder.Entity<AccountingSupplier>()
.Property(c => c.SupplierShiptoLine1)
.HasColumnType("varchar")
.HasColumnName("ShipAddressLine1")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingSupplier>()
.Property(c => c.SupplierShiptoLine2)
.HasColumnName("ShipAddressLine2")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsOptional();
modelBuilder.Entity<AccountingSupplier>()
.Property(c => c.SupplierShiptoCity)
.HasColumnName("ShipCity")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingSupplier>()
.Property(c => c.SupplierShiptoState)
.HasColumnType("varchar")
.HasColumnName("ShipState")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingSupplier>()
.Property(c => c.SupplierShiptoCountry)
.HasColumnType("varchar")
.HasColumnName("ShipCountry")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingSupplier>()
.Property(c => c.SupplierShiptoPostalCode)
.HasColumnType("varchar")
.HasColumnName("ShipPostalCode")
.HasMaxLength(20)
.IsRequired();
#endregion
#region<--AccountingOptions-->
modelBuilder.Entity<AccountingOption>()
.ToTable("AccountingOptions")
.HasKey(o => o.OptionId);
modelBuilder.Entity<AccountingOption>()
.Property(o => o.OptionDate)
.HasColumnName("DateFormat")
.HasColumnType("varchar")
.HasMaxLength(10)
.IsRequired();
modelBuilder.Entity<AccountingOption>()
.Property(o => o.OptionCommas)
.HasColumnName("CommaFormat")
.HasColumnType("varchar")
.HasMaxLength(20)
.IsRequired();
modelBuilder.Entity<AccountingOption>()
.Property(o => o.OptionDecPlaces)
.HasColumnName("DecimalFormat")
.HasColumnType("varchar")
.HasMaxLength(10)
.IsRequired();
modelBuilder.Entity<AccountingOption>()
.Property(o => o.OptionCurrencyName)
.HasColumnName("CurrencyType")
.HasColumnType("varchar")
.HasMaxLength(5)
.IsRequired();
modelBuilder.Entity<AccountingOption>()
.Property(o => o.DefaultCashorBankAcc)
.HasColumnName("DefaultBankAccount")
.HasColumnType("varchar")
.HasMaxLength(20)
.IsRequired();
#endregion
#region<--AccountingProduct-->
modelBuilder.Entity<AccountingProduct>()
.ToTable("AccountingProducts")
.HasKey(p => p.ProductId);
modelBuilder.Entity<AccountingProduct>()
.Property(p => p.ProductCode)
.HasColumnName("ProductCode")
.HasColumnType("int")
.IsRequired();
modelBuilder.Entity<AccountingProduct>()
.Property(p => p.ProductName)
.HasColumnName("Name")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingProduct>()
.Property(p => p.ProductQty)
.HasColumnName("Quantity")
.HasColumnType("int")
.IsRequired();
modelBuilder.Entity<AccountingProduct>()
.Property(p => p.ProductPrice)
.HasColumnName("Price")
.HasColumnType("money")
.IsRequired();
modelBuilder.Entity<AccountingProduct>()
.Property(p => p.ProductDiscount)
.HasColumnName("Discount")
.HasColumnType("decimal")
.IsRequired();
#endregion
#region<--AccountingPurchaseInvoice-->
modelBuilder.Entity<AccountingPurchaseInvoice>()
.ToTable("AccountingPurchaseInvoice")
.HasKey(po => po.PurchaseInvoiceId);
modelBuilder.Entity<AccountingPurchaseInvoice>()
.Property(po => po.PurchaseInvoiceNo)
.HasColumnName("Invoiceno")
.HasColumnType("int")
.IsRequired();
modelBuilder.Entity<AccountingPurchaseInvoice>()
.Property(po => po.PurchaseInvoiceDate)
.HasColumnName("InvoiceDate")
.HasColumnType("date")
.IsRequired();
modelBuilder.Entity<AccountingPurchaseInvoice>()
.Property(po => po.PurchaseInvoicePOno)
.HasColumnName("InvoicePono")
.HasColumnType("int")
.IsRequired();
modelBuilder.Entity<AccountingPurchaseInvoice>()
.Property(po => po.PurchaseSupplierName)
.HasColumnName("SupplierName")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsOptional();
modelBuilder.Entity<AccountingPurchaseInvoice>()
.Property(po => po.PurchaseInvoiceBillToLine1)
.HasColumnName("BillAddressLine1")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingPurchaseInvoice>()
.Property(po => po.PurchaseInvoiceShipToLine1)
.HasColumnName("ShipAddressLine1")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingPurchaseInvoice>()
.Property(po => po.PurchaseProductAmt)
.HasColumnName("Amount")
.HasColumnType("money")
.IsRequired();
modelBuilder.Entity<AccountingPurchaseInvoice>()
.Property(po => po.PurchaseTandC)
.HasColumnName("Terms&Condition")
.HasColumnType("varchar")
.HasMaxLength(200)
.IsRequired();
#endregion
#region<--AccountingPurchaseOrder-->
modelBuilder.Entity<AccountingPurchaseOrder>()
.ToTable("AccountingPurchaseOrder")
.HasKey(po => po.PurchaseOrderId);
modelBuilder.Entity<AccountingPurchaseOrder>()
.Property(po => po.PurchaseOrderNo)
.HasColumnName("Orderno")
.HasColumnType("int")
.IsRequired();
modelBuilder.Entity<AccountingPurchaseOrder>()
.Property(po => po.PurchaseOrderDate)
.HasColumnName("OrderDate")
.HasColumnType("date")
.IsRequired();
modelBuilder.Entity<AccountingPurchaseOrder>()
.Property(po => po.PurchaseOrderDeliveryDate)
.HasColumnName("DeliveryDate")
.HasColumnType("Date")
.IsRequired();
modelBuilder.Entity<AccountingPurchaseOrder>()
.Property(po => po.PurchaseSupplierName)
.HasColumnName("SupplierName")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsOptional();
modelBuilder.Entity<AccountingPurchaseOrder>()
.Property(po => po.PurchaseOrderBillToLine1)
.HasColumnName("BillAddressLine1")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingPurchaseOrder>()
.Property(po => po.PurchaseOrderShipToLine1)
.HasColumnName("ShipAddressLine1")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingPurchaseOrder>()
.Property(po => po.PurchaseProductAmt)
.HasColumnName("Amount")
.HasColumnType("money")
.IsRequired();
modelBuilder.Entity<AccountingPurchaseOrder>()
.Property(po => po.PurchaseTandC)
.HasColumnName("Terms&Condition")
.HasColumnType("varchar")
.HasMaxLength(200)
.IsRequired();
#endregion
#region<--AccountingSalesInvoice-->
modelBuilder.Entity<AccountingSalesInvoice>()
.ToTable("AccountingSalesInvoice")
.HasKey(po => po.SalesInvoiceId);
modelBuilder.Entity<AccountingSalesInvoice>()
.Property(po => po.SalesInvoiceNo)
.HasColumnName("Orderno")
.HasColumnType("int")
.IsRequired();
modelBuilder.Entity<AccountingSalesInvoice>()
.Property(po => po.SalesInvoiceDate)
.HasColumnName("OrderDate")
.HasColumnType("date")
.IsRequired();
modelBuilder.Entity<AccountingSalesInvoice>()
.Property(po => po.SalesInvoicePOno)
.HasColumnName("InvoicePono")
.HasColumnType("int")
.IsRequired();
modelBuilder.Entity<AccountingSalesInvoice>()
.Property(po => po.SalesCustomerName)
.HasColumnName("SupplierName")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsOptional();
modelBuilder.Entity<AccountingSalesInvoice>()
.Property(po => po.SalesInvoiceBillToLine1)
.HasColumnName("BillAddressLine1")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingSalesInvoice>()
.Property(po => po.SalesInvoiceShipToLine1)
.HasColumnName("ShipAddressLine1")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingSalesInvoice>()
.Property(po => po.SalesProductAmt)
.HasColumnName("Amount")
.HasColumnType("money")
.IsRequired();
modelBuilder.Entity<AccountingSalesInvoice>()
.Property(po => po.SalesTandC)
.HasColumnName("Terms&Condition")
.HasColumnType("varchar")
.HasMaxLength(200)
.IsRequired();
#endregion
#region<--AccountingSalesOrder-->
modelBuilder.Entity<AccountingSalesOrder>()
.ToTable("AccountingSalesOrder")
.HasKey(po => po.SalesOrderId);
modelBuilder.Entity<AccountingSalesOrder>()
.Property(po => po.SalesOrderNo)
.HasColumnName("Orderno")
.HasColumnType("int")
.IsRequired();
modelBuilder.Entity<AccountingSalesOrder>()
.Property(po => po.SalesOrderDate)
.HasColumnName("OrderDate")
.HasColumnType("date")
.IsRequired();
modelBuilder.Entity<AccountingSalesOrder>()
.Property(po => po.SalesOrderDeliveryDate)
.HasColumnName("DeliveryDate")
.HasColumnType("Date")
.IsRequired();
modelBuilder.Entity<AccountingSalesOrder>()
.Property(po => po.SalesCustomerName)
.HasColumnName("SupplierName")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsOptional();
modelBuilder.Entity<AccountingSalesOrder>()
.Property(po => po.SalesOrderBillToLine1)
.HasColumnName("BillAddressLine1")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingSalesOrder>()
.Property(po => po.SalesOrderShipToLine1)
.HasColumnName("ShipAddressLine1")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity<AccountingSalesOrder>()
.Property(po => po.SalesProductAmt)
.HasColumnName("Amount")
.HasColumnType("money")
.IsRequired();
modelBuilder.Entity<AccountingSalesOrder>()
.Property(po => po.SalesTandC)
.HasColumnName("Terms&Condition")
.HasColumnType("varchar")
.HasMaxLength(200)
.IsRequired();
#endregion
#region<--AccountingPurchaseOrderDetail-->
modelBuilder.Entity<AccountingPurchaseOrderDetail>()
.ToTable("AccountingPurchaseOrderDetails")
.HasKey(po => po.PurchaseOrderDetailId);
#endregion
#region<--AccountingSalesOrderDetail-->
modelBuilder.Entity<AccountingSalesOrderDetail>()
.ToTable("AccountingSalesOrderDetails")
.HasKey(po => po.SalesOrderDetailId);
#endregion
#region<--AccountingPurchaseInvoiceDetail-->
modelBuilder.Entity<AccountingPurchaseInvoiceDetail>()
.ToTable("AccountingPurchaseInvoiceDetails")
.HasKey(po => po.PurchaseInvoiceDetailId);
#endregion
#region<--AccountingSalesInvoiceDetail-->
modelBuilder.Entity<AccountingSalesInvoiceDetail>()
.ToTable("AccountingSalesInvoiceDetail")
.HasKey(po => po.SalesInvoiceDetailId);
#endregion
modelBuilder.Entity<AccountingSalesOrder>()
.HasRequired(t => t.SOCustomer)
.WithMany(t => t.CustomerSalesOrder)
.HasForeignKey(d => d.CustomerId);
modelBuilder.Entity<AccountingSalesInvoice>()
.HasRequired(t => t.SICustomer)
.WithMany(t => t.CustomerSalesInvoice)
.HasForeignKey(d => d.CustomerId);
modelBuilder.Entity<AccountingPurchaseOrder>()
.HasRequired(t => t.POSupplier)
.WithMany(t => t.SupplierPurchaseOrder)
.HasForeignKey(d => d.SupplierId);
modelBuilder.Entity<AccountingPurchaseInvoice>()
.HasRequired(t => t.PISupplier)
.WithMany(t => t.SupplierPurchaseInvoice)
.HasForeignKey(d => d.SupplierId);
modelBuilder.Entity<AccountingPurchaseInvoiceDetail>()
.HasRequired(t => t.PurchaseInvoiceFK)
.WithRequiredPrincipal(t => t.PurchaseInvoiceDetail);
modelBuilder.Entity<AccountingPurchaseOrderDetail>()
.HasRequired(t => t.PurchaseOrderFK)
.WithRequiredPrincipal(t => t.PurchaseOrderDetail);
modelBuilder.Entity<AccountingSalesInvoiceDetail>()
.HasRequired(t => t.SalesInvoiceFK)
.WithRequiredPrincipal(t => t.SalesInvoiceDetail);
modelBuilder.Entity<AccountingSalesOrderDetail>()
.HasRequired(t => t.SalesOrderFK)
.WithRequiredPrincipal(t => t.SalesOrderDetail);
modelBuilder.Entity<AccountingProduct>()
.HasRequired(t => t.ProductPurchaseInvoice)
.WithMany(t => t.PIProductFK);
modelBuilder.Entity<AccountingProduct>()
.HasRequired(t => t.ProductPurchaseOrder)
.WithMany(t => t.POProductFK);
modelBuilder.Entity<AccountingProduct>()
.HasRequired(t => t.ProductSalesInvoice)
.WithMany(t => t.SIProductFK);
modelBuilder.Entity<AccountingProduct>()
.HasRequired(t => t.ProductSalesOrder)
.WithMany(t => t.SOProductFK);
}
public override int SaveChanges()
{
var modifiedEntries = ChangeTracker.Entries()
.Where(x => x.Entity is IAuditableEntity
&& (x.State == System.Data.Entity.EntityState.Added || x.State == System.Data.Entity.EntityState.Modified));
foreach (var entry in modifiedEntries)
{
IAuditableEntity entity = entry.Entity as IAuditableEntity;
if (entity != null)
{
string identityName = Thread.CurrentPrincipal.Identity.Name;
DateTime now = DateTime.UtcNow;
if (entry.State == System.Data.Entity.EntityState.Added)
{
entity.CreatedBy = identityName;
entity.CreatedDate = now;
}
else
{
base.Entry(entity).Property(x => x.CreatedBy).IsModified = false;
base.Entry(entity).Property(x => x.CreatedDate).IsModified = false;
}
entity.UpdatedBy = identityName;
entity.UpdatedDate = now;
}
}
return base.SaveChanges();
}
public void Commit()
{
base.SaveChanges();
}
}
}
| 34.413569 | 128 | 0.535202 | [
"MIT"
] | SimpleAccountingTeam2/Praneet-Thakur | SimpleAccouning.API/SimpleAccounting.Repository/SimpleAccountingContext.cs | 37,031 | C# |
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using Jwt;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MonitorizareVot.Api.ViewModels;
using MonitorizareVot.Ong.Api.Common;
using MonitorizareVot.Ong.Api.ViewModels;
using MonitorizareVot.Ong.Api.Extensions;
namespace MonitorizareVot.Api.Controllers
{
[Route("api/v1/auth")]
public class JwtController : Controller
{
private readonly IMediator _mediator;
private readonly JwtIssuerOptions _jwtOptions;
private readonly ILogger _logger;
public JwtController(IOptions<JwtIssuerOptions> jwtOptions, ILoggerFactory loggerFactory, IMediator mediator)
{
_mediator = mediator;
_jwtOptions = jwtOptions.Value;
ThrowIfInvalidOptions(_jwtOptions);
_logger = loggerFactory.CreateLogger<JwtController>();
}
[HttpGet]
[AllowAnonymous]
// this method will only be called the token is expired
public async Task<IActionResult> RefreshLogin()
{
string token = Request.Headers[ControllerExtensions.AUTH_HEADER_VALUE];
if (string.IsNullOrEmpty(token))
return Forbid();
if (token.StartsWith(ControllerExtensions.BEARER_VALUE, StringComparison.OrdinalIgnoreCase))
token = token.Substring(ControllerExtensions.BEARER_VALUE.Length).Trim();
if (string.IsNullOrEmpty(token))
return Forbid();
var decoded = JsonWebToken.DecodeToObject<Dictionary<string, string>>(token,
_jwtOptions.SigningCredentials.Kid, false);
var idOng = int.Parse(decoded[ControllerExtensions.ID_NGO_VALUE]);
var organizator = bool.Parse(decoded[ControllerExtensions.ORGANIZER_VALUE]);
var userName = decoded[JwtRegisteredClaimNames.Sub];
var json = await GenerateToken(userName, idOng, organizator);
return new OkObjectResult(json);
}
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login([FromBody] ApplicationUser applicationUser)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
//await _mediator.Send(new ImportObserversRequest {FilePath = "d:\\mv-name-rest.11.15.txt", IdNgo = 3, NameIndexInFile = 2}); // mv
//await _mediator.Send(new ImportObserversRequest { FilePath = "d:\\dv-rest7.txt", IdNgo = 2, NameIndexInFile = 0 }); // usr
var identity = await GetClaimsIdentity(applicationUser);
if (identity == null)
{
_logger.LogInformation(
$"Invalid username ({applicationUser.UserName}) or password ({applicationUser.Password})");
return BadRequest("Invalid credentials");
}
var json = await GenerateToken(applicationUser.UserName,
int.Parse(identity.Claims.FirstOrDefault(c => c.Type == ControllerExtensions.ID_NGO_VALUE)?.Value),
bool.Parse(identity.Claims.FirstOrDefault(c => c.Type == ControllerExtensions.ORGANIZER_VALUE)?.Value));
return new OkObjectResult(json);
}
[Authorize]
[HttpPost("test")]
public async Task<object> Test()
{
var claims = User.Claims.Select(c => new
{
c.Type,
c.Value
});
return await Task.FromResult(claims);
}
private async Task<string> GenerateToken(string userName, int idOng = 0, bool organizator = false)
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, userName),
new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()),
new Claim(JwtRegisteredClaimNames.Iat,
ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(),
ClaimValueTypes.Integer64),
new Claim(ControllerExtensions.ID_NGO_VALUE, idOng.ToString()),
new Claim(ControllerExtensions.ORGANIZER_VALUE, organizator.ToString())
};
// Create the JWT security token and encode it.
var jwt = new JwtSecurityToken(
issuer: _jwtOptions.Issuer,
audience: _jwtOptions.Audience,
claims: claims,
notBefore: _jwtOptions.NotBefore,
expires: _jwtOptions.Expiration,
signingCredentials: _jwtOptions.SigningCredentials);
var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
// Serialize and return the response
//var response = new
//{
// token = encodedJwt,
// expires_in = (int)_jwtOptions.ValidFor.TotalSeconds
//};
//var json = JsonConvert.SerializeObject(response, _serializerSettings);
return encodedJwt;
}
private static void ThrowIfInvalidOptions(JwtIssuerOptions options)
{
if (options == null) throw new ArgumentNullException(nameof(options));
if (options.ValidFor <= TimeSpan.Zero)
{
throw new ArgumentException("Must be a non-zero TimeSpan.", nameof(JwtIssuerOptions.ValidFor));
}
if (options.SigningCredentials == null)
{
throw new ArgumentNullException(nameof(JwtIssuerOptions.SigningCredentials));
}
if (options.JtiGenerator == null)
{
throw new ArgumentNullException(nameof(JwtIssuerOptions.JtiGenerator));
}
}
/// <returns>Date converted to seconds since Unix epoch (Jan 1, 1970, midnight UTC).</returns>
private static long ToUnixEpochDate(DateTime date)
=> (long)Math.Round((date.ToUniversalTime() -
new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero))
.TotalSeconds);
private async Task<ClaimsIdentity> GetClaimsIdentity(ApplicationUser user)
{
var userInfo = await _mediator.Send(user);
if (userInfo == null)
return await Task.FromResult<ClaimsIdentity>(null);
return await Task.FromResult(new ClaimsIdentity(
new GenericIdentity(user.UserName, ControllerExtensions.TOKEN_VALUE), new[]
{
new Claim(ControllerExtensions.ID_NGO_VALUE, userInfo.IdNgo.ToString()),
new Claim(ControllerExtensions.ORGANIZER_VALUE, userInfo.Organizer.ToString())
}));
}
}
} | 40.142857 | 148 | 0.612527 | [
"MPL-2.0"
] | AndyRadulescu/monitorizare-vot-ong | api/MonitorizareVot.Ong/src/MonitorizareVot.Api/Controllers/JwtController.cs | 7,027 | C# |
using Robust.Client.Interfaces.ResourceManagement;
using Robust.Client.Interfaces.UserInterface;
using Robust.Client.UserInterface;
using Robust.Shared.IoC;
namespace Content.Client.UserInterface.Stylesheets
{
public sealed class StylesheetManager : IStylesheetManager
{
#pragma warning disable 649
[Dependency] private readonly IUserInterfaceManager _userInterfaceManager;
[Dependency] private readonly IResourceCache _resourceCache;
#pragma warning restore 649
public Stylesheet SheetNano { get; private set; }
public Stylesheet SheetSpace { get; private set; }
public void Initialize()
{
SheetNano = new StyleNano(_resourceCache).Stylesheet;
SheetSpace = new StyleSpace(_resourceCache).Stylesheet;
_userInterfaceManager.Stylesheet = SheetNano;
}
}
}
| 31.888889 | 82 | 0.729384 | [
"MIT"
] | ComicIronic/space-station-14 | Content.Client/UserInterface/Stylesheets/StylesheetManager.cs | 861 | 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("05.invalidNumber")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("05.invalidNumber")]
[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("c3655b1b-280a-42ee-bfc8-45a54b17edb6")]
// 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.972973 | 84 | 0.745196 | [
"MIT"
] | pkemalov/ProgrammingBasics | ComplexConditionalStatements/05.invalidNumber/Properties/AssemblyInfo.cs | 1,408 | C# |
using System;
using System.Collections.Generic;
namespace Poynt.NET.Model
{
public class Hook
{
private const string TAG = "Hook";
public bool? Active { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
public IList<string> EventTypes { get; set; }
public string Id { get; set; }
public string ApplicationId { get; set; }
public string Secret { get; set; }
public string DeliveryUrl { get; set; }
public System.Guid businessId;
}
}
| 15.352941 | 46 | 0.66092 | [
"MIT"
] | segios/Poynt.NET | Poynt.NET.Model/Hook.cs | 522 | C# |
using System;
using System.Collections;
using TMPro;
using UnityEngine;
namespace NaturalSelectionSimulation
{
public class SimulationIterationController : MonoBehaviour
{
#region Private Variables
private int _iterationCount = 0; // simple counter for currentIteration number (our 'high-score')
private int currentScore = 0;
public TMP_Text SimulationTimeDisplayText;
public TMP_Text SimulationCurrentScoreDisplayText;
public TMP_Text ScoreBonusDiplayText;
#endregion
private void Start()
{
SimulationTimeDisplayText.text = "Day 1 - 00:00";
SimulationCurrentScoreDisplayText.text = "Current Score: 0";
ScoreBonusDiplayText.enabled = false;
}
private void OnEnable()
{
StateController.OnIterationAdvance += AdvanceIteration; // Subscribe to AdvanceCall
}
private void OnDisable()
{
StateController.OnIterationAdvance -= AdvanceIteration; // Unsubscribe from AdvanceCall
}
#region Custom Methods
/// <summary>
/// Simply iterates up the count for the current iteration number
/// </summary>
public void AdvanceIteration()
{
_iterationCount++; //advance turn count
currentScore++;
if (_iterationCount % 1440 == 0)
{
currentScore += 1000;
ShowToast(ScoreBonusDiplayText, "Day Bonus: +1000", 3);
}
else if (_iterationCount % 60 == 0)
{
currentScore += 100;
ShowToast(ScoreBonusDiplayText, "Hour Bonus: +100", 3);
}
SimulationTimeDisplayText.text = $"Day {(_iterationCount / 1440) + 1} - {new TimeSpan((_iterationCount / 60) % 24, _iterationCount % 60, 0).ToString(@"hh\:mm")}";
SimulationCurrentScoreDisplayText.text = $"Current Score: {currentScore.ToString("N0")}";
}
#region Toast Methods
private void ShowToast(TMP_Text textField, string text, int duration)
{
StartCoroutine(showToastCOR(textField, text, duration));
}
private IEnumerator showToastCOR(TMP_Text textField, string text, int duration)
{
Color orginalColor = ScoreBonusDiplayText.color;
textField.text = text;
textField.enabled = true;
//Fade in
yield return fadeInAndOut(textField, true, 0.5f);
//Wait for the duration
float counter = 0;
while (counter < duration)
{
counter += Time.deltaTime;
yield return null;
}
//Fade out
yield return fadeInAndOut(textField, false, 0.5f);
textField.enabled = false;
textField.color = orginalColor;
}
private IEnumerator fadeInAndOut(TMP_Text textField, bool fadeIn, float duration)
{
//Set Values depending on if fadeIn or fadeOut
float a, b;
if (fadeIn)
{
a = 0f;
b = 1f;
}
else
{
a = 1f;
b = 0f;
}
Color currentColor = Color.white;
float counter = 0f;
while (counter < duration)
{
counter += Time.deltaTime;
float alpha = Mathf.Lerp(a, b, counter / duration);
textField.color = new Color(currentColor.r, currentColor.g, currentColor.b, alpha);
yield return null;
}
}
#endregion
#endregion
}
} | 29.833333 | 174 | 0.549082 | [
"MIT"
] | JohnMurwin/NaturalSelectionSimulation | Assets/NaturalSelectionSimulation/Scripts/SimulationStateSystem/SimulationIterationController.cs | 3,759 | C# |
/*
* Exchange Web Services Managed API
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
/// <summary>
/// Represents an entry of a PhoneNumberDictionary.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public sealed class PhoneNumberEntry : DictionaryEntryProperty<PhoneNumberKey>
{
private string phoneNumber;
/// <summary>
/// Initializes a new instance of the <see cref="PhoneNumberEntry"/> class.
/// </summary>
internal PhoneNumberEntry()
: base()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="PhoneNumberEntry"/> class.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="phoneNumber">The phone number.</param>
internal PhoneNumberEntry(PhoneNumberKey key, string phoneNumber)
: base(key)
{
this.phoneNumber = phoneNumber;
}
/// <summary>
/// Reads the text value from XML.
/// </summary>
/// <param name="reader">The reader.</param>
internal override void ReadTextValueFromXml(EwsServiceXmlReader reader)
{
this.phoneNumber = reader.ReadValue();
}
/// <summary>
/// Writes elements to XML.
/// </summary>
/// <param name="writer">The writer.</param>
internal override void WriteElementsToXml(EwsServiceXmlWriter writer)
{
writer.WriteValue(this.PhoneNumber, XmlElementNames.PhoneNumber);
}
/// <summary>
/// Gets or sets the phone number of the entry.
/// </summary>
public string PhoneNumber
{
get { return this.phoneNumber; }
set { this.SetFieldValue<string>(ref this.phoneNumber, value); }
}
}
} | 35.931034 | 93 | 0.649712 | [
"MIT"
] | OfficeDevUnofficial/ews-managed-api | ews-managed-api/ComplexProperties/PhoneNumberEntry.cs | 3,126 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Fixtures.BodyComplex.Models
{
using Newtonsoft.Json;
using System.Linq;
public partial class ByteWrapper
{
/// <summary>
/// Initializes a new instance of the ByteWrapper class.
/// </summary>
public ByteWrapper()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the ByteWrapper class.
/// </summary>
public ByteWrapper(byte[] field = default(byte[]))
{
Field = field;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "field")]
public byte[] Field { get; set; }
}
}
| 26.191489 | 90 | 0.590577 | [
"MIT"
] | ChristianEder/autorest.csharp | test/vanilla/Expected/BodyComplex/Models/ByteWrapper.cs | 1,231 | 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("Middle-Chars")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Middle-Chars")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e5eaf769-1f1e-4fd7-b11b-45c67134aa53")]
// 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.621622 | 84 | 0.746408 | [
"MIT"
] | bodyquest/SoftwareUniversity-Bulgaria | Technology Fundamentals C# Jan2019/4. Methods/Middle-Chars/Properties/AssemblyInfo.cs | 1,395 | C# |
// Part of fCraft | Copyright 2009-2015 Matvei Stefarov <me@matvei.org> | BSD-3 | See LICENSE.txt //Copyright (c) 2011-2013 Jon Baker, Glenn Marien and Lao Tszy <Jonty800@gmail.com> //Copyright (c) <2012-2014> <LeChosenOne, DingusBungus> | ProCraft Copyright 2014-2019 Joseph Beauvais <123DMWM@gmail.com>
using System;
using System.Collections.Generic;
namespace fCraft.Drawing {
/// <summary> Draw operation that creates an outline of a triangle, using three given coordinates as vertices. </summary>
public sealed class TriangleWireframeDrawOperation : DrawOperation {
public override int ExpectedMarks {
get { return 3; }
}
public override string Name {
get { return "TriangleW"; }
}
public TriangleWireframeDrawOperation( Player player )
: base( player ) {
}
public override bool Prepare( Vector3I[] marks ) {
Vector3I minVector = new Vector3I( Math.Min( marks[0].X, Math.Min( marks[1].X, marks[2].X ) ),
Math.Min( marks[0].Y, Math.Min( marks[1].Y, marks[2].Y ) ),
Math.Min( marks[0].Z, Math.Min( marks[1].Z, marks[2].Z ) ) );
Vector3I maxVector = new Vector3I( Math.Max( marks[0].X, Math.Max( marks[1].X, marks[2].X ) ),
Math.Max( marks[0].Y, Math.Max( marks[1].Y, marks[2].Y ) ),
Math.Max( marks[0].Z, Math.Max( marks[1].Z, marks[2].Z ) ) );
Bounds = new BoundingBox( minVector, maxVector );
if( !base.Prepare( marks ) ) return false;
BlocksTotalEstimate = Math.Max( Bounds.Width, Math.Max( Bounds.Height, Bounds.Length ) );
coordEnumerator1 = LineEnumerator( Marks[0], Marks[1] ).GetEnumerator();
coordEnumerator2 = LineEnumerator( Marks[1], Marks[2] ).GetEnumerator();
coordEnumerator3 = LineEnumerator( Marks[2], Marks[0] ).GetEnumerator();
return true;
}
IEnumerator<Vector3I> coordEnumerator1, coordEnumerator2, coordEnumerator3;
public override int DrawBatch( int maxBlocksToDraw ) {
int blocksDone = 0;
while( coordEnumerator1.MoveNext() ) {
Coords = coordEnumerator1.Current;
if( DrawOneBlockIfNotDuplicate() ) {
blocksDone++;
if( blocksDone >= maxBlocksToDraw ) return blocksDone;
}
if( TimeToEndBatch ) return blocksDone;
}
while( coordEnumerator2.MoveNext() ) {
Coords = coordEnumerator2.Current;
if( DrawOneBlockIfNotDuplicate() ) {
blocksDone++;
if( blocksDone >= maxBlocksToDraw ) return blocksDone;
}
if( TimeToEndBatch ) return blocksDone;
}
while( coordEnumerator3.MoveNext() ) {
Coords = coordEnumerator3.Current;
if( DrawOneBlockIfNotDuplicate() ) {
blocksDone++;
if( blocksDone >= maxBlocksToDraw ) return blocksDone;
}
if( TimeToEndBatch ) return blocksDone;
}
IsDone = true;
return blocksDone;
}
readonly HashSet<int> modifiedBlocks = new HashSet<int>();
bool DrawOneBlockIfNotDuplicate() {
int index = Map.Index( Coords );
if( modifiedBlocks.Contains( index ) ) {
return false;
} else {
modifiedBlocks.Add( index );
return DrawOneBlock();
}
}
}
} | 43.344828 | 305 | 0.542031 | [
"BSD-3-Clause"
] | 123DMWM/ProCraft | fCraft/Drawing/DrawOps/TriangleWireframeDrawOperation.cs | 3,773 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Roslyn.Diagnostics.Analyzers
{
// TODO: This should be updated to follow the flow of array creation expressions
// that are eventually converted to and leave a given method as IEnumerable<T> once we have
// the ability to do more thorough data-flow analysis in diagnostic analyzers.
public abstract class SpecializedEnumerableCreationAnalyzer : DiagnosticAnalyzer
{
internal const string SpecializedCollectionsMetadataName = "Roslyn.Utilities.SpecializedCollections";
internal const string IEnumerableMetadataName = "System.Collections.Generic.IEnumerable`1";
internal const string LinqEnumerableMetadataName = "System.Linq.Enumerable";
internal const string EmptyMethodName = "Empty";
private static LocalizableString s_localizableTitleUseEmptyEnumerable = new LocalizableResourceString(nameof(RoslynDiagnosticsResources.UseEmptyEnumerableDescription), RoslynDiagnosticsResources.ResourceManager, typeof(RoslynDiagnosticsResources));
private static LocalizableString s_localizableMessageUseEmptyEnumerable = new LocalizableResourceString(nameof(RoslynDiagnosticsResources.UseEmptyEnumerableMessage), RoslynDiagnosticsResources.ResourceManager, typeof(RoslynDiagnosticsResources));
internal static readonly DiagnosticDescriptor UseEmptyEnumerableRule = new DiagnosticDescriptor(
RoslynDiagnosticIds.UseEmptyEnumerableRuleId,
s_localizableTitleUseEmptyEnumerable,
s_localizableMessageUseEmptyEnumerable,
"Performance",
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
customTags: WellKnownDiagnosticTags.Telemetry);
private static LocalizableString s_localizableTitleUseSingletonEnumerable = new LocalizableResourceString(nameof(RoslynDiagnosticsResources.UseSingletonEnumerableDescription), RoslynDiagnosticsResources.ResourceManager, typeof(RoslynDiagnosticsResources));
private static LocalizableString s_localizableMessageUseSingletonEnumerable = new LocalizableResourceString(nameof(RoslynDiagnosticsResources.UseSingletonEnumerableMessage), RoslynDiagnosticsResources.ResourceManager, typeof(RoslynDiagnosticsResources));
internal static readonly DiagnosticDescriptor UseSingletonEnumerableRule = new DiagnosticDescriptor(
RoslynDiagnosticIds.UseSingletonEnumerableRuleId,
s_localizableTitleUseSingletonEnumerable,
s_localizableMessageUseSingletonEnumerable,
"Performance",
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
customTags: WellKnownDiagnosticTags.Telemetry);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get { return ImmutableArray.Create(UseEmptyEnumerableRule, UseSingletonEnumerableRule); }
}
public override void Initialize(AnalysisContext analysisContext)
{
analysisContext.RegisterCompilationStartAction(
(context) =>
{
var specializedCollectionsSymbol = context.Compilation.GetTypeByMetadataName(SpecializedCollectionsMetadataName);
if (specializedCollectionsSymbol == null)
{
// TODO: In the future, we may want to run this analyzer even if the SpecializedCollections
// type cannot be found in this compilation. In some cases, we may want to add a reference
// to SpecializedCollections as a linked file or an assembly that contains it. With this
// check, we will not warn where SpecializedCollections is not yet referenced.
return;
}
var genericEnumerableSymbol = context.Compilation.GetTypeByMetadataName(IEnumerableMetadataName);
if (genericEnumerableSymbol == null)
{
return;
}
var linqEnumerableSymbol = context.Compilation.GetTypeByMetadataName(LinqEnumerableMetadataName);
if (linqEnumerableSymbol == null)
{
return;
}
var genericEmptyEnumerableSymbol = linqEnumerableSymbol.GetMembers(EmptyMethodName).FirstOrDefault() as IMethodSymbol;
if (genericEmptyEnumerableSymbol == null ||
genericEmptyEnumerableSymbol.Arity != 1 ||
genericEmptyEnumerableSymbol.Parameters.Length != 0)
{
return;
}
GetCodeBlockStartedAnalyzer(context, genericEnumerableSymbol, genericEmptyEnumerableSymbol);
});
}
protected abstract void GetCodeBlockStartedAnalyzer(CompilationStartAnalysisContext context, INamedTypeSymbol genericEnumerableSymbol, IMethodSymbol genericEmptyEnumerableSymbol);
protected abstract class AbstractCodeBlockStartedAnalyzer<TLanguageKindEnum> where TLanguageKindEnum : struct
{
private INamedTypeSymbol _genericEnumerableSymbol;
private IMethodSymbol _genericEmptyEnumerableSymbol;
public AbstractCodeBlockStartedAnalyzer(INamedTypeSymbol genericEnumerableSymbol, IMethodSymbol genericEmptyEnumerableSymbol)
{
_genericEnumerableSymbol = genericEnumerableSymbol;
_genericEmptyEnumerableSymbol = genericEmptyEnumerableSymbol;
}
protected abstract void GetSyntaxAnalyzer(CodeBlockStartAnalysisContext<TLanguageKindEnum> context, INamedTypeSymbol genericEnumerableSymbol, IMethodSymbol genericEmptyEnumerableSymbol);
public void Initialize(CodeBlockStartAnalysisContext<TLanguageKindEnum> context)
{
var methodSymbol = context.OwningSymbol as IMethodSymbol;
if (methodSymbol != null &&
methodSymbol.ReturnType.OriginalDefinition == _genericEnumerableSymbol)
{
GetSyntaxAnalyzer(context, _genericEnumerableSymbol, _genericEmptyEnumerableSymbol);
}
}
}
protected abstract class AbstractSyntaxAnalyzer
{
protected INamedTypeSymbol genericEnumerableSymbol;
private IMethodSymbol _genericEmptyEnumerableSymbol;
public AbstractSyntaxAnalyzer(INamedTypeSymbol genericEnumerableSymbol, IMethodSymbol genericEmptyEnumerableSymbol)
{
this.genericEnumerableSymbol = genericEnumerableSymbol;
_genericEmptyEnumerableSymbol = genericEmptyEnumerableSymbol;
}
public ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get { return ImmutableArray.Create(UseEmptyEnumerableRule, UseSingletonEnumerableRule); }
}
protected bool ShouldAnalyzeArrayCreationExpression(SyntaxNode expression, SemanticModel semanticModel)
{
var typeInfo = semanticModel.GetTypeInfo(expression);
var arrayType = typeInfo.Type as IArrayTypeSymbol;
return typeInfo.ConvertedType != null &&
typeInfo.ConvertedType.OriginalDefinition == this.genericEnumerableSymbol &&
arrayType != null &&
arrayType.Rank == 1;
}
protected void AnalyzeMemberAccessName(SyntaxNode name, SemanticModel semanticModel, Action<Diagnostic> addDiagnostic)
{
var methodSymbol = semanticModel.GetSymbolInfo(name).Symbol as IMethodSymbol;
if (methodSymbol != null &&
methodSymbol.OriginalDefinition == _genericEmptyEnumerableSymbol)
{
addDiagnostic(Diagnostic.Create(UseEmptyEnumerableRule, name.Parent.GetLocation()));
}
}
protected static void AnalyzeArrayLength(int length, SyntaxNode arrayCreationExpression, Action<Diagnostic> addDiagnostic)
{
if (length == 0)
{
addDiagnostic(Diagnostic.Create(UseEmptyEnumerableRule, arrayCreationExpression.GetLocation()));
}
else if (length == 1)
{
addDiagnostic(Diagnostic.Create(UseSingletonEnumerableRule, arrayCreationExpression.GetLocation()));
}
}
}
}
}
| 53.562874 | 264 | 0.679262 | [
"Apache-2.0"
] | DavidKarlas/roslyn | src/Diagnostics/Roslyn/Core/Performance/SpecializedEnumerableCreationAnalyzer.cs | 8,947 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using EasyExplorer;
using System.IO;
using System.Runtime.InteropServices;
namespace ShellDll
{
internal class StreamStorageProvider : IFileInfoProvider, IDirInfoProvider
{
#region Fields
private ShellItem providerItem;
private FileAccess fileAccess;
#endregion
public StreamStorageProvider(FileAccess fileAccess)
{
this.fileAccess = fileAccess;
}
#region Free
internal void ReleaseStorage()
{
dirInfoRetrieved = false;
}
internal void ReleaseStream()
{
if (tempStreamReader != null)
{
tempStreamReader.CloseStream();
tempStreamReader = null;
}
if (tempParentStorage != null)
{
Marshal.ReleaseComObject(tempParentStorage);
Marshal.Release(tempParentStoragePtr);
tempParentStorage = null;
}
}
#endregion
#region IFileInfoProvider Members
private ShellStreamReader tempStreamReader;
private IStorage tempParentStorage;
private IntPtr tempParentStoragePtr;
public ShellAPI.STATSTG GetFileInfo()
{
if (tempStreamReader != null)
return tempStreamReader.StreamInfo;
else if (providerItem != null)
{
if (tempParentStorage == null)
ShellHelper.GetIStorage(providerItem.ParentItem, out tempParentStoragePtr, out tempParentStorage);
tempStreamReader = new ShellStreamReader(providerItem, tempParentStorage, fileAccess);
return tempStreamReader.StreamInfo;
}
else
throw new Exception("Not possible to retrieve the STATSTG.");
}
public Stream GetFileStream()
{
if (tempStreamReader != null)
return tempStreamReader;
else if (providerItem != null)
{
if (tempParentStorage == null)
ShellHelper.GetIStorage(providerItem.ParentItem, out tempParentStoragePtr, out tempParentStorage);
tempStreamReader = new ShellStreamReader(providerItem, tempParentStorage, fileAccess);
return tempStreamReader;
}
else
throw new Exception("Not possible to open a filestream.");
}
#endregion
#region IDirInfoProvider Members
private ShellAPI.STATSTG dirInfo;
private bool dirInfoRetrieved = false;
public ShellAPI.STATSTG GetDirInfo()
{
if (dirInfoRetrieved)
return dirInfo;
else if (providerItem != null)
{
IntPtr tempPtr;
IStorage tempStorage;
if (ShellHelper.GetIStorage(providerItem, out tempPtr, out tempStorage))
{
tempStorage.Stat(out dirInfo, ShellAPI.STATFLAG.NONAME);
Marshal.ReleaseComObject(tempStorage);
Marshal.Release(tempPtr);
}
else
throw new Exception("Not possible to retrieve the STATSTG.");
dirInfoRetrieved = true;
return dirInfo;
}
else
throw new Exception("Not possible to retrieve the STATSTG.");
}
#endregion
#region Properties
public ShellItem ProviderItem
{
get { return providerItem; }
set { providerItem = value; }
}
public FileAccess FileAccess
{
get { return fileAccess; }
set { fileAccess = value; }
}
#endregion
}
public class ShellStreamReader : Stream, IDisposable
{
#region Fields
private ShellItem shellItem;
private IntPtr streamPtr;
private IStream stream;
private bool canRead, canWrite;
private ShellAPI.STATSTG streamInfo;
private bool streamInfoRead = false;
private long currentPos;
private bool disposed = false;
#endregion
internal ShellStreamReader(ShellItem shellItem, IStorage parentStorage, FileAccess access)
{
this.shellItem = shellItem;
OpenStream(parentStorage, ref access);
this.canRead = (access == FileAccess.Read || access == FileAccess.ReadWrite);
this.canWrite = (access == FileAccess.Write || access == FileAccess.ReadWrite);
currentPos = 0;
}
~ShellStreamReader()
{
CloseStream();
}
#region Stream Members
public override bool CanRead
{
get { return canRead; }
}
public override bool CanSeek
{
get { return true; }
}
public override bool CanWrite
{
get { return canWrite; }
}
public override void Flush()
{
}
public override long Length
{
get
{
if (CanRead)
return StreamInfo.cbSize;
else
return 0;
}
}
public override long Position
{
get
{
return currentPos;
}
set
{
Seek(value, SeekOrigin.Begin);
}
}
public override int Read(byte[] buffer, int offset, int count)
{
if (CanRead)
{
byte[] readBytes = new byte[count];
IntPtr readNrPtr = Marshal.AllocCoTaskMem(32);
stream.Read(readBytes, count, readNrPtr);
int readNr = (int)Marshal.PtrToStructure(readNrPtr, typeof(Int32));
Marshal.FreeCoTaskMem(readNrPtr);
Array.Copy(readBytes, 0, buffer, offset, readNr);
currentPos += readNr;
return readNr;
}
else
return 0;
}
public override void SetLength(long value)
{
if (CanWrite)
stream.SetSize(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
if (CanWrite)
{
byte[] writeBytes = new byte[count];
Array.Copy(buffer, offset, writeBytes, 0, count);
IntPtr writtenNrPtr = Marshal.AllocCoTaskMem(64);
stream.Write(writeBytes, count, writtenNrPtr);
long writtenNr = (long)Marshal.PtrToStructure(writtenNrPtr, typeof(Int64));
Marshal.FreeCoTaskMem(writtenNrPtr);
currentPos += writtenNr;
}
}
public override long Seek(long offset, SeekOrigin origin)
{
if (CanSeek)
{
IntPtr newPosPtr = Marshal.AllocCoTaskMem(64);
stream.Seek(offset, origin, newPosPtr);
long newPos = (long)Marshal.PtrToStructure(newPosPtr, typeof(Int64));
Marshal.FreeCoTaskMem(newPosPtr);
return (currentPos = newPos);
}
else
return -1;
}
#endregion
#region IDisposable Members
void IDisposable.Dispose()
{
if (!disposed)
{
disposed = true;
if (stream != null)
{
Marshal.ReleaseComObject(stream);
stream = null;
}
if (streamPtr != IntPtr.Zero)
{
Marshal.Release(streamPtr);
streamPtr = IntPtr.Zero;
}
GC.SuppressFinalize(this);
}
}
#endregion
#region Open/Close Stream
public override void Close()
{
}
internal void CloseStream()
{
base.Close();
if (stream != null)
{
Marshal.ReleaseComObject(stream);
Marshal.Release(streamPtr);
}
}
internal ShellAPI.STATSTG StreamInfo
{
get
{
if (!streamInfoRead)
{
stream.Stat(out streamInfo, ShellAPI.STATFLAG.NONAME);
streamInfoRead = true;
}
return streamInfo;
}
}
private void OpenStream(IStorage parentStorage, ref FileAccess access)
{
ShellAPI.STGM grfmode = ShellAPI.STGM.SHARE_DENY_WRITE;
switch (access)
{
case FileAccess.ReadWrite:
grfmode |= ShellAPI.STGM.READWRITE;
break;
case FileAccess.Write:
grfmode |= ShellAPI.STGM.WRITE;
break;
}
if (parentStorage != null)
{
if (parentStorage.OpenStream(
shellItem.Text + (shellItem.IsLink ? ".lnk" : string.Empty),
IntPtr.Zero,
grfmode,
0,
out streamPtr) == ShellAPI.S_OK)
{
stream = (IStream)Marshal.GetTypedObjectForIUnknown(streamPtr, typeof(IStream));
}
else if (access != FileAccess.Read)
{
if (parentStorage.OpenStream(
shellItem.Text + (shellItem.IsLink ? ".lnk" : string.Empty),
IntPtr.Zero,
ShellAPI.STGM.SHARE_DENY_WRITE,
0,
out streamPtr) == ShellAPI.S_OK)
{
access = FileAccess.Read;
stream = (IStream)Marshal.GetTypedObjectForIUnknown(streamPtr, typeof(IStream));
}
else
throw new IOException(String.Format("Can't open stream: {0}", shellItem));
}
else
throw new IOException(String.Format("Can't open stream: {0}", shellItem));
}
else
{
access = FileAccess.Read;
if (!ShellHelper.GetIStream(shellItem, out streamPtr, out stream))
throw new IOException(String.Format("Can't open stream: {0}", shellItem));
}
}
#endregion
}
}
| 27.725191 | 118 | 0.49275 | [
"MIT"
] | hgupta9/EasyExplorer | Shell/StreamStorage.cs | 10,896 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class homework33 : MonoBehaviour {
public GameObject cube;
public float movespeed;
public Material[] materials;
public Renderer rend;
// Use this for initialization
void Start () {
movespeed = 7f;
rend = GetComponent<Renderer>();
rend.enabled = true;
rend.sharedMaterial = materials[0];
}
// Update is called once per frame
private void Update()
{
if (Input.GetKey(KeyCode.W))
{
rend.sharedMaterial = materials[0];
}
if (Input.GetKey(KeyCode.A))
{
rend.sharedMaterial = materials[1];
}
if (Input.GetKey(KeyCode.S))
{
rend.sharedMaterial = materials[2];
}
if (Input.GetKey(KeyCode.D))
{
rend.sharedMaterial = materials[3];
}
gameObject.transform.Translate(movespeed * Input.GetAxis("Horizontal") * Time.deltaTime, 0f, movespeed * Input.GetAxis("Vertical") * Time.deltaTime);
}
}
| 25.090909 | 157 | 0.586957 | [
"MIT"
] | Bartlett-RC3/skilling-module-1-shawn8777 | Assets/Script/homework/homework33.cs | 1,106 | C# |
using System;
using System.Reflection;
using Basket.API.GrpcServices;
using Basket.API.Repositories;
using Basket.API.Repositories.Interfaces;
using Discount.Grpc.Protos;
using MassTransit;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
namespace Basket.API
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = Configuration.GetValue<string>("CacheSettings:ConnectionString");
});
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Basket.API", Version = "v1" });
});
// Connect to Rabbit/Mass
services.AddMassTransit(config =>
{
config.UsingRabbitMq((ctx, cfg) =>
{
cfg.Host(Configuration.GetValue<string>("EventBusSettings:HostAddress"));
});
});
services.AddMassTransitHostedService();
services.AddScoped<IBasketRepository, BasketRepository>();
services.AddGrpcClient<DiscountProtoService.DiscountProtoServiceClient>(o => o.Address = new Uri(Configuration["GrpcSettings:DiscountUrl"]));
services.AddScoped<DiscountGrpcService>();
// AutoMapper
services.AddAutoMapper(typeof(Startup));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Basket.API v1"));
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
| 32.860759 | 153 | 0.612866 | [
"MIT"
] | RAxzon/MicroservicesApp | src/Services/Basket/Basket.API/Startup.cs | 2,596 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.CodeAnalysis.UnitTests.Diagnostics
{
// These analyzers are not intended for any actual use. They exist solely to test IOperation support.
/// <summary>Analyzer used to test for bad statements and expressions.</summary>
public class BadStuffTestAnalyzer : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor InvalidExpressionDescriptor = new DiagnosticDescriptor(
"InvalidExpression",
"Invalid Expression",
"Invalid expression found.",
"Testing",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor InvalidStatementDescriptor = new DiagnosticDescriptor(
"InvalidStatement",
"Invalid Statement",
"Invalid statement found.",
"Testing",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor IsInvalidDescriptor = new DiagnosticDescriptor(
"IsInvalid",
"Is Invalid",
"Operation found that is invalid.",
"Testing",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get { return ImmutableArray.Create(InvalidExpressionDescriptor, InvalidStatementDescriptor, IsInvalidDescriptor); }
}
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
var invalidOperation = (IInvalidOperation)operationContext.Operation;
if (invalidOperation.Type == null)
{
operationContext.ReportDiagnostic(Diagnostic.Create(InvalidStatementDescriptor, operationContext.Operation.Syntax.GetLocation()));
}
else
{
operationContext.ReportDiagnostic(Diagnostic.Create(InvalidExpressionDescriptor, operationContext.Operation.Syntax.GetLocation()));
}
},
OperationKind.Invalid);
context.RegisterOperationAction(
(operationContext) =>
{
if (operationContext.Operation.HasErrors(operationContext.Compilation, operationContext.CancellationToken))
{
operationContext.ReportDiagnostic(Diagnostic.Create(IsInvalidDescriptor, operationContext.Operation.Syntax.GetLocation()));
}
},
OperationKind.Invocation,
OperationKind.Invalid);
}
}
/// <summary>Analyzer used to test for operations within symbols of certain names.</summary>
public class OwningSymbolTestAnalyzer : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor ExpressionDescriptor = new DiagnosticDescriptor(
"Expression",
"Expression",
"Expression found.",
"Testing",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get { return ImmutableArray.Create(ExpressionDescriptor); }
}
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationBlockStartAction(
(operationBlockContext) =>
{
if (operationBlockContext.Compilation.Language != "Stumble")
{
operationBlockContext.RegisterOperationAction(
(operationContext) =>
{
if (operationContext.ContainingSymbol.Name.StartsWith("Funky") && operationContext.Compilation.Language != "Mumble")
{
operationContext.ReportDiagnostic(Diagnostic.Create(ExpressionDescriptor, operationContext.Operation.Syntax.GetLocation()));
}
},
OperationKind.LocalReference,
OperationKind.Literal);
}
});
}
}
/// <summary>Analyzer used to test for loop IOperations.</summary>
public class BigForTestAnalyzer : DiagnosticAnalyzer
{
/// <summary>Diagnostic category "Reliability".</summary>
private const string ReliabilityCategory = "Reliability";
public static readonly DiagnosticDescriptor BigForDescriptor = new DiagnosticDescriptor(
"BigForRule",
"Big For Loop",
"For loop iterates more than one million times",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
/// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary>
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get { return ImmutableArray.Create(BigForDescriptor); }
}
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(AnalyzeOperation, OperationKind.Loop);
}
private void AnalyzeOperation(OperationAnalysisContext operationContext)
{
ILoopOperation loop = (ILoopOperation)operationContext.Operation;
if (loop.LoopKind == LoopKind.For)
{
IForLoopOperation forLoop = (IForLoopOperation)loop;
IOperation forCondition = forLoop.Condition;
if (forCondition.Kind == OperationKind.BinaryOperator)
{
IBinaryOperation condition = (IBinaryOperation)forCondition;
IOperation conditionLeft = condition.LeftOperand;
IOperation conditionRight = condition.RightOperand;
if (conditionRight.ConstantValue.HasValue &&
conditionRight.Type.SpecialType == SpecialType.System_Int32 &&
conditionLeft.Kind == OperationKind.LocalReference)
{
// Test is known to be a comparison of a local against a constant.
int testValue = (int)conditionRight.ConstantValue.Value;
ILocalSymbol testVariable = ((ILocalReferenceOperation)conditionLeft).Local;
if (forLoop.Before.Length == 1)
{
IOperation setup = forLoop.Before[0];
if (setup.Kind == OperationKind.ExpressionStatement && ((IExpressionStatementOperation)setup).Operation.Kind == OperationKind.SimpleAssignment)
{
ISimpleAssignmentOperation setupAssignment = (ISimpleAssignmentOperation)((IExpressionStatementOperation)setup).Operation;
if (setupAssignment.Target.Kind == OperationKind.LocalReference &&
((ILocalReferenceOperation)setupAssignment.Target).Local == testVariable &&
setupAssignment.Value.ConstantValue.HasValue &&
setupAssignment.Value.Type.SpecialType == SpecialType.System_Int32)
{
// Setup is known to be an assignment of a constant to the local used in the test.
int initialValue = (int)setupAssignment.Value.ConstantValue.Value;
if (forLoop.AtLoopBottom.Length == 1)
{
IOperation advance = forLoop.AtLoopBottom[0];
if (advance.Kind == OperationKind.ExpressionStatement)
{
IOperation advanceExpression = ((IExpressionStatementOperation)advance).Operation;
SemanticModel semanticModel = operationContext.Compilation.GetSemanticModel(advance.Syntax.SyntaxTree);
IOperation advanceIncrement;
BinaryOperatorKind? advanceOperationCode;
GetOperationKindAndValue(semanticModel, testVariable, advanceExpression, out advanceOperationCode, out advanceIncrement);
if (advanceIncrement != null && advanceOperationCode.HasValue)
{
int incrementValue = (int)advanceIncrement.ConstantValue.Value;
if (advanceOperationCode.Value == BinaryOperatorKind.Subtract)
{
advanceOperationCode = BinaryOperatorKind.Add;
incrementValue = -incrementValue;
}
if (advanceOperationCode.Value == BinaryOperatorKind.Add &&
incrementValue != 0 &&
(condition.OperatorKind == BinaryOperatorKind.LessThan ||
condition.OperatorKind == BinaryOperatorKind.LessThanOrEqual ||
condition.OperatorKind == BinaryOperatorKind.NotEquals ||
condition.OperatorKind == BinaryOperatorKind.GreaterThan ||
condition.OperatorKind == BinaryOperatorKind.GreaterThanOrEqual))
{
int iterationCount = (testValue - initialValue) / incrementValue;
if (iterationCount >= 1000000)
{
Report(operationContext, forLoop.Syntax, BigForDescriptor);
}
}
}
}
}
}
}
}
}
}
}
}
private void GetOperationKindAndValue(
SemanticModel semanticModel, ILocalSymbol testVariable, IOperation advanceExpression,
out BinaryOperatorKind? advanceOperationCode, out IOperation advanceIncrement)
{
advanceIncrement = null;
advanceOperationCode = null;
if (advanceExpression.Kind == OperationKind.SimpleAssignment)
{
ISimpleAssignmentOperation advanceAssignment = (ISimpleAssignmentOperation)advanceExpression;
if (advanceAssignment.Target.Kind == OperationKind.LocalReference &&
((ILocalReferenceOperation)advanceAssignment.Target).Local == testVariable &&
advanceAssignment.Value.Kind == OperationKind.BinaryOperator &&
advanceAssignment.Value.Type.SpecialType == SpecialType.System_Int32)
{
// Advance is known to be an assignment of a binary operation to the local used in the test.
IBinaryOperation advanceOperation = (IBinaryOperation)advanceAssignment.Value;
if (advanceOperation.OperatorMethod == null &&
advanceOperation.LeftOperand.Kind == OperationKind.LocalReference &&
((ILocalReferenceOperation)advanceOperation.LeftOperand).Local == testVariable &&
advanceOperation.RightOperand.ConstantValue.HasValue &&
advanceOperation.RightOperand.Type.SpecialType == SpecialType.System_Int32)
{
// Advance binary operation is known to involve a reference to the local used in the test and a constant.
advanceIncrement = advanceOperation.RightOperand;
advanceOperationCode = advanceOperation.OperatorKind;
}
}
}
else if (advanceExpression.Kind == OperationKind.CompoundAssignment)
{
ICompoundAssignmentOperation advanceAssignment = (ICompoundAssignmentOperation)advanceExpression;
if (advanceAssignment.Target.Kind == OperationKind.LocalReference &&
((ILocalReferenceOperation)advanceAssignment.Target).Local == testVariable &&
advanceAssignment.Value.ConstantValue.HasValue &&
advanceAssignment.Value.Type.SpecialType == SpecialType.System_Int32)
{
// Advance binary operation is known to involve a reference to the local used in the test and a constant.
advanceIncrement = advanceAssignment.Value;
advanceOperationCode = advanceAssignment.OperatorKind;
}
}
else if (advanceExpression.Kind == OperationKind.Increment)
{
IIncrementOrDecrementOperation advanceAssignment = (IIncrementOrDecrementOperation)advanceExpression;
if (advanceAssignment.Target.Kind == OperationKind.LocalReference &&
((ILocalReferenceOperation)advanceAssignment.Target).Local == testVariable)
{
// Advance binary operation is known to involve a reference to the local used in the test and a constant.
advanceIncrement = CreateIncrementOneLiteralExpression(semanticModel, advanceAssignment);
advanceOperationCode = BinaryOperatorKind.Add;
}
}
}
private static ILiteralOperation CreateIncrementOneLiteralExpression(SemanticModel semanticModel, IIncrementOrDecrementOperation increment)
{
string text = increment.Syntax.ToString();
SyntaxNode syntax = increment.Syntax;
ITypeSymbol type = increment.Type;
Optional<object> constantValue = new Optional<object>(1);
return new LiteralExpression(semanticModel, syntax, type, constantValue, increment.IsImplicit);
}
private static int Abs(int value)
{
return value < 0 ? -value : value;
}
private void Report(OperationAnalysisContext context, SyntaxNode syntax, DiagnosticDescriptor descriptor)
{
context.ReportDiagnostic(Diagnostic.Create(descriptor, syntax.GetLocation()));
}
}
/// <summary>Analyzer used to test switch IOperations.</summary>
public class SwitchTestAnalyzer : DiagnosticAnalyzer
{
/// <summary>Diagnostic category "Reliability".</summary>
private const string ReliabilityCategory = "Reliability";
public static readonly DiagnosticDescriptor SparseSwitchDescriptor = new DiagnosticDescriptor(
"SparseSwitchRule",
"Sparse switch",
"Switch has less than one percept density",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor NoDefaultSwitchDescriptor = new DiagnosticDescriptor(
"NoDefaultSwitchRule",
"No default switch",
"Switch has no default case",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor OnlyDefaultSwitchDescriptor = new DiagnosticDescriptor(
"OnlyDefaultSwitchRule",
"Only default switch",
"Switch only has a default case",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
/// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary>
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(SparseSwitchDescriptor,
NoDefaultSwitchDescriptor,
OnlyDefaultSwitchDescriptor);
}
}
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
ISwitchOperation switchOperation = (ISwitchOperation)operationContext.Operation;
long minCaseValue = long.MaxValue;
long maxCaseValue = long.MinValue;
long caseValueCount = 0;
bool hasDefault = false;
bool hasNonDefault = false;
foreach (ISwitchCaseOperation switchCase in switchOperation.Cases)
{
foreach (ICaseClauseOperation clause in switchCase.Clauses)
{
switch (clause.CaseKind)
{
case CaseKind.SingleValue:
{
hasNonDefault = true;
ISingleValueCaseClauseOperation singleValueClause = (ISingleValueCaseClauseOperation)clause;
IOperation singleValueExpression = singleValueClause.Value;
if (singleValueExpression != null &&
singleValueExpression.ConstantValue.HasValue &&
singleValueExpression.Type.SpecialType == SpecialType.System_Int32)
{
int singleValue = (int)singleValueExpression.ConstantValue.Value;
caseValueCount += IncludeClause(singleValue, singleValue, ref minCaseValue, ref maxCaseValue);
}
else
{
return;
}
break;
}
case CaseKind.Range:
{
hasNonDefault = true;
IRangeCaseClauseOperation rangeClause = (IRangeCaseClauseOperation)clause;
IOperation rangeMinExpression = rangeClause.MinimumValue;
IOperation rangeMaxExpression = rangeClause.MaximumValue;
if (rangeMinExpression != null &&
rangeMinExpression.ConstantValue.HasValue &&
rangeMinExpression.Type.SpecialType == SpecialType.System_Int32 &&
rangeMaxExpression != null &&
rangeMaxExpression.ConstantValue.HasValue &&
rangeMaxExpression.Type.SpecialType == SpecialType.System_Int32)
{
int rangeMinValue = (int)rangeMinExpression.ConstantValue.Value;
int rangeMaxValue = (int)rangeMaxExpression.ConstantValue.Value;
caseValueCount += IncludeClause(rangeMinValue, rangeMaxValue, ref minCaseValue, ref maxCaseValue);
}
else
{
return;
}
break;
}
case CaseKind.Relational:
{
hasNonDefault = true;
IRelationalCaseClauseOperation relationalClause = (IRelationalCaseClauseOperation)clause;
IOperation relationalValueExpression = relationalClause.Value;
if (relationalValueExpression != null &&
relationalValueExpression.ConstantValue.HasValue &&
relationalValueExpression.Type.SpecialType == SpecialType.System_Int32)
{
int rangeMinValue = int.MaxValue;
int rangeMaxValue = int.MinValue;
int relationalValue = (int)relationalValueExpression.ConstantValue.Value;
switch (relationalClause.Relation)
{
case BinaryOperatorKind.Equals:
rangeMinValue = relationalValue;
rangeMaxValue = relationalValue;
break;
case BinaryOperatorKind.NotEquals:
return;
case BinaryOperatorKind.LessThan:
rangeMinValue = int.MinValue;
rangeMaxValue = relationalValue - 1;
break;
case BinaryOperatorKind.LessThanOrEqual:
rangeMinValue = int.MinValue;
rangeMaxValue = relationalValue;
break;
case BinaryOperatorKind.GreaterThanOrEqual:
rangeMinValue = relationalValue;
rangeMaxValue = int.MaxValue;
break;
case BinaryOperatorKind.GreaterThan:
rangeMinValue = relationalValue + 1;
rangeMaxValue = int.MaxValue;
break;
}
caseValueCount += IncludeClause(rangeMinValue, rangeMaxValue, ref minCaseValue, ref maxCaseValue);
}
else
{
return;
}
break;
}
case CaseKind.Default:
{
hasDefault = true;
break;
}
}
}
}
long span = maxCaseValue - minCaseValue + 1;
if (caseValueCount == 0 && !hasDefault ||
caseValueCount != 0 && span / caseValueCount > 100)
{
Report(operationContext, switchOperation.Value.Syntax, SparseSwitchDescriptor);
}
if (!hasDefault)
{
Report(operationContext, switchOperation.Value.Syntax, NoDefaultSwitchDescriptor);
}
if (hasDefault && !hasNonDefault)
{
Report(operationContext, switchOperation.Value.Syntax, OnlyDefaultSwitchDescriptor);
}
},
OperationKind.Switch);
}
private static int IncludeClause(int clauseMinValue, int clauseMaxValue, ref long minCaseValue, ref long maxCaseValue)
{
if (clauseMinValue < minCaseValue)
{
minCaseValue = clauseMinValue;
}
if (clauseMaxValue > maxCaseValue)
{
maxCaseValue = clauseMaxValue;
}
return clauseMaxValue - clauseMinValue + 1;
}
private void Report(OperationAnalysisContext context, SyntaxNode syntax, DiagnosticDescriptor descriptor)
{
context.ReportDiagnostic(Diagnostic.Create(descriptor, syntax.GetLocation()));
}
}
/// <summary>Analyzer used to test invocaton IOperations.</summary>
public class InvocationTestAnalyzer : DiagnosticAnalyzer
{
/// <summary>Diagnostic category "Reliability".</summary>
private const string ReliabilityCategory = "Reliability";
public static readonly DiagnosticDescriptor BigParamArrayArgumentsDescriptor = new DiagnosticDescriptor(
"BigParamarrayRule",
"Big Paramarray",
"Paramarray has more than 10 elements",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor OutOfNumericalOrderArgumentsDescriptor = new DiagnosticDescriptor(
"OutOfOrderArgumentsRule",
"Out of order arguments",
"Argument values are not in increasing order",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor UseDefaultArgumentDescriptor = new DiagnosticDescriptor(
"UseDefaultArgument",
"Use default argument",
"Invocation uses default argument {0}",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor InvalidArgumentDescriptor = new DiagnosticDescriptor(
"InvalidArgument",
"Invalid argument",
"Invocation has invalid argument",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
/// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary>
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(BigParamArrayArgumentsDescriptor,
OutOfNumericalOrderArgumentsDescriptor,
UseDefaultArgumentDescriptor,
InvalidArgumentDescriptor);
}
}
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
IInvocationOperation invocation = (IInvocationOperation)operationContext.Operation;
long priorArgumentValue = long.MinValue;
foreach (IArgumentOperation argument in invocation.Arguments)
{
if (argument.HasErrors(operationContext.Compilation, operationContext.CancellationToken))
{
operationContext.ReportDiagnostic(Diagnostic.Create(InvalidArgumentDescriptor, argument.Syntax.GetLocation()));
return;
}
if (argument.ArgumentKind == ArgumentKind.DefaultValue)
{
operationContext.ReportDiagnostic(Diagnostic.Create(UseDefaultArgumentDescriptor, invocation.Syntax.GetLocation(), argument.Parameter.Name));
}
TestAscendingArgument(operationContext, argument.Value, ref priorArgumentValue);
if (argument.ArgumentKind == ArgumentKind.ParamArray)
{
if (argument.Value is IArrayCreationOperation arrayArgument)
{
var initializer = arrayArgument.Initializer;
if (initializer != null)
{
if (initializer.ElementValues.Length > 10)
{
Report(operationContext, invocation.Syntax, BigParamArrayArgumentsDescriptor);
}
foreach (IOperation element in initializer.ElementValues)
{
TestAscendingArgument(operationContext, element, ref priorArgumentValue);
}
}
}
}
}
},
OperationKind.Invocation);
}
private static void TestAscendingArgument(OperationAnalysisContext operationContext, IOperation argument, ref long priorArgumentValue)
{
Optional<object> argumentValue = argument.ConstantValue;
if (argumentValue.HasValue && argument.Type.SpecialType == SpecialType.System_Int32)
{
int integerArgument = (int)argumentValue.Value;
if (integerArgument < priorArgumentValue)
{
Report(operationContext, argument.Syntax, OutOfNumericalOrderArgumentsDescriptor);
}
priorArgumentValue = integerArgument;
}
}
private static void Report(OperationAnalysisContext context, SyntaxNode syntax, DiagnosticDescriptor descriptor)
{
context.ReportDiagnostic(Diagnostic.Create(descriptor, syntax.GetLocation()));
}
}
/// <summary>Analyzer used to test various contexts in which IOperations can occur.</summary>
public class SeventeenTestAnalyzer : DiagnosticAnalyzer
{
/// <summary>Diagnostic category "Reliability".</summary>
private const string ReliabilityCategory = "Reliability";
public static readonly DiagnosticDescriptor SeventeenDescriptor = new DiagnosticDescriptor(
"SeventeenRule",
"Seventeen",
"Seventeen is a recognized value",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
/// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary>
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get { return ImmutableArray.Create(SeventeenDescriptor); }
}
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
ILiteralOperation literal = (ILiteralOperation)operationContext.Operation;
if (literal.Type.SpecialType == SpecialType.System_Int32 &&
literal.ConstantValue.HasValue &&
(int)literal.ConstantValue.Value == 17)
{
operationContext.ReportDiagnostic(Diagnostic.Create(SeventeenDescriptor, literal.Syntax.GetLocation()));
}
},
OperationKind.Literal);
}
}
/// <summary>Analyzer used to test IArgument IOperations.</summary>
public class NullArgumentTestAnalyzer : DiagnosticAnalyzer
{
/// <summary>Diagnostic category "Reliability".</summary>
private const string ReliabilityCategory = "Reliability";
public static readonly DiagnosticDescriptor NullArgumentsDescriptor = new DiagnosticDescriptor(
"NullArgumentRule",
"Null Argument",
"Value of the argument is null",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
/// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary>
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get { return ImmutableArray.Create(NullArgumentsDescriptor); }
}
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
var argument = (IArgumentOperation)operationContext.Operation;
if (argument.Value.ConstantValue.HasValue && argument.Value.ConstantValue.Value == null)
{
Report(operationContext, argument.Syntax, NullArgumentsDescriptor);
}
},
OperationKind.Argument);
}
private static void Report(OperationAnalysisContext context, SyntaxNode syntax, DiagnosticDescriptor descriptor)
{
context.ReportDiagnostic(Diagnostic.Create(descriptor, syntax.GetLocation()));
}
}
/// <summary>Analyzer used to test IMemberInitializer IOperations.</summary>
public class MemberInitializerTestAnalyzer : DiagnosticAnalyzer
{
/// <summary>Diagnostic category "Reliability".</summary>
private const string ReliabilityCategory = "Reliability";
public static readonly DiagnosticDescriptor DoNotUseFieldInitializerDescriptor = new DiagnosticDescriptor(
"DoNotUseFieldInitializer",
"Do Not Use Field Initializer",
"a field initializer is used for object creation",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor DoNotUsePropertyInitializerDescriptor = new DiagnosticDescriptor(
"DoNotUsePropertyInitializer",
"Do Not Use Property Initializer",
"A property initializer is used for object creation",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
/// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary>
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get { return ImmutableArray.Create(DoNotUseFieldInitializerDescriptor, DoNotUsePropertyInitializerDescriptor); }
}
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
var initializer = operationContext.Operation;
Report(operationContext, initializer.Syntax, initializer.Kind == OperationKind.FieldReference ? DoNotUseFieldInitializerDescriptor : DoNotUsePropertyInitializerDescriptor);
},
OperationKind.FieldReference,
OperationKind.PropertyReference);
}
private static void Report(OperationAnalysisContext context, SyntaxNode syntax, DiagnosticDescriptor descriptor)
{
context.ReportDiagnostic(Diagnostic.Create(descriptor, syntax.GetLocation()));
}
}
/// <summary>Analyzer used to test IAssignmentExpression IOperations.</summary>
public class AssignmentTestAnalyzer : DiagnosticAnalyzer
{
/// <summary>Diagnostic category "Reliability".</summary>
private const string ReliabilityCategory = "Reliability";
public static readonly DiagnosticDescriptor DoNotUseMemberAssignmentDescriptor = new DiagnosticDescriptor(
"DoNotUseMemberAssignment",
"Do Not Use Member Assignment",
"Do not assign values to object members",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get { return ImmutableArray.Create(DoNotUseMemberAssignmentDescriptor); }
}
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
var assignment = (ISimpleAssignmentOperation)operationContext.Operation;
var kind = assignment.Target.Kind;
if (kind == OperationKind.FieldReference ||
kind == OperationKind.PropertyReference)
{
Report(operationContext, assignment.Syntax, DoNotUseMemberAssignmentDescriptor);
}
},
OperationKind.SimpleAssignment);
}
private static void Report(OperationAnalysisContext context, SyntaxNode syntax, DiagnosticDescriptor descriptor)
{
context.ReportDiagnostic(Diagnostic.Create(descriptor, syntax.GetLocation()));
}
}
/// <summary>Analyzer used to test IArrayInitializer IOperations.</summary>
public class ArrayInitializerTestAnalyzer : DiagnosticAnalyzer
{
/// <summary>Diagnostic category "Maintainability".</summary>
private const string Maintainability = nameof(Maintainability);
public static readonly DiagnosticDescriptor DoNotUseLargeListOfArrayInitializersDescriptor = new DiagnosticDescriptor(
"DoNotUseLongListToInitializeArray",
"Do not use long list to initialize array",
"a list of more than 5 elements is used for an array initialization",
Maintainability,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
/// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary>
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get { return ImmutableArray.Create(DoNotUseLargeListOfArrayInitializersDescriptor); }
}
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
var initializer = (IArrayInitializerOperation)operationContext.Operation;
if (initializer.ElementValues.Length > 5)
{
Report(operationContext, initializer.Syntax, DoNotUseLargeListOfArrayInitializersDescriptor);
}
},
OperationKind.ArrayInitializer);
}
private static void Report(OperationAnalysisContext context, SyntaxNode syntax, DiagnosticDescriptor descriptor)
{
context.ReportDiagnostic(Diagnostic.Create(descriptor, syntax.GetLocation()));
}
}
/// <summary>Analyzer used to test IVariableDeclarationStatement IOperations.</summary>
public class VariableDeclarationTestAnalyzer : DiagnosticAnalyzer
{
/// <summary>Diagnostic category "Maintainability".</summary>
private const string Maintainability = nameof(Maintainability);
public static readonly DiagnosticDescriptor TooManyLocalVarDeclarationsDescriptor = new DiagnosticDescriptor(
"TooManyLocalVarDeclarations",
"Too many local variable declarations",
"A declaration statement shouldn't have more than 3 variable declarations",
Maintainability,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor LocalVarInitializedDeclarationDescriptor = new DiagnosticDescriptor(
"LocalVarInitializedDeclaration",
"Local var initialized at declaration",
"A local variable is initialized at declaration.",
Maintainability,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
/// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary>
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get { return ImmutableArray.Create(TooManyLocalVarDeclarationsDescriptor, LocalVarInitializedDeclarationDescriptor); }
}
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
var declarationStatement = (IVariableDeclarationGroupOperation)operationContext.Operation;
if (declarationStatement.GetDeclaredVariables().Count() > 3)
{
Report(operationContext, declarationStatement.Syntax, TooManyLocalVarDeclarationsDescriptor);
}
foreach (var decl in declarationStatement.Declarations.SelectMany(multiDecl => multiDecl.Declarators))
{
var initializer = decl.GetVariableInitializer();
if (initializer != null && !initializer.HasErrors(operationContext.Compilation, operationContext.CancellationToken))
{
Report(operationContext, decl.Symbol.DeclaringSyntaxReferences.Single().GetSyntax(), LocalVarInitializedDeclarationDescriptor);
}
}
},
OperationKind.VariableDeclarationGroup);
}
private static void Report(OperationAnalysisContext context, SyntaxNode syntax, DiagnosticDescriptor descriptor)
{
context.ReportDiagnostic(Diagnostic.Create(descriptor, syntax.GetLocation()));
}
}
/// <summary>Analyzer used to test ICase and ICaseClause.</summary>
public class CaseTestAnalyzer : DiagnosticAnalyzer
{
/// <summary>Diagnostic category "Maintainability".</summary>
private const string Maintainability = nameof(Maintainability);
public static readonly DiagnosticDescriptor HasDefaultCaseDescriptor = new DiagnosticDescriptor(
"HasDefaultCase",
"Has Default Case",
"A default case clause is encountered",
Maintainability,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor MultipleCaseClausesDescriptor = new DiagnosticDescriptor(
"MultipleCaseClauses",
"Multiple Case Clauses",
"A switch section has multiple case clauses",
Maintainability,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
/// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary>
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get { return ImmutableArray.Create(HasDefaultCaseDescriptor, MultipleCaseClausesDescriptor); }
}
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
switch (operationContext.Operation.Kind)
{
case OperationKind.CaseClause:
var caseClause = (ICaseClauseOperation)operationContext.Operation;
if (caseClause.CaseKind == CaseKind.Default)
{
Report(operationContext, caseClause.Syntax, HasDefaultCaseDescriptor);
}
break;
case OperationKind.SwitchCase:
var switchSection = (ISwitchCaseOperation)operationContext.Operation;
if (!switchSection.HasErrors(operationContext.Compilation, operationContext.CancellationToken) && switchSection.Clauses.Length > 1)
{
Report(operationContext, switchSection.Syntax, MultipleCaseClausesDescriptor);
}
break;
}
},
OperationKind.SwitchCase,
OperationKind.CaseClause);
}
private static void Report(OperationAnalysisContext context, SyntaxNode syntax, DiagnosticDescriptor descriptor)
{
context.ReportDiagnostic(Diagnostic.Create(descriptor, syntax.GetLocation()));
}
}
/// <summary>Analyzer used to test for explicit vs. implicit instance references.</summary>
public class ExplicitVsImplicitInstanceAnalyzer : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor ImplicitInstanceDescriptor = new DiagnosticDescriptor(
"ImplicitInstance",
"Implicit Instance",
"Implicit instance found.",
"Testing",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor ExplicitInstanceDescriptor = new DiagnosticDescriptor(
"ExplicitInstance",
"Explicit Instance",
"Explicit instance found.",
"Testing",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(ImplicitInstanceDescriptor, ExplicitInstanceDescriptor);
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
IInstanceReferenceOperation instanceReference = (IInstanceReferenceOperation)operationContext.Operation;
operationContext.ReportDiagnostic(Diagnostic.Create(instanceReference.IsImplicit ? ImplicitInstanceDescriptor : ExplicitInstanceDescriptor,
instanceReference.Syntax.GetLocation()));
},
OperationKind.InstanceReference);
}
}
/// <summary>Analyzer used to test for member references.</summary>
public class MemberReferenceAnalyzer : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor EventReferenceDescriptor = new DiagnosticDescriptor(
"EventReference",
"Event Reference",
"Event reference found.",
"Testing",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor InvalidEventDescriptor = new DiagnosticDescriptor(
"InvalidEvent",
"Invalid Event",
"A EventAssignmentExpression with invalid event found.",
"Testing",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor HandlerAddedDescriptor = new DiagnosticDescriptor(
"HandlerAdded",
"Handler Added",
"Event handler added.",
"Testing",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor HandlerRemovedDescriptor = new DiagnosticDescriptor(
"HandlerRemoved",
"Handler Removed",
"Event handler removed.",
"Testing",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor PropertyReferenceDescriptor = new DiagnosticDescriptor(
"PropertyReference",
"Property Reference",
"Property reference found.",
"Testing",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor FieldReferenceDescriptor = new DiagnosticDescriptor(
"FieldReference",
"Field Reference",
"Field reference found.",
"Testing",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor MethodBindingDescriptor = new DiagnosticDescriptor(
"MethodBinding",
"Method Binding",
"Method binding found.",
"Testing",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics =>
ImmutableArray.Create(EventReferenceDescriptor,
HandlerAddedDescriptor,
HandlerRemovedDescriptor,
PropertyReferenceDescriptor,
FieldReferenceDescriptor,
MethodBindingDescriptor,
InvalidEventDescriptor);
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
operationContext.ReportDiagnostic(Diagnostic.Create(EventReferenceDescriptor, operationContext.Operation.Syntax.GetLocation()));
},
OperationKind.EventReference);
context.RegisterOperationAction(
(operationContext) =>
{
IEventAssignmentOperation eventAssignment = (IEventAssignmentOperation)operationContext.Operation;
operationContext.ReportDiagnostic(Diagnostic.Create(eventAssignment.Adds ? HandlerAddedDescriptor : HandlerRemovedDescriptor, operationContext.Operation.Syntax.GetLocation()));
if (eventAssignment.EventReference.Kind == OperationKind.Invalid || eventAssignment.HasErrors(operationContext.Compilation, operationContext.CancellationToken))
{
operationContext.ReportDiagnostic(Diagnostic.Create(InvalidEventDescriptor, eventAssignment.Syntax.GetLocation()));
}
},
OperationKind.EventAssignment);
context.RegisterOperationAction(
(operationContext) =>
{
operationContext.ReportDiagnostic(Diagnostic.Create(PropertyReferenceDescriptor, operationContext.Operation.Syntax.GetLocation()));
},
OperationKind.PropertyReference);
context.RegisterOperationAction(
(operationContext) =>
{
operationContext.ReportDiagnostic(Diagnostic.Create(FieldReferenceDescriptor, operationContext.Operation.Syntax.GetLocation()));
},
OperationKind.FieldReference);
context.RegisterOperationAction(
(operationContext) =>
{
operationContext.ReportDiagnostic(Diagnostic.Create(MethodBindingDescriptor, operationContext.Operation.Syntax.GetLocation()));
},
OperationKind.MethodReference);
}
}
/// <summary>Analyzer used to test IOperation treatment of params array arguments.</summary>
public class ParamsArrayTestAnalyzer : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor LongParamsDescriptor = new DiagnosticDescriptor(
"LongParams",
"Long Params",
"Params array argument has more than 3 elements.",
"Testing",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor InvalidConstructorDescriptor = new DiagnosticDescriptor(
"InvalidConstructor",
"Invalid Constructor",
"Invalid Constructor.",
"Testing",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(LongParamsDescriptor, InvalidConstructorDescriptor);
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
IInvocationOperation invocation = (IInvocationOperation)operationContext.Operation;
foreach (IArgumentOperation argument in invocation.Arguments)
{
if (argument.Parameter.IsParams)
{
if (argument.Value is IArrayCreationOperation arrayValue)
{
Optional<object> dimensionSize = arrayValue.DimensionSizes[0].ConstantValue;
if (dimensionSize.HasValue && IntegralValue(dimensionSize.Value) > 3)
{
operationContext.ReportDiagnostic(Diagnostic.Create(LongParamsDescriptor, argument.Value.Syntax.GetLocation()));
}
}
}
}
},
OperationKind.Invocation);
context.RegisterOperationAction(
(operationContext) =>
{
IObjectCreationOperation creation = (IObjectCreationOperation)operationContext.Operation;
if (creation.Constructor == null)
{
operationContext.ReportDiagnostic(Diagnostic.Create(InvalidConstructorDescriptor, creation.Syntax.GetLocation()));
}
foreach (IArgumentOperation argument in creation.Arguments)
{
if (argument.Parameter.IsParams)
{
if (argument.Value is IArrayCreationOperation arrayValue)
{
Optional<object> dimensionSize = arrayValue.DimensionSizes[0].ConstantValue;
if (dimensionSize.HasValue && IntegralValue(dimensionSize.Value) > 3)
{
operationContext.ReportDiagnostic(Diagnostic.Create(LongParamsDescriptor, argument.Value.Syntax.GetLocation()));
}
}
}
}
},
OperationKind.ObjectCreation);
}
private static long IntegralValue(object value)
{
if (value is long v)
{
return v;
}
if (value is int i)
{
return i;
}
return 0;
}
}
/// <summary>Analyzer used to test for initializer constructs for members and parameters.</summary>
public class EqualsValueTestAnalyzer : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor EqualsValueDescriptor = new DiagnosticDescriptor(
"EqualsValue",
"Equals Value",
"Equals value found.",
"Testing",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(EqualsValueDescriptor);
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
IFieldInitializerOperation equalsValue = (IFieldInitializerOperation)operationContext.Operation;
if (equalsValue.InitializedFields[0].Name.StartsWith("F"))
{
operationContext.ReportDiagnostic(Diagnostic.Create(EqualsValueDescriptor, equalsValue.Syntax.GetLocation()));
}
},
OperationKind.FieldInitializer);
context.RegisterOperationAction(
(operationContext) =>
{
IParameterInitializerOperation equalsValue = (IParameterInitializerOperation)operationContext.Operation;
if (equalsValue.Parameter.Name.StartsWith("F"))
{
operationContext.ReportDiagnostic(Diagnostic.Create(EqualsValueDescriptor, equalsValue.Syntax.GetLocation()));
}
},
OperationKind.ParameterInitializer);
}
}
/// <summary>Analyzer used to test None IOperations.</summary>
public class NoneOperationTestAnalyzer : DiagnosticAnalyzer
{
private const string ReliabilityCategory = "Reliability";
// We should not see this warning triggered by any code
public static readonly DiagnosticDescriptor NoneOperationDescriptor = new DiagnosticDescriptor(
"NoneOperation",
"None operation found",
"An IOperation of None kind is found",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get { return ImmutableArray.Create(NoneOperationDescriptor); }
}
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
operationContext.ReportDiagnostic(Diagnostic.Create(NoneOperationDescriptor, operationContext.Operation.Syntax.GetLocation()));
},
// None kind is only supposed to be used internally and will not actually register actions.
OperationKind.None);
}
}
public class AddressOfTestAnalyzer : DiagnosticAnalyzer
{
private const string ReliabilityCategory = "Reliability";
public static readonly DiagnosticDescriptor AddressOfDescriptor = new DiagnosticDescriptor(
"AddressOfOperation",
"AddressOf operation found",
"An AddressOf operation found",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor InvalidAddressOfReferenceDescriptor = new DiagnosticDescriptor(
"InvalidAddressOfReference",
"Invalid AddressOf reference found",
"An invalid AddressOf reference found",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics =>
ImmutableArray.Create(AddressOfDescriptor, InvalidAddressOfReferenceDescriptor);
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
var addressOfOperation = (IAddressOfOperation)operationContext.Operation;
operationContext.ReportDiagnostic(Diagnostic.Create(AddressOfDescriptor, addressOfOperation.Syntax.GetLocation()));
if (addressOfOperation.Reference.Kind == OperationKind.Invalid && addressOfOperation.HasErrors(operationContext.Compilation, operationContext.CancellationToken))
{
operationContext.ReportDiagnostic(Diagnostic.Create(InvalidAddressOfReferenceDescriptor, addressOfOperation.Reference.Syntax.GetLocation()));
}
},
OperationKind.AddressOf);
}
}
/// <summary>Analyzer used to test LambdaExpression IOperations.</summary>
public class LambdaTestAnalyzer : DiagnosticAnalyzer
{
private const string ReliabilityCategory = "Reliability";
public static readonly DiagnosticDescriptor LambdaExpressionDescriptor = new DiagnosticDescriptor(
"LambdaExpression",
"Lambda expressionn found",
"An Lambda expression is found",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor TooManyStatementsInLambdaExpressionDescriptor = new DiagnosticDescriptor(
"TooManyStatementsInLambdaExpression",
"Too many statements in a Lambda expression",
"More than 3 statements in a Lambda expression",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
// This warning should never be triggered.
public static readonly DiagnosticDescriptor NoneOperationInLambdaExpressionDescriptor = new DiagnosticDescriptor(
"NoneOperationInLambdaExpression",
"None Operation found in Lambda expression",
"None Operation is found Lambda expression",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics =>
ImmutableArray.Create(LambdaExpressionDescriptor,
TooManyStatementsInLambdaExpressionDescriptor,
NoneOperationInLambdaExpressionDescriptor);
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
var lambdaExpression = (IAnonymousFunctionOperation)operationContext.Operation;
operationContext.ReportDiagnostic(Diagnostic.Create(LambdaExpressionDescriptor, operationContext.Operation.Syntax.GetLocation()));
var block = lambdaExpression.Body;
// TODO: Can this possibly be null? Remove check if not.
if (block == null)
{
return;
}
if (block.Operations.Length > 3)
{
operationContext.ReportDiagnostic(Diagnostic.Create(TooManyStatementsInLambdaExpressionDescriptor, operationContext.Operation.Syntax.GetLocation()));
}
bool flag = false;
foreach (var statement in block.Operations)
{
if (statement.Kind == OperationKind.None)
{
flag = true;
break;
}
}
if (flag)
{
operationContext.ReportDiagnostic(Diagnostic.Create(NoneOperationInLambdaExpressionDescriptor, operationContext.Operation.Syntax.GetLocation()));
}
},
OperationKind.AnonymousFunction);
}
}
public class StaticMemberTestAnalyzer : DiagnosticAnalyzer
{
private const string ReliabilityCategory = "Reliability";
public static readonly DiagnosticDescriptor StaticMemberDescriptor = new DiagnosticDescriptor(
"StaticMember",
"Static member found",
"A static member reference expression is found",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
// We should not see this warning triggered by any code
public static readonly DiagnosticDescriptor StaticMemberWithInstanceDescriptor = new DiagnosticDescriptor(
"StaticMemberWithInstance",
"Static member with non null Instance found",
"A static member reference with non null Instance is found",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(StaticMemberDescriptor,
StaticMemberWithInstanceDescriptor);
}
}
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
var operation = operationContext.Operation;
ISymbol memberSymbol;
IOperation receiver;
switch (operation.Kind)
{
case OperationKind.FieldReference:
memberSymbol = ((IFieldReferenceOperation)operation).Field;
receiver = ((IFieldReferenceOperation)operation).Instance;
break;
case OperationKind.PropertyReference:
memberSymbol = ((IPropertyReferenceOperation)operation).Property;
receiver = ((IPropertyReferenceOperation)operation).Instance;
break;
case OperationKind.EventReference:
memberSymbol = ((IEventReferenceOperation)operation).Event;
receiver = ((IEventReferenceOperation)operation).Instance;
break;
case OperationKind.MethodReference:
memberSymbol = ((IMethodReferenceOperation)operation).Method;
receiver = ((IMethodReferenceOperation)operation).Instance;
break;
case OperationKind.Invocation:
memberSymbol = ((IInvocationOperation)operation).TargetMethod;
receiver = ((IInvocationOperation)operation).Instance;
break;
default:
throw new ArgumentException();
}
if (memberSymbol.IsStatic)
{
operationContext.ReportDiagnostic(Diagnostic.Create(StaticMemberDescriptor, operation.Syntax.GetLocation()));
if (receiver != null)
{
operationContext.ReportDiagnostic(Diagnostic.Create(StaticMemberWithInstanceDescriptor, operation.Syntax.GetLocation()));
}
}
},
OperationKind.FieldReference,
OperationKind.PropertyReference,
OperationKind.EventReference,
OperationKind.MethodReference,
OperationKind.Invocation);
}
}
public class LabelOperationsTestAnalyzer : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor LabelDescriptor = new DiagnosticDescriptor(
"Label",
"Label found",
"A label was was found",
"Testing",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor GotoDescriptor = new DiagnosticDescriptor(
"Goto",
"Goto found",
"A goto was was found",
"Testing",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(LabelDescriptor, GotoDescriptor);
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
ILabelSymbol label = ((ILabeledOperation)operationContext.Operation).Label;
if (label.Name == "Wilma" || label.Name == "Betty")
{
operationContext.ReportDiagnostic(Diagnostic.Create(LabelDescriptor, operationContext.Operation.Syntax.GetLocation()));
}
},
OperationKind.Labeled);
context.RegisterOperationAction(
(operationContext) =>
{
IBranchOperation branch = (IBranchOperation)operationContext.Operation;
if (branch.BranchKind == BranchKind.GoTo)
{
ILabelSymbol label = branch.Target;
if (label.Name == "Wilma" || label.Name == "Betty")
{
operationContext.ReportDiagnostic(Diagnostic.Create(GotoDescriptor, branch.Syntax.GetLocation()));
}
}
},
OperationKind.Branch);
}
}
public class UnaryAndBinaryOperationsTestAnalyzer : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor OperatorAddMethodDescriptor = new DiagnosticDescriptor(
"OperatorAddMethod",
"Operator Add method found",
"An operator Add method was found",
"Testing",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor OperatorMinusMethodDescriptor = new DiagnosticDescriptor(
"OperatorMinusMethod",
"Operator Minus method found",
"An operator Minus method was found",
"Testing",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor DoubleMultiplyDescriptor = new DiagnosticDescriptor(
"DoubleMultiply",
"Double multiply found",
"A double multiply was found",
"Testing",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor BooleanNotDescriptor = new DiagnosticDescriptor(
"BooleanNot",
"Boolean not found",
"A boolean not was found",
"Testing",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(OperatorAddMethodDescriptor, OperatorMinusMethodDescriptor, DoubleMultiplyDescriptor, BooleanNotDescriptor);
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
IBinaryOperation binary = (IBinaryOperation)operationContext.Operation;
if (binary.OperatorKind == BinaryOperatorKind.Add && binary.OperatorMethod != null && binary.OperatorMethod.Name.Contains("Addition"))
{
operationContext.ReportDiagnostic(Diagnostic.Create(OperatorAddMethodDescriptor, binary.Syntax.GetLocation()));
}
if (binary.OperatorKind == BinaryOperatorKind.Multiply && binary.Type.SpecialType == SpecialType.System_Double)
{
operationContext.ReportDiagnostic(Diagnostic.Create(DoubleMultiplyDescriptor, binary.Syntax.GetLocation()));
}
},
OperationKind.BinaryOperator);
context.RegisterOperationAction(
(operationContext) =>
{
IUnaryOperation unary = (IUnaryOperation)operationContext.Operation;
if (unary.OperatorKind == UnaryOperatorKind.Minus && unary.OperatorMethod != null && unary.OperatorMethod.Name.Contains("UnaryNegation"))
{
operationContext.ReportDiagnostic(Diagnostic.Create(OperatorMinusMethodDescriptor, unary.Syntax.GetLocation()));
}
if (unary.OperatorKind == UnaryOperatorKind.Not)
{
operationContext.ReportDiagnostic(Diagnostic.Create(BooleanNotDescriptor, unary.Syntax.GetLocation()));
}
if (unary.OperatorKind == UnaryOperatorKind.BitwiseNegation)
{
operationContext.ReportDiagnostic(Diagnostic.Create(BooleanNotDescriptor, unary.Syntax.GetLocation()));
}
},
OperationKind.UnaryOperator);
}
}
public class BinaryOperatorVBTestAnalyzer : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor BinaryUserDefinedOperatorDescriptor = new DiagnosticDescriptor(
"BinaryUserDefinedOperator",
"Binary user defined operator found",
"A Binary user defined operator {0} is found",
"Testing",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(BinaryUserDefinedOperatorDescriptor);
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
var binary = (IBinaryOperation)operationContext.Operation;
if (binary.OperatorMethod != null)
{
operationContext.ReportDiagnostic(
Diagnostic.Create(BinaryUserDefinedOperatorDescriptor,
binary.Syntax.GetLocation(),
binary.OperatorKind.ToString()));
}
},
OperationKind.BinaryOperator);
}
}
public class OperatorPropertyPullerTestAnalyzer : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor BinaryOperatorDescriptor = new DiagnosticDescriptor(
"BinaryOperator",
"Binary operator found",
"A Binary operator {0} was found",
"Testing",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor UnaryOperatorDescriptor = new DiagnosticDescriptor(
"UnaryOperator",
"Unary operator found",
"A Unary operator {0} was found",
"Testing",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(BinaryOperatorDescriptor, UnaryOperatorDescriptor);
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
var binary = (IBinaryOperation)operationContext.Operation;
var left = binary.LeftOperand;
var right = binary.RightOperand;
if (!left.HasErrors(operationContext.Compilation, operationContext.CancellationToken) &&
!right.HasErrors(operationContext.Compilation, operationContext.CancellationToken) &&
binary.OperatorMethod == null)
{
if (left.Kind == OperationKind.LocalReference)
{
var leftLocal = ((ILocalReferenceOperation)left).Local;
if (leftLocal.Name == "x")
{
if (right.Kind == OperationKind.Literal)
{
var rightValue = right.ConstantValue;
if (rightValue.HasValue && rightValue.Value is int && (int)rightValue.Value == 10)
{
operationContext.ReportDiagnostic(
Diagnostic.Create(BinaryOperatorDescriptor,
binary.Syntax.GetLocation(),
binary.OperatorKind.ToString()));
}
}
}
}
}
},
OperationKind.BinaryOperator);
context.RegisterOperationAction(
(operationContext) =>
{
var unary = (IUnaryOperation)operationContext.Operation;
var operand = unary.Operand;
if (operand.Kind == OperationKind.LocalReference)
{
var operandLocal = ((ILocalReferenceOperation)operand).Local;
if (operandLocal.Name == "x")
{
if (!operand.HasErrors(operationContext.Compilation, operationContext.CancellationToken) && unary.OperatorMethod == null)
{
operationContext.ReportDiagnostic(
Diagnostic.Create(UnaryOperatorDescriptor,
unary.Syntax.GetLocation(),
unary.OperatorKind.ToString()));
}
}
}
},
OperationKind.UnaryOperator);
}
}
public class NullOperationSyntaxTestAnalyzer : DiagnosticAnalyzer
{
private const string ReliabilityCategory = "Reliability";
// We should not see this warning triggered by any code
public static readonly DiagnosticDescriptor NullOperationSyntaxDescriptor = new DiagnosticDescriptor(
"NullOperationSyntax",
"null operation Syntax found",
"An IOperation with Syntax property of value null is found",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
// since we don't expect to see the first diagnostic, we created this one to make sure
// the test didn't pass because the analyzer crashed.
public static readonly DiagnosticDescriptor ParamsArrayOperationDescriptor = new DiagnosticDescriptor(
"ParamsArray",
"Params array argument found",
"A params array argument is found",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get { return ImmutableArray.Create(NullOperationSyntaxDescriptor, ParamsArrayOperationDescriptor); }
}
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
var nullList = new List<IOperation>();
var paramsList = new List<IOperation>();
var collector = new Walker(nullList, paramsList);
collector.Visit(operationContext.Operation);
foreach (var nullSyntaxOperation in nullList)
{
operationContext.ReportDiagnostic(
Diagnostic.Create(NullOperationSyntaxDescriptor, null));
}
foreach (var paramsarrayArgumentOperation in paramsList)
{
operationContext.ReportDiagnostic(
Diagnostic.Create(ParamsArrayOperationDescriptor,
paramsarrayArgumentOperation.Syntax.GetLocation()));
}
},
OperationKind.Invocation);
}
// this OperationWalker collect:
// 1. all the operation with null Syntax property
// 2. all the params array argument operations
private sealed class Walker : OperationWalker
{
private readonly List<IOperation> _nullList;
private readonly List<IOperation> _paramsList;
public Walker(List<IOperation> nullList, List<IOperation> paramsList)
{
_nullList = nullList;
_paramsList = paramsList;
}
public override void Visit(IOperation operation)
{
if (operation != null)
{
if (operation.Syntax == null)
{
_nullList.Add(operation);
}
if (operation.Kind == OperationKind.Argument)
{
if (((IArgumentOperation)operation).ArgumentKind == ArgumentKind.ParamArray)
{
_paramsList.Add(operation);
}
}
}
base.Visit(operation);
}
}
}
public class InvalidOperatorExpressionTestAnalyzer : DiagnosticAnalyzer
{
private const string ReliabilityCategory = "Reliability";
public static readonly DiagnosticDescriptor InvalidBinaryDescriptor = new DiagnosticDescriptor(
"InvalidBinary",
"Invalid binary expression operation with BinaryOperationKind.Invalid",
"An Invalid binary expression operation with BinaryOperationKind.Invalid is found",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor InvalidUnaryDescriptor = new DiagnosticDescriptor(
"InvalidUnary",
"Invalid unary expression operation with UnaryOperationKind.Invalid",
"An Invalid unary expression operation with UnaryOperationKind.Invalid is found",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor InvalidIncrementDescriptor = new DiagnosticDescriptor(
"InvalidIncrement",
"Invalid increment expression operation with ICompoundAssignmentExpression.BinaryOperationKind == BinaryOperationKind.Invalid",
"An Invalid increment expression operation with ICompoundAssignmentExpression.BinaryOperationKind == BinaryOperationKind.Invalid is found",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(InvalidBinaryDescriptor,
InvalidUnaryDescriptor,
InvalidIncrementDescriptor);
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
var operation = operationContext.Operation;
if (operation.Kind == OperationKind.BinaryOperator)
{
var binary = (IBinaryOperation)operation;
if (binary.HasErrors(operationContext.Compilation, operationContext.CancellationToken))
{
operationContext.ReportDiagnostic(Diagnostic.Create(InvalidBinaryDescriptor, binary.Syntax.GetLocation()));
}
}
else if (operation.Kind == OperationKind.UnaryOperator)
{
var unary = (IUnaryOperation)operation;
if (unary.HasErrors(operationContext.Compilation, operationContext.CancellationToken))
{
operationContext.ReportDiagnostic(Diagnostic.Create(InvalidUnaryDescriptor, unary.Syntax.GetLocation()));
}
}
else if (operation.Kind == OperationKind.Increment)
{
var inc = (IIncrementOrDecrementOperation)operation;
if (inc.HasErrors(operationContext.Compilation))
{
operationContext.ReportDiagnostic(Diagnostic.Create(InvalidIncrementDescriptor, inc.Syntax.GetLocation()));
}
}
},
OperationKind.BinaryOperator,
OperationKind.UnaryOperator,
OperationKind.Increment);
}
}
public class ConditionalAccessOperationTestAnalyzer : DiagnosticAnalyzer
{
public static readonly DiagnosticDescriptor ConditionalAccessOperationDescriptor = new DiagnosticDescriptor(
"ConditionalAccessOperation",
"Conditional access operation found",
"Conditional access operation was found",
"Testing",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor ConditionalAccessInstanceOperationDescriptor = new DiagnosticDescriptor(
"ConditionalAccessInstanceOperation",
"Conditional access instance operation found",
"Conditional access instance operation was found",
"Testing",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get { return ImmutableArray.Create(ConditionalAccessOperationDescriptor, ConditionalAccessInstanceOperationDescriptor); }
}
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
IConditionalAccessOperation conditionalAccess = (IConditionalAccessOperation)operationContext.Operation;
if (conditionalAccess.WhenNotNull != null && conditionalAccess.Operation != null)
{
operationContext.ReportDiagnostic(Diagnostic.Create(ConditionalAccessOperationDescriptor, conditionalAccess.Syntax.GetLocation()));
}
},
OperationKind.ConditionalAccess);
context.RegisterOperationAction(
(operationContext) =>
{
IConditionalAccessInstanceOperation conditionalAccessInstance = (IConditionalAccessInstanceOperation)operationContext.Operation;
operationContext.ReportDiagnostic(Diagnostic.Create(ConditionalAccessInstanceOperationDescriptor, conditionalAccessInstance.Syntax.GetLocation()));
},
OperationKind.ConditionalAccessInstance);
// https://github.com/dotnet/roslyn/issues/21294
//context.RegisterOperationAction(
// (operationContext) =>
// {
// IPlaceholderExpression placeholder = (IPlaceholderExpression)operationContext.Operation;
// operationContext.ReportDiagnostic(Diagnostic.Create(ConditionalAccessInstanceOperationDescriptor, placeholder.Syntax.GetLocation()));
// },
// OperationKind.PlaceholderExpression);
}
}
public class ConversionExpressionCSharpTestAnalyzer : DiagnosticAnalyzer
{
private const string ReliabilityCategory = "Reliability";
public static readonly DiagnosticDescriptor InvalidConversionExpressionDescriptor = new DiagnosticDescriptor(
"InvalidConversionExpression",
"Invalid conversion expression",
"Invalid conversion expression.",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get { return ImmutableArray.Create(InvalidConversionExpressionDescriptor); }
}
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
var conversion = (IConversionOperation)operationContext.Operation;
if (conversion.HasErrors(operationContext.Compilation, operationContext.CancellationToken))
{
operationContext.ReportDiagnostic(Diagnostic.Create(InvalidConversionExpressionDescriptor, conversion.Syntax.GetLocation()));
}
},
OperationKind.Conversion);
}
}
public class ForLoopConditionCrashVBTestAnalyzer : DiagnosticAnalyzer
{
private const string ReliabilityCategory = "Reliability";
public static readonly DiagnosticDescriptor ForLoopConditionCrashDescriptor = new DiagnosticDescriptor(
"ForLoopConditionCrash",
"Ensure ForLoopCondition property doesn't crash",
"Ensure ForLoopCondition property doesn't crash",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get { return ImmutableArray.Create(ForLoopConditionCrashDescriptor); }
}
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
ILoopOperation loop = (ILoopOperation)operationContext.Operation;
if (loop.LoopKind == LoopKind.ForTo)
{
var forLoop = (IForToLoopOperation)loop;
var forCondition = forLoop.LimitValue;
if (forCondition.HasErrors(operationContext.Compilation, operationContext.CancellationToken))
{
// Generate a warning to prove we didn't crash
operationContext.ReportDiagnostic(Diagnostic.Create(ForLoopConditionCrashDescriptor, forLoop.LimitValue.Syntax.GetLocation()));
}
}
},
OperationKind.Loop);
}
}
public class TrueFalseUnaryOperationTestAnalyzer : DiagnosticAnalyzer
{
private const string ReliabilityCategory = "Reliability";
public static readonly DiagnosticDescriptor UnaryTrueDescriptor = new DiagnosticDescriptor(
"UnaryTrue",
"An unary True operation is found",
"A unary True operation is found",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor UnaryFalseDescriptor = new DiagnosticDescriptor(
"UnaryFalse",
"An unary False operation is found",
"A unary False operation is found",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(UnaryTrueDescriptor, UnaryFalseDescriptor);
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
var unary = (IUnaryOperation)operationContext.Operation;
if (unary.OperatorKind == UnaryOperatorKind.True)
{
operationContext.ReportDiagnostic(Diagnostic.Create(UnaryTrueDescriptor, unary.Syntax.GetLocation()));
}
else if (unary.OperatorKind == UnaryOperatorKind.False)
{
operationContext.ReportDiagnostic(Diagnostic.Create(UnaryFalseDescriptor, unary.Syntax.GetLocation()));
}
},
OperationKind.UnaryOperator);
}
}
public class AssignmentOperationSyntaxTestAnalyzer : DiagnosticAnalyzer
{
private const string ReliabilityCategory = "Reliability";
public static readonly DiagnosticDescriptor AssignmentOperationDescriptor = new DiagnosticDescriptor(
"AssignmentOperation",
"An assignment operation is found",
"An assignment operation is found",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor AssignmentSyntaxDescriptor = new DiagnosticDescriptor(
"AssignmentSyntax",
"An assignment syntax is found",
"An assignment syntax is found",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get { return ImmutableArray.Create(AssignmentOperationDescriptor, AssignmentSyntaxDescriptor); }
}
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
operationContext.ReportDiagnostic(Diagnostic.Create(AssignmentOperationDescriptor, operationContext.Operation.Syntax.GetLocation()));
},
OperationKind.SimpleAssignment);
context.RegisterSyntaxNodeAction(
(syntaxContext) =>
{
syntaxContext.ReportDiagnostic(Diagnostic.Create(AssignmentSyntaxDescriptor, syntaxContext.Node.GetLocation()));
},
CSharp.SyntaxKind.SimpleAssignmentExpression);
}
}
public class LiteralTestAnalyzer : DiagnosticAnalyzer
{
private const string ReliabilityCategory = "Reliability";
public static readonly DiagnosticDescriptor LiteralDescriptor = new DiagnosticDescriptor(
"Literal",
"A literal is found",
"A literal of value {0} is found",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get { return ImmutableArray.Create(LiteralDescriptor); }
}
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
var literal = (ILiteralOperation)operationContext.Operation;
operationContext.ReportDiagnostic(Diagnostic.Create(LiteralDescriptor, literal.Syntax.GetLocation(), literal.Syntax.ToString()));
},
OperationKind.Literal);
}
}
// This analyzer is to test operation action registration method in AnalysisContext
public class AnalysisContextAnalyzer : DiagnosticAnalyzer
{
private const string ReliabilityCategory = "Reliability";
public static readonly DiagnosticDescriptor OperationActionDescriptor = new DiagnosticDescriptor(
"AnalysisContext",
"An operation related action is invoked",
"An {0} action is invoked in {1} context.",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(OperationActionDescriptor);
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(
(operationContext) =>
{
operationContext.ReportDiagnostic(
Diagnostic.Create(OperationActionDescriptor, operationContext.Operation.Syntax.GetLocation(), "Operation", "Analysis"));
},
OperationKind.Literal);
}
}
// This analyzer is to test operation action registration method in CompilationStartAnalysisContext
public class CompilationStartAnalysisContextAnalyzer : DiagnosticAnalyzer
{
private const string ReliabilityCategory = "Reliability";
public static readonly DiagnosticDescriptor OperationActionDescriptor = new DiagnosticDescriptor(
"CompilationStartAnalysisContext",
"An operation related action is invoked",
"An {0} action is invoked in {1} context.",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(OperationActionDescriptor);
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterCompilationStartAction(
(compilationStartContext) =>
{
compilationStartContext.RegisterOperationAction(
(operationContext) =>
{
operationContext.ReportDiagnostic(
Diagnostic.Create(OperationActionDescriptor, operationContext.Operation.Syntax.GetLocation(), "Operation", "CompilationStart within Analysis"));
},
OperationKind.Literal);
});
}
}
// This analyzer is to test GetOperation method in SemanticModel
public class SemanticModelAnalyzer : DiagnosticAnalyzer
{
private const string ReliabilityCategory = "Reliability";
public static readonly DiagnosticDescriptor GetOperationDescriptor = new DiagnosticDescriptor(
"GetOperation",
"An IOperation is returned by SemanticModel",
"An IOperation is returned by SemanticModel.",
ReliabilityCategory,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(GetOperationDescriptor);
public sealed override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(
(syntaxContext) =>
{
var node = syntaxContext.Node;
var model = syntaxContext.SemanticModel;
if (model.GetOperation(node) != null)
{
syntaxContext.ReportDiagnostic(Diagnostic.Create(GetOperationDescriptor, node.GetLocation()));
}
},
Microsoft.CodeAnalysis.CSharp.SyntaxKind.NumericLiteralExpression);
context.RegisterSyntaxNodeAction(
(syntaxContext) =>
{
var node = syntaxContext.Node;
var model = syntaxContext.SemanticModel;
if (model.GetOperation(node) != null)
{
syntaxContext.ReportDiagnostic(Diagnostic.Create(GetOperationDescriptor, node.GetLocation()));
}
},
Microsoft.CodeAnalysis.VisualBasic.SyntaxKind.NumericLiteralExpression);
}
}
}
| 47.589508 | 222 | 0.568029 | [
"Apache-2.0"
] | ObsidianMinor/roslyn | src/Test/Utilities/Portable/Diagnostics/OperationTestAnalyzer.cs | 103,414 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace XOutput.Devices.XInput
{
/// <summary>
/// <see cref="IInputHelper{T}"/> for <see cref="XInputTypes"/>.
/// </summary>
public class XInputHelper : AbstractInputHelper<XInputTypes>
{
protected static readonly XInputHelper instance = new XInputHelper();
/// <summary>
/// Gets the singleton instance of the class.
/// </summary>
public static XInputHelper Instance => instance;
/// <summary>
/// Gets if the value is axis type.
/// <para>Implements <see cref="IInputHelper{T}.IsAxis(T)"/> enum value</para>
/// </summary>
/// <param name="type"><see cref="XInputTypes"/> enum value</param>
/// <returns></returns>
public override bool IsAxis(XInputTypes input)
{
switch (input)
{
case XInputTypes.LX:
case XInputTypes.LY:
case XInputTypes.RX:
case XInputTypes.RY:
case XInputTypes.L2:
case XInputTypes.R2:
return true;
default:
return false;
}
}
/// <summary>
/// Gets if the value is button type.
/// <para>Implements <see cref="IInputHelper{T}.IsButton(T)"/> enum value</para>
/// </summary>
/// <param name="type"><see cref="XInputTypes"/> enum value</param>
/// <returns></returns>
public override bool IsButton(XInputTypes input)
{
switch (input)
{
case XInputTypes.A:
case XInputTypes.B:
case XInputTypes.X:
case XInputTypes.Y:
case XInputTypes.L1:
case XInputTypes.R1:
case XInputTypes.L3:
case XInputTypes.R3:
case XInputTypes.Start:
case XInputTypes.Back:
case XInputTypes.Home:
return true;
default:
return false;
}
}
/// <summary>
/// Gets if the value is DPad type.
/// <para>Implements <see cref="IInputHelper{T}.IsDPad(T)"/> enum value</para>
/// </summary>
/// <param name="type"><see cref="XInputTypes"/> enum value</param>
/// <returns></returns>
public override bool IsDPad(XInputTypes input)
{
switch (input)
{
case XInputTypes.LEFT:
case XInputTypes.RIGHT:
case XInputTypes.UP:
case XInputTypes.DOWN:
return true;
default:
return false;
}
}
/// <summary>
/// Returns false. XInput devices has no sliders.
/// <para>Implements <see cref="IInputHelper{T}.IsSlider(T)"/> enum value</para>
/// </summary>
/// <param name="type"><see cref="XInputTypes"/> enum value</param>
/// <returns></returns>
public override bool IsSlider(XInputTypes type)
{
return false;
}
/// <summary>
/// Gets the value for disabled mapping.
/// </summary>
/// <param name="input"><see cref="XInputTypes"/> enum value</param>
/// <returns></returns>
public double GetDisableValue(XInputTypes input)
{
switch (input)
{
case XInputTypes.LX:
case XInputTypes.LY:
case XInputTypes.RX:
case XInputTypes.RY:
return 0.5;
default:
return 0;
}
}
}
/// <summary>
/// Extension helper class for <see cref="XInputTypes"/>.
/// It proxies all calls to <see cref="XInputHelper.Instance"/>.
/// </summary>
public static class XInputExtension
{
public static bool IsAxis(this XInputTypes input)
{
return XInputHelper.Instance.IsAxis(input);
}
public static bool IsDPad(this XInputTypes input)
{
return XInputHelper.Instance.IsDPad(input);
}
public static bool IsButton(this XInputTypes input)
{
return XInputHelper.Instance.IsButton(input);
}
public static double GetDisableValue(this XInputTypes input)
{
return XInputHelper.Instance.GetDisableValue(input);
}
}
}
| 31.591837 | 88 | 0.512489 | [
"MIT"
] | LLltirlec/XOutput | XOutput/Devices/XInput/XInputHelper.cs | 4,646 | C# |
using TheMountaineer.Fisobs;
using UnityEngine;
namespace TheMountaineer.Equipment
{
public class HardhatAbstract : AbstractPhysicalObject
{
public HardhatAbstract(World world, WorldCoordinate pos, EntityID id) :
base(world, HardhatFisob.instance.Type, null, pos, id)
{
charge = 1f - Random.value * 0.2f;
}
public override void Realize()
{
if (realizedObject is null)
realizedObject = new Hardhat(this);
base.Realize();
}
public override string ToString() => this.SaveToString($"{charge}");
public float charge;
}
}
| 24.392857 | 79 | 0.581259 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | casheww/RW-Slugs | TheMountaineer/Equipment/HardhatAbstract.cs | 685 | C# |
using Nop.Web.Framework.Models;
namespace Nop.Plugin.Tax.Avalara.Models.Checkout
{
/// <summary>
/// Represents an address validation model
/// </summary>
public class AddressValidationModel : BaseNopModel
{
#region Properties
public string Message { get; set; }
public bool IsError { get; set; }
public bool IsNewAddress { get; set; }
public int AddressId { get; set; }
#endregion
}
} | 21.090909 | 54 | 0.616379 | [
"MIT"
] | ASP-WAF/FireWall | Samples/NopeCommerce/Plugins/Nop.Plugin.Tax.Avalara/Models/Checkout/AddressValidationModel.cs | 466 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.