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 |
|---|---|---|---|---|---|---|---|---|
// 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 Carbon.TaskScheduler
{
public enum Month
{
January = 1,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December,
}
}
| 25.032258 | 76 | 0.688144 | [
"Apache-2.0"
] | Acidburn0zzz/Carbon-1 | Source/TaskScheduler/Months.cs | 776 | C# |
//******************************************************************************************************
// DataReceiver.cs - Gbtc
//
// Copyright © 2019, Grid Protection Alliance. All Rights Reserved.
//
// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
// the NOTICE file distributed with this work for additional information regarding copyright ownership.
// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this
// file except in compliance with the License. You may obtain a copy of the License at:
//
// http://opensource.org/licenses/MIT
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 02/11/2019 - J. Ritchie Carroll
// Generated original version of source code.
//
//******************************************************************************************************
using System;
using System.Collections.Generic;
using GSF;
using GSF.TimeSeries;
using GSF.TimeSeries.Transport;
namespace GEPDataExtractor
{
/// <summary>
/// Retrieves data from openHistorian using GEP
/// </summary>
internal sealed class DataReceiver : IDisposable
{
#region [ Members ]
// Fields
private DataSubscriber m_subscriber;
private readonly UnsynchronizedSubscriptionInfo m_subscriptionInfo;
private bool m_disposed;
#endregion
#region [ Constructors ]
/// <summary>
/// Creates a new <see cref="DataReceiver"/> instance with the specified <paramref name="connectionString"/>.
/// </summary>
/// <param name="connectionString">GEP connection string for openHistorian.</param>
/// <param name="filterExpression">Filter expression defining measurements to query.</param>
/// <param name="startTime">Temporal subscription start time.</param>
/// <param name="stopTime">Temporal subscription stop time.</param>
public DataReceiver(string connectionString, string filterExpression, DateTime startTime, DateTime stopTime)
{
m_subscriber = new DataSubscriber
{
ConnectionString = connectionString,
OperationalModes = OperationalModes.UseCommonSerializationFormat | OperationalModes.CompressPayloadData,
CompressionModes = CompressionModes.TSSC
};
m_subscriptionInfo = new UnsynchronizedSubscriptionInfo(false)
{
FilterExpression = filterExpression,
StartTime = startTime.ToString(TimeTagBase.DefaultFormat),
StopTime = stopTime.ToString(TimeTagBase.DefaultFormat),
ProcessingInterval = 0, // Zero value requests data as fast as possible
UseMillisecondResolution = true
};
// Attach to needed subscriber events
m_subscriber.ConnectionEstablished += m_subscriber_ConnectionEstablished;
m_subscriber.NewMeasurements += m_subscriber_NewMeasurements;
m_subscriber.StatusMessage += m_subscriber_StatusMessage;
m_subscriber.ProcessException += m_subscriber_ProcessException;
m_subscriber.ProcessingComplete += m_subscriber_ProcessingComplete;
// Initialize the subscriber
m_subscriber.Initialize();
// Start subscriber connection cycle
m_subscriber.Start();
}
/// <summary>
/// Releases the unmanaged resources before the <see cref="DataReceiver"/> object is reclaimed by <see cref="GC"/>.
/// </summary>
~DataReceiver() => Dispose(false);
public Action<ICollection<IMeasurement>> NewMeasurementsCallback { get; set; }
public Action<string> StatusMessageCallback { get; set; }
public Action<Exception> ProcessExceptionCallback { get; set; }
public Action ReadCompletedCallback { get; set; }
#endregion
#region [ Methods ]
/// <summary>
/// Releases all the resources used by the <see cref="DataReceiver"/> object.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases the unmanaged resources used by the <see cref="DataReceiver"/> object and optionally releases the managed resources.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
private void Dispose(bool disposing)
{
if (!m_disposed)
{
try
{
if (disposing)
{
if ((object)m_subscriber != null)
{
m_subscriber.Unsubscribe();
m_subscriber.Stop();
// Detach from subscriber events
m_subscriber.ConnectionEstablished -= m_subscriber_ConnectionEstablished;
m_subscriber.NewMeasurements -= m_subscriber_NewMeasurements;
m_subscriber.StatusMessage -= m_subscriber_StatusMessage;
m_subscriber.ProcessException -= m_subscriber_ProcessException;
m_subscriber.ProcessingComplete -= m_subscriber_ProcessingComplete;
m_subscriber.Dispose();
m_subscriber = null;
}
}
}
finally
{
m_disposed = true; // Prevent duplicate dispose.
}
}
}
private void m_subscriber_ConnectionEstablished(object sender, EventArgs e) => m_subscriber.UnsynchronizedSubscribe(m_subscriptionInfo);
private void m_subscriber_NewMeasurements(object sender, EventArgs<ICollection<IMeasurement>> e) => NewMeasurementsCallback?.Invoke(e.Argument);
private void m_subscriber_StatusMessage(object sender, EventArgs<string> e) => StatusMessageCallback?.Invoke(e.Argument);
private void m_subscriber_ProcessException(object sender, EventArgs<Exception> e) => ProcessExceptionCallback?.Invoke(e.Argument);
private void m_subscriber_ProcessingComplete(object sender, EventArgs<string> e) => ReadCompletedCallback?.Invoke();
#endregion
}
}
| 42.62963 | 152 | 0.60223 | [
"MIT"
] | zobo/gsf | Source/Tools/GEPDataExtractor/DataReceiver.cs | 6,909 | C# |
using System;
using System.Linq;
namespace _02_DancingMoves
{
class Program
{
static void Main(string[] args)
{
var input = Console.ReadLine()
.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
long sum = 0;
var startPosition = 0;
var counter = 0;
while (true)
{
var token = Console.ReadLine().Split().ToArray();
if (token[0] == "stop")
{
break;
}
var times = int.Parse(token[0]);
var direction = token[1];
var step = int.Parse(token[2]);
if (direction == "right")
{
for (int i = 0; i < times; i++)
{
startPosition += step;
while (startPosition > input.Length - 1)
{
startPosition -= input.Length;
}
sum += input[startPosition];
}
}
else if (direction == "left")
{
for (int i = 0; i < times; i++)
{
startPosition -= step;
while (startPosition < 0)
{
startPosition += input.Length;
}
sum += input[startPosition];
}
}
counter++;
}
decimal result = (decimal)sum / counter;
Console.WriteLine("{0:f1}", result);
}
}
} | 28.40625 | 80 | 0.352585 | [
"MIT"
] | alekhristov/TelerikAcademyAlpha | 01-Module1/01-C# Advanced/ExamPrep/ExamPrep2/02-DancingMoves/02-DancingMoves.cs | 1,820 | C# |
namespace Octokit.Webhooks.Events.ContentReference
{
public static class ContentReferenceActionValue
{
public const string Created = "created";
}
}
| 21 | 51 | 0.720238 | [
"MIT"
] | JamieMagee/JamieMagee.Octokit.Webhooks | src/Octokit.Webhooks/Events/ContentReference/ContentReferenceActionValue.cs | 168 | C# |
using System.Collections.Generic;
using System.Linq;
using UnityEngine.Purchasing.Utils;
namespace UnityEngine.Purchasing.Models
{
/// <summary>
/// This is C# representation of the Java Class PurchasesResult
/// <a href="https://developer.android.com/reference/com/android/billingclient/api/Purchase.PurchasesResult">See more</a>
/// </summary>
class GooglePurchaseResult
{
internal int m_ResponseCode;
internal List<GooglePurchase> m_Purchases = new List<GooglePurchase>();
internal GooglePurchaseResult(AndroidJavaObject purchaseResult, IGoogleCachedQuerySkuDetailsService cachedQuerySkuDetailsService)
{
m_ResponseCode = purchaseResult.Call<int>("getResponseCode");
FillPurchases(purchaseResult, cachedQuerySkuDetailsService);
}
void FillPurchases(AndroidJavaObject purchaseResult, IGoogleCachedQuerySkuDetailsService cachedQuerySkuDetailsService)
{
AndroidJavaObject purchaseList = purchaseResult.Call<AndroidJavaObject>("getPurchasesList");
if (purchaseList != null)
{
int size = purchaseList.Call<int>("size");
for (int index = 0; index < size; index++)
{
AndroidJavaObject purchase = purchaseList.Call<AndroidJavaObject>("get", index);
if (purchase != null)
{
m_Purchases.Add(GooglePurchaseHelper.MakeGooglePurchase(cachedQuerySkuDetailsService.GetCachedQueriedSkus().ToList(), purchase));
}
else
{
Debug.LogWarning("Failed to retrieve Purchase from Purchase List at index " + index + " of " + size + ". FillPurchases will skip this item");
}
}
}
}
}
}
| 42.727273 | 165 | 0.62234 | [
"MIT"
] | 2PUEG-VRIK/UnityEscapeGame | 2P-UnityEscapeGame/Library/PackageCache/com.unity.purchasing@3.1.0/Runtime/Stores/Android/GooglePlay/AAR/Models/GooglePurchaseResult.cs | 1,880 | C# |
using System.Collections.Concurrent;
using Microsoft.Extensions.Configuration;
using Abp.Extensions;
using Abp.Reflection.Extensions;
namespace SlowDI.Configuration
{
public static class AppConfigurations
{
private static readonly ConcurrentDictionary<string, IConfigurationRoot> _configurationCache;
static AppConfigurations()
{
_configurationCache = new ConcurrentDictionary<string, IConfigurationRoot>();
}
public static IConfigurationRoot Get(string path, string environmentName = null, bool addUserSecrets = false)
{
var cacheKey = path + "#" + environmentName + "#" + addUserSecrets;
return _configurationCache.GetOrAdd(
cacheKey,
_ => BuildConfiguration(path, environmentName, addUserSecrets)
);
}
private static IConfigurationRoot BuildConfiguration(string path, string environmentName = null, bool addUserSecrets = false)
{
var builder = new ConfigurationBuilder()
.SetBasePath(path)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
if (!environmentName.IsNullOrWhiteSpace())
{
builder = builder.AddJsonFile($"appsettings.{environmentName}.json", optional: true);
}
builder = builder.AddEnvironmentVariables();
if (addUserSecrets)
{
builder.AddUserSecrets(typeof(AppConfigurations).GetAssembly());
}
return builder.Build();
}
}
}
| 33.645833 | 133 | 0.629721 | [
"MIT"
] | naazz1992/AspnetboilerplateSlowDiTest | src/SlowDI.Core/Configuration/AppConfigurations.cs | 1,617 | C# |
using DotVVM.Framework.Controls;
using DotVVM.Framework.Controls.DynamicData;
using DotVVM.Framework.Controls.DynamicData.Metadata;
using DotVVM.Framework.Controls.DynamicData.PropertyHandlers.FormEditors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace Bcs.Admin.Web.Controls.Dynamic
{
public class CodeEditorAttribute : Attribute
{
public CodeEditorAttribute(string keyUpMethodName = null)
{
KeyUpMethodName = keyUpMethodName;
}
public string KeyUpMethodName { get; }
}
public class CodeEditorProvider : FormEditorProviderBase
{
public override bool CanHandleProperty(PropertyInfo propertyInfo, DynamicDataContext context)
{
return GetCodeEditorAttribute(propertyInfo) != null && propertyInfo.PropertyType == typeof(string);
}
public override void CreateControl(DotvvmControl container, PropertyDisplayMetadata property, DynamicDataContext context)
{
var codeControl = new CodeEditor();
container.Children.Add(codeControl);
var cssClass = ControlHelpers.ConcatCssClasses(ControlCssClass, property.Styles?.FormControlCssClass);
codeControl.Attributes["class"] = "form-control code-editor";
var attribute = GetCodeEditorAttribute(property.PropertyInfo);
codeControl.SetBinding(CodeEditor.HtmlProperty, context.CreateValueBinding(property.PropertyInfo.Name));
codeControl.SetBinding(CodeEditor.StyleSpansProperty, context.CreateValueBinding($"{property.PropertyInfo.Name}Spans"));
codeControl.SetBinding(CodeEditor.TextProperty, context.CreateValueBinding($"{property.PropertyInfo.Name}Text"));
if (attribute.KeyUpMethodName != null)
{
codeControl.SetBinding(CodeEditor.KeyDownProperty, context.CreateCommandBinding($"{attribute.KeyUpMethodName}()"));
}
}
private static CodeEditorAttribute GetCodeEditorAttribute(PropertyInfo propertyInfo)
{
return propertyInfo.GetCustomAttribute<CodeEditorAttribute>();
}
}
}
| 38.912281 | 132 | 0.71596 | [
"Apache-2.0"
] | sybila/BCSParser | Bcs.Admin.Web/Controls/Dynamic/CodeEditorProvider.cs | 2,220 | C# |
using Geisha.Editor.CreateTextureAsset.Model;
using Geisha.Editor.ProjectHandling.Model;
namespace Geisha.Editor.CreateTextureAsset.UserInterface
{
internal interface ICreateTextureAssetCommandFactory
{
CreateTextureAssetCommand Create(IProjectFile sourceTextureFile);
}
internal class CreateTextureAssetCommandFactory : ICreateTextureAssetCommandFactory
{
private readonly ICreateTextureAssetService _createTextureAssetService;
public CreateTextureAssetCommandFactory(ICreateTextureAssetService createTextureAssetService)
{
_createTextureAssetService = createTextureAssetService;
}
public CreateTextureAssetCommand Create(IProjectFile sourceTextureFile)
{
return new CreateTextureAssetCommand(_createTextureAssetService, sourceTextureFile);
}
}
} | 34.56 | 101 | 0.771991 | [
"MIT"
] | dawidkomorowski/geisha | src/Geisha.Editor/CreateTextureAsset/UserInterface/CreateTextureAssetCommandFactory.cs | 866 | C# |
using Entities.Models;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace BlazorProducts.Server.Repository
{
public interface IProductRepository
{
Task<IEnumerable<Product>> GetProducts();
}
}
| 19.833333 | 49 | 0.747899 | [
"MIT"
] | CodeMazeBlog/blazor-wasm-signalr-charts | End/BlazorProducts.Server/BlazorProducts.Server/Repository/IProductRepository.cs | 240 | C# |
using System;
using System.ComponentModel;
using Demo.Utilities;
using Spectre.Console.Cli;
namespace Demo.Commands
{
[Description("Launches a web server in the current working directory and serves all files in it.")]
public sealed class ServeCommand : Command<ServeCommand.Settings>
{
public sealed class Settings : CommandSettings
{
[CommandOption("-p|--port <PORT>")]
[Description("Port to use. Defaults to [grey]8080[/]. Use [grey]0[/] for a dynamic port.")]
public int Port { get; set; }
[CommandOption("-o|--open-browser [BROWSER]")]
[Description("Open a web browser when the server starts. You can also specify which browser to use. If none is specified, the default one will be used.")]
public FlagValue<string> OpenBrowser { get; set; }
}
public override int Execute(CommandContext context, Settings settings)
{
if (settings.OpenBrowser.IsSet)
{
var browser = settings.OpenBrowser.Value;
if (browser != null)
{
Console.WriteLine($"Open in {browser}");
}
else
{
Console.WriteLine($"Open in default browser.");
}
}
SettingsDumper.Dump(settings);
return 0;
}
}
}
| 33.833333 | 166 | 0.561576 | [
"MIT"
] | 0xced/spectre.console | examples/Cli/Demo/Commands/Serve/ServeCommand.cs | 1,421 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.Management.Network.Models;
namespace Azure.Management.Network
{
internal partial class ExpressRouteCrossConnectionsRestOperations
{
private string subscriptionId;
private Uri endpoint;
private ClientDiagnostics _clientDiagnostics;
private HttpPipeline _pipeline;
/// <summary> Initializes a new instance of ExpressRouteCrossConnectionsRestOperations. </summary>
/// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param>
/// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="endpoint"> server parameter. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception>
public ExpressRouteCrossConnectionsRestOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string subscriptionId, Uri endpoint = null)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
endpoint ??= new Uri("https://management.azure.com");
this.subscriptionId = subscriptionId;
this.endpoint = endpoint;
_clientDiagnostics = clientDiagnostics;
_pipeline = pipeline;
}
internal HttpMessage CreateListRequest()
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/providers/Microsoft.Network/expressRouteCrossConnections", false);
uri.AppendQuery("api-version", "2020-04-01", true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
return message;
}
/// <summary> Retrieves all the ExpressRouteCrossConnections in a subscription. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async Task<Response<ExpressRouteCrossConnectionListResult>> ListAsync(CancellationToken cancellationToken = default)
{
using var message = CreateListRequest();
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
ExpressRouteCrossConnectionListResult value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = ExpressRouteCrossConnectionListResult.DeserializeExpressRouteCrossConnectionListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Retrieves all the ExpressRouteCrossConnections in a subscription. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public Response<ExpressRouteCrossConnectionListResult> List(CancellationToken cancellationToken = default)
{
using var message = CreateListRequest();
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
ExpressRouteCrossConnectionListResult value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = ExpressRouteCrossConnectionListResult.DeserializeExpressRouteCrossConnectionListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateListByResourceGroupRequest(string resourceGroupName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Network/expressRouteCrossConnections", false);
uri.AppendQuery("api-version", "2020-04-01", true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
return message;
}
/// <summary> Retrieves all the ExpressRouteCrossConnections in a resource group. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/> is null. </exception>
public async Task<Response<ExpressRouteCrossConnectionListResult>> ListByResourceGroupAsync(string resourceGroupName, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
using var message = CreateListByResourceGroupRequest(resourceGroupName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
ExpressRouteCrossConnectionListResult value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = ExpressRouteCrossConnectionListResult.DeserializeExpressRouteCrossConnectionListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Retrieves all the ExpressRouteCrossConnections in a resource group. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/> is null. </exception>
public Response<ExpressRouteCrossConnectionListResult> ListByResourceGroup(string resourceGroupName, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
using var message = CreateListByResourceGroupRequest(resourceGroupName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
ExpressRouteCrossConnectionListResult value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = ExpressRouteCrossConnectionListResult.DeserializeExpressRouteCrossConnectionListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateGetRequest(string resourceGroupName, string crossConnectionName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Network/expressRouteCrossConnections/", false);
uri.AppendPath(crossConnectionName, true);
uri.AppendQuery("api-version", "2020-04-01", true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
return message;
}
/// <summary> Gets details about the specified ExpressRouteCrossConnection. </summary>
/// <param name="resourceGroupName"> The name of the resource group (peering location of the circuit). </param>
/// <param name="crossConnectionName"> The name of the ExpressRouteCrossConnection (service key of the circuit). </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/> or <paramref name="crossConnectionName"/> is null. </exception>
public async Task<Response<ExpressRouteCrossConnection>> GetAsync(string resourceGroupName, string crossConnectionName, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (crossConnectionName == null)
{
throw new ArgumentNullException(nameof(crossConnectionName));
}
using var message = CreateGetRequest(resourceGroupName, crossConnectionName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
ExpressRouteCrossConnection value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = ExpressRouteCrossConnection.DeserializeExpressRouteCrossConnection(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Gets details about the specified ExpressRouteCrossConnection. </summary>
/// <param name="resourceGroupName"> The name of the resource group (peering location of the circuit). </param>
/// <param name="crossConnectionName"> The name of the ExpressRouteCrossConnection (service key of the circuit). </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/> or <paramref name="crossConnectionName"/> is null. </exception>
public Response<ExpressRouteCrossConnection> Get(string resourceGroupName, string crossConnectionName, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (crossConnectionName == null)
{
throw new ArgumentNullException(nameof(crossConnectionName));
}
using var message = CreateGetRequest(resourceGroupName, crossConnectionName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
ExpressRouteCrossConnection value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = ExpressRouteCrossConnection.DeserializeExpressRouteCrossConnection(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateCreateOrUpdateRequest(string resourceGroupName, string crossConnectionName, ExpressRouteCrossConnection parameters)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Put;
var uri = new RawRequestUriBuilder();
uri.Reset(endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Network/expressRouteCrossConnections/", false);
uri.AppendPath(crossConnectionName, true);
uri.AppendQuery("api-version", "2020-04-01", true);
request.Uri = uri;
request.Headers.Add("Content-Type", "application/json");
request.Headers.Add("Accept", "application/json");
var content = new Utf8JsonRequestContent();
content.JsonWriter.WriteObjectValue(parameters);
request.Content = content;
return message;
}
/// <summary> Update the specified ExpressRouteCrossConnection. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="crossConnectionName"> The name of the ExpressRouteCrossConnection. </param>
/// <param name="parameters"> Parameters supplied to the update express route crossConnection operation. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="crossConnectionName"/>, or <paramref name="parameters"/> is null. </exception>
public async Task<Response> CreateOrUpdateAsync(string resourceGroupName, string crossConnectionName, ExpressRouteCrossConnection parameters, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (crossConnectionName == null)
{
throw new ArgumentNullException(nameof(crossConnectionName));
}
if (parameters == null)
{
throw new ArgumentNullException(nameof(parameters));
}
using var message = CreateCreateOrUpdateRequest(resourceGroupName, crossConnectionName, parameters);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
return message.Response;
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Update the specified ExpressRouteCrossConnection. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="crossConnectionName"> The name of the ExpressRouteCrossConnection. </param>
/// <param name="parameters"> Parameters supplied to the update express route crossConnection operation. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="crossConnectionName"/>, or <paramref name="parameters"/> is null. </exception>
public Response CreateOrUpdate(string resourceGroupName, string crossConnectionName, ExpressRouteCrossConnection parameters, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (crossConnectionName == null)
{
throw new ArgumentNullException(nameof(crossConnectionName));
}
if (parameters == null)
{
throw new ArgumentNullException(nameof(parameters));
}
using var message = CreateCreateOrUpdateRequest(resourceGroupName, crossConnectionName, parameters);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
return message.Response;
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateUpdateTagsRequest(string resourceGroupName, string crossConnectionName, TagsObject crossConnectionParameters)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Patch;
var uri = new RawRequestUriBuilder();
uri.Reset(endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Network/expressRouteCrossConnections/", false);
uri.AppendPath(crossConnectionName, true);
uri.AppendQuery("api-version", "2020-04-01", true);
request.Uri = uri;
request.Headers.Add("Content-Type", "application/json");
request.Headers.Add("Accept", "application/json");
var content = new Utf8JsonRequestContent();
content.JsonWriter.WriteObjectValue(crossConnectionParameters);
request.Content = content;
return message;
}
/// <summary> Updates an express route cross connection tags. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="crossConnectionName"> The name of the cross connection. </param>
/// <param name="crossConnectionParameters"> Parameters supplied to update express route cross connection tags. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="crossConnectionName"/>, or <paramref name="crossConnectionParameters"/> is null. </exception>
public async Task<Response<ExpressRouteCrossConnection>> UpdateTagsAsync(string resourceGroupName, string crossConnectionName, TagsObject crossConnectionParameters, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (crossConnectionName == null)
{
throw new ArgumentNullException(nameof(crossConnectionName));
}
if (crossConnectionParameters == null)
{
throw new ArgumentNullException(nameof(crossConnectionParameters));
}
using var message = CreateUpdateTagsRequest(resourceGroupName, crossConnectionName, crossConnectionParameters);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
ExpressRouteCrossConnection value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = ExpressRouteCrossConnection.DeserializeExpressRouteCrossConnection(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Updates an express route cross connection tags. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="crossConnectionName"> The name of the cross connection. </param>
/// <param name="crossConnectionParameters"> Parameters supplied to update express route cross connection tags. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="crossConnectionName"/>, or <paramref name="crossConnectionParameters"/> is null. </exception>
public Response<ExpressRouteCrossConnection> UpdateTags(string resourceGroupName, string crossConnectionName, TagsObject crossConnectionParameters, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (crossConnectionName == null)
{
throw new ArgumentNullException(nameof(crossConnectionName));
}
if (crossConnectionParameters == null)
{
throw new ArgumentNullException(nameof(crossConnectionParameters));
}
using var message = CreateUpdateTagsRequest(resourceGroupName, crossConnectionName, crossConnectionParameters);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
ExpressRouteCrossConnection value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = ExpressRouteCrossConnection.DeserializeExpressRouteCrossConnection(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateListArpTableRequest(string resourceGroupName, string crossConnectionName, string peeringName, string devicePath)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Post;
var uri = new RawRequestUriBuilder();
uri.Reset(endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Network/expressRouteCrossConnections/", false);
uri.AppendPath(crossConnectionName, true);
uri.AppendPath("/peerings/", false);
uri.AppendPath(peeringName, true);
uri.AppendPath("/arpTables/", false);
uri.AppendPath(devicePath, true);
uri.AppendQuery("api-version", "2020-04-01", true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
return message;
}
/// <summary> Gets the currently advertised ARP table associated with the express route cross connection in a resource group. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="crossConnectionName"> The name of the ExpressRouteCrossConnection. </param>
/// <param name="peeringName"> The name of the peering. </param>
/// <param name="devicePath"> The path of the device. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="crossConnectionName"/>, <paramref name="peeringName"/>, or <paramref name="devicePath"/> is null. </exception>
public async Task<Response> ListArpTableAsync(string resourceGroupName, string crossConnectionName, string peeringName, string devicePath, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (crossConnectionName == null)
{
throw new ArgumentNullException(nameof(crossConnectionName));
}
if (peeringName == null)
{
throw new ArgumentNullException(nameof(peeringName));
}
if (devicePath == null)
{
throw new ArgumentNullException(nameof(devicePath));
}
using var message = CreateListArpTableRequest(resourceGroupName, crossConnectionName, peeringName, devicePath);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
case 202:
return message.Response;
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Gets the currently advertised ARP table associated with the express route cross connection in a resource group. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="crossConnectionName"> The name of the ExpressRouteCrossConnection. </param>
/// <param name="peeringName"> The name of the peering. </param>
/// <param name="devicePath"> The path of the device. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="crossConnectionName"/>, <paramref name="peeringName"/>, or <paramref name="devicePath"/> is null. </exception>
public Response ListArpTable(string resourceGroupName, string crossConnectionName, string peeringName, string devicePath, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (crossConnectionName == null)
{
throw new ArgumentNullException(nameof(crossConnectionName));
}
if (peeringName == null)
{
throw new ArgumentNullException(nameof(peeringName));
}
if (devicePath == null)
{
throw new ArgumentNullException(nameof(devicePath));
}
using var message = CreateListArpTableRequest(resourceGroupName, crossConnectionName, peeringName, devicePath);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
case 202:
return message.Response;
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateListRoutesTableSummaryRequest(string resourceGroupName, string crossConnectionName, string peeringName, string devicePath)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Post;
var uri = new RawRequestUriBuilder();
uri.Reset(endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Network/expressRouteCrossConnections/", false);
uri.AppendPath(crossConnectionName, true);
uri.AppendPath("/peerings/", false);
uri.AppendPath(peeringName, true);
uri.AppendPath("/routeTablesSummary/", false);
uri.AppendPath(devicePath, true);
uri.AppendQuery("api-version", "2020-04-01", true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
return message;
}
/// <summary> Gets the route table summary associated with the express route cross connection in a resource group. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="crossConnectionName"> The name of the ExpressRouteCrossConnection. </param>
/// <param name="peeringName"> The name of the peering. </param>
/// <param name="devicePath"> The path of the device. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="crossConnectionName"/>, <paramref name="peeringName"/>, or <paramref name="devicePath"/> is null. </exception>
public async Task<Response> ListRoutesTableSummaryAsync(string resourceGroupName, string crossConnectionName, string peeringName, string devicePath, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (crossConnectionName == null)
{
throw new ArgumentNullException(nameof(crossConnectionName));
}
if (peeringName == null)
{
throw new ArgumentNullException(nameof(peeringName));
}
if (devicePath == null)
{
throw new ArgumentNullException(nameof(devicePath));
}
using var message = CreateListRoutesTableSummaryRequest(resourceGroupName, crossConnectionName, peeringName, devicePath);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
case 202:
return message.Response;
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Gets the route table summary associated with the express route cross connection in a resource group. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="crossConnectionName"> The name of the ExpressRouteCrossConnection. </param>
/// <param name="peeringName"> The name of the peering. </param>
/// <param name="devicePath"> The path of the device. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="crossConnectionName"/>, <paramref name="peeringName"/>, or <paramref name="devicePath"/> is null. </exception>
public Response ListRoutesTableSummary(string resourceGroupName, string crossConnectionName, string peeringName, string devicePath, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (crossConnectionName == null)
{
throw new ArgumentNullException(nameof(crossConnectionName));
}
if (peeringName == null)
{
throw new ArgumentNullException(nameof(peeringName));
}
if (devicePath == null)
{
throw new ArgumentNullException(nameof(devicePath));
}
using var message = CreateListRoutesTableSummaryRequest(resourceGroupName, crossConnectionName, peeringName, devicePath);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
case 202:
return message.Response;
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateListRoutesTableRequest(string resourceGroupName, string crossConnectionName, string peeringName, string devicePath)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Post;
var uri = new RawRequestUriBuilder();
uri.Reset(endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Network/expressRouteCrossConnections/", false);
uri.AppendPath(crossConnectionName, true);
uri.AppendPath("/peerings/", false);
uri.AppendPath(peeringName, true);
uri.AppendPath("/routeTables/", false);
uri.AppendPath(devicePath, true);
uri.AppendQuery("api-version", "2020-04-01", true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
return message;
}
/// <summary> Gets the currently advertised routes table associated with the express route cross connection in a resource group. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="crossConnectionName"> The name of the ExpressRouteCrossConnection. </param>
/// <param name="peeringName"> The name of the peering. </param>
/// <param name="devicePath"> The path of the device. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="crossConnectionName"/>, <paramref name="peeringName"/>, or <paramref name="devicePath"/> is null. </exception>
public async Task<Response> ListRoutesTableAsync(string resourceGroupName, string crossConnectionName, string peeringName, string devicePath, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (crossConnectionName == null)
{
throw new ArgumentNullException(nameof(crossConnectionName));
}
if (peeringName == null)
{
throw new ArgumentNullException(nameof(peeringName));
}
if (devicePath == null)
{
throw new ArgumentNullException(nameof(devicePath));
}
using var message = CreateListRoutesTableRequest(resourceGroupName, crossConnectionName, peeringName, devicePath);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
case 202:
return message.Response;
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Gets the currently advertised routes table associated with the express route cross connection in a resource group. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="crossConnectionName"> The name of the ExpressRouteCrossConnection. </param>
/// <param name="peeringName"> The name of the peering. </param>
/// <param name="devicePath"> The path of the device. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="crossConnectionName"/>, <paramref name="peeringName"/>, or <paramref name="devicePath"/> is null. </exception>
public Response ListRoutesTable(string resourceGroupName, string crossConnectionName, string peeringName, string devicePath, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (crossConnectionName == null)
{
throw new ArgumentNullException(nameof(crossConnectionName));
}
if (peeringName == null)
{
throw new ArgumentNullException(nameof(peeringName));
}
if (devicePath == null)
{
throw new ArgumentNullException(nameof(devicePath));
}
using var message = CreateListRoutesTableRequest(resourceGroupName, crossConnectionName, peeringName, devicePath);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
case 202:
return message.Response;
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateListNextPageRequest(string nextLink)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(endpoint);
uri.AppendRawNextLink(nextLink, false);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
return message;
}
/// <summary> Retrieves all the ExpressRouteCrossConnections in a subscription. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> is null. </exception>
public async Task<Response<ExpressRouteCrossConnectionListResult>> ListNextPageAsync(string nextLink, CancellationToken cancellationToken = default)
{
if (nextLink == null)
{
throw new ArgumentNullException(nameof(nextLink));
}
using var message = CreateListNextPageRequest(nextLink);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
ExpressRouteCrossConnectionListResult value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = ExpressRouteCrossConnectionListResult.DeserializeExpressRouteCrossConnectionListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Retrieves all the ExpressRouteCrossConnections in a subscription. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> is null. </exception>
public Response<ExpressRouteCrossConnectionListResult> ListNextPage(string nextLink, CancellationToken cancellationToken = default)
{
if (nextLink == null)
{
throw new ArgumentNullException(nameof(nextLink));
}
using var message = CreateListNextPageRequest(nextLink);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
ExpressRouteCrossConnectionListResult value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = ExpressRouteCrossConnectionListResult.DeserializeExpressRouteCrossConnectionListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateListByResourceGroupNextPageRequest(string nextLink, string resourceGroupName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(endpoint);
uri.AppendRawNextLink(nextLink, false);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
return message;
}
/// <summary> Retrieves all the ExpressRouteCrossConnections in a resource group. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> or <paramref name="resourceGroupName"/> is null. </exception>
public async Task<Response<ExpressRouteCrossConnectionListResult>> ListByResourceGroupNextPageAsync(string nextLink, string resourceGroupName, CancellationToken cancellationToken = default)
{
if (nextLink == null)
{
throw new ArgumentNullException(nameof(nextLink));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
using var message = CreateListByResourceGroupNextPageRequest(nextLink, resourceGroupName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
ExpressRouteCrossConnectionListResult value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = ExpressRouteCrossConnectionListResult.DeserializeExpressRouteCrossConnectionListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Retrieves all the ExpressRouteCrossConnections in a resource group. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> or <paramref name="resourceGroupName"/> is null. </exception>
public Response<ExpressRouteCrossConnectionListResult> ListByResourceGroupNextPage(string nextLink, string resourceGroupName, CancellationToken cancellationToken = default)
{
if (nextLink == null)
{
throw new ArgumentNullException(nameof(nextLink));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
using var message = CreateListByResourceGroupNextPageRequest(nextLink, resourceGroupName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
ExpressRouteCrossConnectionListResult value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = ExpressRouteCrossConnectionListResult.DeserializeExpressRouteCrossConnectionListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
}
}
| 53.807475 | 219 | 0.627231 | [
"MIT"
] | Banani-Rath/azure-sdk-for-net | sdk/testcommon/Azure.Management.Network.2020_04/src/Generated/ExpressRouteCrossConnectionsRestOperations.cs | 47,512 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web.Mvc;
using wR.DAL;
using wR.Web.ViewModels;
namespace wR.Web.Controllers
{
[RoutePrefix("configuration")]
public class ConfigurationController : Controller
{
private readonly ApplicationDbContext _context;
public ConfigurationController()
{
_context = new ApplicationDbContext();
}
[Route(""), HttpGet]
public ActionResult Index()
{
var changeConfigurationVm = new ChangeConfigurationVm
{
SourceLanguageSelection = GetLanguageSelection(),
SourceLanguageId = Guid.Parse(ConfigurationManager.AppSettings["SourceLanguage"]),
DestinationLanguageSelection = GetLanguageSelection(),
DestinationLanguageId = Guid.Parse(ConfigurationManager.AppSettings["DestinationLanguage"]),
IsFlipModeOn = bool.Parse(ConfigurationManager.AppSettings["FlipMode"])
};
return View(changeConfigurationVm);
}
[Route(""), HttpPost]
public ActionResult Change(ChangeConfigurationVm changeViewModel)
{
ConfigurationManager.AppSettings["SourceLanguage"] = changeViewModel.SourceLanguageId.ToString();
ConfigurationManager.AppSettings["DestinationLanguage"] = changeViewModel.DestinationLanguageId.ToString();
ConfigurationManager.AppSettings["FlipMode"] = changeViewModel.IsFlipModeOn.ToString();
return RedirectToAction("Index", "Home");
}
/// <summary>
/// Fetches the list of available languages from the datastore
/// </summary>
/// <returns></returns>
public IEnumerable<SelectListItem> GetLanguageSelection()
{
var languages = _context.Languages.Select(l => new SelectListItem
{
Value = l.Id.ToString(),
Text = l.Code
});
return new SelectList(languages, "Value", "Text");
}
}
} | 35.166667 | 119 | 0.633649 | [
"MIT"
] | piotr-mamenas/personal-tools | tools/word-repeater/wR.Web/Controllers/ConfigurationController.cs | 2,112 | C# |
// Copyright 2013 Xamarin Inc. All rights reserved.
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Xml;
using MonoMac.AppKit;
// Test
// * application use some attributes that the linker will remove (unneeded at runtime)
// * Application is build in debug mode so the [System.Diagnostics.Debug*] attributes are kept
//
// Requirement
// * Link SDK or Link All must be enabled
// * Debug mode
// removed in release builds only
[assembly: Debuggable (DebuggableAttribute.DebuggingModes.Default)]
[assembly: MonoMac.Foundation.LinkerSafe]
// not removed
[assembly: AssemblyCompany ("Xamarin Inc.")]
namespace Xamarin.Mac.Linker.Test {
// [System.MonoDocumentationNote]
// [System.MonoExtension]
// [System.MonoLimitation]
// [System.MonoNotSupported]
// [System.MonoTODO]
[System.Obsolete]
// [System.Xml.MonoFIX]
[MonoMac.ObjCRuntime.Availability]
[MonoMac.ObjCRuntime.Lion]
[MonoMac.ObjCRuntime.MountainLion]
[MonoMac.ObjCRuntime.Mavericks]
[MonoMac.ObjCRuntime.Since (5,0)]
[MonoMac.ObjCRuntime.ThreadSafe]
[DebuggerDisplay ("")]
[DebuggerNonUserCode]
[DebuggerTypeProxy ("")]
[DebuggerVisualizer ("")]
// not removed
[Guid ("20f66ee8-2ddc-4fc3-b690-82e1e43a93c7")]
class DebugLinkRemoveAttributes {
// will be removed - but the instance field will be kept
[MonoMac.Foundation.Preserve]
// removed in release builds only
[DebuggerBrowsable (DebuggerBrowsableState.Never)]
XmlDocument document;
[MonoMac.Foundation.Advice ("")]
// removed in release builds only
[DebuggerHidden]
[DebuggerStepperBoundary]
[DebuggerStepThrough]
// not removed
[LoaderOptimization (LoaderOptimization.SingleDomain)]
static void CheckPresence (ICustomAttributeProvider provider, string typeName, bool expected)
{
// the linker should have removed the *attributes* - maybe not the type
bool success = !expected;
foreach (var ca in provider.GetCustomAttributes (false)) {
if (ca.GetType ().FullName.StartsWith (typeName, StringComparison.Ordinal))
success = expected;
}
Test.Log.WriteLine ("{0}\t{1} {2}", success ? "[PASS]" : "[FAIL]", typeName, expected ? "present" : "absent");
}
#if DEBUG
const bool debug = true;
#else
const bool debug = false;
#endif
static void Main (string[] args)
{
NSApplication.Init ();
Test.EnsureLinker (true);
try {
var type = typeof (DebugLinkRemoveAttributes);
CheckPresence (type, "System.ObsoleteAttribute", false);
CheckPresence (type, "MonoMac.Foundation.AdviceAttribute", false);
CheckPresence (type, "MonoMac.ObjCRuntime.AvailabilityAttribute", false);
CheckPresence (type, "MonoMac.ObjCRuntime.LionAttribute", false);
CheckPresence (type, "MonoMac.ObjCRuntime.MountainLionAttribute", false);
CheckPresence (type, "MonoMac.ObjCRuntime.MavericksAttribute", false);
CheckPresence (type, "MonoMac.ObjCRuntime.SinceAttribute", false);
CheckPresence (type, "MonoMac.ObjCRuntime.ThreadSafeAttribute", false);
CheckPresence (type, "System.Diagnostics.DebuggerDisplay", debug);
CheckPresence (type, "System.Diagnostics.DebuggerNonUserCode", debug);
CheckPresence (type, "System.Diagnostics.DebuggerTypeProxy", debug);
CheckPresence (type, "System.Diagnostics.DebuggerVisualizer", debug);
CheckPresence (type, "System.Runtime.InteropServices.GuidAttribute", true);
var assembly = type.Assembly;
CheckPresence (assembly, "MonoMac.Foundation.LinkerSafeAttribute", false);
CheckPresence (assembly, "System.Diagnostics.DebuggableAttribute", debug);
CheckPresence (assembly, "System.Reflection.AssemblyCompanyAttribute", true);
var method = type.GetMethod ("CheckPresence", BindingFlags.Static | BindingFlags.NonPublic);
CheckPresence (method, "MonoMac.Foundation.AdviceAttribute", false);
CheckPresence (method, "System.Diagnostics.DebuggerHiddenAttribute", debug);
CheckPresence (method, "System.Diagnostics.DebuggerStepperBoundaryAttribute", debug);
CheckPresence (method, "System.Diagnostics.DebuggerStepThroughAttribute", debug);
CheckPresence (method, "System.LoaderOptimizationAttribute", true);
var field = type.GetField ("document", BindingFlags.Instance| BindingFlags.NonPublic);
CheckPresence (field, "MonoMac.Foundation.PreserveAttribute", false);
CheckPresence (field, "System.Diagnostics.DebuggerBrowsableAttribute", debug);
}
finally {
Test.Terminate ();
}
}
}
} | 35.808 | 113 | 0.747096 | [
"BSD-3-Clause"
] | 1975781737/xamarin-macios | tests/mmptest/regression/link-remove-attributes-1/LinkRemoveAttributes.cs | 4,476 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Device.I2c;
using System.Threading;
namespace Iot.Device.Mlx90614.Sample
{
internal class Program
{
public static void Main(string[] args)
{
I2cConnectionSettings settings = new I2cConnectionSettings(1, Mlx90614.DefaultI2cAddress);
I2cDevice i2cDevice = I2cDevice.Create(settings);
using (Mlx90614 sensor = new Mlx90614(i2cDevice))
{
while (true)
{
Console.WriteLine($"Ambient: {sensor.ReadAmbientTemperature().DegreesCelsius} ℃");
Console.WriteLine($"Object: {sensor.ReadObjectTemperature().DegreesCelsius} ℃");
Console.WriteLine();
Thread.Sleep(1000);
}
}
}
}
}
| 31.96875 | 102 | 0.602151 | [
"MIT"
] | Raregine/iot | src/devices/Mlx90614/samples/Program.cs | 1,029 | 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 Microsoft.TestCommon;
using Moq;
namespace System.Web.Mvc.Test
{
public class JavaScriptResultTest
{
[Fact]
public void AllPropertiesDefaultToNull()
{
// Act
JavaScriptResult result = new JavaScriptResult();
// Assert
Assert.Null(result.Script);
}
[Fact]
public void ExecuteResult()
{
// Arrange
string script = "alert('foo');";
string contentType = "application/x-javascript";
// Arrange expectations
Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>(MockBehavior.Strict);
mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentType = contentType).Verifiable();
mockControllerContext.Setup(c => c.HttpContext.Response.Write(script)).Verifiable();
JavaScriptResult result = new JavaScriptResult
{
Script = script
};
// Act
result.ExecuteResult(mockControllerContext.Object);
// Assert
mockControllerContext.Verify();
}
[Fact]
public void ExecuteResultWithNullContextThrows()
{
Assert.ThrowsArgumentNull(
delegate { new JavaScriptResult().ExecuteResult(null /* context */); }, "context");
}
[Fact]
public void NullScriptIsNotOutput()
{
// Arrange
string contentType = "application/x-javascript";
// Arrange expectations
Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentType = contentType).Verifiable();
JavaScriptResult result = new JavaScriptResult();
// Act
result.ExecuteResult(mockControllerContext.Object);
// Assert
mockControllerContext.Verify();
}
}
}
| 30.555556 | 111 | 0.595455 | [
"Apache-2.0"
] | 1508553303/AspNetWebStack | test/System.Web.Mvc.Test/Test/JavaScriptResultTest.cs | 2,202 | C# |
using System;
using Xamarin.Forms;
namespace ImageGesture
{
public class SamplePage : ContentPage
{
public SamplePage ()
{
var i = new TappedImage () {
Source = "drawable/Sample.png",
};
i.TapLocationEvent += (sender, e) => {
this.DisplayAlert ("Click", "It was at: " + e.TapLocation.X + ", " + e.TapLocation.Y, "Thanks");
};
Content = new StackLayout () {
Children = {
new Label(){
Text = "Hello world"
},
i
}
};
}
}
} | 17.392857 | 100 | 0.562628 | [
"MIT"
] | chrispellett/Xamarin-Forms-TappedImage | ImageGesture/SamplePage.cs | 489 | C# |
using System;
using System.Web;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Owin;
using MemoEngine.Models;
namespace MemoEngine.Account
{
public partial class RegisterExternalLogin : System.Web.UI.Page
{
protected string ProviderName
{
get { return (string)ViewState["ProviderName"] ?? String.Empty; }
private set { ViewState["ProviderName"] = value; }
}
protected string ProviderAccountKey
{
get { return (string)ViewState["ProviderAccountKey"] ?? String.Empty; }
private set { ViewState["ProviderAccountKey"] = value; }
}
private void RedirectOnFail()
{
Response.Redirect((User.Identity.IsAuthenticated) ? "~/Account/Manage" : "~/Account/Login");
}
protected void Page_Load()
{
// 요청의 인증 공급자 결과 처리
ProviderName = IdentityHelper.GetProviderNameFromRequest(Request);
if (String.IsNullOrEmpty(ProviderName))
{
RedirectOnFail();
return;
}
if (!IsPostBack)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>();
var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
if (loginInfo == null)
{
RedirectOnFail();
return;
}
var user = manager.Find(loginInfo.Login);
if (user != null)
{
signInManager.SignIn(user, isPersistent: false, rememberBrowser: false);
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
}
else if (User.Identity.IsAuthenticated)
{
// 연결할 때 Xsrf 검사 적용
var verifiedloginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId());
if (verifiedloginInfo == null)
{
RedirectOnFail();
return;
}
var result = manager.AddLogin(User.Identity.GetUserId(), verifiedloginInfo.Login);
if (result.Succeeded)
{
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
}
else
{
AddErrors(result);
return;
}
}
else
{
email.Text = loginInfo.Email;
}
}
}
protected void LogIn_Click(object sender, EventArgs e)
{
CreateAndLoginUser();
}
private void CreateAndLoginUser()
{
if (!IsValid)
{
return;
}
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var signInManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();
var user = new ApplicationUser() { UserName = email.Text, Email = email.Text };
IdentityResult result = manager.Create(user);
if (result.Succeeded)
{
var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
if (loginInfo == null)
{
RedirectOnFail();
return;
}
result = manager.AddLogin(user.Id, loginInfo.Login);
if (result.Succeeded)
{
signInManager.SignIn(user, isPersistent: false, rememberBrowser: false);
// 계정 확인 및 암호 재설정을 사용하도록 설정하는 방법에 대한 자세한 내용은 https://go.microsoft.com/fwlink/?LinkID=320771을 참조하세요.
// var code = manager.GenerateEmailConfirmationToken(user.Id);
// 전자 메일을 통해 이 링크 보내기: IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id)
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
return;
}
}
AddErrors(result);
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
}
} | 36.992308 | 156 | 0.515492 | [
"MIT"
] | VisualAcademy/Answers | MemoEngine/Account/RegisterExternalLogin.aspx.cs | 4,951 | C# |
namespace Luis_Dialog_Sample
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Bot.Builder.Community.Dialogs.Luis;
using Bot.Builder.Community.Dialogs.Luis.Models;
using Luis_Dialog_Sample.Models;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Extensions.Configuration;
/// <summary>
/// This sample was ported from V3
/// </summary>
/// <remarks>
/// LuisModelAttribute can be added to the class, and LuisDialog will
/// construct the LuisService dynamically. Or, the developer can pass
/// a LuisService to the base class constructor directly.
/// </remarks>
/// [LuisModel("7d8ea658-f01a-49f2-a239-2d7ef805dde9", "1cf447f840ee414e87c7b93bb6d5cc63", domain: "westus.api.cognitive.microsoft.com")]
public class SimpleNoteDialog : LuisDialog<object>
{
// Default note title
private const string DefaultNoteTitle = "default";
// Name of note title entity
private const string EntityNoteTitle = "Note.Title";
// Store notes in a dictionary that uses the title as a key
private static readonly Dictionary<string, Note> NoteByTitle = new Dictionary<string, Note>();
// The current note being created by the user.
private IStatePropertyAccessor<Note> currentNote;
public SimpleNoteDialog(ConversationState conversationState, IConfiguration configuration)
: base(nameof(SimpleNoteDialog), new[] { GetLuisService(configuration) })
{
this.AddDialog(new PromptWaterfallDialog());
this.currentNote = conversationState.CreateProperty<Note>("CurrentNote");
}
/// <summary>
/// Create a LuisService using configuration settings.
/// </summary>
/// <param name="configuration">IConfiguration used to retrieve app settings for
/// creating the LuisModelAttribute.</param>
/// <returns>A LuisService constructed from configuration settings.</returns>
static ILuisService GetLuisService(IConfiguration configuration)
{
if (configuration == null)
{
throw new ArgumentNullException(nameof(configuration));
}
var luisModel = new LuisModelAttribute(configuration["LuisModelId"], configuration["LuisSubscriptionKey"], domain: configuration["LuisHostDomain"]);
return new LuisService(luisModel);
}
/// <summary>
/// OnContinueDialogAsync is executed on every turn of a dialog after the first turn,
/// and when a child dialog finishes executing.
/// </summary>
/// <param name="innerDc">Current DialogContext</param>
/// <param name="cancellationToken">Thread CancellationToken</param>
/// <returns>A DialogTurnResult</returns>
protected override async Task<DialogTurnResult> OnContinueDialogAsync(DialogContext innerDc, CancellationToken cancellationToken = default(CancellationToken))
{
var childResult = await innerDc.ContinueDialogAsync(cancellationToken);
var result = childResult.Result as DialogTurnResult;
if (result != null)
{
var promptResult = result.Result as PromptDialogOptions;
if (promptResult != null)
{
switch (promptResult.ReturnMethod)
{
case PromptReturnMethods.After_DeleteTitlePrompt:
return await this.After_DeleteTitlePrompt(innerDc, promptResult.Result);
case PromptReturnMethods.After_TextPrompt:
return await this.After_TextPrompt(innerDc, promptResult.Result);
case PromptReturnMethods.After_TitlePrompt:
return await this.After_TitlePrompt(innerDc, promptResult.Result);
default:
throw new InvalidOperationException("Invalid PromptReturnMethods");
}
}
else
{
return await base.OnContinueDialogAsync(innerDc, cancellationToken);
}
}
else
{
return await base.OnContinueDialogAsync(innerDc, cancellationToken);
}
}
/// <summary>
/// This method overload inspects the result from LUIS to see if a title entity was detected, and finds the note with that title, or the note with the default title, if no title entity was found.
/// </summary>
/// <param name="result">The result from LUIS that contains intents and entities that LUIS recognized.</param>
/// <param name="note">This parameter returns any note that is found in the list of notes that has a matching title.</param>
/// <returns>true if a note was found, otherwise false</returns>
private bool TryFindNote(LuisResult result, out Note note)
{
note = null;
string titleToFind;
EntityRecommendation title;
if (result.TryFindEntity(EntityNoteTitle, out title))
{
titleToFind = title.Entity;
}
else
{
titleToFind = DefaultNoteTitle;
}
return NoteByTitle.TryGetValue(titleToFind, out note); // TryGetValue returns false if no match is found.
}
/// <summary>
/// This method overload takes a string and finds the note with that title.
/// </summary>
/// <param name="noteTitle">A string containing the title of the note to search for.</param>
/// <param name="note">This parameter returns any note that is found in the list of notes that has a matching title.</param>
/// <returns>true if a note was found, otherwise false</returns>
private bool TryFindNote(string noteTitle, out Note note)
{
bool foundNote = NoteByTitle.TryGetValue(noteTitle, out note); // TryGetValue returns false if no match is found.
return foundNote;
}
/// <summary>
/// Send a generic help message if an intent without an intent handler is detected.
/// </summary>
/// <param name="context">Dialog context.</param>
/// <param name="result">The result from LUIS.</param>
/// <returns>A DialogTurnResult</returns>
[LuisIntent("")]
private async Task<DialogTurnResult> None(DialogContext context, LuisResult result)
{
string message = $"I'm the Notes bot. I can understand requests to create, delete, and read notes. \n\n Detected intent: " + string.Join(", ", result.Intents.Select(i => i.Intent));
await context.PostAsync(message);
return new DialogTurnResult(DialogTurnStatus.Complete);
}
/// <summary>
/// Handle the Note.Delete intent. If a title isn't detected in the LUIS result, prompt the user for a title.
/// </summary>
/// <param name="context">Dialog context.</param>
/// <param name="result">The result from LUIS.</param>
/// <returns>A DialogTurnResult</returns>
[LuisIntent("Note.Delete")]
private async Task<DialogTurnResult> DeleteNote(DialogContext context, LuisResult result)
{
Note note;
if (this.TryFindNote(result, out note))
{
NoteByTitle.Remove(note.Title);
await context.PostAsync($"Note {note.Title} deleted");
return new DialogTurnResult(DialogTurnStatus.Complete);
}
else
{
// Prompt the user for a note title
var options = new PromptDialogOptions()
{
Prompt = "What is the title of the note you want to delete?",
ReturnMethod = PromptReturnMethods.After_DeleteTitlePrompt
};
return await context.BeginDialogAsync(nameof(PromptWaterfallDialog), options);
}
}
/// <summary>
/// Handles the Note.ReadAloud intent by displaying a note or notes.
/// If a title of an existing note is found in the LuisResult, that note is displayed.
/// If no title is detected in the LuisResult, all of the notes are displayed.
/// </summary>
/// <param name="context">Dialog context.</param>
/// <param name="result">LUIS result.</param>
/// <returns>A DialogTurnResult</returns>
[LuisIntent("Note.ReadAloud")]
private async Task<DialogTurnResult> FindNote(DialogContext context, LuisResult result)
{
Note note;
if (this.TryFindNote(result, out note))
{
await context.PostAsync($"**{note.Title}**: {note.Text}.");
}
else
{
// Print out all the notes if no specific note name was detected
string noteList = "Here's the list of all notes: \n\n";
foreach (KeyValuePair<string, Note> entry in NoteByTitle)
{
Note noteInList = entry.Value;
noteList += $"**{noteInList.Title}**: {noteInList.Text}.\n\n";
}
await context.PostAsync(noteList);
}
return new DialogTurnResult(DialogTurnStatus.Complete);
}
/// <summary>
/// Handles the Note.Create intent. Prompts the user for the note title if the title isn't detected in the LuisResult.
/// </summary>
/// <param name="context">Dialog context.</param>
/// <param name="result">LUIS result.</param>
/// <returns>A DialogTurnResult</returns>
[LuisIntent("Note.Create")]
private async Task<DialogTurnResult> CreateNote(DialogContext context, LuisResult result)
{
EntityRecommendation title;
if (!result.TryFindEntity(EntityNoteTitle, out title))
{
// Prompt the user for a note title
var options = new PromptDialogOptions()
{
Prompt = "What is the title of the note you want to create?",
ReturnMethod = PromptReturnMethods.After_TitlePrompt
};
return await context.BeginDialogAsync(nameof(PromptWaterfallDialog), options);
}
else
{
var note = await this.currentNote.GetAsync(context.Context, () => new Note());
note.Title = title.Entity;
NoteByTitle[note.Title] = note;
// Prompt the user for what they want to say in the note
var options = new PromptDialogOptions()
{
Prompt = "What do you want to say in your note?",
ReturnMethod = PromptReturnMethods.After_TextPrompt
};
return await context.BeginDialogAsync(nameof(PromptWaterfallDialog), options);
}
}
/// <summary>
/// Executed after asking the user for the Title of the Note they wish to create.
/// </summary>
/// <param name="context">Current dialog context</param>
/// <param name="noteTitle">Title of the note to create.</param>
/// <returns>A DialogTurnResult</returns>
private async Task<DialogTurnResult> After_TitlePrompt(DialogContext context, string noteTitle)
{
// Set the title (used for creation, deletion, and reading)
if (string.IsNullOrEmpty(noteTitle))
{
noteTitle = DefaultNoteTitle;
}
// Add the new note to the list of notes and also save it in order to add text to it later
var note = await this.currentNote.GetAsync(context.Context, () => new Note());
note.Title = noteTitle;
NoteByTitle[note.Title] = note;
// Prompt the user for what they want to say in the note
var options = new PromptDialogOptions()
{
Prompt = "What do you want to say in your note?",
ReturnMethod = PromptReturnMethods.After_TextPrompt
};
return await context.BeginDialogAsync(nameof(PromptWaterfallDialog), options);
}
/// <summary>
/// Executed after asking the user for the Text of the Note they wish to create.
/// </summary>
/// <param name="context">Current dialog context</param>
/// <param name="noteText">The Text of the note the user wants to create.</param>
/// <returns>A DiaogTurnResult</returns>
private async Task<DialogTurnResult> After_TextPrompt(DialogContext context, string noteText)
{
// Set the text of the note
var note = await this.currentNote.GetAsync(context.Context, () => new Note());
note.Text = noteText;
NoteByTitle[note.Title] = note;
await context.PostAsync($"Created note **{note.Title}** that says \"{note.Text}\".");
await this.currentNote.DeleteAsync(context.Context);
return new DialogTurnResult(DialogTurnStatus.Complete);
}
/// <summary>
/// Executed after asking the user for the Title of the Note they wish to delete.
/// </summary>
/// <param name="context">Current dialog context</param>
/// <param name="titleToDelete">The title of the note the user wants to delete</param>
/// <returns>A DialogTurnResult</returns>
private async Task<DialogTurnResult> After_DeleteTitlePrompt(DialogContext context, string titleToDelete)
{
Note note;
bool foundNote = NoteByTitle.TryGetValue(titleToDelete, out note);
if (foundNote)
{
NoteByTitle.Remove(note.Title);
await context.PostAsync($"Note {note.Title} deleted");
}
else
{
await context.PostAsync($"Did not find note named {titleToDelete}.");
}
return new DialogTurnResult(DialogTurnStatus.Complete);
}
}
}
| 44.604938 | 203 | 0.595212 | [
"MIT"
] | Amit-singh96/Test1 | samples/Luis Dialog Sample/Dialogs/SimpleNoteDialog.cs | 14,454 | C# |
using Xunit;
namespace BDSA2020.Assignment03.Tests
{
public class WizardTests
{
[Fact]
public void Wizards_contains_12_wizards()
{
var wizards = Wizard.Wizards.Value;
Assert.Equal(12, wizards.Count);
}
[Theory]
[InlineData("Darth Vader", "Star Wars", 1977, "George Lucas")]
[InlineData("Sauron", "The Fellowship of the Ring", 1954, "J.R.R. Tolkien")]
[InlineData("Harry Potter", "Harry Potter and the Philosopher's Stone", 1997, "J.K. Rowling")]
[InlineData("Gandalf", "The Fellowship of the Ring", 1954, "J.R.R. Tolkien")]
[InlineData("Merlin", "The Lost Years of Merlin", 1996, "T.A. Barron")]
[InlineData("Yoda", "Star Wars", 1977, "George Lucas")]
[InlineData("Albus Dumbledore", "Harry Potter and the Philosopher's Stone", 1997, "J.K. Rowling")]
[InlineData("Severus Snape", "Harry Potter and the Philosopher's Stone", 1997, "J.K. Rowling")]
[InlineData("Sirius Black", "Harry Potter and the Prisoner of Azkaban", 1999, "J.K. Rowling")]
[InlineData("Raistlin Majere", "The Test of the twins", 1984, "Margaret Weis")]
[InlineData("Voldemort", "Harry Potter and the Philosopher's Stone", 1997, "J.K. Rowling")]
[InlineData("Remus Lupin", "Harry Potter and the Prisoner of Azkaban", 1999, "J.K. Rowling")]
public void Spot_check_wizards(string name, string medium, int year, string creator)
{
var wizards = Wizard.Wizards.Value;
Assert.Contains(wizards, w =>
w.Name == name &&
w.Medium == medium &&
w.Year == year &&
w.Creator == creator
);
}
}
}
| 41.666667 | 106 | 0.589714 | [
"MIT"
] | REXKrash/BDSA2021-Assignment3 | Assignment3.Tests/WizardTests.cs | 1,750 | C# |
using System;
#pragma warning disable 1591
// ReSharper disable UnusedMember.Global
// ReSharper disable UnusedParameter.Local
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable IntroduceOptionalParameters.Global
// ReSharper disable MemberCanBeProtected.Global
// ReSharper disable InconsistentNaming
namespace JetBrains.Annotations
{
/// <summary>
/// Indicates that the value of the marked element could be <c>null</c> sometimes,
/// so the check for <c>null</c> is necessary before its usage
/// </summary>
/// <example>
/// <code>
/// [CanBeNull] public object Test() { return null; }
/// public void UseTest() {
/// var p = Test();
/// var s = p.ToString(); // Warning: Possible 'System.NullReferenceException'
/// }
/// </code>
/// </example>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter |
AttributeTargets.Property | AttributeTargets.Delegate |
AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public sealed class CanBeNullAttribute : Attribute
{
}
/// <summary>
/// Indicates that the value of the marked element could never be <c>null</c>
/// </summary>
/// <example>
/// <code>
/// [NotNull] public object Foo() {
/// return null; // Warning: Possible 'null' assignment
/// }
/// </code>
/// </example>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter |
AttributeTargets.Property | AttributeTargets.Delegate |
AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public sealed class NotNullAttribute : Attribute
{
}
/// <summary>
/// Indicates that the marked method builds string by format pattern and (optional) arguments.
/// Parameter, which contains format string, should be given in constructor. The format string
/// should be in <see cref="string.Format(IFormatProvider,string,object[])" />-like form
/// </summary>
/// <example>
/// <code>
/// [StringFormatMethod("message")]
/// public void ShowError(string message, params object[] args) { /* do something */ }
/// public void Foo() {
/// ShowError("Failed: {0}"); // Warning: Non-existing argument in format string
/// }
/// </code>
/// </example>
[AttributeUsage(
AttributeTargets.Constructor | AttributeTargets.Method,
AllowMultiple = false, Inherited = true)]
public sealed class StringFormatMethodAttribute : Attribute
{
/// <param name="formatParameterName">
/// Specifies which parameter of an annotated method should be treated as format-string
/// </param>
public StringFormatMethodAttribute(string formatParameterName)
{
FormatParameterName = formatParameterName;
}
public string FormatParameterName { get; private set; }
}
/// <summary>
/// Indicates that the function argument should be string literal and match one
/// of the parameters of the caller function. For example, ReSharper annotates
/// the parameter of <see cref="System.ArgumentNullException" />
/// </summary>
/// <example>
/// <code>
/// public void Foo(string param) {
/// if (param == null)
/// throw new ArgumentNullException("par"); // Warning: Cannot resolve symbol
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
public sealed class InvokerParameterNameAttribute : Attribute
{
}
/// <summary>
/// Indicates that the method is contained in a type that implements
/// <see cref="System.ComponentModel.INotifyPropertyChanged" /> interface
/// and this method is used to notify that some property value changed
/// </summary>
/// <remarks>
/// The method should be non-static and conform to one of the supported signatures:
/// <list>
/// <item>
/// <c>NotifyChanged(string)</c>
/// </item>
/// <item>
/// <c>NotifyChanged(params string[])</c>
/// </item>
/// <item>
/// <c>NotifyChanged{T}(Expression{Func{T}})</c>
/// </item>
/// <item>
/// <c>NotifyChanged{T,U}(Expression{Func{T,U}})</c>
/// </item>
/// <item>
/// <c>SetProperty{T}(ref T, T, string)</c>
/// </item>
/// </list>
/// </remarks>
/// <example>
/// <code>
/// public class Foo : INotifyPropertyChanged {
/// public event PropertyChangedEventHandler PropertyChanged;
/// [NotifyPropertyChangedInvocator]
/// protected virtual void NotifyChanged(string propertyName) { ... }
///
/// private string _name;
/// public string Name {
/// get { return _name; }
/// set { _name = value; NotifyChanged("LastName"); /* Warning */ }
/// }
/// }
/// </code>
/// Examples of generated notifications:
/// <list>
/// <item>
/// <c>NotifyChanged("Property")</c>
/// </item>
/// <item>
/// <c>NotifyChanged(() => Property)</c>
/// </item>
/// <item>
/// <c>NotifyChanged((VM x) => x.Property)</c>
/// </item>
/// <item>
/// <c>SetProperty(ref myField, value, "Property")</c>
/// </item>
/// </list>
/// </example>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class NotifyPropertyChangedInvocatorAttribute : Attribute
{
public NotifyPropertyChangedInvocatorAttribute()
{
}
public NotifyPropertyChangedInvocatorAttribute(string parameterName)
{
ParameterName = parameterName;
}
public string ParameterName { get; private set; }
}
/// <summary>
/// Describes dependency between method input and output
/// </summary>
/// <syntax>
/// <p>Function Definition Table syntax:</p>
/// <list>
/// <item>FDT ::= FDTRow [;FDTRow]*</item>
/// <item>FDTRow ::= Input => Output | Output <= Input</item>
/// <item>Input ::= ParameterName: Value [, Input]*</item>
/// <item>Output ::= [ParameterName: Value]* {halt|stop|void|nothing|Value}</item>
/// <item>Value ::= true | false | null | notnull | canbenull</item>
/// </list>
/// If method has single input parameter, it's name could be omitted.<br />
/// Using <c>halt</c> (or <c>void</c>/<c>nothing</c>, which is the same)
/// for method output means that the methos doesn't return normally.<br />
/// <c>canbenull</c> annotation is only applicable for output parameters.<br />
/// You can use multiple <c>[ContractAnnotation]</c> for each FDT row,
/// or use single attribute with rows separated by semicolon.<br />
/// </syntax>
/// <examples>
/// <list>
/// <item>
/// <code>
/// [ContractAnnotation("=> halt")]
/// public void TerminationMethod()
/// </code>
/// </item>
/// <item>
/// <code>
/// [ContractAnnotation("halt <= condition: false")]
/// public void Assert(bool condition, string text) // regular assertion method
/// </code>
/// </item>
/// <item>
/// <code>
/// [ContractAnnotation("s:null => true")]
/// public bool IsNullOrEmpty(string s) // string.IsNullOrEmpty()
/// </code>
/// </item>
/// <item>
/// <code>
/// // A method that returns null if the parameter is null, and not null if the parameter is not null
/// [ContractAnnotation("null => null; notnull => notnull")]
/// public object Transform(object data)
/// </code>
/// </item>
/// <item>
/// <code>
/// [ContractAnnotation("s:null=>false; =>true,result:notnull; =>false, result:null")]
/// public bool TryParse(string s, out Person result)
/// </code>
/// </item>
/// </list>
/// </examples>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public sealed class ContractAnnotationAttribute : Attribute
{
public ContractAnnotationAttribute([NotNull] string contract)
: this(contract, false)
{
}
public ContractAnnotationAttribute([NotNull] string contract, bool forceFullStates)
{
Contract = contract;
ForceFullStates = forceFullStates;
}
public string Contract { get; private set; }
public bool ForceFullStates { get; private set; }
}
/// <summary>
/// Indicates that marked element should be localized or not
/// </summary>
/// <example>
/// <code>
/// [LocalizationRequiredAttribute(true)]
/// public class Foo {
/// private string str = "my string"; // Warning: Localizable string
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
public sealed class LocalizationRequiredAttribute : Attribute
{
public LocalizationRequiredAttribute() : this(true)
{
}
public LocalizationRequiredAttribute(bool required)
{
Required = required;
}
public bool Required { get; private set; }
}
/// <summary>
/// Indicates that the value of the marked type (or its derivatives)
/// cannot be compared using '==' or '!=' operators and <c>Equals()</c>
/// should be used instead. However, using '==' or '!=' for comparison
/// with <c>null</c> is always permitted.
/// </summary>
/// <example>
/// <code>
/// [CannotApplyEqualityOperator]
/// class NoEquality { }
/// class UsesNoEquality {
/// public void Test() {
/// var ca1 = new NoEquality();
/// var ca2 = new NoEquality();
/// if (ca1 != null) { // OK
/// bool condition = ca1 == ca2; // Warning
/// }
/// }
/// }
/// </code>
/// </example>
[AttributeUsage(
AttributeTargets.Interface | AttributeTargets.Class |
AttributeTargets.Struct, AllowMultiple = false, Inherited = true)]
public sealed class CannotApplyEqualityOperatorAttribute : Attribute
{
}
/// <summary>
/// When applied to a target attribute, specifies a requirement for any type marked
/// with the target attribute to implement or inherit specific type or types.
/// </summary>
/// <example>
/// <code>
/// [BaseTypeRequired(typeof(IComponent)] // Specify requirement
/// public class ComponentAttribute : Attribute { }
/// [Component] // ComponentAttribute requires implementing IComponent interface
/// public class MyComponent : IComponent { }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
[BaseTypeRequired(typeof(Attribute))]
public sealed class BaseTypeRequiredAttribute : Attribute
{
public BaseTypeRequiredAttribute([NotNull] Type baseType)
{
BaseType = baseType;
}
[NotNull]
public Type BaseType { get; private set; }
}
/// <summary>
/// Indicates that the marked symbol is used implicitly
/// (e.g. via reflection, in external library), so this symbol
/// will not be marked as unused (as well as by other usage inspections)
/// </summary>
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
public sealed class UsedImplicitlyAttribute : Attribute
{
public UsedImplicitlyAttribute()
: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default)
{
}
public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags)
: this(useKindFlags, ImplicitUseTargetFlags.Default)
{
}
public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags)
: this(ImplicitUseKindFlags.Default, targetFlags)
{
}
public UsedImplicitlyAttribute(
ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
{
UseKindFlags = useKindFlags;
TargetFlags = targetFlags;
}
public ImplicitUseKindFlags UseKindFlags { get; private set; }
public ImplicitUseTargetFlags TargetFlags { get; private set; }
}
/// <summary>
/// Should be used on attributes and causes ReSharper
/// to not mark symbols marked with such attributes as unused
/// (as well as by other usage inspections)
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public sealed class MeansImplicitUseAttribute : Attribute
{
public MeansImplicitUseAttribute()
: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default)
{
}
public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags)
: this(useKindFlags, ImplicitUseTargetFlags.Default)
{
}
public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags)
: this(ImplicitUseKindFlags.Default, targetFlags)
{
}
public MeansImplicitUseAttribute(
ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
{
UseKindFlags = useKindFlags;
TargetFlags = targetFlags;
}
[UsedImplicitly]
public ImplicitUseKindFlags UseKindFlags { get; private set; }
[UsedImplicitly]
public ImplicitUseTargetFlags TargetFlags { get; private set; }
}
[Flags]
public enum ImplicitUseKindFlags
{
Default = Access | Assign | InstantiatedWithFixedConstructorSignature,
/// <summary>Only entity marked with attribute considered used</summary>
Access = 1,
/// <summary>Indicates implicit assignment to a member</summary>
Assign = 2,
/// <summary>
/// Indicates implicit instantiation of a type with fixed constructor signature.
/// That means any unused constructor parameters won't be reported as such.
/// </summary>
InstantiatedWithFixedConstructorSignature = 4,
/// <summary>Indicates implicit instantiation of a type</summary>
InstantiatedNoFixedConstructorSignature = 8,
}
/// <summary>
/// Specify what is considered used implicitly
/// when marked with <see cref="MeansImplicitUseAttribute" />
/// or <see cref="UsedImplicitlyAttribute" />
/// </summary>
[Flags]
public enum ImplicitUseTargetFlags
{
Default = Itself,
Itself = 1,
/// <summary>Members of entity marked with attribute are considered used</summary>
Members = 2,
/// <summary>Entity marked with attribute and all its members considered used</summary>
WithMembers = Itself | Members
}
/// <summary>
/// This attribute is intended to mark publicly available API
/// which should not be removed and so is treated as used
/// </summary>
[MeansImplicitUse]
public sealed class PublicAPIAttribute : Attribute
{
public PublicAPIAttribute()
{
}
public PublicAPIAttribute([NotNull] string comment)
{
Comment = comment;
}
[NotNull]
public string Comment { get; private set; }
}
/// <summary>
/// Tells code analysis engine if the parameter is completely handled
/// when the invoked method is on stack. If the parameter is a delegate,
/// indicates that delegate is executed while the method is executed.
/// If the parameter is an enumerable, indicates that it is enumerated
/// while the method is executed
/// </summary>
[AttributeUsage(AttributeTargets.Parameter, Inherited = true)]
public sealed class InstantHandleAttribute : Attribute
{
}
/// <summary>
/// Indicates that a method does not make any observable state changes.
/// The same as <c>System.Diagnostics.Contracts.PureAttribute</c>
/// </summary>
/// <example>
/// <code>
/// [Pure] private int Multiply(int x, int y) { return x * y; }
/// public void Foo() {
/// const int a = 2, b = 2;
/// Multiply(a, b); // Waring: Return value of pure method is not used
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Method, Inherited = true)]
public sealed class PureAttribute : Attribute
{
}
/// <summary>
/// Indicates that a parameter is a path to a file or a folder
/// within a web project. Path can be relative or absolute,
/// starting from web root (~)
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public class PathReferenceAttribute : Attribute
{
public PathReferenceAttribute()
{
}
public PathReferenceAttribute([PathReference] string basePath)
{
BasePath = basePath;
}
[NotNull]
public string BasePath { get; private set; }
}
// ASP.NET MVC attributes
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcAreaMasterLocationFormatAttribute : Attribute
{
public AspMvcAreaMasterLocationFormatAttribute(string format)
{
}
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcAreaPartialViewLocationFormatAttribute : Attribute
{
public AspMvcAreaPartialViewLocationFormatAttribute(string format)
{
}
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcAreaViewLocationFormatAttribute : Attribute
{
public AspMvcAreaViewLocationFormatAttribute(string format)
{
}
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcMasterLocationFormatAttribute : Attribute
{
public AspMvcMasterLocationFormatAttribute(string format)
{
}
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcPartialViewLocationFormatAttribute : Attribute
{
public AspMvcPartialViewLocationFormatAttribute(string format)
{
}
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcViewLocationFormatAttribute : Attribute
{
public AspMvcViewLocationFormatAttribute(string format)
{
}
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC action. If applied to a method, the MVC action name is calculated
/// implicitly from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcActionAttribute : Attribute
{
public AspMvcActionAttribute()
{
}
public AspMvcActionAttribute([NotNull] string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
[NotNull]
public string AnonymousProperty { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC area.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcAreaAttribute : PathReferenceAttribute
{
public AspMvcAreaAttribute()
{
}
public AspMvcAreaAttribute([NotNull] string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
[NotNull]
public string AnonymousProperty { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that
/// the parameter is an MVC controller. If applied to a method,
/// the MVC controller name is calculated implicitly from the context.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcControllerAttribute : Attribute
{
public AspMvcControllerAttribute()
{
}
public AspMvcControllerAttribute([NotNull] string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
[NotNull]
public string AnonymousProperty { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC Master.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Controller.View(String, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcMasterAttribute : Attribute
{
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC model type.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Controller.View(String, Object)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcModelTypeAttribute : Attribute
{
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that
/// the parameter is an MVC partial view. If applied to a method,
/// the MVC partial view name is calculated implicitly from the context.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcPartialViewAttribute : PathReferenceAttribute
{
}
/// <summary>
/// ASP.NET MVC attribute. Allows disabling all inspections
/// for MVC views within a class or a method.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class AspMvcSupressViewErrorAttribute : Attribute
{
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC display template.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.DisplayExtensions.DisplayForModel(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcDisplayTemplateAttribute : Attribute
{
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC editor template.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.EditorExtensions.EditorForModel(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcEditorTemplateAttribute : Attribute
{
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC template.
/// Use this attribute for custom wrappers similar to
/// <c>System.ComponentModel.DataAnnotations.UIHintAttribute(System.String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcTemplateAttribute : Attribute
{
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC view. If applied to a method, the MVC view name is calculated implicitly
/// from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Controller.View(Object)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcViewAttribute : PathReferenceAttribute
{
}
/// <summary>
/// ASP.NET MVC attribute. When applied to a parameter of an attribute,
/// indicates that this parameter is an MVC action name
/// </summary>
/// <example>
/// <code>
/// [ActionName("Foo")]
/// public ActionResult Login(string returnUrl) {
/// ViewBag.ReturnUrl = Url.Action("Foo"); // OK
/// return RedirectToAction("Bar"); // Error: Cannot resolve action
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)]
public sealed class AspMvcActionSelectorAttribute : Attribute
{
}
[AttributeUsage(
AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Field, Inherited = true)]
public sealed class HtmlElementAttributesAttribute : Attribute
{
public HtmlElementAttributesAttribute()
{
}
public HtmlElementAttributesAttribute([NotNull] string name)
{
Name = name;
}
[NotNull]
public string Name { get; private set; }
}
[AttributeUsage(
AttributeTargets.Parameter | AttributeTargets.Field |
AttributeTargets.Property, Inherited = true)]
public sealed class HtmlAttributeValueAttribute : Attribute
{
public HtmlAttributeValueAttribute([NotNull] string name)
{
Name = name;
}
[NotNull]
public string Name { get; private set; }
}
// Razor attributes
/// <summary>
/// Razor attribute. Indicates that a parameter or a method is a Razor section.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.WebPages.WebPageBase.RenderSection(String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method, Inherited = true)]
public sealed class RazorSectionAttribute : Attribute
{
}
} | 31.73622 | 102 | 0.688417 | [
"MIT"
] | jfheins/IGCV-Protokoll | IGCV-Protokoll/util/ResharperAnnotations.cs | 24,185 | C# |
using System.Collections.Generic;
using Cbn.Infrastructure.Common.Foundation.Exceptions.Bases;
namespace Cbn.Infrastructure.Common.Foundation.Exceptions
{
public class InfrastructureException : CbnException
{
/// <summary>
/// ビジネスロジック例外
/// </summary>
/// <param name="msg">エラー メッセージ</param>
public InfrastructureException(string msg) : base(msg) { }
/// <summary>
/// ビジネスロジック例外
/// </summary>
/// <param name="msgs">エラー メッセージ</param>
/// <param name="sep">セパレータ</param>
public InfrastructureException(IEnumerable<string> msgs, string sep = ",") : base(string.Join(sep, msgs)) { }
}
} | 34.35 | 117 | 0.620087 | [
"MIT"
] | wakuwaku3/cbn.clean-sample | Cbn.Infrastructure.Common/Foundation/Exceptions/InfrastructureException.cs | 769 | C# |
/*******************************************************************************
* Copyright (c) 2013 IBM Corporation.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v. 1.0 which accompanies this distribution.
*
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Steve Pitschke - initial API and implementation
*******************************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using ParseException = OSLC4Net.Core.Query.ParseException;
using OSLC4Net.Core.Query.Impl;
using Antlr.Runtime;
using Antlr.Runtime.Tree;
namespace OSLC4Net.Core.Query
{
public class QueryUtils
{
/// <summary>
/// Parse a oslc.prefix clause into a map between prefixes
/// and corresponding URIs
/// <p><b>Note</b>: {@link Object#toString()} of result has been overridden to
/// return input expression.
/// </summary>
/// <param name="prefixExpression">the oslc.prefix expression</param>
/// <returns>the prefix map</returns>
public static IDictionary<string, string>
ParsePrefixes(
string prefixExpression
)
{
if (prefixExpression == null) {
return new Dictionary<string, string>();
}
OslcPrefixParser parser = new OslcPrefixParser(prefixExpression);
CommonTree rawTree = (CommonTree)parser.Result;
IList<ITree> rawPrefixes = rawTree.Children;
PrefixMap prefixMap =
new PrefixMap(rawPrefixes.Count);
foreach (CommonTree rawPrefix in rawPrefixes) {
if (rawPrefix.Token == Tokens.Skip || rawPrefix is CommonErrorNode) {
throw new ParseException(rawPrefix.ToString());
}
string pn = rawPrefix.GetChild(0).Text;
string uri = rawPrefix.GetChild(1).Text;
uri = uri.Substring(1, uri.Length - 2);
prefixMap.Add(pn, uri);
}
return prefixMap;
}
/// <summary>
/// Parse a oslc.where expression
/// </summary>
/// <param name="whereExpression"contents of an oslc.where HTTP query
/// parameter></param>
/// <param name="prefixMap">map between XML namespace prefixes and
/// associated URLs</param>
/// <returns>the parsed where clause</returns>
public static WhereClause
ParseWhere(
string whereExpression,
IDictionary<string, string> prefixMap
)
{
try
{
OslcWhereParser parser = new OslcWhereParser(whereExpression);
CommonTree rawTree = (CommonTree)parser.Result;
ITree child = rawTree.GetChild(0);
if (child is CommonErrorNode)
{
throw new ParseException(child.ToString());
}
return (WhereClause) new WhereClauseImpl(rawTree, prefixMap);
} catch (RecognitionException e) {
throw new ParseException(e);
}
}
/// <summary>
/// Parse a oslc.select expression
/// </summary>
/// <param name="selectExpression">contents of an oslc.select HTTP query
/// parameter</param>
/// <param name="prefixMap">map between XML namespace prefixes and
/// associated URLs</param>
/// <returns>the parsed select clause</returns>
public static SelectClause
ParseSelect(
string selectExpression,
IDictionary<string, string> prefixMap
)
{
try
{
OslcSelectParser parser = new OslcSelectParser(selectExpression);
CommonTree rawTree = (CommonTree)parser.Result;
ITree child = rawTree.GetChild(0);
if (child is CommonErrorNode)
{
throw new ParseException(child.ToString());
}
return new SelectClauseImpl(rawTree, prefixMap);
} catch (RecognitionException e) {
throw new ParseException(e);
}
}
/// <summary>
/// Parse a oslc.properties expression
/// </summary>
/// <param name="propertiesExpression">contents of an oslc.properties HTTP query
/// parameter</param>
/// <param name="prefixMap"map between XML namespace prefixes and
///associated URLs></param>
/// <returns>the parsed properties clause</returns>
public static PropertiesClause
parseProperties(
string propertiesExpression,
IDictionary<string, string> prefixMap
)
{
try
{
OslcSelectParser parser = new OslcSelectParser(propertiesExpression);
CommonTree rawTree = (CommonTree)parser.Result;
ITree child = rawTree.GetChild(0);
if (child is CommonErrorNode)
{
throw new ParseException(child.ToString());
}
return new PropertiesClauseImpl(rawTree, prefixMap);
}
catch (RecognitionException e)
{
throw new ParseException(e);
}
}
/// <summary>
/// Parse a oslc.orderBy expression
/// </summary>
/// <param name="orderByExpression">contents of an oslc.orderBy HTTP query
/// parameter</param>
/// <param name="prefixMap">map between XML namespace prefixes and
/// associated URLs</param>
/// <returns></returns>
public static OrderByClause
ParseOrderBy(
string orderByExpression,
IDictionary<string, string> prefixMap
)
{
try {
OslcOrderByParser parser = new OslcOrderByParser(orderByExpression);
CommonTree rawTree = (CommonTree)parser.Result;
ITree child = rawTree.GetChild(0);
if (child is CommonErrorNode) {
throw new ParseException(child.ToString());
}
return (OrderByClause)new SortTermsImpl(rawTree, prefixMap);
} catch (RecognitionException e) {
throw new ParseException(e);
}
}
/// <summary>
/// Create a map representation of the Properties returned
/// from parsing oslc.properties or olsc.select URL query
/// parameters suitable for generating a property result from an
/// HTTP GET request.<p/>
///
/// The map keys are the property names; i.e. the local name of the
/// property concatenated to the XML namespace of the property. The
/// values of the map are:<p/>
///
/// <ul>
/// <li> OSLC4NetConstants.OSLC4NET_PROPERTY_WILDCARD - if all
/// properties at this level are to be output. No recursion
/// below this level is to be done.</li>
/// <li> OSLC4NetConstants.OSLC4NET_PROPERTY_SINGLETON - if only
/// the named property is to be output, without recursion</li>
/// <li> a nested property list to recurse through</li>
/// </ul>
/// </summary>
/// <param name="properties"></param>
/// <returns>the property map</returns>
public static IDictionary<string, object>
InvertSelectedProperties(Properties properties)
{
IList<Property> children = properties.Children;
IDictionary<string, object> result = new Dictionary<string, object>(children.Count);
foreach (Property property in children) {
PName pname = null;
string propertyName = null;
if (! property.IsWildcard) {
pname = property.Identifier;
propertyName = pname.ns + pname.local;
}
switch (property.Type) {
case PropertyType.IDENTIFIER:
if (property.IsWildcard) {
if (result is SingletonWildcardProperties) {
break;
}
if (result is NestedWildcardProperties) {
result = new BothWildcardPropertiesImpl(
(NestedWildcardPropertiesImpl)result);
} else {
result = new SingletonWildcardPropertiesImpl();
}
break;
} else {
if (result is SingletonWildcardProperties) {
break;
}
}
result.Add(propertyName,
OSLC4NetConstants.OSLC4NET_PROPERTY_SINGLETON);
break;
case PropertyType.NESTED_PROPERTY:
if (property.IsWildcard) {
if (! (result is NestedWildcardProperties)) {
if (result is SingletonWildcardProperties) {
result = new BothWildcardPropertiesImpl();
} else {
result = new NestedWildcardPropertiesImpl(result);
}
((NestedWildcardPropertiesImpl)result).commonNestedProperties =
InvertSelectedProperties((NestedProperty)property);
} else {
MergePropertyMaps(
((NestedWildcardProperties)result).CommonNestedProperties(),
InvertSelectedProperties((NestedProperty)property));
}
break;
}
result.Add(propertyName,
InvertSelectedProperties(
(NestedProperty)property));
break;
}
}
if (! (result is NestedWildcardProperties)) {
return result;
}
IDictionary<String, Object> commonNestedProperties =
((NestedWildcardProperties)result).CommonNestedProperties();
foreach (string propertyName in result.Keys) {
IDictionary<String, Object> nestedProperties =
(IDictionary<string, object>)result[propertyName];
if (nestedProperties == OSLC4NetConstants.OSLC4NET_PROPERTY_SINGLETON) {
result.Add(propertyName, commonNestedProperties);
} else {
MergePropertyMaps(nestedProperties, commonNestedProperties);
}
}
return result;
}
/// <summary>
/// Parse a oslc.searchTerms expression
///
/// <p><b>Note</b>: {@link Object#toString()} of result has been overridden to
/// return input expression.
/// </summary>
/// <param name="searchTermsExpression">contents of an oslc.searchTerms HTTP query
/// parameter</param>
/// <returns>the parsed search terms clause</returns>
public static SearchTermsClause
ParseSearchTerms(
string searchTermsExpression
)
{
try {
OslcSearchTermsParser parser = new OslcSearchTermsParser(searchTermsExpression);
CommonTree rawTree = (CommonTree)parser.Result;
CommonTree child = (CommonTree)rawTree.GetChild(0);
if (child is CommonErrorNode) {
throw ((CommonErrorNode)child).trappedException;
}
IList<ITree> rawList = rawTree.Children;
StringList stringList = new StringList(rawList.Count);
foreach (CommonTree str in rawList) {
string rawString = str.Text;
stringList.Add(rawString.Substring(1, rawString.Length-2));
}
return stringList;
} catch (RecognitionException e) {
throw new ParseException(e);
}
}
/// <summary>
/// Implementation of a IDictionary<String, String> prefixMap
/// </summary>
private class PrefixMap : Dictionary<string, string>
{
public
PrefixMap(int size)
: base(size)
{
}
public override string
ToString()
{
StringBuilder buffer = new StringBuilder();
bool first = true;
foreach (string key in Keys)
{
if (first)
{
first = false;
}
else
{
buffer.Append(',');
}
buffer.Append(key);
buffer.Append('=');
buffer.Append('<');
buffer.Append(this[key]);
buffer.Append('>');
}
return buffer.ToString();
}
}
/// <summary>
/// Implementation of a SearchTermsClause interface
/// </summary>
private class StringList : List<string>, SearchTermsClause
{
public
StringList(int size) : base(size)
{
}
public override string
ToString()
{
StringBuilder buffer = new StringBuilder();
bool first = true;
foreach (string str in this) {
if (first) {
first = false;
} else {
buffer.Append(',');
}
buffer.Append('"');
buffer.Append(str);
buffer.Append('"');
}
return buffer.ToString();
}
}
/// <summary>
/// Implementation of SingletonWildcardProperties
/// </summary>
private class SingletonWildcardPropertiesImpl :
Dictionary<string, object>,
SingletonWildcardProperties
{
public
SingletonWildcardPropertiesImpl() : base(0)
{
}
}
/// <summary>
/// Implementation of NestedWildcardProperties
/// </summary>
private class NestedWildcardPropertiesImpl :
Dictionary<string, object>,
NestedWildcardProperties
{
public
NestedWildcardPropertiesImpl(IDictionary<string, object> accumulated) : base(accumulated)
{
}
protected
NestedWildcardPropertiesImpl()
{
}
public IDictionary<string, object>
CommonNestedProperties()
{
return commonNestedProperties;
}
internal IDictionary<string, object> commonNestedProperties =
new Dictionary<string, object>();
}
/// <summary>
/// Implementation of both SingletonWildcardProperties and
/// NestedWildcardProperties
/// </summary>
private class BothWildcardPropertiesImpl :
NestedWildcardPropertiesImpl,
SingletonWildcardProperties
{
public
BothWildcardPropertiesImpl()
{
}
public
BothWildcardPropertiesImpl(NestedWildcardPropertiesImpl accumulated) : this()
{
commonNestedProperties = accumulated.CommonNestedProperties();
}
}
/// <summary>
/// Merge into lhs properties those of rhs property
/// map, merging any common, nested property maps
/// </summary>
/// <param name="lhs">target of property map merge</param>
/// <param name="rhs">source of property map merge</param>
private static void
MergePropertyMaps(
IDictionary<string, object> lhs,
IDictionary<string, object> rhs
)
{
ICollection<String> propertyNames = rhs.Keys;
foreach (string propertyName in propertyNames) {
IDictionary<String, Object> lhsNestedProperties =
(IDictionary<string, object>)lhs[propertyName];
IDictionary<String, Object> rhsNestedProperties =
(IDictionary<string, object>)rhs[propertyName];
if (lhsNestedProperties == rhsNestedProperties) {
continue;
}
if (lhsNestedProperties == null ||
lhsNestedProperties == OSLC4NetConstants.OSLC4NET_PROPERTY_SINGLETON) {
lhs.Add(propertyName, rhsNestedProperties);
continue;
}
MergePropertyMaps(lhsNestedProperties, rhsNestedProperties);
}
}
/// <summary>
/// Check list of errors from parsing some expression, generating
/// @{link {@link ParseException} if there are any.
/// </summary>
/// <param name="parser"></param>
private static void
CheckErrors(Parser parser)
{
if (! parser.Failed) {
return;
}
throw new ParseException("error");
}
}
}
| 34.701275 | 101 | 0.491733 | [
"EPL-1.0"
] | nenaaki/oslc4net | OSLC4Net_SDK/OSLC4Net.Core.Query/QueryUtils.cs | 19,053 | 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 autoscaling-2011-01-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.AutoScaling.Model
{
/// <summary>
/// Container for the parameters to the CreateAutoScalingGroup operation.
/// <b>We strongly recommend using a launch template when calling this operation to ensure
/// full functionality for Amazon EC2 Auto Scaling and Amazon EC2.</b>
///
///
/// <para>
/// Creates an Auto Scaling group with the specified name and attributes.
/// </para>
///
/// <para>
/// If you exceed your maximum limit of Auto Scaling groups, the call fails. To query
/// this limit, call the <a>DescribeAccountLimits</a> API. For information about updating
/// this limit, see <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-account-limits.html">Amazon
/// EC2 Auto Scaling service quotas</a> in the <i>Amazon EC2 Auto Scaling User Guide</i>.
/// </para>
///
/// <para>
/// For introductory exercises for creating an Auto Scaling group, see <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/GettingStartedTutorial.html">Getting
/// started with Amazon EC2 Auto Scaling</a> and <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-register-lbs-with-asg.html">Tutorial:
/// Set up a scaled and load-balanced application</a> in the <i>Amazon EC2 Auto Scaling
/// User Guide</i>. For more information, see <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/AutoScalingGroup.html">Auto
/// Scaling groups</a> in the <i>Amazon EC2 Auto Scaling User Guide</i>.
/// </para>
///
/// <para>
/// Every Auto Scaling group has three size parameters (<code>DesiredCapacity</code>,
/// <code>MaxSize</code>, and <code>MinSize</code>). Usually, you set these sizes based
/// on a specific number of instances. However, if you configure a mixed instances policy
/// that defines weights for the instance types, you must specify these sizes with the
/// same units that you use for weighting instances.
/// </para>
/// </summary>
public partial class CreateAutoScalingGroupRequest : AmazonAutoScalingRequest
{
private string _autoScalingGroupName;
private List<string> _availabilityZones = new List<string>();
private bool? _capacityRebalance;
private string _context;
private int? _defaultCooldown;
private int? _defaultInstanceWarmup;
private int? _desiredCapacity;
private string _desiredCapacityType;
private int? _healthCheckGracePeriod;
private string _healthCheckType;
private string _instanceId;
private string _launchConfigurationName;
private LaunchTemplateSpecification _launchTemplate;
private List<LifecycleHookSpecification> _lifecycleHookSpecificationList = new List<LifecycleHookSpecification>();
private List<string> _loadBalancerNames = new List<string>();
private int? _maxInstanceLifetime;
private int? _maxSize;
private int? _minSize;
private MixedInstancesPolicy _mixedInstancesPolicy;
private bool? _newInstancesProtectedFromScaleIn;
private string _placementGroup;
private string _serviceLinkedRoleARN;
private List<Tag> _tags = new List<Tag>();
private List<string> _targetGroupARNs = new List<string>();
private List<string> _terminationPolicies = new List<string>();
private string _vpcZoneIdentifier;
/// <summary>
/// Gets and sets the property AutoScalingGroupName.
/// <para>
/// The name of the Auto Scaling group. This name must be unique per Region per account.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=255)]
public string AutoScalingGroupName
{
get { return this._autoScalingGroupName; }
set { this._autoScalingGroupName = value; }
}
// Check to see if AutoScalingGroupName property is set
internal bool IsSetAutoScalingGroupName()
{
return this._autoScalingGroupName != null;
}
/// <summary>
/// Gets and sets the property AvailabilityZones.
/// <para>
/// A list of Availability Zones where instances in the Auto Scaling group can be created.
/// This parameter is optional if you specify one or more subnets for <code>VPCZoneIdentifier</code>.
/// </para>
///
/// <para>
/// Conditional: If your account supports EC2-Classic and VPC, this parameter is required
/// to launch instances into EC2-Classic.
/// </para>
/// </summary>
public List<string> AvailabilityZones
{
get { return this._availabilityZones; }
set { this._availabilityZones = value; }
}
// Check to see if AvailabilityZones property is set
internal bool IsSetAvailabilityZones()
{
return this._availabilityZones != null && this._availabilityZones.Count > 0;
}
/// <summary>
/// Gets and sets the property CapacityRebalance.
/// <para>
/// Indicates whether Capacity Rebalancing is enabled. Otherwise, Capacity Rebalancing
/// is disabled. When you turn on Capacity Rebalancing, Amazon EC2 Auto Scaling attempts
/// to launch a Spot Instance whenever Amazon EC2 notifies that a Spot Instance is at
/// an elevated risk of interruption. After launching a new instance, it then terminates
/// an old instance. For more information, see <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-capacity-rebalancing.html">Amazon
/// EC2 Auto Scaling Capacity Rebalancing</a> in the <i>Amazon EC2 Auto Scaling User Guide</i>.
/// </para>
/// </summary>
public bool CapacityRebalance
{
get { return this._capacityRebalance.GetValueOrDefault(); }
set { this._capacityRebalance = value; }
}
// Check to see if CapacityRebalance property is set
internal bool IsSetCapacityRebalance()
{
return this._capacityRebalance.HasValue;
}
/// <summary>
/// Gets and sets the property Context.
/// <para>
/// Reserved.
/// </para>
/// </summary>
public string Context
{
get { return this._context; }
set { this._context = value; }
}
// Check to see if Context property is set
internal bool IsSetContext()
{
return this._context != null;
}
/// <summary>
/// Gets and sets the property DefaultCooldown.
/// <para>
/// <i>Only needed if you use simple scaling policies.</i>
/// </para>
///
/// <para>
/// The amount of time, in seconds, between one scaling activity ending and another one
/// starting due to simple scaling policies. For more information, see <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/Cooldown.html">Scaling
/// cooldowns for Amazon EC2 Auto Scaling</a> in the <i>Amazon EC2 Auto Scaling User Guide</i>.
/// </para>
///
/// <para>
/// Default: <code>300</code> seconds
/// </para>
/// </summary>
public int DefaultCooldown
{
get { return this._defaultCooldown.GetValueOrDefault(); }
set { this._defaultCooldown = value; }
}
// Check to see if DefaultCooldown property is set
internal bool IsSetDefaultCooldown()
{
return this._defaultCooldown.HasValue;
}
/// <summary>
/// Gets and sets the property DefaultInstanceWarmup.
/// <para>
/// The amount of time, in seconds, until a newly launched instance can contribute to
/// the Amazon CloudWatch metrics. This delay lets an instance finish initializing before
/// Amazon EC2 Auto Scaling aggregates instance metrics, resulting in more reliable usage
/// data. Set this value equal to the amount of time that it takes for resource consumption
/// to become stable after an instance reaches the <code>InService</code> state. For more
/// information, see <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-default-instance-warmup.html">Set
/// the default instance warmup for an Auto Scaling group</a> in the <i>Amazon EC2 Auto
/// Scaling User Guide</i>.
/// </para>
/// <important>
/// <para>
/// To manage your warm-up settings at the group level, we recommend that you set the
/// default instance warmup, <i>even if its value is set to 0 seconds</i>. This also optimizes
/// the performance of scaling policies that scale continuously, such as target tracking
/// and step scaling policies.
/// </para>
///
/// <para>
/// If you need to remove a value that you previously set, include the property but specify
/// <code>-1</code> for the value. However, we strongly recommend keeping the default
/// instance warmup enabled by specifying a minimum value of <code>0</code>.
/// </para>
/// </important>
/// <para>
/// Default: None
/// </para>
/// </summary>
public int DefaultInstanceWarmup
{
get { return this._defaultInstanceWarmup.GetValueOrDefault(); }
set { this._defaultInstanceWarmup = value; }
}
// Check to see if DefaultInstanceWarmup property is set
internal bool IsSetDefaultInstanceWarmup()
{
return this._defaultInstanceWarmup.HasValue;
}
/// <summary>
/// Gets and sets the property DesiredCapacity.
/// <para>
/// The desired capacity is the initial capacity of the Auto Scaling group at the time
/// of its creation and the capacity it attempts to maintain. It can scale beyond this
/// capacity if you configure auto scaling. This number must be greater than or equal
/// to the minimum size of the group and less than or equal to the maximum size of the
/// group. If you do not specify a desired capacity, the default is the minimum size of
/// the group.
/// </para>
/// </summary>
public int DesiredCapacity
{
get { return this._desiredCapacity.GetValueOrDefault(); }
set { this._desiredCapacity = value; }
}
// Check to see if DesiredCapacity property is set
internal bool IsSetDesiredCapacity()
{
return this._desiredCapacity.HasValue;
}
/// <summary>
/// Gets and sets the property DesiredCapacityType.
/// <para>
/// The unit of measurement for the value specified for desired capacity. Amazon EC2 Auto
/// Scaling supports <code>DesiredCapacityType</code> for attribute-based instance type
/// selection only. For more information, see <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/create-asg-instance-type-requirements.html">Creating
/// an Auto Scaling group using attribute-based instance type selection</a> in the <i>Amazon
/// EC2 Auto Scaling User Guide</i>.
/// </para>
///
/// <para>
/// By default, Amazon EC2 Auto Scaling specifies <code>units</code>, which translates
/// into number of instances.
/// </para>
///
/// <para>
/// Valid values: <code>units</code> | <code>vcpu</code> | <code>memory-mib</code>
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=255)]
public string DesiredCapacityType
{
get { return this._desiredCapacityType; }
set { this._desiredCapacityType = value; }
}
// Check to see if DesiredCapacityType property is set
internal bool IsSetDesiredCapacityType()
{
return this._desiredCapacityType != null;
}
/// <summary>
/// Gets and sets the property HealthCheckGracePeriod.
/// <para>
/// <i/>
/// </para>
///
/// <para>
/// The amount of time, in seconds, that Amazon EC2 Auto Scaling waits before checking
/// the health status of an EC2 instance that has come into service and marking it unhealthy
/// due to a failed Elastic Load Balancing or custom health check. This is useful if your
/// instances do not immediately pass these health checks after they enter the <code>InService</code>
/// state. For more information, see <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/healthcheck.html#health-check-grace-period">Health
/// check grace period</a> in the <i>Amazon EC2 Auto Scaling User Guide</i>.
/// </para>
///
/// <para>
/// Default: <code>0</code> seconds
/// </para>
/// </summary>
public int HealthCheckGracePeriod
{
get { return this._healthCheckGracePeriod.GetValueOrDefault(); }
set { this._healthCheckGracePeriod = value; }
}
// Check to see if HealthCheckGracePeriod property is set
internal bool IsSetHealthCheckGracePeriod()
{
return this._healthCheckGracePeriod.HasValue;
}
/// <summary>
/// Gets and sets the property HealthCheckType.
/// <para>
/// The service to use for the health checks. The valid values are <code>EC2</code> (default)
/// and <code>ELB</code>. If you configure an Auto Scaling group to use load balancer
/// (ELB) health checks, it considers the instance unhealthy if it fails either the EC2
/// status checks or the load balancer health checks. For more information, see <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/healthcheck.html">Health
/// checks for Auto Scaling instances</a> in the <i>Amazon EC2 Auto Scaling User Guide</i>.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=32)]
public string HealthCheckType
{
get { return this._healthCheckType; }
set { this._healthCheckType = value; }
}
// Check to see if HealthCheckType property is set
internal bool IsSetHealthCheckType()
{
return this._healthCheckType != null;
}
/// <summary>
/// Gets and sets the property InstanceId.
/// <para>
/// The ID of the instance used to base the launch configuration on. If specified, Amazon
/// EC2 Auto Scaling uses the configuration values from the specified instance to create
/// a new launch configuration. To get the instance ID, use the Amazon EC2 <a href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstances.html">DescribeInstances</a>
/// API operation. For more information, see <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/create-asg-from-instance.html">Creating
/// an Auto Scaling group using an EC2 instance</a> in the <i>Amazon EC2 Auto Scaling
/// User Guide</i>.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=19)]
public string InstanceId
{
get { return this._instanceId; }
set { this._instanceId = value; }
}
// Check to see if InstanceId property is set
internal bool IsSetInstanceId()
{
return this._instanceId != null;
}
/// <summary>
/// Gets and sets the property LaunchConfigurationName.
/// <para>
/// The name of the launch configuration to use to launch instances.
/// </para>
///
/// <para>
/// Conditional: You must specify either a launch template (<code>LaunchTemplate</code>
/// or <code>MixedInstancesPolicy</code>) or a launch configuration (<code>LaunchConfigurationName</code>
/// or <code>InstanceId</code>).
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=255)]
public string LaunchConfigurationName
{
get { return this._launchConfigurationName; }
set { this._launchConfigurationName = value; }
}
// Check to see if LaunchConfigurationName property is set
internal bool IsSetLaunchConfigurationName()
{
return this._launchConfigurationName != null;
}
/// <summary>
/// Gets and sets the property LaunchTemplate.
/// <para>
/// Parameters used to specify the launch template and version to use to launch instances.
///
/// </para>
///
/// <para>
/// Conditional: You must specify either a launch template (<code>LaunchTemplate</code>
/// or <code>MixedInstancesPolicy</code>) or a launch configuration (<code>LaunchConfigurationName</code>
/// or <code>InstanceId</code>).
/// </para>
/// <note>
/// <para>
/// The launch template that is specified must be configured for use with an Auto Scaling
/// group. For more information, see <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/create-launch-template.html">Creating
/// a launch template for an Auto Scaling group</a> in the <i>Amazon EC2 Auto Scaling
/// User Guide</i>.
/// </para>
/// </note>
/// </summary>
public LaunchTemplateSpecification LaunchTemplate
{
get { return this._launchTemplate; }
set { this._launchTemplate = value; }
}
// Check to see if LaunchTemplate property is set
internal bool IsSetLaunchTemplate()
{
return this._launchTemplate != null;
}
/// <summary>
/// Gets and sets the property LifecycleHookSpecificationList.
/// <para>
/// One or more lifecycle hooks for the group, which specify actions to perform when Amazon
/// EC2 Auto Scaling launches or terminates instances.
/// </para>
/// </summary>
public List<LifecycleHookSpecification> LifecycleHookSpecificationList
{
get { return this._lifecycleHookSpecificationList; }
set { this._lifecycleHookSpecificationList = value; }
}
// Check to see if LifecycleHookSpecificationList property is set
internal bool IsSetLifecycleHookSpecificationList()
{
return this._lifecycleHookSpecificationList != null && this._lifecycleHookSpecificationList.Count > 0;
}
/// <summary>
/// Gets and sets the property LoadBalancerNames.
/// <para>
/// A list of Classic Load Balancers associated with this Auto Scaling group. For Application
/// Load Balancers, Network Load Balancers, and Gateway Load Balancers, specify the <code>TargetGroupARNs</code>
/// property instead.
/// </para>
/// </summary>
public List<string> LoadBalancerNames
{
get { return this._loadBalancerNames; }
set { this._loadBalancerNames = value; }
}
// Check to see if LoadBalancerNames property is set
internal bool IsSetLoadBalancerNames()
{
return this._loadBalancerNames != null && this._loadBalancerNames.Count > 0;
}
/// <summary>
/// Gets and sets the property MaxInstanceLifetime.
/// <para>
/// The maximum amount of time, in seconds, that an instance can be in service. The default
/// is null. If specified, the value must be either 0 or a number equal to or greater
/// than 86,400 seconds (1 day). For more information, see <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-max-instance-lifetime.html">Replacing
/// Auto Scaling instances based on maximum instance lifetime</a> in the <i>Amazon EC2
/// Auto Scaling User Guide</i>.
/// </para>
/// </summary>
public int MaxInstanceLifetime
{
get { return this._maxInstanceLifetime.GetValueOrDefault(); }
set { this._maxInstanceLifetime = value; }
}
// Check to see if MaxInstanceLifetime property is set
internal bool IsSetMaxInstanceLifetime()
{
return this._maxInstanceLifetime.HasValue;
}
/// <summary>
/// Gets and sets the property MaxSize.
/// <para>
/// The maximum size of the group.
/// </para>
/// <note>
/// <para>
/// With a mixed instances policy that uses instance weighting, Amazon EC2 Auto Scaling
/// may need to go above <code>MaxSize</code> to meet your capacity requirements. In this
/// event, Amazon EC2 Auto Scaling will never go above <code>MaxSize</code> by more than
/// your largest instance weight (weights that define how many units each instance contributes
/// to the desired capacity of the group).
/// </para>
/// </note>
/// </summary>
[AWSProperty(Required=true)]
public int MaxSize
{
get { return this._maxSize.GetValueOrDefault(); }
set { this._maxSize = value; }
}
// Check to see if MaxSize property is set
internal bool IsSetMaxSize()
{
return this._maxSize.HasValue;
}
/// <summary>
/// Gets and sets the property MinSize.
/// <para>
/// The minimum size of the group.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public int MinSize
{
get { return this._minSize.GetValueOrDefault(); }
set { this._minSize = value; }
}
// Check to see if MinSize property is set
internal bool IsSetMinSize()
{
return this._minSize.HasValue;
}
/// <summary>
/// Gets and sets the property MixedInstancesPolicy.
/// <para>
/// An embedded object that specifies a mixed instances policy.
/// </para>
///
/// <para>
/// For more information, see <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-mixed-instances-groups.html">Auto
/// Scaling groups with multiple instance types and purchase options</a> in the <i>Amazon
/// EC2 Auto Scaling User Guide</i>.
/// </para>
/// </summary>
public MixedInstancesPolicy MixedInstancesPolicy
{
get { return this._mixedInstancesPolicy; }
set { this._mixedInstancesPolicy = value; }
}
// Check to see if MixedInstancesPolicy property is set
internal bool IsSetMixedInstancesPolicy()
{
return this._mixedInstancesPolicy != null;
}
/// <summary>
/// Gets and sets the property NewInstancesProtectedFromScaleIn.
/// <para>
/// Indicates whether newly launched instances are protected from termination by Amazon
/// EC2 Auto Scaling when scaling in. For more information about preventing instances
/// from terminating on scale in, see <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-instance-protection.html">Using
/// instance scale-in protection</a> in the <i>Amazon EC2 Auto Scaling User Guide</i>.
/// </para>
/// </summary>
public bool NewInstancesProtectedFromScaleIn
{
get { return this._newInstancesProtectedFromScaleIn.GetValueOrDefault(); }
set { this._newInstancesProtectedFromScaleIn = value; }
}
// Check to see if NewInstancesProtectedFromScaleIn property is set
internal bool IsSetNewInstancesProtectedFromScaleIn()
{
return this._newInstancesProtectedFromScaleIn.HasValue;
}
/// <summary>
/// Gets and sets the property PlacementGroup.
/// <para>
/// The name of an existing placement group into which to launch your instances. For more
/// information, see <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html">Placement
/// groups</a> in the <i>Amazon EC2 User Guide for Linux Instances</i>.
/// </para>
/// <note>
/// <para>
/// A <i>cluster</i> placement group is a logical grouping of instances within a single
/// Availability Zone. You cannot specify multiple Availability Zones and a cluster placement
/// group.
/// </para>
/// </note>
/// </summary>
[AWSProperty(Min=1, Max=255)]
public string PlacementGroup
{
get { return this._placementGroup; }
set { this._placementGroup = value; }
}
// Check to see if PlacementGroup property is set
internal bool IsSetPlacementGroup()
{
return this._placementGroup != null;
}
/// <summary>
/// Gets and sets the property ServiceLinkedRoleARN.
/// <para>
/// The Amazon Resource Name (ARN) of the service-linked role that the Auto Scaling group
/// uses to call other Amazon Web Services on your behalf. By default, Amazon EC2 Auto
/// Scaling uses a service-linked role named <code>AWSServiceRoleForAutoScaling</code>,
/// which it creates if it does not exist. For more information, see <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-service-linked-role.html">Service-linked
/// roles</a> in the <i>Amazon EC2 Auto Scaling User Guide</i>.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=1600)]
public string ServiceLinkedRoleARN
{
get { return this._serviceLinkedRoleARN; }
set { this._serviceLinkedRoleARN = value; }
}
// Check to see if ServiceLinkedRoleARN property is set
internal bool IsSetServiceLinkedRoleARN()
{
return this._serviceLinkedRoleARN != null;
}
/// <summary>
/// Gets and sets the property Tags.
/// <para>
/// One or more tags. You can tag your Auto Scaling group and propagate the tags to the
/// Amazon EC2 instances it launches. Tags are not propagated to Amazon EBS volumes. To
/// add tags to Amazon EBS volumes, specify the tags in a launch template but use caution.
/// If the launch template specifies an instance tag with a key that is also specified
/// for the Auto Scaling group, Amazon EC2 Auto Scaling overrides the value of that instance
/// tag with the value specified by the Auto Scaling group. For more information, see
/// <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-tagging.html">Tagging
/// Auto Scaling groups and instances</a> in the <i>Amazon EC2 Auto Scaling User Guide</i>.
/// </para>
/// </summary>
public List<Tag> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
/// <summary>
/// Gets and sets the property TargetGroupARNs.
/// <para>
/// The Amazon Resource Names (ARN) of the target groups to associate with the Auto Scaling
/// group. Instances are registered as targets in a target group, and traffic is routed
/// to the target group. For more information, see <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-load-balancer.html">Elastic
/// Load Balancing and Amazon EC2 Auto Scaling</a> in the <i>Amazon EC2 Auto Scaling User
/// Guide</i>.
/// </para>
/// </summary>
public List<string> TargetGroupARNs
{
get { return this._targetGroupARNs; }
set { this._targetGroupARNs = value; }
}
// Check to see if TargetGroupARNs property is set
internal bool IsSetTargetGroupARNs()
{
return this._targetGroupARNs != null && this._targetGroupARNs.Count > 0;
}
/// <summary>
/// Gets and sets the property TerminationPolicies.
/// <para>
/// A policy or a list of policies that are used to select the instance to terminate.
/// These policies are executed in the order that you list them. For more information,
/// see <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-instance-termination.html">Controlling
/// which Auto Scaling instances terminate during scale in</a> in the <i>Amazon EC2 Auto
/// Scaling User Guide</i>.
/// </para>
/// </summary>
public List<string> TerminationPolicies
{
get { return this._terminationPolicies; }
set { this._terminationPolicies = value; }
}
// Check to see if TerminationPolicies property is set
internal bool IsSetTerminationPolicies()
{
return this._terminationPolicies != null && this._terminationPolicies.Count > 0;
}
/// <summary>
/// Gets and sets the property VPCZoneIdentifier.
/// <para>
/// A comma-separated list of subnet IDs for a virtual private cloud (VPC) where instances
/// in the Auto Scaling group can be created. If you specify <code>VPCZoneIdentifier</code>
/// with <code>AvailabilityZones</code>, the subnets that you specify for this parameter
/// must reside in those Availability Zones.
/// </para>
///
/// <para>
/// Conditional: If your account supports EC2-Classic and VPC, this parameter is required
/// to launch instances into a VPC.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=2047)]
public string VPCZoneIdentifier
{
get { return this._vpcZoneIdentifier; }
set { this._vpcZoneIdentifier = value; }
}
// Check to see if VPCZoneIdentifier property is set
internal bool IsSetVPCZoneIdentifier()
{
return this._vpcZoneIdentifier != null;
}
}
} | 42.929635 | 196 | 0.612482 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/AutoScaling/Generated/Model/CreateAutoScalingGroupRequest.cs | 31,725 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("06.PowerPlants")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("06.PowerPlants")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("63e0459d-38a3-4d6c-b984-a3e890886a43")]
// 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.72973 | 84 | 0.747135 | [
"MIT"
] | Peter-Georgiev/Programming.Fundamentals | Arrays - More Exercises/06.PowerPlants/Properties/AssemblyInfo.cs | 1,399 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.RabbitMQ
{
/// <summary>
/// The ``rabbitmq.Permissions`` resource creates and manages a user's set of
/// permissions.
///
/// ## Example Usage
///
/// ```csharp
/// using Pulumi;
/// using RabbitMQ = Pulumi.RabbitMQ;
///
/// class MyStack : Stack
/// {
/// public MyStack()
/// {
/// var testVHost = new RabbitMQ.VHost("testVHost", new RabbitMQ.VHostArgs
/// {
/// });
/// var testUser = new RabbitMQ.User("testUser", new RabbitMQ.UserArgs
/// {
/// Password = "foobar",
/// Tags =
/// {
/// "administrator",
/// },
/// });
/// var testPermissions = new RabbitMQ.Permissions("testPermissions", new RabbitMQ.PermissionsArgs
/// {
/// Permissions = new RabbitMQ.Inputs.PermissionsPermissionsArgs
/// {
/// Configure = ".*",
/// Read = ".*",
/// Write = ".*",
/// },
/// User = testUser.Name,
/// Vhost = testVHost.Name,
/// });
/// }
///
/// }
/// ```
///
/// ## Import
///
/// Permissions can be imported using the `id` which is composed of
///
/// `user@vhost`. E.g.
///
/// ```sh
/// $ pulumi import rabbitmq:index/permissions:Permissions test user@vhost
/// ```
/// </summary>
[RabbitMQResourceType("rabbitmq:index/permissions:Permissions")]
public partial class Permissions : Pulumi.CustomResource
{
/// <summary>
/// The settings of the permissions. The structure is
/// described below.
/// </summary>
[Output("permissions")]
public Output<Outputs.PermissionsPermissions> PermissionDetails { get; private set; } = null!;
/// <summary>
/// The user to apply the permissions to.
/// </summary>
[Output("user")]
public Output<string> User { get; private set; } = null!;
/// <summary>
/// The vhost to create the resource in.
/// </summary>
[Output("vhost")]
public Output<string?> Vhost { get; private set; } = null!;
/// <summary>
/// Create a Permissions resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public Permissions(string name, PermissionsArgs args, CustomResourceOptions? options = null)
: base("rabbitmq:index/permissions:Permissions", name, args ?? new PermissionsArgs(), MakeResourceOptions(options, ""))
{
}
private Permissions(string name, Input<string> id, PermissionsState? state = null, CustomResourceOptions? options = null)
: base("rabbitmq:index/permissions:Permissions", name, state, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing Permissions resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="state">Any extra arguments used during the lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static Permissions Get(string name, Input<string> id, PermissionsState? state = null, CustomResourceOptions? options = null)
{
return new Permissions(name, id, state, options);
}
}
public sealed class PermissionsArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The settings of the permissions. The structure is
/// described below.
/// </summary>
[Input("permissions", required: true)]
public Input<Inputs.PermissionsPermissionsArgs> PermissionDetails { get; set; } = null!;
/// <summary>
/// The user to apply the permissions to.
/// </summary>
[Input("user", required: true)]
public Input<string> User { get; set; } = null!;
/// <summary>
/// The vhost to create the resource in.
/// </summary>
[Input("vhost")]
public Input<string>? Vhost { get; set; }
public PermissionsArgs()
{
}
}
public sealed class PermissionsState : Pulumi.ResourceArgs
{
/// <summary>
/// The settings of the permissions. The structure is
/// described below.
/// </summary>
[Input("permissions")]
public Input<Inputs.PermissionsPermissionsGetArgs>? PermissionDetails { get; set; }
/// <summary>
/// The user to apply the permissions to.
/// </summary>
[Input("user")]
public Input<string>? User { get; set; }
/// <summary>
/// The vhost to create the resource in.
/// </summary>
[Input("vhost")]
public Input<string>? Vhost { get; set; }
public PermissionsState()
{
}
}
}
| 35.342541 | 139 | 0.55401 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi/pulumi-rabbitmq | sdk/dotnet/Permissions.cs | 6,397 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace N400.Packets
{
internal class IfsCommitRequest : IfsChainedPacketBase
{
public const ushort ID = 0x0006;
public uint Handle
{
get
{
return Data.ReadUInt32BE(22);
}
set
{
Data.WriteBE(22, value);
}
}
public IfsCommitRequest(uint handle) : base(26)
{
TemplateLength = 26;
RequestResponseID = ID;
Handle = handle;
}
}
}
| 19.294118 | 58 | 0.515244 | [
"MIT"
] | MonoOni/N400 | N400/Packets/IfsCommitRequest.cs | 658 | C# |
using ManagePlan.Core.Models;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace ManagePlan.Service.IServices
{
public interface ITransactionService
{
Task AddTransaction(Transaction transaction);
Task DeleteTransaction(int id);
Task<IEnumerable<Transaction>> GetAllTransactions();
Task<Transaction> GetTransactionById(int id);
Task UpdateTransaction(Transaction transaction);
Task<IEnumerable<Transaction>> GetTransactionsByAccountId(int accountId);
}
}
| 31.764706 | 81 | 0.746296 | [
"MIT"
] | Baintastic/ManagePlan | ManagePlan.Service/IServices/ITransactionService.cs | 542 | C# |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v9/errors/field_error.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Ads.GoogleAds.V9.Errors {
/// <summary>Holder for reflection information generated from google/ads/googleads/v9/errors/field_error.proto</summary>
public static partial class FieldErrorReflection {
#region Descriptor
/// <summary>File descriptor for google/ads/googleads/v9/errors/field_error.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static FieldErrorReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CjBnb29nbGUvYWRzL2dvb2dsZWFkcy92OS9lcnJvcnMvZmllbGRfZXJyb3Iu",
"cHJvdG8SHmdvb2dsZS5hZHMuZ29vZ2xlYWRzLnY5LmVycm9ycxocZ29vZ2xl",
"L2FwaS9hbm5vdGF0aW9ucy5wcm90byLYAQoORmllbGRFcnJvckVudW0ixQEK",
"CkZpZWxkRXJyb3ISDwoLVU5TUEVDSUZJRUQQABILCgdVTktOT1dOEAESDAoI",
"UkVRVUlSRUQQAhITCg9JTU1VVEFCTEVfRklFTEQQAxIRCg1JTlZBTElEX1ZB",
"TFVFEAQSFwoTVkFMVUVfTVVTVF9CRV9VTlNFVBAFEhoKFlJFUVVJUkVEX05P",
"TkVNUFRZX0xJU1QQBhIbChdGSUVMRF9DQU5OT1RfQkVfQ0xFQVJFRBAHEhEK",
"DUJMT0NLRURfVkFMVUUQCULqAQoiY29tLmdvb2dsZS5hZHMuZ29vZ2xlYWRz",
"LnY5LmVycm9yc0IPRmllbGRFcnJvclByb3RvUAFaRGdvb2dsZS5nb2xhbmcu",
"b3JnL2dlbnByb3RvL2dvb2dsZWFwaXMvYWRzL2dvb2dsZWFkcy92OS9lcnJv",
"cnM7ZXJyb3JzogIDR0FBqgIeR29vZ2xlLkFkcy5Hb29nbGVBZHMuVjkuRXJy",
"b3JzygIeR29vZ2xlXEFkc1xHb29nbGVBZHNcVjlcRXJyb3Jz6gIiR29vZ2xl",
"OjpBZHM6Okdvb2dsZUFkczo6Vjk6OkVycm9yc2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V9.Errors.FieldErrorEnum), global::Google.Ads.GoogleAds.V9.Errors.FieldErrorEnum.Parser, null, null, new[]{ typeof(global::Google.Ads.GoogleAds.V9.Errors.FieldErrorEnum.Types.FieldError) }, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Container for enum describing possible field errors.
/// </summary>
public sealed partial class FieldErrorEnum : pb::IMessage<FieldErrorEnum>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<FieldErrorEnum> _parser = new pb::MessageParser<FieldErrorEnum>(() => new FieldErrorEnum());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<FieldErrorEnum> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Ads.GoogleAds.V9.Errors.FieldErrorReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public FieldErrorEnum() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public FieldErrorEnum(FieldErrorEnum other) : this() {
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public FieldErrorEnum Clone() {
return new FieldErrorEnum(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as FieldErrorEnum);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(FieldErrorEnum other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(FieldErrorEnum other) {
if (other == null) {
return;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
}
#endif
#region Nested types
/// <summary>Container for nested types declared in the FieldErrorEnum message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static partial class Types {
/// <summary>
/// Enum describing possible field errors.
/// </summary>
public enum FieldError {
/// <summary>
/// Enum unspecified.
/// </summary>
[pbr::OriginalName("UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// The received error code is not known in this version.
/// </summary>
[pbr::OriginalName("UNKNOWN")] Unknown = 1,
/// <summary>
/// The required field was not present.
/// </summary>
[pbr::OriginalName("REQUIRED")] Required = 2,
/// <summary>
/// The field attempted to be mutated is immutable.
/// </summary>
[pbr::OriginalName("IMMUTABLE_FIELD")] ImmutableField = 3,
/// <summary>
/// The field's value is invalid.
/// </summary>
[pbr::OriginalName("INVALID_VALUE")] InvalidValue = 4,
/// <summary>
/// The field cannot be set.
/// </summary>
[pbr::OriginalName("VALUE_MUST_BE_UNSET")] ValueMustBeUnset = 5,
/// <summary>
/// The required repeated field was empty.
/// </summary>
[pbr::OriginalName("REQUIRED_NONEMPTY_LIST")] RequiredNonemptyList = 6,
/// <summary>
/// The field cannot be cleared.
/// </summary>
[pbr::OriginalName("FIELD_CANNOT_BE_CLEARED")] FieldCannotBeCleared = 7,
/// <summary>
/// The field's value is on a deny-list for this field.
/// </summary>
[pbr::OriginalName("BLOCKED_VALUE")] BlockedValue = 9,
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| 38.55 | 279 | 0.68692 | [
"Apache-2.0"
] | friedenberg/google-ads-dotnet | src/V9/Types/FieldError.g.cs | 10,023 | C# |
// MonoGame - Copyright (C) The MonoGame Team
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
using System.Diagnostics;
using MonoGame.Utilities;
#if __IOS__ || __TVOS__ || MONOMAC
using ObjCRuntime;
#endif
namespace MonoGame.OpenGL
{
internal enum BufferAccess
{
ReadOnly = 0x88B8,
}
internal enum BufferUsageHint
{
StreamDraw = 0x88E0,
StaticDraw = 0x88E4,
}
internal enum StencilFace
{
Front = 0x0404,
Back = 0x0405,
}
internal enum DrawBuffersEnum
{
UnsignedShort,
UnsignedInt,
}
internal enum ShaderType
{
VertexShader = 0x8B31,
FragmentShader = 0x8B30,
}
internal enum ShaderParameter
{
LogLength = 0x8B84,
CompileStatus = 0x8B81,
SourceLength = 0x8B88,
}
internal enum GetProgramParameterName
{
LogLength = 0x8B84,
LinkStatus = 0x8B82,
}
internal enum DrawElementsType
{
UnsignedShort = 0x1403,
UnsignedInt = 0x1405,
}
internal enum QueryTarget
{
SamplesPassed = 0x8914,
SamplesPassedExt = 0x8C2F,
}
internal enum GetQueryObjectParam
{
QueryResultAvailable = 0x8867,
QueryResult = 0x8866,
}
internal enum GenerateMipmapTarget
{
Texture1D = 0x0DE0,
Texture2D = 0x0DE1,
Texture3D = 0x806F,
TextureCubeMap = 0x8513,
Texture1DArray = 0x8C18,
Texture2DArray = 0x8C1A,
Texture2DMultisample = 0x9100,
Texture2DMultisampleArray = 0x9102,
}
internal enum BlitFramebufferFilter
{
Nearest = 0x2600,
}
internal enum ReadBufferMode
{
ColorAttachment0 = 0x8CE0,
}
internal enum DrawBufferMode
{
ColorAttachment0 = 0x8CE0,
}
internal enum FramebufferErrorCode
{
FramebufferUndefined = 0x8219,
FramebufferComplete = 0x8CD5,
FramebufferCompleteExt = 0x8CD5,
FramebufferIncompleteAttachment = 0x8CD6,
FramebufferIncompleteAttachmentExt = 0x8CD6,
FramebufferIncompleteMissingAttachment = 0x8CD7,
FramebufferIncompleteMissingAttachmentExt = 0x8CD7,
FramebufferIncompleteDimensionsExt = 0x8CD9,
FramebufferIncompleteFormatsExt = 0x8CDA,
FramebufferIncompleteDrawBuffer = 0x8CDB,
FramebufferIncompleteDrawBufferExt = 0x8CDB,
FramebufferIncompleteReadBuffer = 0x8CDC,
FramebufferIncompleteReadBufferExt = 0x8CDC,
FramebufferUnsupported = 0x8CDD,
FramebufferUnsupportedExt = 0x8CDD,
FramebufferIncompleteMultisample = 0x8D56,
FramebufferIncompleteLayerTargets = 0x8DA8,
FramebufferIncompleteLayerCount = 0x8DA9,
}
internal enum BufferTarget
{
ArrayBuffer = 0x8892,
ElementArrayBuffer = 0x8893,
}
internal enum RenderbufferTarget
{
Renderbuffer = 0x8D41,
RenderbufferExt = 0x8D41,
}
internal enum FramebufferTarget
{
Framebuffer = 0x8D40,
FramebufferExt = 0x8D40,
ReadFramebuffer = 0x8CA8,
}
internal enum RenderbufferStorage
{
Rgba8 = 0x8058,
DepthComponent16 = 0x81a5,
DepthComponent24 = 0x81a6,
Depth24Stencil8 = 0x88F0,
// GLES Values
DepthComponent24Oes = 0x81A6,
Depth24Stencil8Oes = 0x88F0,
StencilIndex8 = 0x8D48,
}
internal enum EnableCap : int
{
PointSmooth = 0x0B10,
LineSmooth = 0x0B20,
CullFace = 0x0B44,
Lighting = 0x0B50,
ColorMaterial = 0x0B57,
Fog = 0x0B60,
DepthTest = 0x0B71,
StencilTest = 0x0B90,
Normalize = 0x0BA1,
AlphaTest = 0x0BC0,
Dither = 0x0BD0,
Blend = 0x0BE2,
ColorLogicOp = 0x0BF2,
ScissorTest = 0x0C11,
Texture2D = 0x0DE1,
PolygonOffsetFill = 0x8037,
RescaleNormal = 0x803A,
VertexArray = 0x8074,
NormalArray = 0x8075,
ColorArray = 0x8076,
TextureCoordArray = 0x8078,
Multisample = 0x809D,
SampleAlphaToCoverage = 0x809E,
SampleAlphaToOne = 0x809F,
SampleCoverage = 0x80A0,
DebugOutputSynchronous = 0x8242,
DebugOutput = 0x92E0,
}
internal enum VertexPointerType
{
Float = 0x1406,
Short = 0x1402,
}
internal enum VertexAttribPointerType
{
Float = 0x1406,
Short = 0x1402,
UnsignedByte = 0x1401,
HalfFloat = 0x140B,
}
internal enum CullFaceMode
{
Back = 0x0405,
Front = 0x0404,
}
internal enum FrontFaceDirection
{
Cw = 0x0900,
Ccw = 0x0901,
}
internal enum MaterialFace
{
FrontAndBack = 0x0408,
}
internal enum PolygonMode
{
Fill = 0x1B02,
Line = 0x1B01,
}
internal enum ColorPointerType
{
Float = 0x1406,
Short = 0x1402,
UnsignedShort = 0x1403,
UnsignedByte = 0x1401,
HalfFloat = 0x140B,
}
internal enum NormalPointerType
{
Byte = 0x1400,
Float = 0x1406,
Short = 0x1402,
UnsignedShort = 0x1403,
UnsignedByte = 0x1401,
HalfFloat = 0x140B,
}
internal enum TexCoordPointerType
{
Byte = 0x1400,
Float = 0x1406,
Short = 0x1402,
UnsignedShort = 0x1403,
UnsignedByte = 0x1401,
HalfFloat = 0x140B,
}
internal enum BlendEquationMode
{
FuncAdd = 0x8006,
Max = 0x8008, // ios MaxExt
Min = 0x8007, // ios MinExt
FuncReverseSubtract = 0x800B,
FuncSubtract = 0x800A,
}
internal enum BlendingFactorSrc
{
Zero = 0,
SrcColor = 0x0300,
OneMinusSrcColor = 0x0301,
SrcAlpha = 0x0302,
OneMinusSrcAlpha = 0x0303,
DstAlpha = 0x0304,
OneMinusDstAlpha = 0x0305,
DstColor = 0x0306,
OneMinusDstColor = 0x0307,
SrcAlphaSaturate = 0x0308,
ConstantColor = 0x8001,
OneMinusConstantColor = 0x8002,
ConstantAlpha = 0x8003,
OneMinusConstantAlpha = 0x8004,
One = 1,
}
internal enum BlendingFactorDest
{
Zero = 0,
SrcColor = 0x0300,
OneMinusSrcColor = 0x0301,
SrcAlpha = 0x0302,
OneMinusSrcAlpha = 0x0303,
DstAlpha = 0x0304,
OneMinusDstAlpha = 0x0305,
DstColor = 0X0306,
OneMinusDstColor = 0x0307,
SrcAlphaSaturate = 0x0308,
ConstantColor = 0x8001,
OneMinusConstantColor = 0x8002,
ConstantAlpha = 0x8003,
OneMinusConstantAlpha = 0x8004,
One = 1,
}
internal enum DepthFunction
{
Always = 0x0207,
Equal = 0x0202,
Greater = 0x0204,
Gequal = 0x0206,
Less = 0x0201,
Lequal = 0x0203,
Never = 0x0200,
Notequal = 0x0205,
}
internal enum GetPName : int
{
ArrayBufferBinding = 0x8894,
MaxTextureImageUnits = 0x8872,
MaxVertexAttribs = 0x8869,
MaxTextureSize = 0x0D33,
MaxDrawBuffers = 0x8824,
TextureBinding2D = 0x8069,
MaxTextureMaxAnisotropyExt = 0x84FF,
MaxSamples = 0x8D57,
}
internal enum StringName
{
Extensions = 0x1F03,
Version = 0x1F02,
}
internal enum FramebufferAttachment
{
ColorAttachment0 = 0x8CE0,
ColorAttachment0Ext = 0x8CE0,
DepthAttachment = 0x8D00,
StencilAttachment = 0x8D20,
ColorAttachmentExt = 0x1800,
DepthAttachementExt = 0x1801,
StencilAttachmentExt = 0x1802,
}
internal enum GLPrimitiveType
{
Lines = 0x0001,
LineStrip = 0x0003,
Triangles = 0x0004,
TriangleStrip = 0x0005,
}
[Flags]
internal enum ClearBufferMask
{
DepthBufferBit = 0x00000100,
StencilBufferBit = 0x00000400,
ColorBufferBit = 0x00004000,
}
internal enum ErrorCode
{
NoError = 0,
}
internal enum TextureUnit
{
Texture0 = 0x84C0,
}
internal enum TextureTarget
{
Texture2D = 0x0DE1,
Texture3D = 0x806F,
TextureCubeMap = 0x8513,
TextureCubeMapPositiveX = 0x8515,
TextureCubeMapPositiveY = 0x8517,
TextureCubeMapPositiveZ = 0x8519,
TextureCubeMapNegativeX = 0x8516,
TextureCubeMapNegativeY = 0x8518,
TextureCubeMapNegativeZ = 0x851A,
}
internal enum PixelInternalFormat
{
Rgba = 0x1908,
Rgb = 0x1907,
Rgba4 = 0x8056,
Luminance = 0x1909,
CompressedRgbS3tcDxt1Ext = 0x83F0,
CompressedSrgbS3tcDxt1Ext = 0x8C4C,
CompressedRgbaS3tcDxt1Ext = 0x83F1,
CompressedRgbaS3tcDxt3Ext = 0x83F2,
CompressedSrgbAlphaS3tcDxt3Ext = 0x8C4E,
CompressedRgbaS3tcDxt5Ext = 0x83F3,
CompressedSrgbAlphaS3tcDxt5Ext = 0x8C4F,
R32f = 0x822E,
Rg16f = 0x822F,
Rgba16f = 0x881A,
R16f = 0x822D,
Rg32f = 0x8230,
Rgba32f = 0x8814,
Rg8i = 0x8237,
Rgba8i = 0x8D8E,
Rg16ui = 0x823A,
Rgba16ui = 0x8D76,
Rgb10A2ui = 0x906F,
Rgba16 = 0x805B,
// PVRTC
CompressedRgbPvrtc2Bppv1Img = 0x8C01,
CompressedRgbPvrtc4Bppv1Img = 0x8C00,
CompressedRgbaPvrtc2Bppv1Img = 0x8C03,
CompressedRgbaPvrtc4Bppv1Img = 0x8C02,
// ATITC
AtcRgbaExplicitAlphaAmd = 0x8C93,
AtcRgbaInterpolatedAlphaAmd = 0x87EE,
// ETC1
Etc1 = 0x8D64,
Srgb = 0x8C40,
// ETC2 RGB8A1
Etc2Rgb8 = 0x9274,
Etc2Srgb8 = 0x9275,
Etc2Rgb8A1 = 0x9276,
Etc2Srgb8A1 = 0x9277,
Etc2Rgba8Eac = 0x9278,
Etc2SRgb8A8Eac = 0x9279,
}
internal enum PixelFormat
{
Rgba = 0x1908,
Rgb = 0x1907,
Luminance = 0x1909,
CompressedTextureFormats = 0x86A3,
Red = 0x1903,
Rg = 0x8227,
}
internal enum PixelType
{
UnsignedByte = 0x1401,
UnsignedShort565 = 0x8363,
UnsignedShort4444 = 0x8033,
UnsignedShort5551 = 0x8034,
Float = 0x1406,
HalfFloat = 0x140B,
HalfFloatOES = 0x8D61,
Byte = 0x1400,
UnsignedShort = 0x1403,
UnsignedInt1010102 = 0x8036,
}
internal enum PixelStoreParameter
{
UnpackAlignment = 0x0CF5,
PackAlignment = 0x0D05,
}
internal enum GLStencilFunction
{
Always = 0x0207,
Equal = 0x0202,
Greater = 0x0204,
Gequal = 0x0206,
Less = 0x0201,
Lequal = 0x0203,
Never = 0x0200,
Notequal = 0x0205,
}
internal enum StencilOp
{
Keep = 0x1E00,
DecrWrap = 0x8508,
Decr = 0x1E03,
Incr = 0x1E02,
IncrWrap = 0x8507,
Invert = 0x150A,
Replace = 0x1E01,
Zero = 0,
}
internal enum TextureParameterName
{
TextureMaxAnisotropyExt = 0x84FE,
TextureBaseLevel = 0x813C,
TextureMaxLevel = 0x813D,
TextureMinFilter = 0x2801,
TextureMagFilter = 0x2800,
TextureWrapS = 0x2802,
TextureWrapT = 0x2803,
TextureBorderColor = 0x1004,
TextureLodBias = 0x8501,
TextureCompareMode = 0x884C,
TextureCompareFunc = 0x884D,
GenerateMipmap = 0x8191,
}
internal enum Bool
{
True = 1,
False = 0,
}
internal enum TextureMinFilter
{
LinearMipmapNearest = 0x2701,
NearestMipmapLinear = 0x2702,
LinearMipmapLinear = 0x2703,
Linear = 0x2601,
NearestMipmapNearest = 0x2700,
Nearest = 0x2600,
}
internal enum TextureMagFilter
{
Linear = 0x2601,
Nearest = 0x2600,
}
internal enum TextureCompareMode
{
CompareRefToTexture = 0x884E,
None = 0,
}
internal enum TextureWrapMode
{
ClampToEdge = 0x812F,
Repeat = 0x2901,
MirroredRepeat = 0x8370,
//GLES
ClampToBorder = 0x812D,
}
internal partial class ColorFormat
{
internal ColorFormat (int r, int g, int b, int a)
{
R = r;
G = g;
B = b;
A = a;
}
internal int R { get; private set; }
internal int G { get; private set; }
internal int B { get; private set; }
internal int A { get; private set; }
}
internal partial class GL
{
internal enum RenderApi
{
ES = 12448,
GL = 12450,
}
internal static RenderApi BoundApi = RenderApi.GL;
private const CallingConvention callingConvention = CallingConvention.Winapi;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void EnableVertexAttribArrayDelegate(int attrib);
internal static EnableVertexAttribArrayDelegate EnableVertexAttribArray;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void DisableVertexAttribArrayDelegate(int attrib);
internal static DisableVertexAttribArrayDelegate DisableVertexAttribArray;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void MakeCurrentDelegate(IntPtr window);
internal static MakeCurrentDelegate MakeCurrent;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal unsafe delegate void GetIntegerDelegate(int param, [Out] int* data);
internal static GetIntegerDelegate GetIntegerv;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate IntPtr GetStringDelegate(StringName param);
internal static GetStringDelegate GetStringInternal;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void ClearDepthDelegate(float depth);
internal static ClearDepthDelegate ClearDepth;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void DepthRangedDelegate(double min, double max);
internal static DepthRangedDelegate DepthRanged;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void DepthRangefDelegate(float min, float max);
internal static DepthRangefDelegate DepthRangef;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void ClearDelegate(ClearBufferMask mask);
internal static ClearDelegate Clear;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void ClearColorDelegate(float red, float green, float blue, float alpha);
internal static ClearColorDelegate ClearColor;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void ClearStencilDelegate(int stencil);
internal static ClearStencilDelegate ClearStencil;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void ViewportDelegate(int x, int y, int w, int h);
internal static ViewportDelegate Viewport;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate ErrorCode GetErrorDelegate();
internal static GetErrorDelegate GetError;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void FlushDelegate();
internal static FlushDelegate Flush;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void GenTexturesDelegte(int count, [Out] out int id);
internal static GenTexturesDelegte GenTextures;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void BindTextureDelegate(TextureTarget target, int id);
internal static BindTextureDelegate BindTexture;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate int EnableDelegate(EnableCap cap);
internal static EnableDelegate Enable;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate int DisableDelegate(EnableCap cap);
internal static DisableDelegate Disable;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void CullFaceDelegate(CullFaceMode mode);
internal static CullFaceDelegate CullFace;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void FrontFaceDelegate(FrontFaceDirection direction);
internal static FrontFaceDelegate FrontFace;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void PolygonModeDelegate(MaterialFace face, PolygonMode mode);
internal static PolygonModeDelegate PolygonMode;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void PolygonOffsetDelegate(float slopeScaleDepthBias, float depthbias);
internal static PolygonOffsetDelegate PolygonOffset;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void DrawBuffersDelegate(int count, DrawBuffersEnum[] buffers);
internal static DrawBuffersDelegate DrawBuffers;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void UseProgramDelegate(int program);
internal static UseProgramDelegate UseProgram;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal unsafe delegate void Uniform4fvDelegate(int location, int size, float* values);
internal static Uniform4fvDelegate Uniform4fv;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void Uniform1iDelegate(int location, int value);
internal static Uniform1iDelegate Uniform1i;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void ScissorDelegate(int x, int y, int width, int height);
internal static ScissorDelegate Scissor;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void ReadPixelsDelegate(int x, int y, int width, int height, PixelFormat format, PixelType type, IntPtr data);
internal static ReadPixelsDelegate ReadPixelsInternal;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void BindBufferDelegate(BufferTarget target, int buffer);
internal static BindBufferDelegate BindBuffer;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void DrawElementsDelegate(GLPrimitiveType primitiveType, int count, DrawElementsType elementType, IntPtr offset);
internal static DrawElementsDelegate DrawElements;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void DrawArraysDelegate(GLPrimitiveType primitiveType, int offset, int count);
internal static DrawArraysDelegate DrawArrays;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void GenRenderbuffersDelegate(int count, [Out] out int buffer);
internal static GenRenderbuffersDelegate GenRenderbuffers;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void BindRenderbufferDelegate(RenderbufferTarget target, int buffer);
internal static BindRenderbufferDelegate BindRenderbuffer;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void DeleteRenderbuffersDelegate(int count, [In] [Out] ref int buffer);
internal static DeleteRenderbuffersDelegate DeleteRenderbuffers;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void RenderbufferStorageMultisampleDelegate(RenderbufferTarget target, int sampleCount,
RenderbufferStorage storage, int width, int height);
internal static RenderbufferStorageMultisampleDelegate RenderbufferStorageMultisample;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void GenFramebuffersDelegate(int count, out int buffer);
internal static GenFramebuffersDelegate GenFramebuffers;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void BindFramebufferDelegate(FramebufferTarget target, int buffer);
internal static BindFramebufferDelegate BindFramebuffer;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void DeleteFramebuffersDelegate(int count, ref int buffer);
internal static DeleteFramebuffersDelegate DeleteFramebuffers;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
public delegate void InvalidateFramebufferDelegate(FramebufferTarget target, int numAttachments, FramebufferAttachment[] attachments);
public static InvalidateFramebufferDelegate InvalidateFramebuffer;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void FramebufferTexture2DDelegate(FramebufferTarget target, FramebufferAttachment attachement,
TextureTarget textureTarget, int texture, int level);
internal static FramebufferTexture2DDelegate FramebufferTexture2D;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void FramebufferTexture2DMultiSampleDelegate(FramebufferTarget target, FramebufferAttachment attachement,
TextureTarget textureTarget, int texture, int level, int samples);
internal static FramebufferTexture2DMultiSampleDelegate FramebufferTexture2DMultiSample;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void FramebufferRenderbufferDelegate(FramebufferTarget target, FramebufferAttachment attachement,
RenderbufferTarget renderBufferTarget, int buffer);
internal static FramebufferRenderbufferDelegate FramebufferRenderbuffer;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
public delegate void RenderbufferStorageDelegate(RenderbufferTarget target, RenderbufferStorage storage, int width, int hegiht);
public static RenderbufferStorageDelegate RenderbufferStorage;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void GenerateMipmapDelegate(GenerateMipmapTarget target);
internal static GenerateMipmapDelegate GenerateMipmap;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void ReadBufferDelegate(ReadBufferMode buffer);
internal static ReadBufferDelegate ReadBuffer;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void DrawBufferDelegate(DrawBufferMode buffer);
internal static DrawBufferDelegate DrawBuffer;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void BlitFramebufferDelegate(int srcX0,
int srcY0,
int srcX1,
int srcY1,
int dstX0,
int dstY0,
int dstX1,
int dstY1,
ClearBufferMask mask,
BlitFramebufferFilter filter);
internal static BlitFramebufferDelegate BlitFramebuffer;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate FramebufferErrorCode CheckFramebufferStatusDelegate(FramebufferTarget target);
internal static CheckFramebufferStatusDelegate CheckFramebufferStatus;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void TexParameterFloatDelegate(TextureTarget target, TextureParameterName name, float value);
internal static TexParameterFloatDelegate TexParameterf;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal unsafe delegate void TexParameterFloatArrayDelegate(TextureTarget target, TextureParameterName name, float* values);
internal static TexParameterFloatArrayDelegate TexParameterfv;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void TexParameterIntDelegate(TextureTarget target, TextureParameterName name, int value);
internal static TexParameterIntDelegate TexParameteri;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void GenQueriesDelegate(int count, [Out] out int queryId);
internal static GenQueriesDelegate GenQueries;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void BeginQueryDelegate(QueryTarget target, int queryId);
internal static BeginQueryDelegate BeginQuery;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void EndQueryDelegate(QueryTarget target);
internal static EndQueryDelegate EndQuery;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void GetQueryObjectDelegate(int queryId, GetQueryObjectParam getparam, [Out] out int ready);
internal static GetQueryObjectDelegate GetQueryObject;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void DeleteQueriesDelegate(int count, [In] [Out] ref int queryId);
internal static DeleteQueriesDelegate DeleteQueries;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void ActiveTextureDelegate(TextureUnit textureUnit);
internal static ActiveTextureDelegate ActiveTexture;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate int CreateShaderDelegate(ShaderType type);
internal static CreateShaderDelegate CreateShader;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal unsafe delegate void ShaderSourceDelegate(int shaderId, int count, IntPtr code, int* length);
internal static ShaderSourceDelegate ShaderSourceInternal;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void CompileShaderDelegate(int shaderId);
internal static CompileShaderDelegate CompileShader;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal unsafe delegate void GetShaderDelegate(int shaderId, int parameter, int* value);
internal static GetShaderDelegate GetShaderiv;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void GetShaderInfoLogDelegate(int shader, int bufSize, IntPtr length, StringBuilder infoLog);
internal static GetShaderInfoLogDelegate GetShaderInfoLogInternal;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate bool IsShaderDelegate(int shaderId);
internal static IsShaderDelegate IsShader;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void DeleteShaderDelegate(int shaderId);
internal static DeleteShaderDelegate DeleteShader;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate int GetAttribLocationDelegate(int programId, string name);
internal static GetAttribLocationDelegate GetAttribLocation;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate int GetUniformLocationDelegate(int programId, string name);
internal static GetUniformLocationDelegate GetUniformLocation;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate bool IsProgramDelegate(int programId);
internal static IsProgramDelegate IsProgram;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void DeleteProgramDelegate(int programId);
internal static DeleteProgramDelegate DeleteProgram;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate int CreateProgramDelegate();
internal static CreateProgramDelegate CreateProgram;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void AttachShaderDelegate(int programId, int shaderId);
internal static AttachShaderDelegate AttachShader;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void LinkProgramDelegate(int programId);
internal static LinkProgramDelegate LinkProgram;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal unsafe delegate void GetProgramDelegate(int programId, int name, int* linked);
internal static GetProgramDelegate GetProgramiv;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void GetProgramInfoLogDelegate(int program, int bufSize, IntPtr length, StringBuilder infoLog);
internal static GetProgramInfoLogDelegate GetProgramInfoLogInternal;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void DetachShaderDelegate(int programId, int shaderId);
internal static DetachShaderDelegate DetachShader;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void BlendColorDelegate(float r, float g, float b, float a);
internal static BlendColorDelegate BlendColor;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void BlendEquationSeparateDelegate(BlendEquationMode colorMode, BlendEquationMode alphaMode);
internal static BlendEquationSeparateDelegate BlendEquationSeparate;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void BlendEquationSeparateiDelegate(int buffer, BlendEquationMode colorMode, BlendEquationMode alphaMode);
internal static BlendEquationSeparateiDelegate BlendEquationSeparatei;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void BlendFuncSeparateDelegate(BlendingFactorSrc colorSrc, BlendingFactorDest colorDst,
BlendingFactorSrc alphaSrc, BlendingFactorDest alphaDst);
internal static BlendFuncSeparateDelegate BlendFuncSeparate;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void BlendFuncSeparateiDelegate(int buffer, BlendingFactorSrc colorSrc, BlendingFactorDest colorDst,
BlendingFactorSrc alphaSrc, BlendingFactorDest alphaDst);
internal static BlendFuncSeparateiDelegate BlendFuncSeparatei;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void ColorMaskDelegate(bool r, bool g, bool b, bool a);
internal static ColorMaskDelegate ColorMask;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void DepthFuncDelegate(DepthFunction function);
internal static DepthFuncDelegate DepthFunc;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void DepthMaskDelegate(bool enabled);
internal static DepthMaskDelegate DepthMask;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void StencilFuncSeparateDelegate(StencilFace face, GLStencilFunction function, int referenceStencil, int mask);
internal static StencilFuncSeparateDelegate StencilFuncSeparate;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void StencilOpSeparateDelegate(StencilFace face, StencilOp stencilfail, StencilOp depthFail, StencilOp pass);
internal static StencilOpSeparateDelegate StencilOpSeparate;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void StencilFuncDelegate(GLStencilFunction function, int referenceStencil, int mask);
internal static StencilFuncDelegate StencilFunc;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void StencilOpDelegate(StencilOp stencilfail, StencilOp depthFail, StencilOp pass);
internal static StencilOpDelegate StencilOp;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void StencilMaskDelegate(int mask);
internal static StencilMaskDelegate StencilMask;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void CompressedTexImage2DDelegate(TextureTarget target, int level, PixelInternalFormat internalFormat,
int width, int height, int border, int size, IntPtr data);
internal static CompressedTexImage2DDelegate CompressedTexImage2D;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void TexImage2DDelegate(TextureTarget target, int level, PixelInternalFormat internalFormat,
int width, int height, int border, PixelFormat format, PixelType pixelType, IntPtr data);
internal static TexImage2DDelegate TexImage2D;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void CompressedTexSubImage2DDelegate(TextureTarget target, int level,
int x, int y, int width, int height, PixelInternalFormat format, int size, IntPtr data);
internal static CompressedTexSubImage2DDelegate CompressedTexSubImage2D;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void TexSubImage2DDelegate(TextureTarget target, int level,
int x, int y, int width, int height, PixelFormat format, PixelType pixelType, IntPtr data);
internal static TexSubImage2DDelegate TexSubImage2D;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void PixelStoreDelegate(PixelStoreParameter parameter, int size);
internal static PixelStoreDelegate PixelStore;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void FinishDelegate();
internal static FinishDelegate Finish;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void GetTexImageDelegate(TextureTarget target, int level, PixelFormat format, PixelType type, [Out] IntPtr pixels);
internal static GetTexImageDelegate GetTexImageInternal;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void GetCompressedTexImageDelegate(TextureTarget target, int level, [Out] IntPtr pixels);
internal static GetCompressedTexImageDelegate GetCompressedTexImageInternal;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void TexImage3DDelegate(TextureTarget target, int level, PixelInternalFormat internalFormat,
int width, int height, int depth, int border, PixelFormat format, PixelType pixelType, IntPtr data);
internal static TexImage3DDelegate TexImage3D;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void TexSubImage3DDelegate(TextureTarget target, int level,
int x, int y, int z, int width, int height, int depth, PixelFormat format, PixelType pixelType, IntPtr data);
internal static TexSubImage3DDelegate TexSubImage3D;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void DeleteTexturesDelegate(int count, ref int id);
internal static DeleteTexturesDelegate DeleteTextures;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void GenBuffersDelegate(int count, out int buffer);
internal static GenBuffersDelegate GenBuffers;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void BufferDataDelegate(BufferTarget target, IntPtr size, IntPtr n, BufferUsageHint usage);
internal static BufferDataDelegate BufferData;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate IntPtr MapBufferDelegate(BufferTarget target, BufferAccess access);
internal static MapBufferDelegate MapBuffer;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void UnmapBufferDelegate(BufferTarget target);
internal static UnmapBufferDelegate UnmapBuffer;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void BufferSubDataDelegate(BufferTarget target, IntPtr offset, IntPtr size, IntPtr data);
internal static BufferSubDataDelegate BufferSubData;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void DeleteBuffersDelegate(int count, [In] [Out] ref int buffer);
internal static DeleteBuffersDelegate DeleteBuffers;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void VertexAttribPointerDelegate(int location, int elementCount, VertexAttribPointerType type, bool normalize,
int stride, IntPtr data);
internal static VertexAttribPointerDelegate VertexAttribPointer;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void DrawElementsInstancedDelegate(GLPrimitiveType primitiveType, int count, DrawElementsType elementType,
IntPtr offset, int instanceCount);
internal static DrawElementsInstancedDelegate DrawElementsInstanced;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void DrawElementsInstancedBaseInstanceDelegate(GLPrimitiveType primitiveType, int count, DrawElementsType elementType,
IntPtr offset, int instanceCount, int baseInstance);
internal static DrawElementsInstancedBaseInstanceDelegate DrawElementsInstancedBaseInstance;
[System.Security.SuppressUnmanagedCodeSecurity()]
[UnmanagedFunctionPointer(callingConvention)]
[MonoNativeFunctionWrapper]
internal delegate void VertexAttribDivisorDelegate(int location, int frequency);
internal static VertexAttribDivisorDelegate VertexAttribDivisor;
#if DEBUG
[UnmanagedFunctionPointer (CallingConvention.StdCall)]
delegate void DebugMessageCallbackProc (int source, int type, int id, int severity, int length, IntPtr message, IntPtr userParam);
static DebugMessageCallbackProc DebugProc;
[System.Security.SuppressUnmanagedCodeSecurity ()]
[MonoNativeFunctionWrapper]
delegate void DebugMessageCallbackDelegate (DebugMessageCallbackProc callback, IntPtr userParam);
static DebugMessageCallbackDelegate DebugMessageCallback;
internal delegate void ErrorDelegate (string message);
internal static event ErrorDelegate OnError;
static void DebugMessageCallbackHandler(int source, int type, int id, int severity, int length, IntPtr message, IntPtr userParam)
{
var errorMessage = Marshal.PtrToStringAnsi(message);
System.Diagnostics.Debug.WriteLine(errorMessage);
if (OnError != null)
OnError(errorMessage);
}
#endif
internal static int SwapInterval { get; set; }
internal static void LoadEntryPoints ()
{
LoadPlatformEntryPoints ();
if (Viewport == null)
Viewport = LoadFunction<ViewportDelegate> ("glViewport");
if (Scissor == null)
Scissor = LoadFunction<ScissorDelegate> ("glScissor");
if (MakeCurrent == null)
MakeCurrent = LoadFunction<MakeCurrentDelegate> ("glMakeCurrent");
GetError = LoadFunction<GetErrorDelegate> ("glGetError");
TexParameterf = LoadFunction<TexParameterFloatDelegate> ("glTexParameterf");
TexParameterfv = LoadFunction<TexParameterFloatArrayDelegate> ("glTexParameterfv");
TexParameteri = LoadFunction<TexParameterIntDelegate> ("glTexParameteri");
EnableVertexAttribArray = LoadFunction<EnableVertexAttribArrayDelegate> ("glEnableVertexAttribArray");
DisableVertexAttribArray = LoadFunction<DisableVertexAttribArrayDelegate> ("glDisableVertexAttribArray");
GetIntegerv = LoadFunction<GetIntegerDelegate> ("glGetIntegerv");
GetStringInternal = LoadFunction<GetStringDelegate> ("glGetString");
ClearDepth = LoadFunction<ClearDepthDelegate> ("glClearDepth");
if (ClearDepth == null)
ClearDepth = LoadFunction<ClearDepthDelegate> ("glClearDepthf");
DepthRanged = LoadFunction<DepthRangedDelegate> ("glDepthRange");
DepthRangef = LoadFunction<DepthRangefDelegate> ("glDepthRangef");
Clear = LoadFunction<ClearDelegate> ("glClear");
ClearColor = LoadFunction<ClearColorDelegate> ("glClearColor");
ClearStencil = LoadFunction<ClearStencilDelegate> ("glClearStencil");
Flush = LoadFunction<FlushDelegate> ("glFlush");
GenTextures = LoadFunction<GenTexturesDelegte> ("glGenTextures");
BindTexture = LoadFunction<BindTextureDelegate> ("glBindTexture");
Enable = LoadFunction<EnableDelegate> ("glEnable");
Disable = LoadFunction<DisableDelegate> ("glDisable");
CullFace = LoadFunction<CullFaceDelegate> ("glCullFace");
FrontFace = LoadFunction<FrontFaceDelegate> ("glFrontFace");
PolygonMode = LoadFunction<PolygonModeDelegate> ("glPolygonMode");
PolygonOffset = LoadFunction<PolygonOffsetDelegate> ("glPolygonOffset");
BindBuffer = LoadFunction<BindBufferDelegate> ("glBindBuffer");
DrawBuffers = LoadFunction<DrawBuffersDelegate> ("glDrawBuffers");
DrawElements = LoadFunction<DrawElementsDelegate> ("glDrawElements");
DrawArrays = LoadFunction<DrawArraysDelegate> ("glDrawArrays");
Uniform1i = LoadFunction<Uniform1iDelegate> ("glUniform1i");
Uniform4fv = LoadFunction<Uniform4fvDelegate> ("glUniform4fv");
ReadPixelsInternal = LoadFunction<ReadPixelsDelegate>("glReadPixels");
ReadBuffer = LoadFunction<ReadBufferDelegate> ("glReadBuffer");
DrawBuffer = LoadFunction<DrawBufferDelegate> ("glDrawBuffer");
// Render Target Support. These might be null if they are not supported
// see GraphicsDevice.OpenGL.FramebufferHelper.cs for handling other extensions.
GenRenderbuffers = LoadFunction<GenRenderbuffersDelegate> ("glGenRenderbuffers");
BindRenderbuffer = LoadFunction<BindRenderbufferDelegate> ("glBindRenderbuffer");
DeleteRenderbuffers = LoadFunction<DeleteRenderbuffersDelegate> ("glDeleteRenderbuffers");
GenFramebuffers = LoadFunction<GenFramebuffersDelegate> ("glGenFramebuffers");
BindFramebuffer = LoadFunction<BindFramebufferDelegate> ("glBindFramebuffer");
DeleteFramebuffers = LoadFunction<DeleteFramebuffersDelegate> ("glDeleteFramebuffers");
FramebufferTexture2D = LoadFunction<FramebufferTexture2DDelegate> ("glFramebufferTexture2D");
FramebufferRenderbuffer = LoadFunction<FramebufferRenderbufferDelegate> ("glFramebufferRenderbuffer");
RenderbufferStorage = LoadFunction<RenderbufferStorageDelegate> ("glRenderbufferStorage");
RenderbufferStorageMultisample = LoadFunction<RenderbufferStorageMultisampleDelegate> ("glRenderbufferStorageMultisample");
GenerateMipmap = LoadFunction<GenerateMipmapDelegate> ("glGenerateMipmap");
BlitFramebuffer = LoadFunction<BlitFramebufferDelegate> ("glBlitFramebuffer");
CheckFramebufferStatus = LoadFunction<CheckFramebufferStatusDelegate> ("glCheckFramebufferStatus");
GenQueries = LoadFunction<GenQueriesDelegate> ("glGenQueries");
BeginQuery = LoadFunction<BeginQueryDelegate> ("glBeginQuery");
EndQuery = LoadFunction<EndQueryDelegate> ("glEndQuery");
GetQueryObject = LoadFunction<GetQueryObjectDelegate>("glGetQueryObjectuiv");
if (GetQueryObject == null)
GetQueryObject = LoadFunction<GetQueryObjectDelegate> ("glGetQueryObjectivARB");
if (GetQueryObject == null)
GetQueryObject = LoadFunction<GetQueryObjectDelegate> ("glGetQueryObjectiv");
DeleteQueries = LoadFunction<DeleteQueriesDelegate> ("glDeleteQueries");
ActiveTexture = LoadFunction<ActiveTextureDelegate> ("glActiveTexture");
CreateShader = LoadFunction<CreateShaderDelegate> ("glCreateShader");
ShaderSourceInternal = LoadFunction<ShaderSourceDelegate> ("glShaderSource");
CompileShader = LoadFunction<CompileShaderDelegate> ("glCompileShader");
GetShaderiv = LoadFunction<GetShaderDelegate> ("glGetShaderiv");
GetShaderInfoLogInternal = LoadFunction<GetShaderInfoLogDelegate> ("glGetShaderInfoLog");
IsShader = LoadFunction<IsShaderDelegate> ("glIsShader");
DeleteShader = LoadFunction<DeleteShaderDelegate> ("glDeleteShader");
GetAttribLocation = LoadFunction<GetAttribLocationDelegate> ("glGetAttribLocation");
GetUniformLocation = LoadFunction<GetUniformLocationDelegate> ("glGetUniformLocation");
IsProgram = LoadFunction<IsProgramDelegate> ("glIsProgram");
DeleteProgram = LoadFunction<DeleteProgramDelegate> ("glDeleteProgram");
CreateProgram = LoadFunction<CreateProgramDelegate> ("glCreateProgram");
AttachShader = LoadFunction<AttachShaderDelegate> ("glAttachShader");
UseProgram = LoadFunction<UseProgramDelegate> ("glUseProgram");
LinkProgram = LoadFunction<LinkProgramDelegate> ("glLinkProgram");
GetProgramiv = LoadFunction<GetProgramDelegate> ("glGetProgramiv");
GetProgramInfoLogInternal = LoadFunction<GetProgramInfoLogDelegate> ("glGetProgramInfoLog");
DetachShader = LoadFunction<DetachShaderDelegate> ("glDetachShader");
BlendColor = LoadFunction<BlendColorDelegate> ("glBlendColor");
BlendEquationSeparate = LoadFunction<BlendEquationSeparateDelegate> ("glBlendEquationSeparate");
BlendEquationSeparatei = LoadFunction<BlendEquationSeparateiDelegate>("glBlendEquationSeparatei");
BlendFuncSeparate = LoadFunction<BlendFuncSeparateDelegate> ("glBlendFuncSeparate");
BlendFuncSeparatei = LoadFunction<BlendFuncSeparateiDelegate>("glBlendFuncSeparatei");
ColorMask = LoadFunction<ColorMaskDelegate> ("glColorMask");
DepthFunc = LoadFunction<DepthFuncDelegate> ("glDepthFunc");
DepthMask = LoadFunction<DepthMaskDelegate> ("glDepthMask");
StencilFuncSeparate = LoadFunction<StencilFuncSeparateDelegate> ("glStencilFuncSeparate");
StencilOpSeparate = LoadFunction<StencilOpSeparateDelegate> ("glStencilOpSeparate");
StencilFunc = LoadFunction<StencilFuncDelegate> ("glStencilFunc");
StencilOp = LoadFunction<StencilOpDelegate> ("glStencilOp");
StencilMask = LoadFunction<StencilMaskDelegate> ("glStencilMask");
CompressedTexImage2D = LoadFunction<CompressedTexImage2DDelegate> ("glCompressedTexImage2D");
TexImage2D = LoadFunction<TexImage2DDelegate> ("glTexImage2D");
CompressedTexSubImage2D = LoadFunction<CompressedTexSubImage2DDelegate> ("glCompressedTexSubImage2D");
TexSubImage2D = LoadFunction<TexSubImage2DDelegate> ("glTexSubImage2D");
PixelStore = LoadFunction<PixelStoreDelegate> ("glPixelStorei");
Finish = LoadFunction<FinishDelegate> ("glFinish");
GetTexImageInternal = LoadFunction<GetTexImageDelegate> ("glGetTexImage");
GetCompressedTexImageInternal = LoadFunction<GetCompressedTexImageDelegate> ("glGetCompressedTexImage");
TexImage3D = LoadFunction<TexImage3DDelegate> ("glTexImage3D");
TexSubImage3D = LoadFunction<TexSubImage3DDelegate> ("glTexSubImage3D");
DeleteTextures = LoadFunction<DeleteTexturesDelegate> ("glDeleteTextures");
GenBuffers = LoadFunction<GenBuffersDelegate> ("glGenBuffers");
BufferData = LoadFunction<BufferDataDelegate> ("glBufferData");
MapBuffer = LoadFunction<MapBufferDelegate> ("glMapBuffer");
UnmapBuffer = LoadFunction<UnmapBufferDelegate> ("glUnmapBuffer");
BufferSubData = LoadFunction<BufferSubDataDelegate> ("glBufferSubData");
DeleteBuffers = LoadFunction<DeleteBuffersDelegate> ("glDeleteBuffers");
VertexAttribPointer = LoadFunction<VertexAttribPointerDelegate> ("glVertexAttribPointer");
// Instanced drawing requires GL 3.2 or up, if the either of the following entry points can not be loaded
// this will get flagged by setting SupportsInstancing in GraphicsCapabilities to false.
try {
DrawElementsInstanced = LoadFunction<DrawElementsInstancedDelegate> ("glDrawElementsInstanced");
VertexAttribDivisor = LoadFunction<VertexAttribDivisorDelegate> ("glVertexAttribDivisor");
DrawElementsInstancedBaseInstance = LoadFunction<DrawElementsInstancedBaseInstanceDelegate>("glDrawElementsInstancedBaseInstance");
}
catch (EntryPointNotFoundException) {
// this will be detected in the initialization of GraphicsCapabilities
}
#if DEBUG
try
{
DebugMessageCallback = LoadFunction<DebugMessageCallbackDelegate>("glDebugMessageCallback");
if (DebugMessageCallback != null)
{
DebugProc = DebugMessageCallbackHandler;
DebugMessageCallback(DebugProc, IntPtr.Zero);
Enable(EnableCap.DebugOutput);
Enable(EnableCap.DebugOutputSynchronous);
}
}
catch (EntryPointNotFoundException)
{
// Ignore the debug message callback if the entry point can not be found
}
#endif
if (BoundApi == RenderApi.ES) {
InvalidateFramebuffer = LoadFunction<InvalidateFramebufferDelegate> ("glDiscardFramebufferEXT");
}
LoadExtensions ();
}
internal static List<string> Extensions = new List<string> ();
//[Conditional("DEBUG")]
//[DebuggerHidden]
static void LogExtensions()
{
#if __ANDROID__
Android.Util.Log.Verbose("GL","Supported Extensions");
foreach (var ext in Extensions)
Android.Util.Log.Verbose("GL", " " + ext);
#endif
}
internal static void LoadExtensions()
{
string extstring = GL.GetString(StringName.Extensions);
var error = GL.GetError();
if (!string.IsNullOrEmpty(extstring) && error == ErrorCode.NoError)
Extensions.AddRange(extstring.Split(' '));
LogExtensions();
// now load Extensions :)
if (GL.GenRenderbuffers == null && Extensions.Contains("GL_EXT_framebuffer_object"))
{
GL.LoadFrameBufferObjectEXTEntryPoints();
}
if (GL.RenderbufferStorageMultisample == null)
{
if (Extensions.Contains("GL_APPLE_framebuffer_multisample"))
{
GL.RenderbufferStorageMultisample = LoadFunction<GL.RenderbufferStorageMultisampleDelegate>("glRenderbufferStorageMultisampleAPPLE");
GL.BlitFramebuffer = LoadFunction<GL.BlitFramebufferDelegate>("glResolveMultisampleFramebufferAPPLE");
}
else if (Extensions.Contains("GL_EXT_multisampled_render_to_texture"))
{
GL.RenderbufferStorageMultisample = LoadFunction<GL.RenderbufferStorageMultisampleDelegate>("glRenderbufferStorageMultisampleEXT");
GL.FramebufferTexture2DMultiSample = LoadFunction<GL.FramebufferTexture2DMultiSampleDelegate>("glFramebufferTexture2DMultisampleEXT");
}
else if (Extensions.Contains("GL_IMG_multisampled_render_to_texture"))
{
GL.RenderbufferStorageMultisample = LoadFunction<GL.RenderbufferStorageMultisampleDelegate>("glRenderbufferStorageMultisampleIMG");
GL.FramebufferTexture2DMultiSample = LoadFunction<GL.FramebufferTexture2DMultiSampleDelegate>("glFramebufferTexture2DMultisampleIMG");
}
else if (Extensions.Contains("GL_NV_framebuffer_multisample"))
{
GL.RenderbufferStorageMultisample = LoadFunction<GL.RenderbufferStorageMultisampleDelegate>("glRenderbufferStorageMultisampleNV");
GL.BlitFramebuffer = LoadFunction<GL.BlitFramebufferDelegate>("glBlitFramebufferNV");
}
}
if (GL.BlendFuncSeparatei == null && Extensions.Contains("GL_ARB_draw_buffers_blend"))
{
GL.BlendFuncSeparatei = LoadFunction<GL.BlendFuncSeparateiDelegate>("BlendFuncSeparateiARB");
}
if (GL.BlendEquationSeparatei == null && Extensions.Contains("GL_ARB_draw_buffers_blend"))
{
GL.BlendEquationSeparatei = LoadFunction<GL.BlendEquationSeparateiDelegate>("BlendEquationSeparateiARB");
}
}
internal static void LoadFrameBufferObjectEXTEntryPoints()
{
GenRenderbuffers = LoadFunction<GenRenderbuffersDelegate>("glGenRenderbuffersEXT");
BindRenderbuffer = LoadFunction<BindRenderbufferDelegate>("glBindRenderbufferEXT");
DeleteRenderbuffers = LoadFunction<DeleteRenderbuffersDelegate>("glDeleteRenderbuffersEXT");
GenFramebuffers = LoadFunction<GenFramebuffersDelegate>("glGenFramebuffersEXT");
BindFramebuffer = LoadFunction<BindFramebufferDelegate>("glBindFramebufferEXT");
DeleteFramebuffers = LoadFunction<DeleteFramebuffersDelegate>("glDeleteFramebuffersEXT");
FramebufferTexture2D = LoadFunction<FramebufferTexture2DDelegate>("glFramebufferTexture2DEXT");
FramebufferRenderbuffer = LoadFunction<FramebufferRenderbufferDelegate>("glFramebufferRenderbufferEXT");
RenderbufferStorage = LoadFunction<RenderbufferStorageDelegate>("glRenderbufferStorageEXT");
RenderbufferStorageMultisample = LoadFunction<RenderbufferStorageMultisampleDelegate>("glRenderbufferStorageMultisampleEXT");
GenerateMipmap = LoadFunction<GenerateMipmapDelegate>("glGenerateMipmapEXT");
BlitFramebuffer = LoadFunction<BlitFramebufferDelegate>("glBlitFramebufferEXT");
CheckFramebufferStatus = LoadFunction<CheckFramebufferStatusDelegate>("glCheckFramebufferStatusEXT");
}
static partial void LoadPlatformEntryPoints();
internal static IGraphicsContext CreateContext(IWindowInfo info)
{
return PlatformCreateContext(info);
}
/* Helper Functions */
internal static void DepthRange(float min, float max)
{
if (BoundApi == RenderApi.ES)
DepthRangef(min, max);
else
DepthRanged(min, max);
}
internal static void Uniform1 (int location, int value) {
Uniform1i(location, value);
}
internal static unsafe void Uniform4 (int location, int size, float* value) {
Uniform4fv(location, size, value);
}
internal unsafe static string GetString (StringName name)
{
return Marshal.PtrToStringAnsi (GetStringInternal (name));
}
protected static IntPtr MarshalStringArrayToPtr (string[] strings)
{
IntPtr intPtr = IntPtr.Zero;
if (strings != null && strings.Length != 0) {
intPtr = Marshal.AllocHGlobal (strings.Length * IntPtr.Size);
if (intPtr == IntPtr.Zero) {
throw new OutOfMemoryException ();
}
int i = 0;
try {
for (i = 0; i < strings.Length; i++) {
IntPtr val = MarshalStringToPtr (strings [i]);
Marshal.WriteIntPtr (intPtr, i * IntPtr.Size, val);
}
}
catch (OutOfMemoryException) {
for (i--; i >= 0; i--) {
Marshal.FreeHGlobal (Marshal.ReadIntPtr (intPtr, i * IntPtr.Size));
}
Marshal.FreeHGlobal (intPtr);
throw;
}
}
return intPtr;
}
protected unsafe static IntPtr MarshalStringToPtr (string str)
{
if (string.IsNullOrEmpty (str)) {
return IntPtr.Zero;
}
int num = Encoding.ASCII.GetMaxByteCount (str.Length) + 1;
IntPtr intPtr = Marshal.AllocHGlobal (num);
if (intPtr == IntPtr.Zero) {
throw new OutOfMemoryException ();
}
fixed (char* chars = str + RuntimeHelpers.OffsetToStringData / 2) {
int bytes = Encoding.ASCII.GetBytes (chars, str.Length, (byte*)((void*)intPtr), num);
Marshal.WriteByte (intPtr, bytes, 0);
return intPtr;
}
}
protected static void FreeStringArrayPtr (IntPtr ptr, int length)
{
for (int i = 0; i < length; i++) {
Marshal.FreeHGlobal (Marshal.ReadIntPtr (ptr, i * IntPtr.Size));
}
Marshal.FreeHGlobal (ptr);
}
internal static string GetProgramInfoLog (int programId)
{
int length = 0;
GetProgram(programId, GetProgramParameterName.LogLength, out length);
var sb = new StringBuilder();
GetProgramInfoLogInternal (programId, length, IntPtr.Zero, sb);
return sb.ToString();
}
internal static string GetShaderInfoLog (int shaderId) {
int length = 0;
GetShader(shaderId, ShaderParameter.LogLength, out length);
var sb = new StringBuilder();
GetShaderInfoLogInternal (shaderId, length, IntPtr.Zero, sb);
return sb.ToString();
}
internal unsafe static void ShaderSource(int shaderId, string code)
{
int length = code.Length;
IntPtr intPtr = MarshalStringArrayToPtr (new string[] { code });
ShaderSourceInternal(shaderId, 1, intPtr, &length);
FreeStringArrayPtr(intPtr, 1);
}
internal unsafe static void GetShader (int shaderId, ShaderParameter name, out int result)
{
fixed (int* ptr = &result)
{
GetShaderiv(shaderId, (int)name, ptr);
}
}
internal unsafe static void GetProgram(int programId, GetProgramParameterName name, out int result)
{
fixed (int* ptr = &result)
{
GetProgramiv(programId, (int)name, ptr);
}
}
internal unsafe static void GetInteger (GetPName name, out int value)
{
fixed (int* ptr = &value) {
GetIntegerv ((int)name, ptr);
}
}
internal unsafe static void GetInteger (int name, out int value)
{
fixed (int* ptr = &value)
{
GetIntegerv (name, ptr);
}
}
internal static void TexParameter(TextureTarget target, TextureParameterName name, float value)
{
TexParameterf(target, name, value);
}
internal unsafe static void TexParameter(TextureTarget target, TextureParameterName name, float[] values)
{
fixed (float* ptr = &values[0])
{
TexParameterfv(target, name, ptr);
}
}
internal static void TexParameter(TextureTarget target, TextureParameterName name, int value)
{
TexParameteri(target, name, value);
}
internal static void GetTexImage<T>(TextureTarget target, int level, PixelFormat format, PixelType type, T[] pixels) where T : struct
{
var pixelsPtr = GCHandle.Alloc(pixels, GCHandleType.Pinned);
try
{
GetTexImageInternal(target, level, format, type, pixelsPtr.AddrOfPinnedObject());
}
finally
{
pixelsPtr.Free();
}
}
internal static void GetCompressedTexImage<T>(TextureTarget target, int level, T[] pixels) where T : struct
{
var pixelsPtr = GCHandle.Alloc(pixels, GCHandleType.Pinned);
try
{
GetCompressedTexImageInternal(target, level, pixelsPtr.AddrOfPinnedObject());
}
finally
{
pixelsPtr.Free();
}
}
public static void ReadPixels<T>(int x, int y, int width, int height, PixelFormat format, PixelType type, T[] data)
{
var dataPtr = GCHandle.Alloc(data, GCHandleType.Pinned);
try
{
ReadPixelsInternal(x, y, width, height, format, type, dataPtr.AddrOfPinnedObject());
}
finally
{
dataPtr.Free();
}
}
}
}
| 41.887515 | 154 | 0.686369 | [
"MIT"
] | moolicc/MonoGame | MonoGame.Framework/Platform/Graphics/OpenGL.cs | 71,127 | C# |
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
namespace Microsoft.WindowsAzure.MobileServices.Test
{
/// <summary>
/// Provides access to platform-specific framework API's.
/// </summary>
public static class TestPlatform
{
public static readonly string Net45 = "Net45";
public static readonly string WindowsStore = "WindowsStore";
public static readonly string WindowsPhone8 = "WindowsPhone8";
public static readonly string WindowsPhone81 = "WindowsPhone81";
public static readonly string XamarinAndroid = "XamarinAndroid";
public static readonly string XamariniOS = "XamariniOS";
public static string GetMobileServicesSdkVersion(Assembly executingAssembly)
{
string packagesConfigResourceName = executingAssembly.GetManifestResourceNames().FirstOrDefault(s => s.EndsWith(".packages.config"));
if (packagesConfigResourceName == null)
return "?";
using (Stream stream = executingAssembly.GetManifestResourceStream(packagesConfigResourceName))
{
StreamReader reader = new StreamReader(stream);
string result = reader.ReadToEnd();
string line = result.Split('\n').FirstOrDefault(s => s.Contains("\"WindowsAzure.MobileServices\""));
if (line == null)
return "?";
const string versionSearchString = "version=\"";
int index = line.IndexOf(versionSearchString);
if (index < 0 || index + versionSearchString.Length >= line.Length)
return "?";
int closeIndex = line.IndexOf('"', index + versionSearchString.Length);
if (closeIndex < 0)
return "?";
return line.Substring(index + versionSearchString.Length, closeIndex - index - versionSearchString.Length);
}
}
/// <summary>
/// The string value to use for the operating system name, arch, or version if
/// the value is unknown.
/// </summary>
public const string UnknownValueString = "--";
private static ITestPlatform current;
/// <summary>
/// Name of the assembly containing the Class with the <see cref="Platform.PlatformTypeFullName"/> name.
/// </summary>
public static IList<string> PlatformAssemblyNames = new string[]
{
"Microsoft.WindowsAzure.Mobile.Win8.Test2",
"Microsoft.WindowsAzure.Mobile.WP8.Test2",
"Microsoft.WindowsAzure.Mobile.WP81.Test2",
"Microsoft.WindowsAzure.Mobile.Android.Test2",
"MicrosoftWindowsAzureMobileiOSE2ETest"
};
/// <summary>
/// Name of the type implementing <see cref="IPlatform"/>.
/// </summary>
public static string PlatformTypeFullName = "Microsoft.WindowsAzure.MobileServices.Test.CurrentTestPlatform";
/// <summary>
/// Gets the current platform. If none is loaded yet, accessing this property triggers platform resolution.
/// </summary>
public static ITestPlatform Instance
{
get
{
// create if not yet created
if (current == null)
{
// assume the platform assembly has the same key, same version and same culture
// as the assembly where the ITestPlatform interface lives.
var provider = typeof(ITestPlatform);
var asm = new AssemblyName(provider.GetTypeInfo().Assembly.FullName);
// change name to the specified name
foreach (string assemblyName in PlatformAssemblyNames)
{
asm.Name = assemblyName;
var name = PlatformTypeFullName + ", " + asm.FullName;
//look for the type information but do not throw if not found
var type = Type.GetType(name, false);
if (type != null)
{
// create type
// since we are the only one implementing this interface
// this cast is safe.
current = (ITestPlatform)Activator.CreateInstance(type);
return current;
}
}
current = new MissingTestPlatform();
}
return current;
}
// keep this public so we can set a TestPlatform for unit testing.
set
{
current = value;
}
}
}
} | 41.713115 | 145 | 0.545294 | [
"Apache-2.0"
] | Reminouche/azure-mobile-apps-net-client | e2etest/E2ETest/TestPlatform/TestPlatform.cs | 5,091 | C# |
using System.Data;
using IntegraData;
using System.Data.SqlClient;
using System;
using System.Text;
using System.Security.Cryptography;
using System.Collections.Generic;
using System.Net;
using System.Net.Mail;
using System.Web.Configuration;
namespace IntegraBussines
{
public class HerramientasController
{
string key = "mikey";
/// <summary>
/// Funcion Encripta
/// </summary>
/// <param name="texto">recibe texto a encriptar</param>
/// <returns>regresa texto de encriptada</returns>
public string gfEncriptar(string texto)
{
//mikey
//arreglo de bytes donde guardaremos la llave
byte[] keyArray;
//arreglo de bytes donde guardaremos el texto
//que vamos a encriptar
byte[] Arreglo_a_Cifrar = UTF8Encoding.UTF8.GetBytes(texto);
//se utilizan las clases de encriptación
//provistas por el Framework
//Algoritmo MD5
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
//se guarda la llave para que se le realice
//hashing
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd5.Clear();
//Algoritmo 3DAS
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
//se empieza con la transformación de la cadena
ICryptoTransform cTransform = tdes.CreateEncryptor();
//arreglo de bytes donde se guarda la
//cadena cifrada
byte[] ArrayResultado = cTransform.TransformFinalBlock(Arreglo_a_Cifrar, 0, Arreglo_a_Cifrar.Length);
tdes.Clear();
//se regresa el resultado en forma de una cadena
return Convert.ToBase64String(ArrayResultado, 0, ArrayResultado.Length);
}
/// <summary>
/// Funcion que desencripta
/// </summary>
/// <param name="textoEncriptado">recibe texto encriptado</param>
/// <returns>regresa texto de encriptada</returns>
public string gfDesencriptar(string textoEncriptado)
{
byte[] keyArray;
//convierte el texto en una secuencia de bytes
byte[] Array_a_Descifrar = Convert.FromBase64String(textoEncriptado);
//byte[] data = Convert.FromBase64String(encodedString);
//string decodedString = Encoding.UTF8.GetString(Array_a_Descifrar);
//se llama a las clases que tienen los algoritmos
//de encriptación se le aplica hashing
//algoritmo MD5
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd5.Clear();
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(Array_a_Descifrar, 0, Array_a_Descifrar.Length);
tdes.Clear();
//se regresa en forma de cadena
return UTF8Encoding.UTF8.GetString(resultArray);
}
/// <summary>
/// Función que registra usuario bloqueado , email a enviar liga de desbloqueo y libera al usuario
/// </summary>
/// <param name="psLIGAENCRIPTADA">Link</param>
/// <param name="psUSUARIOATRAPADO">Numero de usuario</param>
/// <param name="psEMPRESA">Numero de empresa</param>
/// <param name="psEMAIL">Email a enviar</param>
/// <param name="piOPCION">1 registra, 2 elimina liga y desbloquea usuario</param>
public static void gfRegistraDesbloqueaUsuario(string psLIGAENCRIPTADA, string psUSUARIOATRAPADO, string psEMPRESA, string psEMAIL, int piOPCION)
{
DataTable dt = new DataTable();
SQLConection context = new SQLConection();
context.Parametros.Clear();
context.Parametros.Add(new SqlParameter("@LIGAENCRIPTADA ", psLIGAENCRIPTADA));
context.Parametros.Add(new SqlParameter("@USUARIOATRAPADO", psUSUARIOATRAPADO));
context.Parametros.Add(new SqlParameter("@EMPRESA", psEMPRESA));
context.Parametros.Add(new SqlParameter("@EMAIL", psEMAIL));
context.Parametros.Add(new SqlParameter("@OPCION", piOPCION));
dt = context.ExecuteProcedure("[sp_LOG_DesbloqueaUsuarios]", true).Copy();
}
/// <summary>
/// Envia correo de facturación con la liga de desbloqueo
/// </summary>
/// <param name="psLigaDesbloqueo"></param>
/// <param name="plistaContactos"></param>
/// <param name="piNumeroEmpresa"></param>
public static void gfEmailSend(string psLigaDesbloqueo, List<string> plistaContactos, int piNumeroEmpresa)
{
string sMsgEmail = string.Concat("<p style='font-family:Tahoma;font-size:12px;color:#000'>----------------------------------------------------------------------------------------------------------------------------------------------------<br/><br/>Apreciable Cliente <br> En el presente correo encontraras una liga para desbloquear tu usuario quedamos a sus órdenes. <p/>",
"<a href='", psLigaDesbloqueo, "'> Desbloquear usuario </a>");
try
{
var EmailloginInfo = new NetworkCredential(WebConfigurationManager.AppSettings["EmailAccount"],
WebConfigurationManager.AppSettings["EmailPassword"]);
var Emailmsg = new System.Net.Mail.MailMessage();
var EmailsmtpClient = new SmtpClient(WebConfigurationManager.AppSettings["EmailSMTP"],
int.Parse(WebConfigurationManager.AppSettings["EmailPORT"].ToString()));
Emailmsg.From = new MailAddress(WebConfigurationManager.AppSettings["EmailAccount"]);
foreach (string contacto in plistaContactos)
Emailmsg.To.Add(new MailAddress(contacto));
Emailmsg.Subject = "Notificación de Desbloqueo de usuario";
Emailmsg.IsBodyHtml = true;
Emailmsg.Body = sMsgEmail;
EmailsmtpClient.EnableSsl = false;
EmailsmtpClient.UseDefaultCredentials = false;
EmailsmtpClient.Credentials = EmailloginInfo;
EmailsmtpClient.Send(Emailmsg);
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
}
/// <summary>
/// Manda email con link de desbloqueo , desbloquea usuario con la liga enviado al correo
/// </summary>
/// <param name="psInfoEncriptada"></param>
/// <param name="iOpcion"></param>
/// <returns></returns>
public static bool gfDesbloqueUsuario(string psInfoEncriptada, int iOpcion)
{
string sTextoDescriptado = string.Empty;
string sLigaDesbloqueo = string.Concat(WebConfigurationManager.AppSettings["LigaDesbloqueo"].ToString(), psInfoEncriptada);
string[] sIDValor;
try
{
if (iOpcion == 1)
{
sTextoDescriptado = new HerramientasController().gfDesencriptar(psInfoEncriptada);
sIDValor = sTextoDescriptado.Split('|');
string sEmailTemp = sIDValor[0].Replace('+', '@');
sEmailTemp = sIDValor[0].Replace('-', '.');
List<string> listaEmail = new List<string>();
listaEmail.Add(sEmailTemp);
HerramientasController.gfEmailSend(sLigaDesbloqueo, listaEmail, int.Parse(sIDValor[1]));
}
else
{
sTextoDescriptado = new HerramientasController().gfDesencriptar(psInfoEncriptada);
sIDValor = sTextoDescriptado.Split('|');
string sEmailTemp = sIDValor[0].Replace('+', '@');
sEmailTemp = sIDValor[0].Replace('-', '.');
HerramientasController.gfRegistraDesbloqueaUsuario(string.Concat(psInfoEncriptada), sIDValor[1], sIDValor[2], sEmailTemp, 2);
}
return true;
}
catch
{
gfDesbloqueUsuario(psInfoEncriptada, iOpcion);
return false;
}
}
}
}
| 47.358289 | 385 | 0.587624 | [
"MIT"
] | bd3717eb/KONEXUS | IntegraBussines/HerramientasController.cs | 8,865 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Threading.Tasks;
using Meticulous.Patterns;
namespace Meticulous.SandBox
{
}
| 20.647059 | 46 | 0.831909 | [
"MIT"
] | tarik-s/Basis | SandBoxes/Basis.SandBox/CodeGeneration.cs | 353 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
namespace WebClient
{
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.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services
.AddDbContext<IdentityDbContext>(
options =>
{
options.UseInMemoryDatabase(databaseName: "TEST_DB");
}
);
services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<IdentityDbContext>()
.AddDefaultTokenProviders();
services
.AddAuthentication()
.AddOpenIdConnect(
options =>
{
options.ClientId = Configuration["Authentication:OIDC:Google:ClientId"];
options.ClientSecret = Configuration["Authentication:OIDC:Google:ClientSecret"];
options.Authority = Configuration["Authentication:OIDC:Google:Authority"];
options.ResponseType = OpenIdConnectResponseType.CodeIdTokenToken;
options.GetClaimsFromUserInfoEndpoint = true;
options.SaveTokens = true;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc();
}
}
}
| 35.176471 | 119 | 0.597993 | [
"MIT"
] | azydevelopment/aspnet-resttest | RestTest/WebClient/Startup.cs | 2,990 | 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;
internal struct T
{
public string S;
public string SomeOtherString;
public T(string _S)
{
S = _S;
SomeOtherString = null;
}
//
//For the testcase to fail, get_TheString must be inlined
//into bar() which our current heuristics do
//
public string TheString
{
get { return (S != null ? S : "<nothing>"); }
}
}
internal class Tester
{
public static int Main()
{
T t1,
t2;
t1 = new T();
t2 = new T("passed.");
bar(t1);
bar(t2);
return 100;
}
public static void bar(T t)
{
Console.WriteLine(t.TheString);
}
}
| 17.617021 | 71 | 0.55314 | [
"MIT"
] | belav/runtime | src/tests/JIT/jit64/regress/ndpw/21015/interior_pointer.cs | 828 | C# |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using DigitalOcean.Indicator.ViewModels;
using ReactiveUI;
namespace DigitalOcean.Indicator.Views {
/// <summary>
/// Interaction logic for PreferencesView.xaml
/// </summary>
public partial class PreferencesView : Window, IViewFor<PreferencesViewModel> {
public PreferencesView() {
InitializeComponent();
this.WhenActivated(d => {
d(ApiLink.Events().RequestNavigate
.Subscribe(x => Process.Start(x.Uri.ToString())));
d(this.Bind(ViewModel, x => x.ApiKey, x => x.ApiKey.Text));
d(this.Bind(ViewModel, x => x.RefreshInterval, x => x.RefreshInterval.Text));
d(this.BindCommand(ViewModel, x => x.Save, x => x.BtnSave));
d(this.BindCommand(ViewModel, x => x.Close, x => x.BtnClose));
d(this.WhenAnyObservable(x => x.ViewModel.Close)
.Subscribe(_ => Close()));
d(RefreshInterval.Events().PreviewTextInput
.Subscribe(x => {
int dontcare;
var parsed = int.TryParse(string.Format("{0}{1}", RefreshInterval.Text, x.Text),
out dontcare);
if (!parsed) {
x.Handled = true;
}
}));
});
}
#region IViewFor<PreferencesViewModel> Members
object IViewFor.ViewModel {
get { return ViewModel; }
set { ViewModel = (PreferencesViewModel)value; }
}
public PreferencesViewModel ViewModel { get; set; }
#endregion
protected override void OnClosing(CancelEventArgs e) {
base.OnClosing(e);
ViewModel.Closing.Execute(null);
}
}
} | 34.431034 | 104 | 0.549825 | [
"MIT"
] | vevix/DigitalOcean.Indicator | DigitalOcean.Indicator/Views/PreferencesView.xaml.cs | 1,999 | C# |
using System;
using System.Linq;
using Xamarin.Forms.PlatformConfiguration.iOSSpecific;
using UIKit;
namespace Xamarin.Forms.Platform.iOS
{
internal class ModalWrapper : UIViewController
{
IVisualElementRenderer _modal;
internal ModalWrapper(IVisualElementRenderer modal)
{
_modal = modal;
var elementConfiguration = modal.Element as IElementConfiguration<Page>;
var modalPresentationStyle = elementConfiguration?.On<PlatformConfiguration.iOS>()?.ModalPresentationStyle() ?? PlatformConfiguration.iOSSpecific.UIModalPresentationStyle.FullScreen;
ModalPresentationStyle = modalPresentationStyle.ToNativeModalPresentationStyle();
View.BackgroundColor = UIColor.White;
View.AddSubview(modal.ViewController.View);
TransitioningDelegate = modal.ViewController.TransitioningDelegate;
AddChildViewController(modal.ViewController);
modal.ViewController.DidMoveToParentViewController(this);
}
public override void DismissViewController(bool animated, Action completionHandler)
{
if (PresentedViewController == null)
{
// After dismissing a UIDocumentMenuViewController, (for instance, if a WebView with an Upload button
// is asking the user for a source (camera roll, etc.)), the view controller accidentally calls dismiss
// again on itself before presenting the UIImagePickerController; this leaves the UIImagePickerController
// without an anchor to the view hierarchy and it doesn't show up. This appears to be an iOS bug.
// We can work around it by ignoring the dismiss call when PresentedViewController is null.
return;
}
base.DismissViewController(animated, completionHandler);
}
public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations()
{
if ((ChildViewControllers != null) && (ChildViewControllers.Length > 0))
{
return ChildViewControllers[0].GetSupportedInterfaceOrientations();
}
return base.GetSupportedInterfaceOrientations();
}
public override UIInterfaceOrientation PreferredInterfaceOrientationForPresentation()
{
if ((ChildViewControllers != null) && (ChildViewControllers.Length > 0))
{
return ChildViewControllers[0].PreferredInterfaceOrientationForPresentation();
}
return base.PreferredInterfaceOrientationForPresentation();
}
public override bool ShouldAutorotate()
{
if ((ChildViewControllers != null) && (ChildViewControllers.Length > 0))
{
return ChildViewControllers[0].ShouldAutorotate();
}
return base.ShouldAutorotate();
}
public override bool ShouldAutorotateToInterfaceOrientation(UIInterfaceOrientation toInterfaceOrientation)
{
if ((ChildViewControllers != null) && (ChildViewControllers.Length > 0))
{
return ChildViewControllers[0].ShouldAutorotateToInterfaceOrientation(toInterfaceOrientation);
}
return base.ShouldAutorotateToInterfaceOrientation(toInterfaceOrientation);
}
public override bool ShouldAutomaticallyForwardRotationMethods => true;
public override void ViewDidLayoutSubviews()
{
base.ViewDidLayoutSubviews();
if (_modal != null)
_modal.SetElementSize(new Size(View.Bounds.Width, View.Bounds.Height));
}
public override void ViewWillAppear(bool animated)
{
View.BackgroundColor = UIColor.White;
base.ViewWillAppear(animated);
}
protected override void Dispose(bool disposing)
{
if (disposing)
_modal = null;
base.Dispose(disposing);
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
SetNeedsStatusBarAppearanceUpdate();
if (Forms.RespondsToSetNeedsUpdateOfHomeIndicatorAutoHidden)
SetNeedsUpdateOfHomeIndicatorAutoHidden();
}
public override UIViewController ChildViewControllerForStatusBarStyle()
{
return ChildViewControllers?.LastOrDefault();
}
}
} | 32.646552 | 185 | 0.773699 | [
"MIT"
] | 07101994/Xamarin.Forms | Xamarin.Forms.Platform.iOS/ModalWrapper.cs | 3,789 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright company="HillHouse" file="ILogger.cs">
// Copyright © 2009-2012 HillHouse
// </copyright>
// <summary>
// Logger interface
// </summary>
// <license>
// Licensed under the Ms-PL license.
// </license>
// <homepage>
// http://milsym.codeplex.com
// </homepage>
// --------------------------------------------------------------------------------------------------------------------
namespace MilSym.LoadResources
{
using System;
/// <summary>
/// Enum defining log levels to use in the common logging interface
/// </summary>
public enum LogLevel
{
/// <summary>
/// The message represents a fatal, unrecoverable error
/// </summary>
Fatal = 0,
/// <summary>
/// The message represents a recoverable error
/// </summary>
Error = 1,
/// <summary>
/// The message is a warning only
/// </summary>
Warn = 2,
/// <summary>
/// The message is simply informational
/// </summary>
Info = 3,
/// <summary>
/// The message is intended to detail progress or steps
/// </summary>
Verbose = 4
}
/// <summary>
/// The logger interface that log implementations are expected to support
/// </summary>
public interface ILogger
{
/// <summary>
/// Writes a message to the log
/// </summary>
/// <param name="level">The message level</param>
/// <param name="message">The message to write to the log</param>
void WriteMessage(LogLevel level, string message);
/// <summary>
/// Writes a message to the log
/// </summary>
/// <param name="level">The message level</param>
/// <param name="message">The message to write to the log</param>
/// <param name="exception">The exception to write to the log</param>
void WriteMessage(LogLevel level, string message, Exception exception);
}
}
| 29.583333 | 120 | 0.499061 | [
"MIT"
] | HillHouse/MilSym | Silverlight/LoadResources/ILogger.cs | 2,133 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApiDemo.Providers.LocalData
{
public class User
{
public int Id { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string Role { get; set; }
}
} | 23.375 | 44 | 0.628342 | [
"Apache-2.0"
] | vknvnn/requirejs | WebApiDemo/Providers/LocalData/User.cs | 376 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DnDTracker.Web.Objects.Character.Classes
{
public class MonkClass : ICharacterClass
{
public CharacterClassType Type { get; set; }
public List<CharacterSubClassType> SubTypes { get; set; }
public MonkClass()
{
Type = CharacterClassType.Monk;
SubTypes = new List<CharacterSubClassType>
{
CharacterSubClassType.WayOfTheOpenHand,
CharacterSubClassType.WayOfTheFourElements
};
}
}
}
| 25.875 | 65 | 0.634461 | [
"MIT"
] | itsmistad/DnDTracker | src/DnDTracker.Web/Objects/Character/Classes/MonkClass.cs | 623 | C# |
// *****************************************************************************
//
// © Component Factory Pty Ltd, 2006 - 2016. All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, PO Box 1504,
// Glen Waverley, Vic 3150, Australia and are supplied subject to licence terms.
//
// Version 5.400.0.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
using ComponentFactory.Krypton.Toolkit;
namespace KryptonLinkLabelExamples
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Setup the property grid to edit this label
propertyGrid.SelectedObject = new KryptonLabelProxy(label2Professional);
}
private void kryptonLabel_MouseDown(object sender, MouseEventArgs e)
{
// Setup the property grid to edit this label
propertyGrid.SelectedObject = new KryptonLabelProxy(sender as KryptonLabel);
}
private void buttonClose_Click(object sender, EventArgs e)
{
Close();
}
}
public class KryptonLabelProxy
{
private KryptonLabel _label;
public KryptonLabelProxy(KryptonLabel label)
{
_label = label;
}
[Category("Visuals")]
[Description("Label style.")]
public LabelStyle LabelStyle
{
get { return _label.LabelStyle; }
set { _label.LabelStyle = value; }
}
[Category("Visuals")]
[Description("Header values")]
public LabelValues Values
{
get { return _label.Values; }
}
[Category("Visuals")]
[Description("Overrides for defining common label appearance that other states can override.")]
public PaletteContent StateCommon
{
get { return _label.StateCommon; }
}
[Category("Visuals")]
[Description("Overrides for defining disabled label appearance.")]
public PaletteContent StateDisabled
{
get { return _label.StateDisabled; }
}
[Category("Visuals")]
[Description("Overrides for defining normal label appearance.")]
public PaletteContent StateNormal
{
get { return _label.StateNormal; }
}
[Category("Visuals")]
[Description("Visual orientation of the control.")]
public VisualOrientation Orientation
{
get { return _label.Orientation; }
set { _label.Orientation = value; }
}
[Category("Visuals")]
[Description("Palette applied to drawing.")]
public PaletteMode PaletteMode
{
get { return _label.PaletteMode; }
set { _label.PaletteMode = value; }
}
[Category("Layout")]
[Description("Specifies whether a control will automatically size itself to fit its contents.")]
public bool AutoSize
{
get { return _label.AutoSize; }
set { _label.AutoSize = value; }
}
[Category("Layout")]
[Description("Specifies if the control grows and shrinks to fit the contents exactly.")]
public AutoSizeMode AutoSizeMode
{
get { return _label.AutoSizeMode; }
set { _label.AutoSizeMode = value; }
}
[Category("Layout")]
[Description("The size of the control is pixels.")]
public Size Size
{
get { return _label.Size; }
set { _label.Size = value; }
}
[Category("Layout")]
[Description("The location of the control in pixels.")]
public Point Location
{
get { return _label.Location; }
set { _label.Location = value; }
}
[Category("Behavior")]
[Description("Indicates whether the control is enabled.")]
public bool Enabled
{
get { return _label.Enabled; }
set { _label.Enabled = value; }
}
}
}
| 29.938356 | 104 | 0.561885 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy/Krypton-NET-5.400 | Source/Demos/Non-NuGet/Krypton Toolkit Examples/KryptonLinkLabel Examples/Form1.cs | 4,374 | C# |
//Released under the MIT License.
//
//Copyright (c) 2018 Ntreev Soft co., Ltd.
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
//documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
//rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
//persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
//Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
//COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
//OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ntreev.Crema.Services
{
public interface ILogService
{
void Debug(object message);
void Info(object message);
void Error(object message);
void Warn(object message);
void Fatal(object message);
LogVerbose Verbose { get; set; }
TextWriter RedirectionWriter { get; set; }
string Name { get; }
string FileName { get; }
bool IsEnabled { get; }
}
}
| 34.54 | 121 | 0.725536 | [
"MIT"
] | NtreevSoft/Crema | common/Ntreev.Crema.Services.Sharing/ILogService.cs | 1,729 | C# |
using System.Collections.Generic;
using System.Runtime.Serialization;
using _4DMonoEngine.Core.Common.Interfaces;
namespace _4DMonoEngine.Core.Assets.DataObjects
{
[DataContract]
public class General : IDataContainer
{
[DataMember]
public string[] Biomes { get; set; }
[DataMember]
public string[] Provinces { get; set; }
[DataMember]
public int SeaLevel { get; set; }
[DataMember]
public int MountainHeight { get; set; }
[DataMember]
public int DetailScale { get; set; }
[DataMember]
public int SinkHoleDepth { get; set; }
[DataMember]
public int BiomeSampleRescale { get; set; }
[DataMember]
public int BiomeThickness { get; set; }
[DataMember]
public Dictionary<string, string[]> BlockTypeMap { get; set; }
[DataMember]
public float BlockTileMapUnitSize { get; set; }
public string GetKey()
{
return "General";
}
}
}
| 27.263158 | 70 | 0.596525 | [
"MIT"
] | HaKDMoDz/4DBlockEngine | Monogame/4DMonoEngine/Core/Assets/DataObjects/General.cs | 1,038 | C# |
//
// Copyright (c) 2021 karamem0
//
// This software is released under the MIT License.
//
// https://github.com/karamem0/sp-client-core/blob/main/LICENSE
//
using Karamem0.SharePoint.PowerShell.Models;
using Karamem0.SharePoint.PowerShell.Runtime.Commands;
using Karamem0.SharePoint.PowerShell.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
namespace Karamem0.SharePoint.PowerShell.Commands
{
[Cmdlet("Remove", "KshList")]
[OutputType(typeof(void))]
public class RemoveListCommand : ClientObjectCmdlet<IListService>
{
public RemoveListCommand()
{
}
[Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ParameterSetName = "ParamSet1")]
[Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ParameterSetName = "ParamSet2")]
public List Identity { get; private set; }
[Parameter(Mandatory = true, ParameterSetName = "ParamSet2")]
public SwitchParameter RecycleBin { get; private set; }
protected override void ProcessRecordCore(ref List<object> outputs)
{
if (this.ParameterSetName == "ParamSet1")
{
this.Service.RemoveObject(this.Identity);
}
if (this.ParameterSetName == "ParamSet2")
{
this.ValidateSwitchParameter(nameof(this.RecycleBin));
outputs.Add(this.Service.RecycleObject(this.Identity));
}
}
}
}
| 30.396226 | 110 | 0.638734 | [
"MIT"
] | karamem0/spclientcore | source/Karamem0.SPClientCore/Commands/RemoveListCommand.cs | 1,611 | C# |
using Alex.ResourcePackLib.Json.Models.Entities;
using Microsoft.Xna.Framework;
namespace Alex.Entities.Models
{
public partial class SilverfishModel : EntityModel
{
public SilverfishModel()
{
Name = "geometry.silverfish";
VisibleBoundsWidth = 2;
VisibleBoundsHeight = 1;
VisibleBoundsOffset = new Vector3(0f, 0f, 0f);
Texturewidth = 64;
Textureheight = 32;
Bones = new EntityModelBone[10]
{
new EntityModelBone(){
Name = "bodyPart_0",
Parent = "bodyPart_2",
Pivot = new Vector3(0f,2f,-3.5f),
Rotation = new Vector3(0f,0f,0f),
NeverRender = false,
Mirror = false,
Reset = false,
Cubes = new EntityModelCube[1]{
new EntityModelCube()
{
Origin = new Vector3(-1.5f,0f,-4.5f),
Size = new Vector3(3f, 2f, 2f),
Uv = new Vector2(0f, 0f)
},
}
},
new EntityModelBone(){
Name = "bodyPart_1",
Parent = "bodyPart_2",
Pivot = new Vector3(0f,3f,-1.5f),
Rotation = new Vector3(0f,0f,0f),
NeverRender = false,
Mirror = false,
Reset = false,
Cubes = new EntityModelCube[1]{
new EntityModelCube()
{
Origin = new Vector3(-2f,0f,-2.5f),
Size = new Vector3(4f, 3f, 2f),
Uv = new Vector2(0f, 4f)
},
}
},
new EntityModelBone(){
Name = "bodyPart_2",
Parent = "",
Pivot = new Vector3(0f,4f,1f),
Rotation = new Vector3(0f,0f,0f),
NeverRender = false,
Mirror = false,
Reset = false,
Cubes = new EntityModelCube[1]{
new EntityModelCube()
{
Origin = new Vector3(-3f,0f,-0.5f),
Size = new Vector3(6f, 4f, 3f),
Uv = new Vector2(0f, 9f)
},
}
},
new EntityModelBone(){
Name = "bodyPart_3",
Parent = "bodyPart_2",
Pivot = new Vector3(0f,3f,4f),
Rotation = new Vector3(0f,0f,0f),
NeverRender = false,
Mirror = false,
Reset = false,
Cubes = new EntityModelCube[1]{
new EntityModelCube()
{
Origin = new Vector3(-1.5f,0f,2.5f),
Size = new Vector3(3f, 3f, 3f),
Uv = new Vector2(0f, 16f)
},
}
},
new EntityModelBone(){
Name = "bodyPart_4",
Parent = "bodyPart_2",
Pivot = new Vector3(0f,2f,7f),
Rotation = new Vector3(0f,0f,0f),
NeverRender = false,
Mirror = false,
Reset = false,
Cubes = new EntityModelCube[1]{
new EntityModelCube()
{
Origin = new Vector3(-1f,0f,5.5f),
Size = new Vector3(2f, 2f, 3f),
Uv = new Vector2(0f, 22f)
},
}
},
new EntityModelBone(){
Name = "bodyPart_5",
Parent = "bodyPart_2",
Pivot = new Vector3(0f,1f,9.5f),
Rotation = new Vector3(0f,0f,0f),
NeverRender = false,
Mirror = false,
Reset = false,
Cubes = new EntityModelCube[1]{
new EntityModelCube()
{
Origin = new Vector3(-1f,0f,8.5f),
Size = new Vector3(2f, 1f, 2f),
Uv = new Vector2(11f, 0f)
},
}
},
new EntityModelBone(){
Name = "bodyPart_6",
Parent = "bodyPart_2",
Pivot = new Vector3(0f,1f,11.5f),
Rotation = new Vector3(0f,0f,0f),
NeverRender = false,
Mirror = false,
Reset = false,
Cubes = new EntityModelCube[1]{
new EntityModelCube()
{
Origin = new Vector3(-0.5f,0f,10.5f),
Size = new Vector3(1f, 1f, 2f),
Uv = new Vector2(13f, 4f)
},
}
},
new EntityModelBone(){
Name = "bodyLayer_0",
Parent = "bodyPart_2",
Pivot = new Vector3(0f,8f,1f),
Rotation = new Vector3(0f,0f,0f),
NeverRender = false,
Mirror = false,
Reset = false,
Cubes = new EntityModelCube[1]{
new EntityModelCube()
{
Origin = new Vector3(-5f,0f,-0.5f),
Size = new Vector3(10f, 8f, 3f),
Uv = new Vector2(20f, 0f)
},
}
},
new EntityModelBone(){
Name = "bodyLayer_1",
Parent = "bodyPart_4",
Pivot = new Vector3(0f,4f,7f),
Rotation = new Vector3(0f,0f,0f),
NeverRender = false,
Mirror = false,
Reset = false,
Cubes = new EntityModelCube[1]{
new EntityModelCube()
{
Origin = new Vector3(-3f,0f,5.5f),
Size = new Vector3(6f, 4f, 3f),
Uv = new Vector2(20f, 11f)
},
}
},
new EntityModelBone(){
Name = "bodyLayer_2",
Parent = "bodyPart_1",
Pivot = new Vector3(0f,5f,-1.5f),
Rotation = new Vector3(0f,0f,0f),
NeverRender = false,
Mirror = false,
Reset = false,
Cubes = new EntityModelCube[1]{
new EntityModelCube()
{
Origin = new Vector3(-3f,0f,-3f),
Size = new Vector3(6f, 5f, 2f),
Uv = new Vector2(20f, 18f)
},
}
},
};
}
}
} | 25.365482 | 52 | 0.526716 | [
"MPL-2.0"
] | TheBlackPlague/Alex | src/Alex/Entities/Models/SilverfishModel.cs | 4,997 | C# |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;
using System.IO;
using UnityEngine.SceneManagement;
using Object = UnityEngine.Object;
namespace UnityEditor
{
[EditorWindowTitle(title = "Occlusion", icon = "Occlusion")]
internal class OcclusionCullingWindow : EditorWindow
{
static bool s_IsVisible = false;
private bool m_PreVis;
private bool m_ClearCacheData = true;
private bool m_ClearBakeData = true;
private string m_Warning;
static OcclusionCullingWindow ms_OcclusionCullingWindow;
Vector2 m_ScrollPosition = Vector2.zero;
Mode m_Mode = Mode.AreaSettings;
static Styles s_Styles;
class Styles
{
public GUIContent[] ModeToggles =
{
EditorGUIUtility.TrTextContent("Object"),
EditorGUIUtility.TrTextContent("Bake"),
EditorGUIUtility.TrTextContent("Visualization")
};
public GUIStyle labelStyle = EditorStyles.wordWrappedMiniLabel;
public GUIContent emptyAreaSelection = EditorGUIUtility.TrTextContent("Select a Mesh Renderer or an Occlusion Area from the scene.");
public GUIContent emptyCameraSelection = EditorGUIUtility.TrTextContent("Select a Camera from the scene.");
public GUIContent visualizationNote = EditorGUIUtility.TrTextContent("The visualization may not correspond to current bake settings and Occlusion Area placements if they have been changed since last bake.");
public GUIContent seeVisualizationInScene = EditorGUIUtility.TrTextContent("See the occlusion culling visualization in the Scene View based on the selected Camera.");
public GUIContent noOcclusionData = EditorGUIUtility.TrTextContent("No occlusion data has been baked.");
public GUIContent smallestHole = EditorGUIUtility.TrTextContent("Smallest Hole", "Smallest hole in the geometry through which the camera is supposed to see. The single float value of the parameter represents the diameter of the imaginary smallest hole, i.e. the maximum extent of a 3D object that fits through the hole.");
public GUIContent backfaceThreshold = EditorGUIUtility.TrTextContent("Backface Threshold", "The backface threshold is a size optimization that reduces unnecessary details by testing backfaces. A value of 100 is robust and never removes any backfaces. A value of 5 aggressively reduces the data based on locations with visible backfaces. The idea is that typically valid camera positions cannot see many backfaces. For example, geometry under terrain and inside solid objects can be removed.");
public GUIContent farClipPlane = EditorGUIUtility.TrTextContent("Far Clip Plane", "Far Clip Plane used during baking. This should match the largest far clip plane used by any camera in the scene. A value of 0.0 sets the far plane to Infinity.");
public GUIContent smallestOccluder = EditorGUIUtility.TrTextContent("Smallest Occluder", "The size of the smallest object that will be used to hide other objects when doing occlusion culling. For example, if a value of 4 is chosen, then all the objects that are higher or wider than 4 meters will block visibility and the objects that are smaller than that will not. This value is a tradeoff between occlusion accuracy and storage size.");
public GUIContent defaultParameterText = EditorGUIUtility.TrTextContent("Default Parameters", "The default parameters guarantee that any given scene computes fast and the occlusion culling results are good. As the parameters are always scene specific, better results will be achieved when fine tuning the parameters on a scene to scene basis. All the parameters are dependent on the unit scale of the scene and it is imperative that the unit scale parameter is set correctly before setting the default values.");
}
enum Mode
{
AreaSettings = 0,
BakeSettings = 1,
Visualization = 2
}
void OnBecameVisible()
{
if (s_IsVisible == true) return;
s_IsVisible = true;
SceneView.duringSceneGui += OnSceneViewGUI;
StaticOcclusionCullingVisualization.showOcclusionCulling = true;
SceneView.RepaintAll();
}
void OnBecameInvisible()
{
s_IsVisible = false;
SceneView.duringSceneGui -= OnSceneViewGUI;
StaticOcclusionCullingVisualization.showOcclusionCulling = false;
SceneView.RepaintAll();
}
void OnSelectionChange()
{
if (m_Mode == Mode.AreaSettings || m_Mode == Mode.Visualization)
Repaint();
}
void OnEnable()
{
titleContent = GetLocalizedTitleContent();
ms_OcclusionCullingWindow = this;
autoRepaintOnSceneChange = true;
EditorApplication.searchChanged += Repaint;
Repaint();
m_OverlayWindow = new OverlayWindow(EditorGUIUtility.TrTextContent("Occlusion Culling"), DisplayControls, (int)SceneViewOverlay.Ordering.OcclusionCulling, null, SceneViewOverlay.WindowDisplayOption.OneWindowPerTarget);
}
void OnDisable()
{
ms_OcclusionCullingWindow = null;
EditorApplication.searchChanged -= Repaint;
}
static void BackgroundTaskStatusChanged()
{
if (ms_OcclusionCullingWindow)
ms_OcclusionCullingWindow.Repaint();
}
[MenuItem("Window/Rendering/Occlusion Culling", false, 101)]
static void GenerateWindow()
{
var window = GetWindow<OcclusionCullingWindow>(typeof(InspectorWindow));
window.minSize = new Vector2(300, 250);
}
void SummaryGUI()
{
GUILayout.BeginVertical(EditorStyles.helpBox);
if (StaticOcclusionCulling.umbraDataSize == 0)
{
GUILayout.Label(s_Styles.noOcclusionData, s_Styles.labelStyle);
}
else
{
GUILayout.Label("Last bake:", s_Styles.labelStyle);
GUILayout.BeginHorizontal();
GUILayout.BeginVertical();
GUILayout.Label("Occlusion data size ", s_Styles.labelStyle);
GUILayout.EndVertical();
GUILayout.BeginVertical();
GUILayout.Label(EditorUtility.FormatBytes(StaticOcclusionCulling.umbraDataSize), s_Styles.labelStyle);
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
GUILayout.EndVertical();
}
OcclusionArea CreateNewArea()
{
GameObject go = new GameObject("Occlusion Area");
OcclusionArea oa = go.AddComponent<OcclusionArea>();
Selection.activeGameObject = go;
return oa;
}
void AreaSelectionGUI()
{
bool emptySelection = true;
GameObject[] gos;
Type focusType = SceneModeUtility.SearchBar(typeof(Renderer), typeof(OcclusionArea));
EditorGUILayout.Space();
// Occlusion Areas
OcclusionArea[] oas = SceneModeUtility.GetSelectedObjectsOfType<OcclusionArea>(out gos);
if (gos.Length > 0)
{
emptySelection = false;
EditorGUILayout.MultiSelectionObjectTitleBar(oas);
SerializedObject so = new SerializedObject(oas);
EditorGUILayout.PropertyField(so.FindProperty("m_IsViewVolume"));
so.ApplyModifiedProperties();
}
// Renderers
Renderer[] renderers = SceneModeUtility.GetSelectedObjectsOfType<Renderer>(out gos, typeof(MeshRenderer), typeof(SkinnedMeshRenderer));
if (gos.Length > 0)
{
emptySelection = false;
EditorGUILayout.MultiSelectionObjectTitleBar(renderers);
SerializedObject goso = new SerializedObject(gos);
SceneModeUtility.StaticFlagField("Occluder Static", goso.FindProperty("m_StaticEditorFlags"), (int)StaticEditorFlags.OccluderStatic);
SceneModeUtility.StaticFlagField("Occludee Static", goso.FindProperty("m_StaticEditorFlags"), (int)StaticEditorFlags.OccludeeStatic);
goso.ApplyModifiedProperties();
}
if (emptySelection)
{
GUILayout.Label(s_Styles.emptyAreaSelection, EditorStyles.helpBox);
if (focusType == typeof(OcclusionArea))
{
EditorGUIUtility.labelWidth = 80;
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Create New");
if (GUILayout.Button("Occlusion Area", EditorStyles.miniButton, GUILayout.ExpandWidth(false)))
CreateNewArea();
EditorGUILayout.EndHorizontal();
}
}
}
void CameraSelectionGUI()
{
SceneModeUtility.SearchBar(typeof(Camera));
EditorGUILayout.Space();
Camera cam = null;
if (Selection.activeGameObject)
cam = Selection.activeGameObject.GetComponent<Camera>();
// Camera
if (cam)
{
Camera[] cameras = new Camera[] { cam };
EditorGUILayout.MultiSelectionObjectTitleBar(cameras);
EditorGUILayout.HelpBox(s_Styles.seeVisualizationInScene.text, MessageType.Info);
}
else
{
GUILayout.Label(s_Styles.emptyCameraSelection, EditorStyles.helpBox);
}
}
void BakeSettings()
{
// Button for setting default values
float buttonWidth = 150;
if (GUILayout.Button("Set default parameters", GUILayout.Width(buttonWidth)))
{
Undo.RegisterCompleteObjectUndo(StaticOcclusionCulling.occlusionCullingSettings, "Set Default Parameters");
GUIUtility.keyboardControl = 0; // Force focus out from potentially selected field for default parameters setting
StaticOcclusionCulling.SetDefaultOcclusionBakeSettings();
}
// Label for default parameter setting
GUILayout.Label(s_Styles.defaultParameterText.tooltip, EditorStyles.helpBox);
// Edit Smallest Occluder
EditorGUI.BeginChangeCheck();
float smallestOccluder = EditorGUILayout.FloatField(s_Styles.smallestOccluder, StaticOcclusionCulling.smallestOccluder);
if (EditorGUI.EndChangeCheck())
{
Undo.RegisterCompleteObjectUndo(StaticOcclusionCulling.occlusionCullingSettings, "Change Smallest Occluder");
StaticOcclusionCulling.smallestOccluder = smallestOccluder;
}
// Edit smallest hole
EditorGUI.BeginChangeCheck();
float smallestHole = EditorGUILayout.FloatField(s_Styles.smallestHole, StaticOcclusionCulling.smallestHole);
if (EditorGUI.EndChangeCheck())
{
Undo.RegisterCompleteObjectUndo(StaticOcclusionCulling.occlusionCullingSettings, "Change Smallest Hole");
StaticOcclusionCulling.smallestHole = smallestHole;
}
// Edit backface threshold
EditorGUI.BeginChangeCheck();
float backfaceThreshold = EditorGUILayout.Slider(s_Styles.backfaceThreshold, StaticOcclusionCulling.backfaceThreshold, 5.0F, 100.0F);
if (EditorGUI.EndChangeCheck())
{
Undo.RegisterCompleteObjectUndo(StaticOcclusionCulling.occlusionCullingSettings, "Change Backface Threshold");
StaticOcclusionCulling.backfaceThreshold = backfaceThreshold;
}
}
void BakeButtons()
{
float buttonWidth = 95;
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
bool allowBaking = !EditorApplication.isPlayingOrWillChangePlaymode;
bool bakeRunning = StaticOcclusionCulling.isRunning;
GUI.enabled = !bakeRunning && allowBaking;
if (CustomDropdownButton("Clear", buttonWidth))
{
if (m_ClearBakeData)
{
StaticOcclusionCulling.Clear();
}
if (m_ClearCacheData)
{
StaticOcclusionCulling.RemoveCacheFolder();
}
}
GUI.enabled = allowBaking;
if (bakeRunning)
{
if (GUILayout.Button("Cancel", GUILayout.Width(buttonWidth)))
StaticOcclusionCulling.Cancel();
}
else
{
if (GUILayout.Button("Bake", GUILayout.Width(buttonWidth)))
{
StaticOcclusionCulling.GenerateInBackground();
}
}
GUILayout.EndHorizontal();
GUI.enabled = true;
}
private bool CustomDropdownButton(string name, float width, params GUILayoutOption[] options)
{
var content = EditorGUIUtility.TrTextContent(name);
var rect = GUILayoutUtility.GetRect(content, EditorStyles.dropDownList, options);
var halfDiff = (width - rect.width) / 2f;
rect.xMin -= halfDiff;
rect.xMax += halfDiff;
var currPos = rect.position;
currPos.x -= halfDiff;
rect.position = currPos;
var dropDownRect = rect;
const float kDropDownButtonWidth = 20f;
dropDownRect.xMin = dropDownRect.xMax - kDropDownButtonWidth;
string[] names = { "Bake Data", "Cache Data" };
bool[] values = { m_ClearBakeData, m_ClearCacheData };
if (Event.current.type == EventType.MouseDown && dropDownRect.Contains(Event.current.mousePosition))
{
var menu = new GenericMenu();
for (int i = 0; i != names.Length; i++)
menu.AddItem(new GUIContent(names[i]), values[i], CustomDropdownCallback, i);
menu.DropDown(rect);
Event.current.Use();
return false;
}
return GUI.Button(rect, content, EditorStyles.dropDownList);
}
private void CustomDropdownCallback(object userData)
{
int index = (int)userData;
if (index == 0)
{
m_ClearBakeData = !m_ClearBakeData;
}
else if (index == 1)
{
m_ClearCacheData = !m_ClearCacheData;
}
}
void ModeToggle()
{
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
using (var check = new EditorGUI.ChangeCheckScope())
{
m_Mode = (Mode)GUILayout.Toolbar((int)m_Mode, s_Styles.ModeToggles, "LargeButton", GUI.ToolbarButtonSize.FitToContents);
if (check.changed)
{
if (m_Mode == Mode.Visualization && StaticOcclusionCulling.umbraDataSize > 0)
StaticOcclusionCullingVisualization.showPreVisualization = false;
else
StaticOcclusionCullingVisualization.showPreVisualization = true;
SceneView.RepaintAll();
}
}
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
}
void OnGUI()
{
if (s_Styles == null)
s_Styles = new Styles();
// Make sure the tab jumps to visualization if we're in visualize mode.
// (Don't do the reverse. Since tabs can't be marked disabled, the user
// will be confused if the visualization tab can't be clicked, and that
// would be the result if we changed the tab away from visualization
// whenever showPreVisualization is false.)
if (m_Mode != Mode.Visualization && StaticOcclusionCullingVisualization.showPreVisualization == false)
m_Mode = Mode.Visualization;
EditorGUILayout.Space();
ModeToggle();
EditorGUILayout.Space();
m_ScrollPosition = EditorGUILayout.BeginScrollView(m_ScrollPosition);
switch (m_Mode)
{
case Mode.AreaSettings:
AreaSelectionGUI();
break;
case Mode.BakeSettings:
BakeSettings();
break;
case Mode.Visualization:
if (StaticOcclusionCulling.umbraDataSize > 0)
{
CameraSelectionGUI();
GUILayout.FlexibleSpace();
GUILayout.Label(s_Styles.visualizationNote, EditorStyles.helpBox);
}
else
{
GUILayout.Label(s_Styles.noOcclusionData, EditorStyles.helpBox);
}
break;
}
EditorGUILayout.EndScrollView();
EditorGUILayout.Space();
BakeButtons();
EditorGUILayout.Space();
// Info GUI
SummaryGUI();
}
OverlayWindow m_OverlayWindow;
public void OnSceneViewGUI(SceneView sceneView)
{
if (!s_IsVisible)
return;
SceneViewOverlay.ShowWindow(m_OverlayWindow);
}
void OnDidOpenScene()
{
StaticOcclusionCulling.InvalidatePrevisualisationData();
Repaint();
}
void SetShowVolumePreVis()
{
StaticOcclusionCullingVisualization.showPreVisualization = true;
if (m_Mode == Mode.Visualization)
m_Mode = Mode.AreaSettings;
if (ms_OcclusionCullingWindow)
ms_OcclusionCullingWindow.Repaint();
SceneView.RepaintAll();
}
void SetShowVolumeCulling()
{
StaticOcclusionCullingVisualization.showPreVisualization = false;
m_Mode = Mode.Visualization;
if (ms_OcclusionCullingWindow)
ms_OcclusionCullingWindow.Repaint();
SceneView.RepaintAll();
}
bool ShowModePopup(Rect popupRect)
{
// Visualization mode popup
int tomeSize = StaticOcclusionCulling.umbraDataSize;
// We can only change the preVis state during layout mode. However, the Tome data could be emptied at anytime, which will immediately disable preVis.
// We need to detect this and force a repaint, so we can change the state.
if (m_PreVis != StaticOcclusionCullingVisualization.showPreVisualization)
SceneView.RepaintAll();
if (Event.current.type == EventType.Layout)
m_PreVis = StaticOcclusionCullingVisualization.showPreVisualization;
string[] options = new string[] { "Edit", "Visualize" };
int selected = m_PreVis ? 0 : 1;
if (EditorGUI.DropdownButton(popupRect, new GUIContent(options[selected]), FocusType.Passive, EditorStyles.popup))
{
GenericMenu menu = new GenericMenu();
menu.AddItem(new GUIContent(options[0]), selected == 0, SetShowVolumePreVis);
if (tomeSize > 0)
menu.AddItem(new GUIContent(options[1]), selected == 1, SetShowVolumeCulling);
else
menu.AddDisabledItem(new GUIContent(options[1]));
menu.Popup(popupRect, selected);
}
return m_PreVis;
}
void DisplayControls(Object target, SceneView sceneView)
{
if (!sceneView)
return;
if (!s_IsVisible)
return;
bool temp;
// See if pre-vis is set to true.
// If we don't have any Tome data, act as if pvs is true, but don't actually set it to true
// - that way it will act like it switches to false (the default value) by itself as soon as pvs data has been build,
// which better leads to discovery of this feature.
bool preVis = ShowModePopup(GUILayoutUtility.GetRect(170, EditorGUIUtility.singleLineHeight));
if (Event.current.type == EventType.Layout)
{
m_Warning = "";
if (!preVis)
{
if (StaticOcclusionCullingVisualization.previewOcclucionCamera == null)
m_Warning = "No camera selected for occlusion preview.";
else if (!StaticOcclusionCullingVisualization.isPreviewOcclusionCullingCameraInPVS)
m_Warning = "Camera is not inside an Occlusion View Area.";
}
}
int legendHeight = 12;
if (!string.IsNullOrEmpty(m_Warning))
{
Rect warningRect = GUILayoutUtility.GetRect(100, legendHeight + 19);
warningRect.x += EditorGUI.indent;
warningRect.width -= EditorGUI.indent;
GUI.Label(warningRect, m_Warning, EditorStyles.helpBox);
}
else
{
// Show legend / volume toggles
Rect legendRect = GUILayoutUtility.GetRect(200, legendHeight);
legendRect.x += EditorGUI.indent;
legendRect.width -= EditorGUI.indent;
Rect viewLegendRect = new Rect(legendRect.x, legendRect.y, legendRect.width, legendRect.height);
if (preVis)
EditorGUI.DrawLegend(viewLegendRect, Color.white, "View Volumes", StaticOcclusionCullingVisualization.showViewVolumes);
else
EditorGUI.DrawLegend(viewLegendRect, Color.white, "Camera Volumes", StaticOcclusionCullingVisualization.showViewVolumes);
temp = GUI.Toggle(viewLegendRect, StaticOcclusionCullingVisualization.showViewVolumes, "", GUIStyle.none);
if (temp != StaticOcclusionCullingVisualization.showViewVolumes)
{
StaticOcclusionCullingVisualization.showViewVolumes = temp;
SceneView.RepaintAll();
}
if (!preVis)
{
// TODO: FORE REALS cleanup this bad code BUG: 496650
legendRect = GUILayoutUtility.GetRect(100, legendHeight);
legendRect.x += EditorGUI.indent;
legendRect.width -= EditorGUI.indent;
viewLegendRect = new Rect(legendRect.x, legendRect.y, legendRect.width, legendRect.height);
EditorGUI.DrawLegend(viewLegendRect, Color.green, "Visibility Lines", StaticOcclusionCullingVisualization.showVisibilityLines);
temp = GUI.Toggle(viewLegendRect, StaticOcclusionCullingVisualization.showVisibilityLines, "", GUIStyle.none);
if (temp != StaticOcclusionCullingVisualization.showVisibilityLines)
{
StaticOcclusionCullingVisualization.showVisibilityLines = temp;
SceneView.RepaintAll();
}
legendRect = GUILayoutUtility.GetRect(100, legendHeight);
legendRect.x += EditorGUI.indent;
legendRect.width -= EditorGUI.indent;
viewLegendRect = new Rect(legendRect.x, legendRect.y, legendRect.width, legendRect.height);
EditorGUI.DrawLegend(viewLegendRect, Color.grey, "Portals", StaticOcclusionCullingVisualization.showPortals);
temp = GUI.Toggle(viewLegendRect, StaticOcclusionCullingVisualization.showPortals, "", GUIStyle.none);
if (temp != StaticOcclusionCullingVisualization.showPortals)
{
StaticOcclusionCullingVisualization.showPortals = temp;
SceneView.RepaintAll();
}
}
// Geometry culling toggle
if (!preVis)
{
temp = GUILayout.Toggle(StaticOcclusionCullingVisualization.showGeometryCulling, "Occlusion culling");
if (temp != StaticOcclusionCullingVisualization.showGeometryCulling)
{
StaticOcclusionCullingVisualization.showGeometryCulling = temp;
SceneView.RepaintAll();
}
}
}
}
}
}
| 43.209898 | 524 | 0.597291 | [
"Unlicense"
] | HelloWindows/AccountBook | client/framework/UnityCsReference-master/Editor/Mono/SceneModeWindows/OcclusionCullingWindow.cs | 25,321 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Funsafe.Runner.Benches;
namespace Funsafe.Runner
{
internal class Program
{
private static void Main()
{
var benches = LoadBenches();
const int warmupBatchCount = 100;
const int warmupBatchSize = 10;
const int warmupMessagePartCount = 2;
foreach (var bench in benches)
{
bench.Run(warmupBatchCount, warmupBatchSize, warmupMessagePartCount);
}
Console.WriteLine("Serialization");
Console.WriteLine("-------------");
Console.WriteLine();
RunBenches(benches, BenchCategory.Serialization);
Console.WriteLine();
Console.WriteLine("Deserialization");
Console.WriteLine("---------------");
Console.WriteLine();
RunBenches(benches, BenchCategory.Deserialization);
}
private static void RunBenches(IList<Bench> benches, BenchCategory benchCategory)
{
const int batchCount = 100 * 1000;
const int batchSize = 100;
for (var i = 0; i <= 10; i += 2)
{
var messagePartCount = i;
Console.WriteLine();
Console.WriteLine("# {0} message parts", messagePartCount);
Console.WriteLine();
var results = new List<BenchResult>();
foreach (var bench in benches.Where(x => x.Category == benchCategory))
{
results.Add(bench.Run(batchCount, batchSize, messagePartCount));
}
foreach (var result in results.OrderByDescending(x => x.OperationPerSecond))
{
Console.WriteLine(result);
}
}
}
private static IList<Bench> LoadBenches()
{
return (from type in typeof(Program).Assembly.GetTypes()
where typeof(Bench).IsAssignableFrom(type) && !type.IsAbstract
orderby type.Name
let instance = (Bench)Activator.CreateInstance(type)
where instance.Category != BenchCategory.Ignored
select instance).ToList();
}
}
}
| 31.648649 | 92 | 0.533732 | [
"MIT"
] | rverdier/funsafe | Funsafe.Runner/Program.cs | 2,344 | C# |
// Material/Shader Inspector for Unity 2017/2018
// Copyright (C) 2019 Thryrallo
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
using UnityEngine.Networking;
namespace Thry
{
public class Helper
{
private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static long GetCurrentUnixTimestampMillis()
{
return (long)(DateTime.UtcNow - UnixEpoch).TotalMilliseconds;
}
public static long GetUnityStartUpTimeStamp()
{
return GetCurrentUnixTimestampMillis() - (long)EditorApplication.timeSinceStartup * 1000;
}
public static bool ClassExists(string classname)
{
return System.Type.GetType(classname) != null;
}
public static bool NameSpaceExists(string namespace_name)
{
bool namespaceFound = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
where type.Namespace == namespace_name
select type).Any();
return namespaceFound;
}
public static valuetype GetValueFromDictionary<keytype, valuetype>(Dictionary<keytype, valuetype> dictionary, keytype key)
{
valuetype value = default(valuetype);
if (dictionary.ContainsKey(key)) dictionary.TryGetValue(key, out value);
return value;
}
public static valuetype GetValueFromDictionary<keytype, valuetype>(Dictionary<keytype, valuetype> dictionary, keytype key, valuetype defaultValue)
{
valuetype value = default(valuetype);
if (dictionary.ContainsKey(key)) dictionary.TryGetValue(key, out value);
else return defaultValue;
return value;
}
//-------------------Comparetors----------------------
/// <summary>
/// -1 if v1 > v2
/// 0 if v1 == v2
/// 1 if v1 < v2
/// </summary>
public static int compareVersions(string v1, string v2)
{
Match v1_match = Regex.Match(v1, @"\d+(\.\d+)*");
Match v2_match = Regex.Match(v2, @"\d+(\.\d+)*");
if (!v1_match.Success && !v2_match.Success) return 0;
else if (!v1_match.Success) return 1;
else if (!v2_match.Success) return -1;
string[] v1Parts = Regex.Split(v1_match.Value, @"\.");
string[] v2Parts = Regex.Split(v2_match.Value, @"\.");
for (int i = 0; i < Math.Max(v1Parts.Length, v2Parts.Length); i++)
{
if (i >= v1Parts.Length) return 1;
else if (i >= v2Parts.Length) return -1;
int v1P = int.Parse(v1Parts[i]);
int v2P = int.Parse(v2Parts[i]);
if (v1P > v2P) return -1;
else if (v1P < v2P) return 1;
}
return 0;
}
public static bool IsPrimitive(Type t)
{
return t.IsPrimitive || t == typeof(Decimal) || t == typeof(String);
}
}
public class FileHelper
{
public static string FindFile(string name)
{
return FindFile(name, null);
}
public static string FindFile(string name, string type)
{
string[] guids;
if (type != null)
guids = AssetDatabase.FindAssets(name + " t:" + type);
else
guids = AssetDatabase.FindAssets(name);
if (guids.Length == 0)
return null;
return AssetDatabase.GUIDToAssetPath(guids[0]);
}
//-----------------------Value To File Saver----------------------
private static Dictionary<string, string> textFileData = new Dictionary<string, string>();
public static string LoadValueFromFile(string key, string path)
{
if (!textFileData.ContainsKey(path)) textFileData[path] = ReadFileIntoString(path);
Match m = Regex.Match(textFileData[path], Regex.Escape(key) + @"\s*:=.*(?=\r?\n)");
string value = Regex.Replace(m.Value, key + @"\s*:=\s*", "");
if (m.Success) return value;
return null;
}
public static bool SaveValueToFileKeyIsRegex(string keyRegex, string value, string path)
{
if (!textFileData.ContainsKey(path)) textFileData[path] = ReadFileIntoString(path);
Match m = Regex.Match(textFileData[path], keyRegex + @"\s*:=.*\r?\n");
if (m.Success) textFileData[path] = textFileData[path].Replace(m.Value, m.Value.Substring(0, m.Value.IndexOf(":=")) + ":=" + value + "\n");
else textFileData[path] += Regex.Unescape(keyRegex) + ":=" + value + "\n";
WriteStringToFile(textFileData[path], path);
return true;
}
public static bool SaveValueToFile(string key, string value, string path)
{
return SaveValueToFileKeyIsRegex(Regex.Escape(key), value, path);
}
//-----------------------File Interaction---------------------
public static string FindFileAndReadIntoString(string fileName)
{
string[] guids = AssetDatabase.FindAssets(fileName);
if (guids.Length > 0)
return ReadFileIntoString(AssetDatabase.GUIDToAssetPath(guids[0]));
else return "";
}
public static void FindFileAndWriteString(string fileName, string s)
{
string[] guids = AssetDatabase.FindAssets(fileName);
if (guids.Length > 0)
WriteStringToFile(s, AssetDatabase.GUIDToAssetPath(guids[0]));
}
public static string ReadFileIntoString(string path)
{
if (!File.Exists(path))
{
CreateFileWithDirectories(path);
return "";
}
StreamReader reader = new StreamReader(path);
string ret = reader.ReadToEnd();
reader.Close();
return ret;
}
public static void WriteStringToFile(string s, string path)
{
if (!File.Exists(path)) CreateFileWithDirectories(path);
StreamWriter writer = new StreamWriter(path, false);
writer.Write(s);
writer.Close();
}
public static bool writeBytesToFile(byte[] bytes, string path)
{
if (!File.Exists(path)) if (!File.Exists(path)) CreateFileWithDirectories(path);
try
{
using (var fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
{
fs.Write(bytes, 0, bytes.Length);
return true;
}
}
catch (Exception ex)
{
Debug.Log("Exception caught in process: " + ex.ToString());
return false;
}
}
public static void CreateFileWithDirectories(string path)
{
string dir_path = path.GetDirectoryPath();
if (dir_path != "")
Directory.CreateDirectory(dir_path);
File.Create(path).Close();
}
}
public class TrashHandler
{
public static void EmptyThryTrash()
{
if (Directory.Exists(PATH.DELETING_DIR))
{
DeleteDirectory(PATH.DELETING_DIR);
}
}
public static void MoveDirectoryToTrash(string path)
{
string name = path.RemovePath();
if (!Directory.Exists(PATH.DELETING_DIR))
Directory.CreateDirectory(PATH.DELETING_DIR);
int i = 0;
string newpath = PATH.DELETING_DIR + "/" + name + i;
while (Directory.Exists(newpath))
newpath = PATH.DELETING_DIR + "/" + name + (++i);
Directory.Move(path, newpath);
}
static void DeleteDirectory(string path)
{
foreach (string f in Directory.GetFiles(path))
DeleteFile(f);
foreach (string d in Directory.GetDirectories(path))
DeleteDirectory(d);
if (Directory.GetFiles(path).Length + Directory.GetDirectories(path).Length == 0)
Directory.Delete(path);
}
static void DeleteFile(string path)
{
try
{
File.Delete(path);
}
catch (Exception e)
{
e.GetType();
}
}
}
public class TextureHelper
{
public static Gradient GetGradient(Texture texture)
{
if (texture != null)
{
string gradient_data_string = FileHelper.LoadValueFromFile(texture.name, PATH.GRADIENT_INFO_FILE);
if (gradient_data_string != null)
{
return Parser.ParseToObject<Gradient>(gradient_data_string);
}
return Converter.TextureToGradient(GetReadableTexture(texture));
}
return new Gradient();
}
private static Texture2D s_BackgroundTexture;
public static Texture2D GetBackgroundTexture()
{
if (s_BackgroundTexture == null)
s_BackgroundTexture = CreateCheckerTexture(32, 4, 4, Color.white, new Color(0.7f, 0.7f, 0.7f));
return s_BackgroundTexture;
}
public static Texture2D CreateCheckerTexture(int numCols, int numRows, int cellPixelWidth, Color col1, Color col2)
{
int height = numRows * cellPixelWidth;
int width = numCols * cellPixelWidth;
Texture2D texture = new Texture2D(width, height, TextureFormat.RGBA32, false);
texture.hideFlags = HideFlags.HideAndDontSave;
Color[] pixels = new Color[width * height];
for (int i = 0; i < numRows; i++)
for (int j = 0; j < numCols; j++)
for (int ci = 0; ci < cellPixelWidth; ci++)
for (int cj = 0; cj < cellPixelWidth; cj++)
pixels[(i * cellPixelWidth + ci) * width + j * cellPixelWidth + cj] = ((i + j) % 2 == 0) ? col1 : col2;
texture.SetPixels(pixels);
texture.Apply();
return texture;
}
public static Texture SaveTextureAsPNG(Texture2D texture, string path, TextureData settings)
{
if (!path.EndsWith(".png"))
path += ".png";
byte[] encoding = texture.EncodeToPNG();
Debug.Log("Texture saved at \"" + path + "\".");
FileHelper.writeBytesToFile(encoding, path);
AssetDatabase.ImportAsset(path);
if (settings != null)
settings.ApplyModes(path);
Texture saved = AssetDatabase.LoadAssetAtPath<Texture>(path);
return saved;
}
public static void MakeTextureReadible(string path)
{
TextureImporter importer = (TextureImporter)TextureImporter.GetAtPath(path);
if (!importer.isReadable)
{
importer.isReadable = true;
importer.SaveAndReimport();
}
}
public static Texture2D GetReadableTexture(Texture texture)
{
RenderTexture temp = RenderTexture.GetTemporary(texture.width, texture.height, 0, RenderTextureFormat.Default, RenderTextureReadWrite.Linear);
Graphics.Blit(texture, temp);
RenderTexture previous = RenderTexture.active;
RenderTexture.active = temp;
Texture2D ret = new Texture2D(texture.width, texture.height);
ret.ReadPixels(new Rect(0, 0, temp.width, temp.height), 0, 0);
ret.Apply();
RenderTexture.active = previous;
RenderTexture.ReleaseTemporary(temp);
return ret;
}
public static Texture2D Resize(Texture2D texture, int width, int height)
{
Texture2D ret = new Texture2D(width, height, texture.format, texture.mipmapCount > 0);
float scaleX = ((float)texture.width) / width;
float scaleY = ((float)texture.height) / height;
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
ret.SetPixel(x, y, texture.GetPixel((int)(scaleX * x), (int)(scaleY * y)));
}
}
ret.Apply();
return ret;
}
}
public class MaterialHelper
{
public static void UpdateRenderQueue(Material material, Shader defaultShader)
{
if (material.shader.renderQueue != material.renderQueue)
{
Shader renderQueueShader = defaultShader;
if (material.renderQueue != renderQueueShader.renderQueue) renderQueueShader = ShaderHelper.createRenderQueueShaderIfNotExists(defaultShader, material.renderQueue, true);
material.shader = renderQueueShader;
ShaderImportFixer.backupSingleMaterial(material);
}
}
public static void UpdateTargetsValue(MaterialProperty p, System.Object value)
{
if (p.type == MaterialProperty.PropType.Texture)
foreach (UnityEngine.Object m in p.targets)
((Material)m).SetTexture(p.name, (Texture)value);
else if (p.type == MaterialProperty.PropType.Float)
{
foreach (UnityEngine.Object m in p.targets)
if (value.GetType() == typeof(float))
((Material)m).SetFloat(p.name, (float)value);
else if (value.GetType() == typeof(int))
((Material)m).SetFloat(p.name, (int)value);
}
}
public static void UpdateTextureValue(MaterialProperty prop, Texture texture)
{
foreach (UnityEngine.Object m in prop.targets)
{
((Material)m).SetTexture(prop.name, texture);
}
prop.textureValue = texture;
}
public static void UpdateFloatValue(MaterialProperty prop, float f)
{
foreach (UnityEngine.Object m in prop.targets)
{
((Material)m).SetFloat(prop.name, f);
}
prop.floatValue = f;
}
}
public class ColorHelper
{
public static Color Subtract(Color col1, Color col2)
{
return ColorMath(col1, col2, 1, -1);
}
public static Color ColorMath(Color col1, Color col2, float multiplier1, float multiplier2)
{
return new Color(col1.r * multiplier1 + col2.r * multiplier2, col1.g * multiplier1 + col2.g * multiplier2, col1.b * multiplier1 + col2.b * multiplier2);
}
public static float ColorDifference(Color col1, Color col2)
{
return Math.Abs(col1.r - col2.r) + Math.Abs(col1.g - col2.g) + Math.Abs(col1.b - col2.b) + Math.Abs(col1.a - col2.a);
}
}
} | 36.701176 | 186 | 0.551225 | [
"MIT"
] | yamiM0NSTER/PoiyomiToonShader | _PoiyomiToonShader/ThryEditor/Editor/ThryHelper.cs | 15,600 | C# |
#region Licence
/* The MIT License (MIT)
Copyright © 2015 Ian Cooper <ian_hammond_cooper@yahoo.co.uk>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#endregion
using System;
using Microsoft.Data.Sqlite;
using Nito.AsyncEx;
using NUnit.Framework;
using paramore.brighter.commandprocessor.commandstore.sqlite;
using paramore.brighter.commandprocessor.tests.nunit.CommandProcessors.TestDoubles;
namespace paramore.brighter.commandprocessor.tests.nunit.commandstore.sqlite
{
[TestFixture]
public class SqliteCommandStoreEmptyWhenSearchedAsyncTests
{
private SqliteTestHelper _sqliteTestHelper;
private SqliteCommandStore _sqlCommandStore;
private MyCommand _storedCommand;
private SqliteConnection _sqliteConnection;
[SetUp]
public void Establish()
{
_sqliteTestHelper = new SqliteTestHelper();
_sqliteConnection = _sqliteTestHelper.SetupCommandDb();
_sqlCommandStore = new SqliteCommandStore(new SqliteCommandStoreConfiguration(_sqliteTestHelper.ConnectionString, _sqliteTestHelper.TableName));
}
[Test]
public void When_There_Is_No_Message_In_The_Sql_Command_Store_Async()
{
_storedCommand = AsyncContext.Run<MyCommand>(async () => await _sqlCommandStore.GetAsync<MyCommand>(Guid.NewGuid()));
//_should_return_an_empty_command_on_a_missing_command
Assert.AreEqual(Guid.Empty, _storedCommand.Id);
}
[TearDown]
public void Cleanup()
{
_sqliteTestHelper.CleanUpDb();
}
}
}
| 38.58209 | 156 | 0.75087 | [
"MIT"
] | uQr/Paramore.Brighter | paramore.brighter.commandprocessor.tests.nunit/CommandStore/Sqlite/When_There_Is_No_Message_In_The_Sql_Command_Store_Async.cs | 2,596 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Iot.Model.V20180120;
namespace Aliyun.Acs.Iot.Transform.V20180120
{
public class ReleaseProductResponseUnmarshaller
{
public static ReleaseProductResponse Unmarshall(UnmarshallerContext _ctx)
{
ReleaseProductResponse releaseProductResponse = new ReleaseProductResponse();
releaseProductResponse.HttpResponse = _ctx.HttpResponse;
releaseProductResponse.RequestId = _ctx.StringValue("ReleaseProduct.RequestId");
releaseProductResponse.Success = _ctx.BooleanValue("ReleaseProduct.Success");
releaseProductResponse.ErrorMessage = _ctx.StringValue("ReleaseProduct.ErrorMessage");
releaseProductResponse.Code = _ctx.StringValue("ReleaseProduct.Code");
return releaseProductResponse;
}
}
}
| 38.767442 | 90 | 0.763047 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-iot/Iot/Transform/V20180120/ReleaseProductResponseUnmarshaller.cs | 1,667 | 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: Templates\CSharp\Requests\IStreamRequest.cs.tt
namespace Microsoft.Graph
{
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The interface ICompanyInformationPictureRequest.
/// </summary>
public partial interface ICompanyInformationPictureRequest : IBaseRequest
{
/// <summary>
/// Gets the stream.
/// </summary>
/// <returns>The stream.</returns>
System.Threading.Tasks.Task<Stream> GetAsync();
/// <summary>
/// Gets the stream.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <param name="completionOption">The <see cref="HttpCompletionOption"/> to pass to the <see cref="IHttpProvider"/> on send.</param>
/// <returns>The stream.</returns>
System.Threading.Tasks.Task<Stream> GetAsync(CancellationToken cancellationToken, HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead);
/// <summary>
/// PUTs the specified stream.
/// </summary>
/// <typeparam name="T">The type returned by the PUT call.</typeparam>
/// <param name="picture">The stream to PUT.</param>
/// <returns>The object returned by the PUT call.</returns>
System.Threading.Tasks.Task<T> PutAsync<T>(Stream picture) where T : CompanyInformation;
/// <summary>
/// PUTs the specified stream.
/// </summary>
/// <typeparam name="T">The type returned by the PUT call.</typeparam>
/// <param name="picture">The stream to PUT.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <param name="completionOption">The <see cref="HttpCompletionOption"/> to pass to the <see cref="IHttpProvider"/> on send.</param>
/// <returns>The object returned by the PUT call.</returns>
System.Threading.Tasks.Task<T> PutAsync<T>(Stream picture, CancellationToken cancellationToken, HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead) where T : CompanyInformation;
}
}
| 47.087719 | 215 | 0.625186 | [
"MIT"
] | OfficeGlobal/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/ICompanyInformationPictureRequest.cs | 2,684 | C# |
using System.Runtime.Serialization;
namespace Microsoft.Xrm.Sdk.Metadata
{
/// <summary>Contains the metadata for the attribute type Memo.</summary>
[DataContract(Name = "MemoAttributeMetadata", Namespace = "http://schemas.microsoft.com/xrm/2011/Metadata")]
public sealed class MemoAttributeMetadata : AttributeMetadata
{
/// <summary>The minimum supported length is 1.</summary>
public const int MinSupportedLength = 1;
/// <summary>The maximum supported length is 1048576.</summary>
public const int MaxSupportedLength = 1048576;
private StringFormat? _format;
private Microsoft.Xrm.Sdk.Metadata.ImeMode? _imeMode;
private int? _maxLength;
private bool? _isLocalizable;
/// <summary>Initializes a new instance of the <see cref="T:Microsoft.Xrm.Sdk.Metadata.MemoAttributeMetadata"></see> class</summary>
public MemoAttributeMetadata()
: this((string)null)
{
}
/// <summary>Initializes a new instance of the <see cref="T:Microsoft.Xrm.Sdk.Metadata.MemoAttributeMetadata"></see> class</summary>
/// <param name="schemaName">Type: Returns_String
/// The schema name of the attribute.</param>
public MemoAttributeMetadata(string schemaName)
: base(AttributeTypeCode.Memo, schemaName)
{
}
/// <summary>Gets or sets the format options for the memo attribute.</summary>
/// <returns>Type: Returns_Nullable<<see cref="T:Microsoft.Xrm.Sdk.Metadata.StringFormat"></see>>
/// The format options for the memo attribute.</returns>
[DataMember]
public StringFormat? Format
{
get
{
return this._format;
}
set
{
this._format = value;
}
}
/// <summary>Gets or sets the value for the input method editor mode.</summary>
/// <returns>Type: Returns_Nullable<<see cref="T:Microsoft.Xrm.Sdk.Metadata.ImeMode"></see>>
/// The value for the input method editor mode..</returns>
[DataMember]
public Microsoft.Xrm.Sdk.Metadata.ImeMode? ImeMode
{
get
{
return this._imeMode;
}
set
{
this._imeMode = value;
}
}
/// <summary>Gets or sets the maximum length for the attribute.</summary>
/// <returns>Type: Returns_Nullable<Returns_Int32>
/// The maximum length for the attribute.</returns>
[DataMember]
public int? MaxLength
{
get
{
return this._maxLength;
}
set
{
this._maxLength = value;
}
}
/// <summary>Gets whether the attribute supports localizable values</summary>
/// <returns>Type: Returns_Nullable<Returns_Boolean>true if the attribute supports localizable values; otherwise, false.</returns>
[DataMember(Order = 70)]
public bool? IsLocalizable
{
get
{
return this._isLocalizable;
}
internal set
{
this._isLocalizable = value;
}
}
}
} | 35.4 | 144 | 0.573595 | [
"MIT"
] | develmax/Crm.Sdk.Core | Microsoft.Xrm.Sdk/Metadata/MemoAttributeMetadata.cs | 3,365 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Gov.Lclb.Cllb.Interfaces
{
using Microsoft.Rest;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for Adminactivityprocesssession.
/// </summary>
public static partial class AdminactivityprocesssessionExtensions
{
/// <summary>
/// Get adoxio_adminactivity_ProcessSession from adoxio_adminactivities
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='adoxioAdminactivityid'>
/// key: adoxio_adminactivityid of adoxio_adminactivity
/// </param>
/// <param name='top'>
/// </param>
/// <param name='skip'>
/// </param>
/// <param name='search'>
/// </param>
/// <param name='filter'>
/// </param>
/// <param name='count'>
/// </param>
/// <param name='orderby'>
/// Order items by property values
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
public static MicrosoftDynamicsCRMprocesssessionCollection Get(this IAdminactivityprocesssession operations, string adoxioAdminactivityid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>))
{
return operations.GetAsync(adoxioAdminactivityid, top, skip, search, filter, count, orderby, select, expand).GetAwaiter().GetResult();
}
/// <summary>
/// Get adoxio_adminactivity_ProcessSession from adoxio_adminactivities
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='adoxioAdminactivityid'>
/// key: adoxio_adminactivityid of adoxio_adminactivity
/// </param>
/// <param name='top'>
/// </param>
/// <param name='skip'>
/// </param>
/// <param name='search'>
/// </param>
/// <param name='filter'>
/// </param>
/// <param name='count'>
/// </param>
/// <param name='orderby'>
/// Order items by property values
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<MicrosoftDynamicsCRMprocesssessionCollection> GetAsync(this IAdminactivityprocesssession operations, string adoxioAdminactivityid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(adoxioAdminactivityid, top, skip, search, filter, count, orderby, select, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get adoxio_adminactivity_ProcessSession from adoxio_adminactivities
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='adoxioAdminactivityid'>
/// key: adoxio_adminactivityid of adoxio_adminactivity
/// </param>
/// <param name='top'>
/// </param>
/// <param name='skip'>
/// </param>
/// <param name='search'>
/// </param>
/// <param name='filter'>
/// </param>
/// <param name='count'>
/// </param>
/// <param name='orderby'>
/// Order items by property values
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse<MicrosoftDynamicsCRMprocesssessionCollection> GetWithHttpMessages(this IAdminactivityprocesssession operations, string adoxioAdminactivityid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null)
{
return operations.GetWithHttpMessagesAsync(adoxioAdminactivityid, top, skip, search, filter, count, orderby, select, expand, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Get adoxio_adminactivity_ProcessSession from adoxio_adminactivities
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='adoxioAdminactivityid'>
/// key: adoxio_adminactivityid of adoxio_adminactivity
/// </param>
/// <param name='processsessionid'>
/// key: processsessionid of processsession
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
public static MicrosoftDynamicsCRMprocesssession ProcessSessionByKey(this IAdminactivityprocesssession operations, string adoxioAdminactivityid, string processsessionid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>))
{
return operations.ProcessSessionByKeyAsync(adoxioAdminactivityid, processsessionid, select, expand).GetAwaiter().GetResult();
}
/// <summary>
/// Get adoxio_adminactivity_ProcessSession from adoxio_adminactivities
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='adoxioAdminactivityid'>
/// key: adoxio_adminactivityid of adoxio_adminactivity
/// </param>
/// <param name='processsessionid'>
/// key: processsessionid of processsession
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<MicrosoftDynamicsCRMprocesssession> ProcessSessionByKeyAsync(this IAdminactivityprocesssession operations, string adoxioAdminactivityid, string processsessionid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ProcessSessionByKeyWithHttpMessagesAsync(adoxioAdminactivityid, processsessionid, select, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get adoxio_adminactivity_ProcessSession from adoxio_adminactivities
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='adoxioAdminactivityid'>
/// key: adoxio_adminactivityid of adoxio_adminactivity
/// </param>
/// <param name='processsessionid'>
/// key: processsessionid of processsession
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse<MicrosoftDynamicsCRMprocesssession> ProcessSessionByKeyWithHttpMessages(this IAdminactivityprocesssession operations, string adoxioAdminactivityid, string processsessionid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null)
{
return operations.ProcessSessionByKeyWithHttpMessagesAsync(adoxioAdminactivityid, processsessionid, select, expand, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
}
}
| 50.076555 | 535 | 0.577202 | [
"Apache-2.0"
] | BrendanBeachBC/jag-lcrb-carla-public | cllc-interfaces/Dynamics-Autorest/AdminactivityprocesssessionExtensions.cs | 10,466 | C# |
using System;
using Cassette.BundleProcessing;
using Cassette.Configuration;
using Cassette.HtmlTemplates;
using Cassette.Scripts;
namespace Cassette.ScriptAndTemplate
{
public class ScriptAndTemplateBundle : ScriptBundle
{
public ScriptAndTemplateBundle(string name, ScriptBundle bundle, HtmlTemplateBundle templateBundle, Func<IBundleProcessor<HtmlTemplateBundle>> templateProcessor)
: base(name)
{
ScriptBundle = bundle;
HtmlTemplateBundle = templateBundle;
ContentType = "text/javascript";
TemplateProcessor = templateProcessor();
ScriptProcessor = new ScriptPipeline();
}
public HtmlTemplateBundle HtmlTemplateBundle { get; private set; }
public ScriptBundle ScriptBundle { get; private set; }
public IBundleProcessor<ScriptBundle> ScriptProcessor { get; set; }
public IBundleProcessor<HtmlTemplateBundle> TemplateProcessor { get; set; }
protected override void ProcessCore(CassetteSettings settings)
{
//force the internal bundles to be processed in debug mode. Otherwise we prematurely get concatenated assets.
bool isDebug = settings.IsDebuggingEnabled;
settings.IsDebuggingEnabled = true;
ScriptProcessor.Process(ScriptBundle, settings);
TemplateProcessor.Process(HtmlTemplateBundle, settings);
var hash = new byte[ScriptBundle.Hash.Length + HtmlTemplateBundle.Hash.Length];
ScriptBundle.Hash.CopyTo(hash, 0);
HtmlTemplateBundle.Hash.CopyTo(hash, ScriptBundle.Hash.Length);
Hash = hash;
assets.AddRange(HtmlTemplateBundle.Assets);
assets.AddRange(ScriptBundle.Assets);
foreach (var reference in ScriptBundle.References)
{
AddReference(reference);
}
foreach (var localizedString in ScriptBundle.LocalizedStrings)
{
AddLocalizedString(localizedString);
}
foreach (var localizedString in HtmlTemplateBundle.LocalizedStrings)
{
AddLocalizedString(localizedString);
}
foreach (var abConfig in ScriptBundle.AbConfigs)
{
AddAbConfig(abConfig);
}
CombinedBundleUtility.RemoveAssetReferences(new[] { ScriptBundle.Path, HtmlTemplateBundle.Path }, assets, settings);
settings.IsDebuggingEnabled = isDebug;
new AssignScriptRenderer().Process(this, settings);
CombinedBundleUtility.CompressBundle(this, new MicrosoftJavaScriptMinifier(), settings);
}
internal override string Render()
{
return Renderer.Render(this);
}
protected override string UrlBundleTypeArgument
{
get { return "scriptbundle"; }
}
}
}
| 36.746988 | 170 | 0.623279 | [
"MIT"
] | Zocdoc/cassette | src/Cassette/CombinedBundles/ScriptAndTemplateBundle.cs | 3,052 | C# |
using AutoMapper;
namespace MaigcalConch.Abp.Captcha.Web
{
public class CaptchaWebAutoMapperProfile : Profile
{
public CaptchaWebAutoMapperProfile()
{
/* You can configure your AutoMapper mapping configuration here.
* Alternatively, you can split your mapping configurations
* into multiple profile classes for a better organization. */
}
}
} | 29.857143 | 76 | 0.662679 | [
"MIT"
] | git102347501/Abp.Captcha | src/Abp.Captcha.Web/CaptchaWebAutoMapperProfile.cs | 420 | C# |
//
// Copyright (c) 2017 Vulcan, Inc. All rights reserved.
// Licensed under the Apache 2.0 license. See LICENSE file in the project root for full license information.
//
using HoloLensCameraStream;
using System;
using System.Linq;
using UnityEngine;
public class CameraStreamHelper : MonoBehaviour
{
event OnVideoCaptureResourceCreatedCallback VideoCaptureCreated;
static VideoCapture videoCapture;
static CameraStreamHelper instance;
public static CameraStreamHelper Instance
{
get
{
return instance;
}
}
public void SetNativeISpatialCoordinateSystemPtr(IntPtr ptr)
{
videoCapture.WorldOriginPtr = ptr;
}
public void GetVideoCaptureAsync(OnVideoCaptureResourceCreatedCallback onVideoCaptureAvailable)
{
if (onVideoCaptureAvailable == null)
{
Debug.LogError("You must supply the onVideoCaptureAvailable delegate.");
}
if (videoCapture == null)
{
VideoCaptureCreated += onVideoCaptureAvailable;
}
else
{
onVideoCaptureAvailable(videoCapture);
}
}
public HoloLensCameraStream.Resolution GetHighestResolution()
{
if (videoCapture == null)
{
throw new Exception("Please call this method after a VideoCapture instance has been created.");
}
return videoCapture.GetSupportedResolutions().OrderByDescending((r) => r.width * r.height).FirstOrDefault();
}
public HoloLensCameraStream.Resolution GetLowestResolution()
{
if (videoCapture == null)
{
throw new Exception("Please call this method after a VideoCapture instance has been created.");
}
return videoCapture.GetSupportedResolutions().OrderBy((r) => r.width * r.height).FirstOrDefault();
}
public float GetHighestFrameRate(HoloLensCameraStream.Resolution forResolution)
{
if (videoCapture == null)
{
throw new Exception("Please call this method after a VideoCapture instance has been created.");
}
return videoCapture.GetSupportedFrameRatesForResolution(forResolution).OrderByDescending(r => r).FirstOrDefault();
}
public float GetLowestFrameRate(HoloLensCameraStream.Resolution forResolution)
{
if (videoCapture == null)
{
throw new Exception("Please call this method after a VideoCapture instance has been created.");
}
return videoCapture.GetSupportedFrameRatesForResolution(forResolution).OrderBy(r => r).FirstOrDefault();
}
private void Awake()
{
if (instance != null)
{
Debug.LogError("Cannot create two instances of CamStreamManager.");
return;
}
instance = this;
VideoCapture.CreateAync(OnVideoCaptureInstanceCreated);
}
private void OnDestroy()
{
if (instance == this)
{
instance = null;
}
}
private void OnVideoCaptureInstanceCreated(VideoCapture videoCapture)
{
if (videoCapture == null)
{
Debug.LogError("Creating the VideoCapture object failed.");
return;
}
CameraStreamHelper.videoCapture = videoCapture;
if (VideoCaptureCreated != null)
{
VideoCaptureCreated(videoCapture);
}
}
}
| 28.705882 | 122 | 0.642564 | [
"Apache-2.0"
] | AkioUnity/AR-Project | HoloLensVideoCaptureExample/Assets/CamStream/Scripts/CameraStreamHelper.cs | 3,418 | C# |
using System;
namespace QDMarketPlace.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
} | 19.181818 | 70 | 0.672986 | [
"MIT"
] | quocitspkt/QDMarketPlaceFinal | QDMarketPlace/Models/ErrorViewModel.cs | 211 | C# |
/*
Copyright (c) 2014 <a href="http://www.gutgames.com">James Craig</a>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Utilities.IoC.Interfaces;
namespace Ironman.Core.Bootstrapper
{
/// <summary>
/// Dependency resolver base class
/// </summary>
public class DependencyResolver : IDependencyResolver
{
/// <summary>
/// Constructor
/// </summary>
public DependencyResolver(IBootstrapper Container)
{
if (Container == null)
throw new ArgumentNullException(nameof(Container));
this.Container = Container;
}
/// <summary>
/// The IoC container
/// </summary>
protected IBootstrapper Container { get; private set; }
/// <summary>
/// Gets the service based on the type specified
/// </summary>
/// <param name="serviceType">Service type</param>
/// <returns>The object associated with the type</returns>
public object GetService(Type serviceType)
{
return Container.Resolve(serviceType, "", null);
}
/// <summary>
/// Gets the services based on the type specified
/// </summary>
/// <param name="serviceType">Service type</param>
/// <returns>The objects associated with the type</returns>
public IEnumerable<object> GetServices(Type serviceType)
{
return Container.ResolveAll(serviceType);
}
}
} | 37.188406 | 77 | 0.673032 | [
"MIT"
] | JaCraig/Craig-s-Utility-Library | Ironman.Core/Bootstrapper/DependencyResolver.cs | 2,568 | C# |
using UnityEngine;
using System.Collections;
public class BlueBlastScript : Projectile
{
protected void Awake()
{
damage = 35;
moveSpeed = 7.0f;
dissipateSpeed = 0.17f;
description = "A blast of blue?";
type = "water";
}
} | 19.714286 | 41 | 0.586957 | [
"MIT"
] | skywolf829/Project-Woden | Assets/Scripts/Entity.Projectiles/BlueBlastScript.cs | 278 | C# |
using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
namespace LiteUI.Controls
{
public enum WindowBarStyle { Hidden, Normal, Big }
public class Window : System.Windows.Window
{
static Window()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(Window), new FrameworkPropertyMetadata(typeof(Window)));
}
// IsFullscreen
public static readonly DependencyProperty IsFullscreenProperty = DependencyProperty.Register(
nameof(IsFullscreen),
typeof(bool),
typeof(Window),
new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.AffectsRender, FullscreenChanged)
);
[Bindable(true)]
[Category(nameof(LiteUI))]
public bool IsFullscreen
{
get => (bool)GetValue(IsFullscreenProperty);
set => SetValue(IsFullscreenProperty, value);
}
private static void FullscreenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var window = (Window)d;
window.MaxHeight = (bool)e.NewValue ? double.PositiveInfinity : SystemParameters.WorkArea.Height + 8;
if (window.WindowState == WindowState.Maximized)
{
window.WindowState = WindowState.Minimized;
window.WindowState = WindowState.Maximized;
}
}
// BarStyle
public static readonly DependencyProperty BarStyleProperty = DependencyProperty.Register(
nameof(BarStyle),
typeof(WindowBarStyle),
typeof(Window),
new FrameworkPropertyMetadata(WindowBarStyle.Normal, FrameworkPropertyMetadataOptions.AffectsRender)
);
[Bindable(true)]
[Category(nameof(LiteUI))]
public WindowBarStyle BarStyle
{
get => (WindowBarStyle)GetValue(BarStyleProperty);
set => SetValue(BarStyleProperty, value);
}
// Toolbar
public static readonly DependencyProperty ToolbarProperty = DependencyProperty.Register(
nameof(Toolbar),
typeof(ToolbarItemsCollection),
typeof(Window),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender)
);
[Bindable(true)]
[Category(nameof(LiteUI))]
public ToolbarItemsCollection Toolbar
{
get => (ToolbarItemsCollection)GetValue(ToolbarProperty);
set => SetValue(ToolbarProperty, value);
}
//
public Window()
{
// Forza aggiornamento dell'altezza massima
IsFullscreen = false;
// Inizializza comandi bottoni
CommandBindings.Add(new CommandBinding(SystemCommands.CloseWindowCommand, (_, __) => SystemCommands.CloseWindow(this)));
CommandBindings.Add(new CommandBinding(SystemCommands.MinimizeWindowCommand, (_, __) => SystemCommands.MinimizeWindow(this)));
CommandBindings.Add(new CommandBinding(SystemCommands.MaximizeWindowCommand, (_, __) => SystemCommands.MaximizeWindow(this)));
CommandBindings.Add(new CommandBinding(SystemCommands.RestoreWindowCommand, (_, __) => SystemCommands.RestoreWindow(this)));
}
}
} | 35.83871 | 138 | 0.642664 | [
"MIT"
] | ptr224/LambdaCom.LiteUI | LiteUI/Controls/Window.cs | 3,335 | 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: Templates\CSharp\Requests\IEntityCollectionPage.cs.tt
namespace Microsoft.Graph
{
using System;
using Newtonsoft.Json;
/// <summary>
/// The interface ICallParticipantsCollectionPage.
/// </summary>
[JsonConverter(typeof(InterfaceConverter<CallParticipantsCollectionPage>))]
public interface ICallParticipantsCollectionPage : ICollectionPage<Participant>
{
/// <summary>
/// Gets the next page <see cref="ICallParticipantsCollectionRequest"/> instance.
/// </summary>
ICallParticipantsCollectionRequest NextPageRequest { get; }
/// <summary>
/// Initializes the NextPageRequest property.
/// </summary>
void InitializeNextPageRequest(IBaseClient client, string nextPageLinkString);
}
}
| 37.393939 | 153 | 0.612642 | [
"MIT"
] | OfficeGlobal/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/ICallParticipantsCollectionPage.cs | 1,234 | C# |
using CanvasApi.Client.Modules.Enums;
using System.Collections.Generic;
using TiberHealth.Serializer.Attributes;
namespace CanvasApi.Client.Modules.Models
{
public interface IModuleItemSequenceOptions
{
/// <summary>
/// The type of asset to find module sequence information for. Use the ModuleItem if it is known(e.g., the user navigated from a module item), since this will avoid ambiguity if the asset appears more than once in the module sequence.
///
/// Allowed values: <see cref="ModuleItemSequenceAssetTypes"/>
/// </summary>
ModuleItemSequenceAssetTypes AssetType { get; set; }
/// <summary>
/// The id of the asset (or the url in the case of a Page)
/// </summary>
long? AssetId { get; set; }
}
} | 40.05 | 242 | 0.665418 | [
"MIT"
] | dbagnoli/CanvasApi | CanvasApi.Client/Modules/Models/IModuleItemSequenceOptions.cs | 803 | C# |
namespace Acoustics.Tools.Audio
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using log4net;
using Shared;
/// <summary>
/// Soxi (sound exchange information) Audio utility.
/// </summary>
public class SoxAudioUtility : AbstractAudioUtility, IAudioUtility
{
private readonly bool enableShortNameHack;
/*
* Some things to test out/try:
* stat - audio stats
* stats - audio stats
* spectrogram - create an image (has options to change)
* trim - segment audio
* fir - FFT with fir coefficients
*/
/// <summary>
/// Initializes a new instance of the <see cref="SoxAudioUtility"/> class.
/// </summary>
/// <param name="soxExe">
/// The exe file.
/// </param>
/// <exception cref="FileNotFoundException">
/// Could not find exe.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="soxExe"/> is <c>null</c>.
/// </exception>
public SoxAudioUtility(FileInfo soxExe)
{
this.CheckExe(soxExe, "sox");
this.ExecutableModify = soxExe;
this.ExecutableInfo = soxExe;
this.ResampleQuality = SoxResampleQuality.VeryHigh;
this.TemporaryFilesDirectory = TempFileHelper.TempDir();
}
/// <summary>
/// Initializes a new instance of the <see cref="SoxAudioUtility"/> class.
/// </summary>
/// <param name="soxExe">
/// The exe file.
/// </param>
/// <param name="temporaryFilesDirectory">
/// Which directory should hold temporary files.
/// </param>
/// <param name="enableShortNameHack">
/// Whether or not filenames with unicode characters should be shortened
/// to 8.3 filenames on Windows.
/// </param>
/// <exception cref="FileNotFoundException">
/// Could not find exe.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="soxExe"/> is <c>null</c>.
/// </exception>
public SoxAudioUtility(FileInfo soxExe, DirectoryInfo temporaryFilesDirectory, bool enableShortNameHack = true)
{
this.enableShortNameHack = enableShortNameHack;
this.CheckExe(soxExe, "sox");
this.ExecutableModify = soxExe;
this.ExecutableInfo = soxExe;
this.ResampleQuality = SoxResampleQuality.VeryHigh;
this.TemporaryFilesDirectory = temporaryFilesDirectory;
}
/// <summary>
/// Resample quality.
/// </summary>
public enum SoxResampleQuality
{
/// <summary>
/// −q
/// bandwidth: n/a
/// Rej dB: ~30 @ Fs/4
/// Typical Use: playback on ancient hardware.
/// </summary>
Quick = 0,
/// <summary>
/// −l
/// bandwidth: 80%
/// Rej dB: 100
/// Typical Use: playback on old hardware.
/// </summary>
Low = 1,
/// <summary>
/// −m
/// bandwidth: 95%
/// Rej dB: 100
/// Typical Use: audio playback.
/// </summary>
Medium = 2,
/// <summary>
/// −h
/// bandwidth: 125
/// Rej dB: 125
/// Typical Use: 16-bit mastering (use with dither).
/// </summary>
High = 3,
/// <summary>
/// −v
/// bandwidth: 95%
/// Rej dB: 175
/// Typical Use: 24-bit mastering.
/// </summary>
VeryHigh = 4
}
/// <summary>
/// Gets ResampleQuality.
/// </summary>
public SoxResampleQuality? ResampleQuality { get; private set; }
/// <summary>
/// Gets the valid source media types.
/// </summary>
protected override IEnumerable<string> ValidSourceMediaTypes => new[] { MediaTypes.MediaTypeWav, MediaTypes.MediaTypeMp3, MediaTypes.MediaTypeFlacAudio };
/// <summary>
/// Gets the invalid source media types.
/// </summary>
protected override IEnumerable<string> InvalidSourceMediaTypes => null;
/// <summary>
/// Gets the valid output media types.
/// </summary>
protected override IEnumerable<string> ValidOutputMediaTypes => new[] { MediaTypes.MediaTypeWav, MediaTypes.MediaTypeMp3 };
/// <summary>
/// Gets the invalid output media types.
/// </summary>
protected override IEnumerable<string> InvalidOutputMediaTypes => null;
/// <summary>
/// The construct modify args.
/// </summary>
/// <param name="source">
/// The source.
/// </param>
/// <param name="output">
/// The output.
/// </param>
/// <param name="request">
/// The request.
/// </param>
/// <returns>
/// The System.String.
/// </returns>
protected override string ConstructModifyArgs(FileInfo source, FileInfo output, AudioUtilityRequest request)
{
// resample - sox specific
var resampleQuality = this.ResampleQuality.HasValue
? "-" + GetResampleQuality(this.ResampleQuality.Value)
: string.Empty;
// allow aliasing/imaging above the pass-band: -a
// steep filter: -s
// resample
string rate = string.Empty;
string repeatable = string.Empty;
if (request.TargetSampleRate.HasValue)
{
var targetSampleRateHz = request.TargetSampleRate.Value.ToString(CultureInfo.InvariantCulture);
rate = $"rate {resampleQuality} -s -a {targetSampleRateHz}";
// the -R forces sox to run in repeatable mode. It makes SoX use the same seed for the random number generator
repeatable = " -R ";
}
var remix = FormatChannelSelection(request);
// offsets
var trim = string.Empty;
if (request.OffsetStart.HasValue && !request.OffsetEnd.HasValue)
{
trim = "trim " + request.OffsetStart.Value.TotalSeconds.ToString(CultureInfo.InvariantCulture);
}
else if (!request.OffsetStart.HasValue && request.OffsetEnd.HasValue)
{
trim = "trim 0 " + request.OffsetEnd.Value.TotalSeconds.ToString(CultureInfo.InvariantCulture);
}
else if (request.OffsetStart.HasValue && request.OffsetEnd.HasValue)
{
var delta = request.OffsetEnd.Value.TotalSeconds - request.OffsetStart.Value.TotalSeconds;
trim = FormattableString.Invariant($"trim {request.OffsetStart.Value.TotalSeconds} {delta}");
}
var bandpass = string.Empty;
if (request.BandPassType != BandPassType.None)
{
switch (request.BandPassType)
{
case BandPassType.Sinc:
bandpass += FormattableString.Invariant(
$"sinc {request.BandpassLow.Value / 1000}k-{request.BandpassHigh.Value / 1000}k");
break;
case BandPassType.Bandpass:
double width = request.BandpassHigh.Value - request.BandpassLow.Value;
var center = request.BandpassLow.Value + (width / 2.0);
bandpass += FormattableString.Invariant(
$"bandpass { center / 1000 }k { width / 1000 }k");
break;
case BandPassType.None:
default:
throw new ArgumentOutOfRangeException();
}
}
// example
// remix down to 1 channel, medium resample quality using steep filter with target sample rate of 11025hz
// sox input.wav output.wav remix - rate -m -s 11025
// −q, −−no−show−progress
// Run in quiet mode when SoX wouldn’t otherwise do so. This is the opposite of the −S option.
// SoX will encode complex files in the WAVE_FORMAT_EXTENSIBLE encoding by default - even if the source file way not WAVE_FORMAT_EXTENSIBLE.
// Since we largely don't care about any of the advanced features provided by WAVE_FORMAT_EXTENSIBLE we're going to tell sox to always output
// WAVE_FORMAT_PCM.
// More info:
// https://sourceforge.net/p/sox/mailman/message/5863667/
// http://www-mmsp.ece.mcgill.ca/documents/audioformats/wave/wave.html
// http://sox.sourceforge.net/soxformat.html
string forceOutput = string.Empty;
if (MediaTypes.GetMediaType(output.Extension) == MediaTypes.MediaTypeWav)
{
forceOutput = "-t wavpcm ";
}
return $"{repeatable} -q -V4 \"{this.FixFilename(source)}\" {forceOutput}\"{output.FullName}\" {trim} {rate} {remix} {bandpass}";
}
private static string FormatChannelSelection(AudioUtilityRequest request)
{
/*
* Where a range of channels is specified, the channel numbers to the left and right of the hyphen are
* optional and default to 1 and to the number of input channels respectively. Thus
* sox input.wav output.wav remix −
* performs a mix-down of all input channels to mono.
*/
var remix = string.Empty;
var mixDown = request.MixDownToMono.HasValue && request.MixDownToMono.Value;
if (mixDown && request.Channels.NotNull())
{
// select a subset of channels
remix = "remix " + string.Join(",", request.Channels);
}
else if (mixDown)
{
// mix down to mono
remix = "remix -";
}
else if (request.Channels.NotNull())
{
// get channels but don't mix down
remix = "remix " + string.Join(" ", request.Channels);
}
return remix;
}
/// <summary>
/// The construct info args.
/// </summary>
/// <param name="source">
/// The source.
/// </param>
/// <returns>
/// The System.String.
/// </returns>
protected override string ConstructInfoArgs(FileInfo source)
{
string args = $" --info -V4 \"{this.FixFilename(source)}\"";
return args;
}
/// <summary>
/// The get info.
/// </summary>
/// <param name="source">
/// The source.
/// </param>
/// <param name="process">
/// The process.
/// </param>
/// <returns>
/// The Acoustics.Tools.AudioUtilityInfo.
/// </returns>
protected override AudioUtilityInfo GetInfo(FileInfo source, ProcessRunner process)
{
IEnumerable<string> errorlines = process.ErrorOutput.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
// if no lines, or any line contains "no handler for file extension", return empty
if (errorlines.Any(l => l.Contains("no handler for file extension")))
{
return new AudioUtilityInfo();
}
IEnumerable<string> lines = process.StandardOutput.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
var result = new AudioUtilityInfo();
result.SourceFile = source;
foreach (var line in lines)
{
var firstColon = line.IndexOf(':');
if (firstColon > -1)
{
var key = line.Substring(0, firstColon).Trim();
var value = line.Substring(firstColon + 1).Trim();
if (key == "Duration")
{
var values = value.Split('=', '~');
// duration
result.RawData.Add(key, values[0].Trim());
// sample count
result.RawData.Add("Samples", values[1].Replace("samples", string.Empty).Trim());
// approx. CDDA sectors
result.RawData.Add("CDDA sectors", values[2].Replace("CDDA sectors", string.Empty).Trim());
}
else
{
result.RawData.Add(key, value);
}
}
}
// parse info info class
const string keyDuration = "Duration";
const string keySamples = "Samples";
const string keyBitRate = "Bit Rate";
const string keySampleRate = "Sample Rate";
const string keyChannels = "Channels";
const string keyPrecision = "Precision";
if (result.RawData.ContainsKey(keySampleRate))
{
result.SampleRate = this.ParseIntStringWithException(result.RawData[keySampleRate], "sox.samplerate");
}
if (result.RawData.ContainsKey(keyDuration))
{
var sampleCount = result.RawData[keySamples];
// most precise and efficient calculation, duration from sample count
if (sampleCount.IsNotEmpty() && result.SampleRate.HasValue)
{
var samples = this.ParseLongStringWithException(sampleCount, "Samples");
var duration = Math.Round((decimal)samples.Value / result.SampleRate.Value, 6, MidpointRounding.AwayFromZero);
result.Duration = TimeSpan.FromSeconds((double)duration);
}
else
{
// less precise and problematic for very long recordings (because of timespan parsing)
// but still faster than another invocation
var stringDuration = result.RawData[keyDuration];
var formats = new[]
{
@"h\:mm\:ss\.ff", @"hh\:mm\:ss\.ff", @"h:mm:ss.ff",
@"hh:mm:ss.ff",
};
if (TimeSpan.TryParseExact(stringDuration.Trim(), formats, CultureInfo.InvariantCulture,
out var duration))
{
result.Duration = duration;
}
else
{
// last resort: ask sox specifically for the duration with another invocation
// AT: this case used to always happen even if it was not necessary
var extra = this.Duration(source);
if (extra.HasValue)
{
result.Duration = extra.Value;
}
}
}
}
if (result.RawData.ContainsKey(keyChannels))
{
result.ChannelCount = this.ParseIntStringWithException(result.RawData[keyChannels], "sox.channels");
}
if (result.RawData.ContainsKey(keyPrecision))
{
result.BitsPerSample = this.ParseIntStringWithException(result.RawData[keyPrecision].Replace("-bit", string.Empty).Trim(), "sox.precision");
if (result.BitsPerSample < 1)
{
result.BitsPerSample = null;
}
}
result.MediaType = GetMediaType(result.RawData, source.Extension);
if (result.RawData.ContainsKey(keyBitRate))
{
var stringValue = result.RawData[keyBitRate];
int magnitude = 1;
if (stringValue.Contains("k"))
{
stringValue = stringValue.Replace("k", string.Empty);
magnitude = 1000;
}
if (stringValue.Contains("M"))
{
stringValue = stringValue.Replace("M", string.Empty);
magnitude = 1_000_000;
}
if (stringValue.Contains("G") || stringValue.Contains("T"))
{
throw new NotSupportedException(
$"The file {source.FullName} reported a bit rate of {stringValue} which is not supported");
}
var value = double.Parse(stringValue, CultureInfo.InvariantCulture);
value = value * magnitude;
result.BitsPerSecond = Convert.ToInt32(value);
// Further investigation reveals the 'error' I was chasing down was in fact the difference
// between the FormatBitRate (averaged inc. header) and the StreamBitRate.
// For long files this difference approaches 0, for short files the difference is significant
//if (result.MediaType == MediaTypes.MediaTypeWav)
//{
// // deal with inaccuracy - calculate it a second way
// var estimatedBitRate = result.SampleRate * result.ChannelCount * result.BitsPerSample;
// int roundedBitRate = (int)((double)estimatedBitRate).RoundToSignficantDigits(3);
// if (roundedBitRate != result.BitsPerSecond.Value)
// {
// throw new InvalidOperationException(
// $"SoxAudioUtlity could not accurately predict BitPerSecond. Parsed BitsPerSecond: {result.BitsPerSecond}, predicted: {estimatedBitRate}");
// }
//
// // use estimated bit rate
// result.BitsPerSecond = estimatedBitRate;
//}
}
return result;
}
protected override void CheckRequestValid(FileInfo source, string sourceMimeType, FileInfo output, string outputMediaType, AudioUtilityRequest request)
{
AudioUtilityInfo info = null;
if (request?.BitDepth != null)
{
const string message = "Haven't added support for changing bit depth in" + nameof(SoxAudioUtility);
throw new BitDepthOperationNotImplemented(message);
}
// check that if output is mp3, the bit rate and sample rate are set valid amounts.
if (request != null && outputMediaType == MediaTypes.MediaTypeMp3)
{
if (request.TargetSampleRate.HasValue)
{
// sample rate is set - check it
this.CheckMp3SampleRate(request.TargetSampleRate.Value);
}
else
{
// sample rate is not set, get it from the source file
info = this.Info(source);
if (!info.SampleRate.HasValue)
{
throw new ArgumentException("Sample rate for output mp3 may not be correct, as sample rate is not set, and cannot be determined from source file.");
}
this.CheckMp3SampleRate(info.SampleRate.Value);
}
}
if (request != null && request.Channels.NotNull())
{
if (request.Channels.Length == 0)
{
throw new ChannelSelectionOperationNotImplemented("Sox utility cannot choose 0 channels");
}
int max = request.Channels.Max();
int min = request.Channels.Min();
info = info ?? this.Info(source);
if (max > info.ChannelCount || min < 1)
{
var msg = $"Requested channel number was out of range. Requested channel {max} but there are only {info.ChannelCount} channels in {source}.";
throw new ChannelNotAvailableException(nameof(request.Channels), request.Channels.ToCommaSeparatedList(), msg);
}
}
}
private static string GetResampleQuality(SoxResampleQuality rq)
{
switch (rq)
{
case SoxResampleQuality.Quick:
return "q";
case SoxResampleQuality.Low:
return "l";
case SoxResampleQuality.Medium:
return "m";
case SoxResampleQuality.High:
return "h";
case SoxResampleQuality.VeryHigh:
return "v";
default:
return "m";
}
}
private static TimeSpan Parse(string timeToParse)
{
try
{
string hours = timeToParse.Substring(0, 2);
string minutes = timeToParse.Substring(3, 2);
string seconds = timeToParse.Substring(6, 2);
string fractions = timeToParse.Substring(9, 2);
return new TimeSpan(
0, int.Parse(hours), int.Parse(minutes), int.Parse(seconds), int.Parse(fractions) * 10);
}
catch
{
return TimeSpan.Zero;
}
}
private string FixFilename(FileInfo file)
{
var path = file.FullName;
if (!this.enableShortNameHack)
{
return path;
}
if (!AppConfigHelper.IsWindows)
{
return path;
}
if (!PathUtils.HasUnicodeOrUnsafeChars(path))
{
return path;
}
var shortPath = PathUtils.GetShortFilename(path);
this.Log.Trace(
$"SoX unicode path bug avoided by shortening '{path}' to '{shortPath}'");
return shortPath;
}
private AudioUtilityInfo SoxStats(FileInfo source)
{
/*
* −w name
* Window: Hann (default), Hamming, Bartlett, Rectangular or Kaiser
*
*
sox "I:\Projects\QUT\QutSensors\sensors-trunk\QutSensors.Test\TestData\FemaleKoala MaleKoala.wav" -n
* stat stats trim 0 60 spectrogram -m -r -l -w Bartlett -X 45 -y 257 -o
* "I:\Projects\QUT\QutSensors\sensors-trunk\QutSensors.Test\TestData\FemaleKoala MaleKoala.png"
* stats stat
*
* sox "I:\Projects\QUT\QutSensors\sensors-trunk\QutSensors.Test\TestData\FemaleKoala MaleKoala.wav" -n stat stats trim 0 60 spectrogram -m -r -l -w Bartlett -X 45 -y 257 -o "I:\Projects\QUT\QutSensors\sensors-trunk\QutSensors.Test\TestData\FemaleKoala MaleKoala.png" stats stat
sox "I:\Projects\QUT\QutSensors\sensors-trunk\QutSensors.Test\TestData\GParrots_JB2_20090607-173000.wav_minute_8.wav" -n trim 0 10 noiseprof | sox "I:\Projects\QUT\QutSensors\sensors-trunk\QutSensors.Test\TestData\GParrots_JB2_20090607-173000.wav_minute_8.wav" "I:\Projects\QUT\QutSensors\sensors-trunk\QutSensors.Test\TestData\GParrots_JB2_20090607-173000.wav_minute_8-reduced.wav" noisered
sox "I:\Projects\QUT\QutSensors\sensors-trunk\QutSensors.Test\TestData\GParrots_JB2_20090607-173000.wav_minute_8-reduced.wav" -n spectrogram -m -r -l -w Bartlett -X 45 -y 257 -o "I:\Projects\QUT\QutSensors\sensors-trunk\QutSensors.Test\TestData\GParrots_JB2_20090607-173000.wav_minute_8-reduced.png" stats stat
I:\Projects\QUT\QutSensors\sensors-trunk\Extra Assemblies\sox>sox "I:\Projects\QUT\QutSensors\sensors-trunk\QutSensors.Test\TestData\FemaleKoala MaleKoala.wav" -n trim 0 60 spectrogram -m -r -l -w Bartlett -X 45 -y 257 -o "I:\Projects\QUT\QutSensors\sensors-trunk\QutSensors.Test\TestData\FemaleKoal
a MaleKoala.png" -z 180 -q 100 stats stat noiseprof
*
* Could also do this for every minute of recording, using trim <start seconds> <end seconds> and looping.
*/
this.CanProcess(source, null, null);
IEnumerable<string> lines;
using (var process = new ProcessRunner(this.ExecutableInfo.FullName))
{
string args = "\"" + source.FullName + "\" -n stat stats";
this.RunExe(process, args, source.DirectoryName);
if (this.Log.IsDebugEnabled)
{
this.Log.Debug("Source " + this.BuildFileDebuggingOutput(source));
}
lines = process.ErrorOutput.Split(new[] {'\n', '\r'}, StringSplitOptions.RemoveEmptyEntries);
}
// if no lines, or any line contains "no handler for file extension", return empty
if (!lines.Any() || lines.Any(l => l.Contains("no handler for file extension")))
{
return new AudioUtilityInfo();
}
//
// first 15 are split by colon (:)
var statOutputRaw = lines.Take(15).Select(l => l.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries).Select(i => i.Trim()));
var statOutput = statOutputRaw.Select(i => new KeyValuePair<string, string>(i.First(), i.Skip(1).First()));
var results = statOutput.ToDictionary(item => item.Key, item => item.Value);
lines = lines.Skip(15);
// if there is a line that starts with 'Overall' (after being trimed), then count the number of words.
// next 11 may have 1 value, may have more than one
var isMoreThanOneChannel = lines.First().Trim().Contains("Overall");
if (isMoreThanOneChannel)
{
var header = lines.First();
var headerNames = header.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var numValues = headerNames.Count();
lines = lines.Skip(1);
for (var index = 0; index < 11; index++)
{
string[] currentLine = lines.First().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
string keyName = lines.First();
var tempHeaderCount = numValues;
while (tempHeaderCount > 0)
{
keyName = keyName.Substring(0, keyName.LastIndexOf(' ')).Trim();
tempHeaderCount--;
}
for (var headerIndex = 0; headerIndex < numValues; headerIndex++)
{
var value = currentLine[currentLine.Length - 1 - headerIndex];
var channelName = headerNames[numValues - 1 - headerIndex];
results.Add(keyName + " " + channelName, value);
}
lines = lines.Skip(1);
}
}
// next 4 always 1 value
foreach (var line in lines)
{
var index = line.Trim().LastIndexOf(' ');
var keyName = line.Substring(0, index).Trim();
var value = line.Substring(index).Trim();
results.Add(keyName, value);
}
return new AudioUtilityInfo { RawData = results };
}
private TimeSpan? Duration(FileInfo source)
{
IEnumerable<string> lines;
using (var process = new ProcessRunner(this.ExecutableInfo.FullName))
{
string args = " --info -D \"" + source.FullName + "\"";
this.RunExe(process, args, source.DirectoryName);
if (this.Log.IsDebugEnabled)
{
this.Log.Debug("Source " + this.BuildFileDebuggingOutput(source));
}
IEnumerable<string> errorlines = process.ErrorOutput.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
// if no lines, or any line contains "no handler for file extension", return empty
if (errorlines.Any(l => l.Contains("no handler for file extension")))
{
return null;
}
lines = process.StandardOutput.Split(new[] {'\n', '\r'}, StringSplitOptions.RemoveEmptyEntries);
}
return TimeSpan.FromSeconds(this.ParseDoubleStringWithException(lines.FirstOrDefault(), "Duration").Value);
}
private static string GetMediaType(Dictionary<string, string> rawData, string extension)
{
var ext = extension.Trim('.');
// separate stream and format
var formats = rawData.Where(item => item.Key.Contains("Sample Encoding"));
foreach (var item in formats)
{
switch (item.Value)
{
case "MPEG audio (layer I, II or III)":
return MediaTypes.MediaTypeMp3;
case "Vorbis":
return MediaTypes.MediaTypeOggAudio;
case "16-bit Signed Integer PCM":
return MediaTypes.MediaTypeWav;
case "16-bit WavPack":
return MediaTypes.MediaTypeWavpack;
case "16-bit FLAC":
return MediaTypes.MediaTypeFlacAudio;
default:
return null;
}
}
return null;
}
}
}
| 40.371314 | 391 | 0.525916 | [
"Apache-2.0"
] | MazenImadJaber/audio-analysis | src/Acoustics.Tools/Audio/SoxAudioUtility.cs | 30,145 | C# |
// Copyright (c) 2001-2021 Aspose Pty Ltd. All Rights Reserved.
//
// This file is part of Aspose.Words. The source code in this file
// is only intended as a supplement to the documentation, and is provided
// "as is", without warranty of any kind, either expressed or implied.
//////////////////////////////////////////////////////////////////////////
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using Aspose.Words;
using NUnit.Framework;
namespace ApiExamples
{
/// <summary>
/// Provides common infrastructure for all API examples that are implemented as unit tests.
/// </summary>
public class ApiExampleBase
{
[OneTimeSetUp]
public void OneTimeSetUp()
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
ServicePointManager.ServerCertificateValidationCallback = new
RemoteCertificateValidationCallback
(
delegate { return true; }
);
SetUnlimitedLicense();
if (!Directory.Exists(ArtifactsDir))
Directory.CreateDirectory(ArtifactsDir);
}
[SetUp]
public void SetUp()
{
if (CheckForSkipMono() && IsRunningOnMono())
{
Assert.Ignore("Test skipped on mono");
}
Console.WriteLine($"Clr: {RuntimeInformation.FrameworkDescription}\n");
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
ServicePointManager.ServerCertificateValidationCallback = new
RemoteCertificateValidationCallback
(
delegate { return false; }
);
if (Directory.Exists(ArtifactsDir))
Directory.Delete(ArtifactsDir, true);
}
/// <summary>
/// Checks when we need to ignore test on mono.
/// </summary>
private static bool CheckForSkipMono()
{
bool skipMono = TestContext.CurrentContext.Test.Properties["Category"].Contains("SkipMono");
return skipMono;
}
/// <summary>
/// Determine if runtime is Mono.
/// Workaround for .netcore.
/// </summary>
/// <returns>True if being executed in Mono, false otherwise.</returns>
internal static bool IsRunningOnMono() {
return Type.GetType("Mono.Runtime") != null;
}
internal static void SetUnlimitedLicense()
{
// This is where the test license is on my development machine.
string testLicenseFileName = Path.Combine(LicenseDir, "Aspose.Total.NET.lic");
if (File.Exists(testLicenseFileName))
{
// This shows how to use an Aspose.Words license when you have purchased one.
// You don't have to specify full path as shown here. You can specify just the
// file name if you copy the license file into the same folder as your application
// binaries or you add the license to your project as an embedded resource.
License wordsLicense = new License();
wordsLicense.SetLicense(testLicenseFileName);
Aspose.Pdf.License pdfLicense = new Aspose.Pdf.License();
pdfLicense.SetLicense(testLicenseFileName);
Aspose.BarCode.License barcodeLicense = new Aspose.BarCode.License();
barcodeLicense.SetLicense(testLicenseFileName);
}
}
/// <summary>
/// Returns the code-base directory.
/// </summary>
internal static string GetCodeBaseDir(Assembly assembly)
{
// CodeBase is a full URI, such as file:///x:\blahblah.
Uri uri = new Uri(assembly.CodeBase);
string mainFolder = Path.GetDirectoryName(uri.LocalPath)
?.Substring(0, uri.LocalPath.IndexOf("ApiExamples", StringComparison.Ordinal));
return mainFolder;
}
/// <summary>
/// Returns the assembly directory correctly even if the assembly is shadow-copied.
/// </summary>
internal static string GetAssemblyDir(Assembly assembly)
{
// CodeBase is a full URI, such as file:///x:\blahblah.
Uri uri = new Uri(assembly.CodeBase);
return Path.GetDirectoryName(uri.LocalPath) + Path.DirectorySeparatorChar;
}
/// <summary>
/// Gets the path to the currently running executable.
/// </summary>
internal static string AssemblyDir { get; }
/// <summary>
/// Gets the path to the codebase directory.
/// </summary>
internal static string CodeBaseDir { get; }
/// <summary>
/// Gets the path to the license used by the code examples.
/// </summary>
internal static string LicenseDir { get; }
/// <summary>
/// Gets the path to the documents used by the code examples. Ends with a back slash.
/// </summary>
internal static string ArtifactsDir { get; }
/// <summary>
/// Gets the path to the documents used by the code examples. Ends with a back slash.
/// </summary>
internal static string GoldsDir { get; }
/// <summary>
/// Gets the path to the documents used by the code examples. Ends with a back slash.
/// </summary>
internal static string MyDir { get; }
/// <summary>
/// Gets the path to the images used by the code examples. Ends with a back slash.
/// </summary>
internal static string ImageDir { get; }
/// <summary>
/// Gets the path of the demo database. Ends with a back slash.
/// </summary>
internal static string DatabaseDir { get; }
/// <summary>
/// Gets the path of the free fonts. Ends with a back slash.
/// </summary>
internal static string FontsDir { get; }
/// <summary>
/// Gets the URL of the Aspose logo.
/// </summary>
internal static string AsposeLogoUrl { get; }
static ApiExampleBase()
{
AssemblyDir = GetAssemblyDir(Assembly.GetExecutingAssembly());
CodeBaseDir = GetCodeBaseDir(Assembly.GetExecutingAssembly());
ArtifactsDir = new Uri(new Uri(CodeBaseDir), @"Data/Artifacts/").LocalPath;
LicenseDir = new Uri(new Uri(CodeBaseDir), @"Data/License/").LocalPath;
GoldsDir = new Uri(new Uri(CodeBaseDir), @"Data/Golds/").LocalPath;
MyDir = new Uri(new Uri(CodeBaseDir), @"Data/").LocalPath;
ImageDir = new Uri(new Uri(CodeBaseDir), @"Data/Images/").LocalPath;
DatabaseDir = new Uri(new Uri(CodeBaseDir), @"Data/Database/").LocalPath;
FontsDir = new Uri(new Uri(CodeBaseDir), @"Data/MyFonts/").LocalPath;
AsposeLogoUrl = new Uri("https://www.aspose.cloud/templates/aspose/App_Themes/V3/images/words/header/aspose_words-for-net.png").AbsoluteUri;
}
}
} | 37.670103 | 152 | 0.58867 | [
"MIT"
] | Web-Dev-Collaborative/Aspose.Words-for-.NET | Examples/ApiExamples/ApiExamples/ApiExampleBase.cs | 7,310 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using IdSharp.Common.Events;
using IdSharp.Common.Utils;
using IdSharp.Tagging.ID3v1;
using IdSharp.Tagging.ID3v2.Frames;
namespace IdSharp.Tagging.ID3v2
{
/// <summary>
/// ID3v2 Frame Container
/// </summary>
public abstract partial class FrameContainer : IFrameContainer
{
/// <summary>
/// Occurs when a property value changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Occurs when invalid data is assigned to a property.
/// </summary>
public event InvalidDataEventHandler InvalidData;
internal void Read(Stream stream, ID3v2TagVersion tagVersion, TagReadingInfo tagReadingInfo, int readUntil, int frameIDSize)
{
Dictionary<string, IBindingList> multipleOccurrenceFrames = GetMultipleOccurrenceFrames(tagVersion);
Dictionary<string, IFrame> singleOccurrenceFrames = GetSingleOccurrenceFrames(tagVersion);
int bytesRead = 0;
while (bytesRead < readUntil)
{
byte[] frameIDBytes = stream.Read(frameIDSize);
// If character is not a letter or number, padding reached, audio began,
// or otherwise the frame is not readable
if (frameIDSize == 4)
{
if (frameIDBytes[0] < 0x30 || frameIDBytes[0] > 0x5A ||
frameIDBytes[1] < 0x30 || frameIDBytes[1] > 0x5A ||
frameIDBytes[2] < 0x30 || frameIDBytes[2] > 0x5A ||
frameIDBytes[3] < 0x30 || frameIDBytes[3] > 0x5A)
{
// TODO: Try to keep reading and look for a valid frame
if (frameIDBytes[0] != 0 && frameIDBytes[0] != 0xFF)
{
string msg = string.Format("Out of range FrameID - 0x{0:X}|0x{1:X}|0x{2:X}|0x{3:X}",
frameIDBytes[0], frameIDBytes[1], frameIDBytes[2], frameIDBytes[3]);
if (ByteUtils.ISO88591GetString(frameIDBytes) != "MP3e")
{
string tmpBadFrameID = ByteUtils.ISO88591GetString(frameIDBytes).TrimEnd('\0');
Trace.WriteLine(msg + " - " + tmpBadFrameID);
}
}
break;
}
}
else if (frameIDSize == 3)
{
if (frameIDBytes[0] < 0x30 || frameIDBytes[0] > 0x5A ||
frameIDBytes[1] < 0x30 || frameIDBytes[1] > 0x5A ||
frameIDBytes[2] < 0x30 || frameIDBytes[2] > 0x5A)
{
// TODO: Try to keep reading and look for a valid frame
if (frameIDBytes[0] != 0 && frameIDBytes[0] != 0xFF)
{
string msg = string.Format("Out of range FrameID - 0x{0:X}|0x{1:X}|0x{2:X}",
frameIDBytes[0], frameIDBytes[1], frameIDBytes[2]);
Trace.WriteLine(msg);
Trace.WriteLine(ByteUtils.ISO88591GetString(frameIDBytes));
}
break;
}
}
string frameID = ByteUtils.ISO88591GetString(frameIDBytes);
// TODO: Take out
//Console.WriteLine(tmpFrameID); // TODO: take out
/*
COMM Frames:
SoundJam_CDDB_TrackNumber
SoundJam_CDDB_1
iTunNORM
iTunSMPB
iTunes_CDDB_IDs
iTunes_CDDB_1
iTunes_CDDB_TrackNumber
*/
IFrame frame;
do
{
IBindingList bindingList;
if (singleOccurrenceFrames.TryGetValue(frameID, out frame))
{
frame.Read(tagReadingInfo, stream);
bytesRead += frame.FrameHeader.FrameSizeTotal;
//m_ReadFrames.Add(tmpFrame);
}
else if (multipleOccurrenceFrames.TryGetValue(frameID, out bindingList))
{
frame = (IFrame)bindingList.AddNew();
frame.Read(tagReadingInfo, stream);
//m_ReadFrames.Add(tmpFrame);
bytesRead += frame.FrameHeader.FrameSizeTotal;
}
else
{
if (tagVersion == ID3v2TagVersion.ID3v24)
{
string newFrameID;
if (_id3v24FrameAliases.TryGetValue(frameID, out newFrameID))
frameID = newFrameID;
else
break;
}
else if (tagVersion == ID3v2TagVersion.ID3v23)
{
string newFrameID;
if (_id3v23FrameAliases.TryGetValue(frameID, out newFrameID))
frameID = newFrameID;
else
break;
}
else
{
break;
}
}
} while (frame == null);
// Frame is unknown
if (frame == null)
{
if (frameID != "NCON" && // non standard (old music match)
frameID != "MJMD" && // Non standard frame (Music Match XML)
frameID != "TT22" && // 000.00 - maybe meant to be 3 letter TT2 frame, and value be 2000.00? still makes no sense
frameID != "PCST" && // null data
frameID != "TCAT" && // category (ie, comedy) (distorted view)
frameID != "TKWD" && // looks like blog tags "comedy funny weird", etc (distorted view)
frameID != "TDES" && // xml file - used by distortedview.com
frameID != "TGID" && // url (from distortedview)
frameID != "WFED" && // url (thanks distortedview)
frameID != "CM1" && // some kind of comment, seen in ID3v2.2
frameID != "TMB" && // ripped by something other, not in spec
frameID != "RTNG" &&
frameID != "XDOR" && // year
frameID != "XSOP" && // looks like artist, "Allman Brothers Band, The"
frameID != "TENK") // itunes encoder (todo: add alias?)
{
/*String msg = String.Format("Unrecognized FrameID '{0}' (not critical)", tmpFrameID);
Trace.WriteLine(msg);*/
}
UnknownFrame unknownFrame = new UnknownFrame(frameID, tagReadingInfo, stream);
_unknownFrames.Add(unknownFrame);
//m_ReadFrames.Add(tmpUNKN);
bytesRead += unknownFrame.FrameHeader.FrameSizeTotal;
}
}
// Process iTunes comments
foreach (var comment in new List<IComments>(m_CommentsList))
{
if (comment.Description != null && comment.Description.StartsWith("iTun"))
{
m_CommentsList.Remove(comment);
m_iTunesCommentsList.Add(comment);
}
}
// Process genre // TODO: may need cleanup
if (!string.IsNullOrEmpty(m_Genre.Value))
{
if (m_Genre.Value.StartsWith("("))
{
int closeIndex = m_Genre.Value.IndexOf(')');
if (closeIndex != -1)
{
if (closeIndex != m_Genre.Value.Length - 1)
{
// Take text description
m_Genre.Value = m_Genre.Value.Substring(closeIndex + 1, m_Genre.Value.Length - (closeIndex + 1));
}
else
{
// Lookup genre value
string innerValue = m_Genre.Value.Substring(1, closeIndex - 1);
int innerValueResult;
if (int.TryParse(innerValue, out innerValueResult))
{
if (GenreHelper.GenreByIndex.Length > innerValueResult && innerValueResult >= 0)
{
m_Genre.Value = GenreHelper.GenreByIndex[innerValueResult];
}
else
{
Trace.WriteLine("Unrecognized genre");
}
}
else
{
Trace.WriteLine("Unrecognized genre");
}
}
}
}
}
}
internal List<IFrame> GetAllFrames(ID3v2TagVersion tagVersion)
{
Dictionary<string, IBindingList> multipleOccurrenceFrames = GetMultipleOccurrenceFrames(tagVersion);
Dictionary<string, IFrame> singleOccurenceFrames = GetSingleOccurrenceFrames(tagVersion);
List<IFrame> allFrames = new List<IFrame>();
allFrames.AddRange(singleOccurenceFrames.Select(p => p.Value));
foreach (KeyValuePair<string, IBindingList> kvp in multipleOccurrenceFrames)
{
IBindingList bindingList = kvp.Value;
allFrames.AddRange(bindingList.Cast<IFrame>());
// Special handling for iTunes comment frames
if (kvp.Key == "COMM" || kvp.Key == "COM")
{
allFrames.AddRange(m_iTunesCommentsList);
}
}
allFrames.AddRange(_unknownFrames);
foreach (IFrame frame in new List<IFrame>(allFrames))
{
if (frame.GetBytes(tagVersion).Length == 0)
allFrames.Remove(frame);
}
return allFrames;
}
internal List<IFrame> GetAllFrames(ID3v2TagVersion tagVersion, string frameID)
{
if (string.IsNullOrEmpty(frameID))
throw new ArgumentNullException("frameID");
return GetAllFrames(tagVersion, new List<string> { frameID });
}
internal List<IFrame> GetAllFrames(ID3v2TagVersion tagVersion, IEnumerable<string> frameIDs)
{
if (frameIDs == null)
throw new ArgumentNullException("frameIDs");
List<IFrame> allFrames = GetAllFrames(tagVersion);
foreach (IFrame frame in new List<IFrame>(allFrames))
{
bool found = false;
foreach (string frameID in frameIDs)
{
if (frame.GetFrameID(ID3v2TagVersion.ID3v22) == frameID ||
frame.GetFrameID(ID3v2TagVersion.ID3v23) == frameID ||
frame.GetFrameID(ID3v2TagVersion.ID3v24) == frameID)
{
found = true;
break;
}
}
if (!found)
allFrames.Remove(frame);
}
return allFrames;
}
internal byte[] GetBytes(ID3v2TagVersion tagVersion)
{
using (MemoryStream frameData = new MemoryStream())
{
// Note: this doesn't use GetAllFrames() because it would cause multiple calls to IFrame.GetBytes
Dictionary<string, IBindingList> multipleOccurrenceFrames = GetMultipleOccurrenceFrames(tagVersion);
Dictionary<string, IFrame> singleOccurrenceFrames = GetSingleOccurrenceFrames(tagVersion);
foreach (var frame in singleOccurrenceFrames.Values)
{
byte[] rawData = frame.GetBytes(tagVersion);
frameData.Write(rawData);
}
foreach (KeyValuePair<string, IBindingList> kvp in multipleOccurrenceFrames)
{
IBindingList bindingList = kvp.Value;
foreach (var frame in bindingList.Cast<IFrame>())
{
byte[] rawData = frame.GetBytes(tagVersion);
frameData.Write(rawData);
}
// Special handling for iTunes comment frames
if (kvp.Key == "COMM" || kvp.Key == "COM")
{
foreach (var frame in m_iTunesCommentsList)
{
byte[] rawData = frame.GetBytes(tagVersion);
frameData.Write(rawData);
}
}
}
foreach (UnknownFrame unknownFrame in _unknownFrames)
{
//if (m_ReadFrames.Contains(tmpUNKN))
// continue;
byte[] rawData = unknownFrame.GetBytes(tagVersion);
frameData.Write(rawData);
}
return frameData.ToArray();
}
}
/// <summary>
/// Forces the <see cref="INotifyPropertyChanged.PropertyChanged"/> event to fire.
/// </summary>
/// <param name="propertyName">The property name.</param>
public void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler propertyChanged = PropertyChanged;
if (propertyChanged != null)
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
| 42.55814 | 137 | 0.46373 | [
"MIT"
] | Mapaler/osu-export | IdSharp/IdSharp.Tagging/ID3v2/Classes/FrameContainer.cs | 14,640 | C# |
using System.Configuration;
namespace Sitecore.Foundation.Common.Specflow.Extensions.Infrastructure
{
using System;
using Sitecore.Foundation.Common.Specflow.UtfService;
public class BaseSettings
{
public static string BaseUrl => ConfigurationManager.AppSettings["baseUrl"];
public static string RegisterPageUrl => BaseUrl + ConfigurationManager.AppSettings["registerUrl"];
public static string LoginPageUrl => BaseUrl + ConfigurationManager.AppSettings["loginPageUrl"];
public static string EditUserProfileUrl => BaseUrl + ConfigurationManager.AppSettings["editUserProfileUrl"];
public static string ContactUsPageUrl => BaseUrl + ConfigurationManager.AppSettings["contactUsPageUrl"];
public static string TestHelperService => BaseUrl + ConfigurationManager.AppSettings["testsProxyUrl"];
public static string ForgotPasswordPageUrl => BaseUrl + ConfigurationManager.AppSettings["forgotPasswordUrl"];
public static string EndSessionUrl => BaseUrl + ConfigurationManager.AppSettings["endSessionUrl"];
public static string UtfHelperService => BaseUrl + ConfigurationManager.AppSettings["utfProxyUrl"];
public static string UserName => "sitecore\\admin";
public static string UserNameOnUi => "admin";
public static string Password => "b";
public static string EndVisitUrl => BaseUrl + ConfigurationManager.AppSettings["endVisitUrl"];
public static string DemoSiteUrl => ConfigurationManager.AppSettings["demoSiteUrl"];
public static string DemoSiteCampaignUrl => ConfigurationManager.AppSettings["demoSiteCampaignUrl"];
public static string FormsPageUrl =>BaseUrl + ConfigurationManager.AppSettings["formsPageUrl"];
public static string EmployeeList => BaseUrl + ConfigurationManager.AppSettings["employeeList"];
public static string GettingStartedPageUrl => BaseUrl + ConfigurationManager.AppSettings["GettingStartedPageUrl"];
public static string ExperianceEditorUrl => BaseUrl + ConfigurationManager.AppSettings["ExperianceEditorUrl"];
public static string SocialPageExperienceEditorUrl => BaseUrl + ConfigurationManager.AppSettings["SocialPageExperienceEditorUrl"];
public static string SocialPageUrl => BaseUrl + ConfigurationManager.AppSettings["SocialPageUrl"];
public static string MainPageExperienceEditorUrl => BaseUrl + ConfigurationManager.AppSettings["MainPageExperienceEditorUrl"];
public static Database ContextDatabase => (Database)Enum.Parse(typeof(Database), ConfigurationManager.AppSettings["database"]);
}
} | 52.9375 | 134 | 0.794963 | [
"Apache-2.0"
] | BIGANDYT/HabitatDemo | src/Project/Habitat/specs/Foundation.Common/Extensions/Infrastructure/BaseSettings.cs | 2,543 | C# |
using Kimera.Entities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Kimera
{
public class Settings
{
private static Settings _instance;
public static Settings Instance
{
get
{
if (_instance == null)
{
_instance = new Settings();
}
return _instance;
}
set
{
_instance = value;
}
}
public readonly static Guid GUID_ALL_CATEGORY = Guid.Parse("B34641DF-A149-4670-BB27-D0A9696B3E3F");
public readonly static Guid GUID_FAVORITE_CATEGORY = Guid.Parse("DD297C4A-3CC4-4E67-8E5F-512B02B5AF61");
#region ::Application Settings::
#endregion
#region ::General::
/// <summary>
/// Gets or sets the work directory which is used by kimera.
/// </summary>
public string WorkDirectory { get; set; } = Path.Combine(Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.Windows)), "Kimera");
#endregion
#region ::Network::
/// <summary>
/// Gets or sets the value whether the Anti DPI Service is used or not.
/// </summary>
public bool UseAntiDPIService { get; set; } = true;
#endregion
#region ::Game Service::
/// <summary>
/// Gets or sets the value whether the auto remover is used or not.
/// </summary>
public bool UseAutoRemover { get; set; } = false;
/// <summary>
/// Gets or sets the interval(days) of auto removing task.
/// </summary>
public int AutoRemovingInterval { get; set; } = 7;
/// <summary>
/// Gets or sets the list of master keys.
/// </summary>
public List<string> MasterKeyCollection { get; set; } = new List<string>();
#endregion
}
}
| 25.375 | 155 | 0.557635 | [
"MIT"
] | AngleGN/kimera | src/Kimera/Settings.cs | 2,032 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Google;
using Microsoft.Owin.Security.OAuth;
using Owin;
using Web.Providers;
using Web.Models;
namespace Web
{
public partial class Startup
{
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
public static string PublicClientId { get; private set; }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
// clientId: "",
// clientSecret: "");
//app.UseTwitterAuthentication(
// consumerKey: "",
// consumerSecret: "");
//app.UseFacebookAuthentication(
// appId: "",
// appSecret: "");
//app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
//{
// ClientId = "",
// ClientSecret = ""
//});
}
}
}
| 40.257143 | 126 | 0.62846 | [
"Apache-2.0"
] | manhquynh8x/DangKyThuoc | src/HSDK/Web/App_Start/Startup.Auth.cs | 2,820 | C# |
using ExpressionDebugger;
using Mapster;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
namespace TemplateTest
{
[TestClass]
public class CreateMapExpressionTest
{
[TestMethod]
public void TestCreateMapExpression()
{
TypeAdapterConfig.GlobalSettings.SelfContainedCodeGeneration = true;
var foo = default(Customer);
var def = new ExpressionDefinitions
{
IsStatic = true,
MethodName = "Map",
Namespace = "Benchmark",
TypeName = "CustomerMapper"
};
var code = foo.BuildAdapter()
.CreateMapExpression<CustomerDTO>()
.ToScript(def);
Assert.IsNotNull(code);
}
[TestMethod]
public void TestCreateMapToTargetExpression()
{
TypeAdapterConfig.GlobalSettings.SelfContainedCodeGeneration = true;
var foo = default(Customer);
var def = new ExpressionDefinitions
{
IsStatic = true,
MethodName = "Map",
Namespace = "Benchmark",
TypeName = "CustomerMapper"
};
var code = foo.BuildAdapter()
.CreateMapToTargetExpression<CustomerDTO>()
.ToScript(def);
Assert.IsNotNull(code);
}
[TestMethod]
public void TestCreateProjectionExpression()
{
TypeAdapterConfig.GlobalSettings.SelfContainedCodeGeneration = true;
var foo = default(Customer);
var def = new ExpressionDefinitions
{
IsStatic = true,
MethodName = "Map",
Namespace = "Benchmark",
TypeName = "CustomerMapper"
};
var code = foo.BuildAdapter()
.CreateProjectionExpression<CustomerDTO>()
.ToScript(def);
Assert.IsNotNull(code);
}
}
public class Address
{
public int Id { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
public class AddressDTO
{
public int Id { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public decimal? Credit { get; set; }
public Address Address { get; set; }
public Address HomeAddress { get; set; }
public Address[] Addresses { get; set; }
public ICollection<Address> WorkAddresses { get; set; }
}
public class CustomerDTO
{
public int Id { get; set; }
public string Name { get; set; }
public AddressDTO Address { get; set; }
public AddressDTO HomeAddress { get; set; }
public AddressDTO[] Addresses { get; set; }
public List<AddressDTO> WorkAddresses { get; set; }
public string AddressCity { get; set; }
}
} | 30.238095 | 80 | 0.546772 | [
"MIT"
] | Philippe-Laval/Mapster | src/TemplateTest/CreateMapExpressionTest.cs | 3,175 | C# |
using System;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
#pragma warning disable 1591
#pragma warning disable CA1401 // P/Invokes should not be visible
#pragma warning disable IDE1006 // Naming style
namespace OpenCvSharp
{
static partial class NativeMethods
{
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_MatExpr_new1(out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_MatExpr_new2(IntPtr mat, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_MatExpr_delete(IntPtr expr);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_MatExpr_toMat(IntPtr expr, IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_MatExpr_row(IntPtr self, int y, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_MatExpr_col(IntPtr self, int x, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_MatExpr_diag(IntPtr self, int d, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_MatExpr_submat(
IntPtr self, int rowStart, int rowEnd, int colStart, int colEnd, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_MatExpr_t(IntPtr self, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_MatExpr_inv(IntPtr self, int method, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_MatExpr_mul_toMatExpr(IntPtr self, IntPtr e, double scale, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_MatExpr_mul_toMat(IntPtr self, IntPtr m, double scale, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_MatExpr_cross(IntPtr self, IntPtr m, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_MatExpr_dot(IntPtr self, IntPtr m, out double returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_MatExpr_size(IntPtr self, out Size returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_MatExpr_type(IntPtr self, out int returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_operatorUnaryMinus_MatExpr(IntPtr e, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_operatorUnaryNot_MatExpr(IntPtr e, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_operatorAdd_MatExprMat(IntPtr e, IntPtr m, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_operatorAdd_MatMatExpr(IntPtr m, IntPtr e, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_operatorAdd_MatExprScalar(IntPtr e, Scalar s, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_operatorAdd_ScalarMatExpr(Scalar s, IntPtr e, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_operatorAdd_MatExprMatExpr(IntPtr e1, IntPtr e2, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_operatorSubtract_MatExprMat(IntPtr e, IntPtr m, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_operatorSubtract_MatMatExpr(IntPtr m, IntPtr e, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_operatorSubtract_MatExprScalar(IntPtr e, Scalar s, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_operatorSubtract_ScalarMatExpr(Scalar s, IntPtr e, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_operatorSubtract_MatExprMatExpr(IntPtr e1, IntPtr e2, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_operatorMultiply_MatExprMat(IntPtr e, IntPtr m, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_operatorMultiply_MatMatExpr(IntPtr m, IntPtr e, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_operatorMultiply_MatExprDouble(IntPtr e, double s, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_operatorMultiply_DoubleMatExpr(double s, IntPtr e, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_operatorMultiply_MatExprMatExpr(IntPtr e1, IntPtr e2, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_operatorDivide_MatExprMat(IntPtr e, IntPtr m, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_operatorDivide_MatMatExpr(IntPtr m, IntPtr e, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_operatorDivide_MatExprDouble(IntPtr e, double s, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_operatorDivide_DoubleMatExpr(double s, IntPtr e, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_operatorDivide_MatExprMatExpr(IntPtr e1, IntPtr e2, out IntPtr returnValue);
[Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ExceptionStatus core_abs_MatExpr(IntPtr e, out IntPtr returnValue);
}
} | 80.900901 | 133 | 0.767929 | [
"BSD-3-Clause"
] | AJEETX/opencvsharp | src/OpenCvSharp/PInvoke/NativeMethods/core/NativeMethods_core_MatExpr.cs | 8,982 | C# |
using System;
using System.Runtime.Serialization;
namespace etcdclientv3.impl
{
[Serializable]
internal class ClosedWatcherException : Exception
{
public ClosedWatcherException()
{
}
public ClosedWatcherException(string message) : base(message)
{
}
public ClosedWatcherException(string message, Exception innerException) : base(message, innerException)
{
}
protected ClosedWatcherException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
} | 23.44 | 112 | 0.651877 | [
"MIT"
] | jinyuttt/etcdclientv3 | etcdclientv3/etcdclientv3/impl/ClosedWatcherException.cs | 588 | C# |
using System;
using SDL2;
using SoLoud;
namespace Flora.Audio {
/// <summary>
/// Audio instance that suit better for playing fire-and-forget type of short sound effects.
/// </summary>
public class Sound : IDisposable {
internal Wav wav;
private float _volume = 1f;
public float Volume {
get { return _volume; }
set {
_volume = Math.Clamp(value, 0f, 1f);
wav.setVolume(_volume);
}
}
/// <summary>
/// Create a new sound.<br/>
/// Sound is better suited for playing fire-and-forget type of short sound clips.
/// </summary>
/// <param name="path">Path to the sound file. WAV/MP3/OGG are supported.</param>
/// <param name="volume">Volume of the sound. must be between 0 to 1.</param>
/// <returns></returns>
public Sound(string path, float volume = 1f) {
if (!Audio.isAudioInitialized) throw new InvalidOperationException("Audio is not initialized");
wav = new Wav();
wav.load(path);
this.Volume = volume;
}
/// <summary>
/// Play the sound.
/// </summary>
/// <param name="singleton">If true, any of this sound playing will be halted before playing.</param>
public void Play(bool singleton = false) {
if (singleton) Audio.soloud.stopAudioSource(wav);
Audio.soloud.play(wav, _volume);
}
private bool _disposed = false;
protected virtual void Dispose(bool disposing) {
if (_disposed) return;
/* if (disposing) {} */
wav.Dispose();
_disposed = true;
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
~Sound() => Dispose(false);
}
} | 29.78125 | 109 | 0.538825 | [
"MIT"
] | sinusinu/Flora | src/Audio/Sound.cs | 1,906 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace iOSConsortium.Models
{
public class SpeakersModel
{
public bool IsBusy { get; set; }
public ObservableCollection<Speaker> Speakers { get; set; } = new ObservableCollection<Speaker>();
private static HttpClient client = new HttpClient();
public SpeakersModel()
{
}
public async Task GetSpeakersAsync()
{
if (IsBusy)
return;
Exception error = null;
try
{
IsBusy = true;
var json = await client.GetStringAsync("http://demo4404797.mockable.io/speakers");
var items = JsonConvert.DeserializeObject<ObservableCollection<Speaker>>(json);
Speakers.Clear();
foreach (var item in items)
Speakers.Add(item);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Error: " + ex);
error = ex;
}
finally
{
IsBusy = false;
}
}
}
}
| 26.518519 | 107 | 0.539106 | [
"MIT"
] | ytabuchi/iOSConsortium | iOSConsortium/iOSConsortium/Models/SpeakersModel.cs | 1,434 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Sql.Models
{
using System.Linq;
/// <summary>
/// Start Azure SQL Server Upgrade parameters.
/// </summary>
[Microsoft.Rest.Serialization.JsonTransformation]
public partial class ServerUpgradeStartParameters
{
/// <summary>
/// Initializes a new instance of the ServerUpgradeStartParameters
/// class.
/// </summary>
public ServerUpgradeStartParameters() { }
/// <summary>
/// Initializes a new instance of the ServerUpgradeStartParameters
/// class.
/// </summary>
/// <param name="scheduleUpgradeAfterUtcDateTime">The earliest time to
/// upgrade the Azure SQL Server (ISO8601 format).</param>
/// <param name="databaseCollection">The collection of recommended
/// database properties to upgrade the Azure SQL Server.</param>
/// <param name="elasticPoolCollection">The collection of recommended
/// elastic pool properties to upgrade the Azure SQL Server.</param>
public ServerUpgradeStartParameters(System.DateTime? scheduleUpgradeAfterUtcDateTime = default(System.DateTime?), System.Collections.Generic.IList<RecommendedDatabaseProperties> databaseCollection = default(System.Collections.Generic.IList<RecommendedDatabaseProperties>), System.Collections.Generic.IList<UpgradeRecommendedElasticPoolProperties> elasticPoolCollection = default(System.Collections.Generic.IList<UpgradeRecommendedElasticPoolProperties>))
{
ScheduleUpgradeAfterUtcDateTime = scheduleUpgradeAfterUtcDateTime;
DatabaseCollection = databaseCollection;
ElasticPoolCollection = elasticPoolCollection;
}
/// <summary>
/// Static constructor for ServerUpgradeStartParameters class.
/// </summary>
static ServerUpgradeStartParameters()
{
Version = "12.0";
}
/// <summary>
/// Gets or sets the earliest time to upgrade the Azure SQL Server
/// (ISO8601 format).
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "serverUpgradeProperties.ScheduleUpgradeAfterUtcDateTime")]
public System.DateTime? ScheduleUpgradeAfterUtcDateTime { get; set; }
/// <summary>
/// Gets or sets the collection of recommended database properties to
/// upgrade the Azure SQL Server.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "serverUpgradeProperties.DatabaseCollection")]
public System.Collections.Generic.IList<RecommendedDatabaseProperties> DatabaseCollection { get; set; }
/// <summary>
/// Gets or sets the collection of recommended elastic pool properties
/// to upgrade the Azure SQL Server.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "serverUpgradeProperties.ElasticPoolCollection")]
public System.Collections.Generic.IList<UpgradeRecommendedElasticPoolProperties> ElasticPoolCollection { get; set; }
/// <summary>
/// The version for the Azure SQL Server being upgraded.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "serverUpgradeProperties.Version")]
public static string Version { get; private set; }
}
}
| 46.75641 | 462 | 0.69043 | [
"MIT"
] | dnelly/azure-sdk-for-net | src/ResourceManagement/SqlManagement/Microsoft.Azure.Management.Sql/Generated/Models/ServerUpgradeStartParameters.cs | 3,647 | C# |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
namespace DocumentDB.AspNet.Identity.Samples.Mvc.Models
{
public class IndexViewModel
{
public bool HasPassword { get; set; }
public IList<UserLoginInfo> Logins { get; set; }
public string PhoneNumber { get; set; }
public bool TwoFactor { get; set; }
public bool BrowserRemembered { get; set; }
}
public class ManageLoginsViewModel
{
public IList<UserLoginInfo> CurrentLogins { get; set; }
public IList<AuthenticationDescription> OtherLogins { get; set; }
}
public class FactorViewModel
{
public string Purpose { get; set; }
}
public class SetPasswordViewModel
{
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class ChangePasswordViewModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class AddPhoneNumberViewModel
{
[Required]
[Phone]
[Display(Name = "Phone Number")]
public string Number { get; set; }
}
public class VerifyPhoneNumberViewModel
{
[Required]
[Display(Name = "Code")]
public string Code { get; set; }
[Required]
[Phone]
[Display(Name = "Phone Number")]
public string PhoneNumber { get; set; }
}
public class ConfigureTwoFactorViewModel
{
public string SelectedProvider { get; set; }
public ICollection<System.Web.Mvc.SelectListItem> Providers { get; set; }
}
} | 31.186047 | 110 | 0.628262 | [
"MIT"
] | chrisnott/DocumentDB.AspNet.Identity | samples/DocumentDB.AspNet.Identity.Samples.Mvc/Models/ManageViewModels.cs | 2,684 | C# |
using System;
using System.Threading.Tasks;
using BookFast.Web.Contracts.Files;
namespace BookFast.Web.Contracts
{
public interface IFileAccessProxy
{
Task<FileAccessToken> IssueAccommodationImageUploadTokenAsync(Guid accommodationId, string originalFileName);
Task<FileAccessToken> IssueFacilityImageUploadTokenAsync(Guid facilityId, string originalFileName);
}
} | 32.833333 | 117 | 0.796954 | [
"MIT"
] | The-real-Urb/book-fast-service-fabric | BookFast.Web.Contracts/IFileAccessProxy.cs | 396 | C# |
using System.Linq;
using FluentAssertions;
using NUnit.Framework;
using ParserObjects.Parsers;
using ParserObjects.Sequences;
using static ParserObjects.ParserMethods<char>;
namespace ParserObjects.Tests.Parsers
{
public class AnyParserTests
{
[Test]
public void Parse_Test()
{
var target = new AnyParser<char>();
var input = new StringCharacterSequence("abc");
target.Parse(input).Value.Should().Be('a');
target.Parse(input).Value.Should().Be('b');
target.Parse(input).Value.Should().Be('c');
target.Parse(input).Success.Should().BeFalse();
}
[Test]
public void Any_Test()
{
var target = Any();
var input = new StringCharacterSequence("abc");
target.Parse(input).Value.Should().Be('a');
target.Parse(input).Value.Should().Be('b');
target.Parse(input).Value.Should().Be('c');
target.Parse(input).Success.Should().BeFalse();
}
[Test]
public void GetChildren_Test()
{
var target = Any();
target.GetChildren().Count().Should().Be(0);
}
}
}
| 28.97619 | 59 | 0.566146 | [
"Apache-2.0"
] | Whiteknight/ParserObjects | ParserObjects.Tests/Parsers/AnyParserTests.cs | 1,219 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebSanchez2016.es.Equipo.GS_Digital
{
public partial class Dobladoras_y_Ecuadernadoras_Baum : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
} | 21.352941 | 78 | 0.721763 | [
"MIT"
] | juanitomemelas/GSWEB | es/Equipo/GS_Digital/Dobladoras_y_Ecuadernadoras_Baum.aspx.cs | 365 | C# |
using System;
namespace Gma.QrCodeNet.Encoding.EncodingRegion
{
/// <summary>
/// Embed version information for version larger than or equal to 7.
/// </summary>
/// <remarks>ISO/IEC 18004:2000 Chapter 8.10 Page 54</remarks>
internal static class VersionInformation
{
private const int VIRectangleHeight = 3;
private const int VIRectangleWidth = 6;
private const int LengthDataBits = 6;
private const int LengthECBits = 12;
private const int VersionBCHPoly = 0x1f25;
/// <summary>
/// Embed version information to Matrix
/// Only for version greater than or equal to 7
/// </summary>
internal static void EmbedVersionInformation(this TriStateMatrix tsMatrix, int version)
{
if (version < 7)
{
return;
}
BitList versionInfo = VersionInfoBitList(version);
int matrixWidth = tsMatrix.Width;
// 1 cell between version info and position stencil
int shiftLength = QRCodeConstantVariable.PositionStencilWidth + VIRectangleHeight + 1;
// Reverse order input
int viIndex = LengthDataBits + LengthECBits - 1;
for (int viWidth = 0; viWidth < VIRectangleWidth; viWidth++)
{
for (int viHeight = 0; viHeight < VIRectangleHeight; viHeight++)
{
bool bit = versionInfo[viIndex];
viIndex--;
// Bottom left
tsMatrix[viWidth, (matrixWidth - shiftLength + viHeight), MatrixStatus.NoMask] = bit;
// Top right
tsMatrix[(matrixWidth - shiftLength + viHeight), viWidth, MatrixStatus.NoMask] = bit;
}
}
}
private static BitList VersionInfoBitList(int version)
{
BitList result = new BitList
{
{ version, LengthDataBits },
{ BCHCalculator.CalculateBCH(version, VersionBCHPoly), LengthECBits }
};
if (result.Count != (LengthECBits + LengthDataBits))
{
throw new Exception("Version Info creation error. Result is not 18 bits");
}
return result;
}
}
}
| 27.691176 | 90 | 0.694105 | [
"MIT"
] | CoboVault/WalletWasabi | WalletWasabi/Gma/QrCodeNet/Encoding/EncodingRegion/VersionInformation.cs | 1,883 | C# |
//-----------------------------------------------------------------------
// <copyright file="FramingSpec.cs" company="Akka.NET Project">
// Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using Akka.IO;
using Akka.Streams.Dsl;
using Akka.Streams.Implementation.Fusing;
using Akka.Streams.Stage;
using Akka.Streams.TestKit.Tests;
using Akka.TestKit;
using Akka.Util;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
namespace Akka.Streams.Tests.Dsl
{
public class FramingSpec : AkkaSpec
{
private readonly ITestOutputHelper _helper;
private ActorMaterializer Materializer { get; }
public FramingSpec(ITestOutputHelper helper) : base(helper)
{
_helper = helper;
var settings = ActorMaterializerSettings.Create(Sys);
Materializer = ActorMaterializer.Create(Sys, settings);
}
private sealed class Rechunker : SimpleLinearGraphStage<ByteString>
{
#region Logic
private sealed class Logic : InAndOutGraphStageLogic
{
private readonly Rechunker _stage;
private ByteString _buffer;
public Logic(Rechunker stage) : base(stage.Shape)
{
_stage = stage;
_buffer = ByteString.Empty;
SetHandler(stage.Inlet, stage.Outlet, this);
}
public override void OnPush()
{
_buffer += Grab(_stage.Inlet);
Rechunk();
}
public override void OnPull() => Rechunk();
public override void OnUpstreamFinish()
{
if (_buffer.IsEmpty)
CompleteStage();
else if (IsAvailable(_stage.Outlet))
OnPull();
}
private void Rechunk()
{
if (!IsClosed(_stage.Inlet) && ThreadLocalRandom.Current.Next(1, 3) == 2)
Pull(_stage.Inlet);
else
{
var nextChunkSize = _buffer.IsEmpty
? 0
: ThreadLocalRandom.Current.Next(0, _buffer.Count + 1);
var newChunk = _buffer.Slice(0, nextChunkSize).Compact();
_buffer = _buffer.Slice(nextChunkSize).Compact();
Push(_stage.Outlet, newChunk);
if (IsClosed(_stage.Inlet) && _buffer.IsEmpty)
CompleteStage();
}
}
}
#endregion
public Rechunker() : base("Rechunker")
{
}
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
}
private Flow<ByteString, ByteString, NotUsed> Rechunk
=> Flow.Create<ByteString>().Via(new Rechunker()).Named("rechunker");
private static readonly List<ByteString> DelimiterBytes =
new List<string> {"\n", "\r\n", "FOO"}.Select(ByteString.FromString).ToList();
private static readonly List<ByteString> BaseTestSequences =
new List<string> { "", "foo", "hello world" }.Select(ByteString.FromString).ToList();
private static Flow<ByteString, string, NotUsed> SimpleLines(string delimiter, int maximumBytes, bool allowTruncation = true)
{
return Framing.Delimiter(ByteString.FromString(delimiter), maximumBytes, allowTruncation)
.Select(x => x.ToString(Encoding.UTF8)).Named("LineFraming");
}
private static IEnumerable<ByteString> CompleteTestSequence(ByteString delimiter)
{
for (var i = 0; i < delimiter.Count; i++)
foreach (var sequence in BaseTestSequences)
yield return delimiter.Slice(0, i) + sequence;
}
[Fact]
public void Delimiter_bytes_based_framing_must_work_with_various_delimiters_and_test_sequences()
{
for (var i = 1; i <= 100; i++)
{
foreach (var delimiter in DelimiterBytes)
{
var testSequence = CompleteTestSequence(delimiter).ToList();
var task = Source.From(testSequence)
.Select(x => x + delimiter)
.Via(Rechunk)
.Via(Framing.Delimiter(delimiter, 256))
.RunWith(Sink.Seq<ByteString>(), Materializer);
task.Wait(TimeSpan.FromDays(3)).Should().BeTrue();
task.Result.ShouldAllBeEquivalentTo(testSequence);
}
}
}
[Fact]
public void Delimiter_bytes_based_framing_must_respect_maximum_line_settings()
{
var task1 = Source.Single(ByteString.FromString("a\nb\nc\nd\n"))
.Via(SimpleLines("\n", 1))
.Limit(100)
.RunWith(Sink.Seq<string>(), Materializer);
task1.Wait(TimeSpan.FromDays(3)).Should().BeTrue();
task1.Result.ShouldAllBeEquivalentTo(new[] {"a", "b", "c", "d"});
var task2 =
Source.Single(ByteString.FromString("ab\n"))
.Via(SimpleLines("\n", 1))
.Limit(100)
.RunWith(Sink.Seq<string>(), Materializer);
task2.Invoking(t => t.Wait(TimeSpan.FromSeconds(3))).ShouldThrow<Framing.FramingException>();
var task3 =
Source.Single(ByteString.FromString("aaa"))
.Via(SimpleLines("\n", 2))
.Limit(100)
.RunWith(Sink.Seq<string>(), Materializer);
task3.Invoking(t => t.Wait(TimeSpan.FromSeconds(3))).ShouldThrow<Framing.FramingException>();
}
[Fact]
public void Delimiter_bytes_based_framing_must_work_with_empty_streams()
{
var task = Source.Empty<ByteString>().Via(SimpleLines("\n", 256)).RunAggregate(new List<string>(), (list, s) =>
{
list.Add(s);
return list;
}, Materializer);
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
task.Result.Should().BeEmpty();
}
[Fact]
public void Delimiter_bytes_based_framing_must_report_truncated_frames()
{
var task =
Source.Single(ByteString.FromString("I have no end"))
.Via(SimpleLines("\n", 256, false))
.Grouped(1000)
.RunWith(Sink.First<IEnumerable<string>>(), Materializer);
task.Invoking(t => t.Wait(TimeSpan.FromSeconds(3))).ShouldThrow<Framing.FramingException>();
}
[Fact]
public void Delimiter_bytes_based_framing_must_allow_truncated_frames_if_configured_so()
{
var task =
Source.Single(ByteString.FromString("I have no end"))
.Via(SimpleLines("\n", 256))
.Grouped(1000)
.RunWith(Sink.First<IEnumerable<string>>(), Materializer);
task.AwaitResult().Should().ContainSingle(s => s.Equals("I have no end"));
}
private static string RandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var random = new Random();
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
private static readonly ByteString ReferenceChunk = ByteString.FromString(RandomString(0x100001));
private static readonly List<ByteOrder> ByteOrders = new List<ByteOrder>
{
ByteOrder.BigEndian,
ByteOrder.LittleEndian
};
private static readonly List<int> FrameLengths = new List<int>
{
0,
1,
2,
3,
0xFF,
0x100,
0x101,
0xFFF,
0x1000,
0x1001,
0xFFFF,
0x10000,
0x10001
};
private static readonly List<int> FieldLengths = new List<int> {1, 2, 3, 4};
private static readonly List<int> FieldOffsets = new List<int> {0, 1, 2, 3, 15, 16, 31, 32, 44, 107};
private static ByteString Encode(ByteString payload, int fieldOffset, int fieldLength, ByteOrder byteOrder)
{
var h = ByteString.FromBytes(new byte[4].PutInt(payload.Count, order: byteOrder));
var header = byteOrder == ByteOrder.LittleEndian ? h.Slice(0, fieldLength) : h.Slice(4 - fieldLength);
return ByteString.FromBytes(new byte[fieldOffset]) + header + payload;
}
[Fact]
public void Length_field_based_framing_must_work_with_various_byte_orders_frame_lengths_and_offsets()
{
var counter = 1;
foreach (var byteOrder in ByteOrders)
{
foreach (var fieldOffset in FieldOffsets)
{
foreach (var fieldLength in FieldLengths)
{
var encodedFrames = FrameLengths.Where(x => x < 1L << (fieldLength * 8)).Select(length =>
{
var payload = ReferenceChunk.Slice(0, length);
return Encode(payload, fieldOffset, fieldLength, byteOrder);
}).ToList();
var task = Source.From(encodedFrames)
.Via(Rechunk)
.Via(Framing.LengthField(fieldLength, int.MaxValue, fieldOffset, byteOrder))
.Grouped(10000)
.RunWith(Sink.First<IEnumerable<ByteString>>(), Materializer);
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
task.Result.ShouldAllBeEquivalentTo(encodedFrames);
_helper.WriteLine($"{counter++} from 80 passed");
}
}
}
}
[Fact]
public void Length_field_based_framing_must_work_with_empty_streams()
{
var task = Source.Empty<ByteString>()
.Via(Framing.LengthField(4, int.MaxValue, 0, ByteOrder.BigEndian))
.RunAggregate(new List<ByteString>(), (list, s) =>
{
list.Add(s);
return list;
}, Materializer);
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
task.Result.Should().BeEmpty();
}
[Fact]
public void Length_field_based_framing_must_report_oversized_frames()
{
var task1 = Source.Single(Encode(ReferenceChunk.Slice(0, 100), 0, 1, ByteOrder.BigEndian))
.Via(Framing.LengthField(1, 99, 0, ByteOrder.BigEndian))
.RunAggregate(new List<ByteString>(), (list, s) =>
{
list.Add(s);
return list;
}, Materializer);
task1.Invoking(t => t.Wait(TimeSpan.FromSeconds(3))).ShouldThrow<Framing.FramingException>();
var task2 = Source.Single(Encode(ReferenceChunk.Slice(0, 100), 49, 1, ByteOrder.BigEndian))
.Via(Framing.LengthField(1, 100, 0, ByteOrder.BigEndian))
.RunAggregate(new List<ByteString>(), (list, s) =>
{
list.Add(s);
return list;
}, Materializer);
task2.Invoking(t => t.Wait(TimeSpan.FromSeconds(3))).ShouldThrow<Framing.FramingException>();
}
[Fact]
public void Length_field_based_framing_must_report_truncated_frames()
{
foreach (var byteOrder in ByteOrders)
{
foreach (var fieldOffset in FieldOffsets)
{
foreach (var fieldLength in FieldLengths)
{
foreach (var frameLength in FrameLengths.Where(f => f < 1 << (fieldLength * 8) && f != 0))
{
var fullFrame = Encode(ReferenceChunk.Slice(0, frameLength), fieldOffset, fieldLength, byteOrder);
var partialFrame = fullFrame.Slice(0, fullFrame.Count - 1); // dropRight equivalent
Action action = () =>
{
Source.From(new[] {fullFrame, partialFrame})
.Via(Rechunk)
.Via(Framing.LengthField(fieldLength, int.MaxValue, fieldOffset, byteOrder))
.Grouped(10000)
.RunWith(Sink.First<IEnumerable<ByteString>>(), Materializer)
.Wait(TimeSpan.FromSeconds(5))
.ShouldBeTrue("Stream should complete withing 5 seconds");
};
action.ShouldThrow<Framing.FramingException>();
}
}
}
}
}
[Fact]
public void Length_field_based_framing_must_support_simple_framing_adapter()
{
var rechunkBidi = BidiFlow.FromFlowsMat(Rechunk, Rechunk, Keep.Left);
var codecFlow = Framing.SimpleFramingProtocol(1024)
.Atop(rechunkBidi)
.Atop(Framing.SimpleFramingProtocol(1024).Reversed())
.Join(Flow.Create<ByteString>()); // Loopback
var random= new Random();
var testMessages = Enumerable.Range(1, 100).Select(_ => ReferenceChunk.Slice(0, random.Next(1024))).ToList();
var task = Source.From(testMessages)
.Via(codecFlow)
.Limit(1000)
.RunWith(Sink.Seq<ByteString>(), Materializer);
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
task.Result.ShouldAllBeEquivalentTo(testMessages);
}
[Fact]
public void Length_field_based_framing_must_fail_the_stage_on_negative_length_field_values()
{
// A 4-byte message containing only an Int specifying the length of the payload
// The issue shows itself if length in message is less than or equal
// to -4 (if expected length field is length 4)
var bytes = ByteString.FromBytes(BitConverter.GetBytes(-4).ToArray());
var result = Source.Single(bytes)
.Via(Flow.Create<ByteString>().Via(Framing.LengthField(4, 1000)))
.RunWith(Sink.Seq<ByteString>(), Materializer);
result.Invoking(t => t.AwaitResult())
.ShouldThrow<Framing.FramingException>()
.WithMessage("Decoded frame header reported negative size -4");
}
[Fact]
public void Length_field_based_framing_must_let_zero_length_field_values_pass_through()
{
// Interleave empty frames with a frame with data
var b = ByteString.FromBytes(BitConverter.GetBytes(42).ToArray());
var encodedPayload = Encode(b, 0, 4, ByteOrder.LittleEndian);
var emptyFrame = Encode(ByteString.Empty, 0, 4, ByteOrder.LittleEndian);
var bytes = new[] { emptyFrame, encodedPayload, emptyFrame };
var result = Source.From(bytes)
.Via(Flow.Create<ByteString>().Via(Framing.LengthField(4, 1000)))
.RunWith(Sink.Seq<ByteString>(), Materializer);
result.AwaitResult().Should().BeEquivalentTo(bytes.ToImmutableList());
}
}
}
| 40.355556 | 133 | 0.533346 | [
"Apache-2.0"
] | vilinski/akka.net | src/core/Akka.Streams.Tests/Dsl/FramingSpec.cs | 16,346 | C# |
namespace Iec608705104
{
using Iec608705104.Messages;
using Iec608705104.Messages.Asdu;
using System;
internal static class Bytes
{
/// <param name="buffer">starts at the position 2 of the whole frame</param>
internal static (ErrorCode error, FrameType type, AsduTypeId asduTypeId) IdentifyFrame(ReadOnlySpan<byte> buffer)
{
var isSorU = buffer.Length == Constants.NoPrefix.MinFrameLength;
var isI = buffer.Length >= Constants.NoPrefix.MinFrameILength;
if (!isSorU && !isI)
{
return (ErrorCode.BufferDoesNotFit, FrameType.Unknown, AsduTypeId.Unknown);
}
var byte2Bit0 = (buffer[0] & 0x01) != 0;
var byte4Bit0 = (buffer[2] & 0x01) != 0;
if (isI && !byte2Bit0 && !byte4Bit0)
{
var byte6 = buffer[4];
if (!Enum.IsDefined(typeof(AsduTypeId), byte6))
{
return (ErrorCode.InvalidAsduType, FrameType.I, AsduTypeId.Unknown);
}
return (ErrorCode.None, FrameType.I, (AsduTypeId)byte6);
}
else if (isSorU)
{
var byte2Bit1 = (buffer[0] & 0x02) != 0;
if (byte2Bit1 && !byte2Bit0 && !byte4Bit0)
{
return (ErrorCode.None, FrameType.S, AsduTypeId.Unknown);
}
if (byte2Bit1 && byte2Bit0 && !byte4Bit0)
{
return (ErrorCode.None, FrameType.U, AsduTypeId.Unknown);
}
}
return (ErrorCode.NonIdentifiableFrame, FrameType.Unknown, AsduTypeId.Unknown);
}
internal static (ErrorCode, IFrame) ReadFrame(ReadOnlySpan<byte> buffer)
{
var apduLength = buffer.Length;
var (error, frameType, asduTypeId) = IdentifyFrame(buffer);
if (error != ErrorCode.None)
{
return (error, null);
}
return frameType switch
{
FrameType.I => asduTypeId switch
{
AsduTypeId.C_CS_NA_1 => ReadFrameI<C_CS_NA_1>(buffer, apduLength),
_ => (ErrorCode.NotSupportedAsduType, null),
},
FrameType.S => FrameS.Read(buffer),
FrameType.U => FrameU.Read(buffer),
_ => (ErrorCode.NotSupportedFrameType, null),
};
}
internal static (ErrorCode, FrameI<T>) ReadFrameI<T>(ReadOnlySpan<byte> buffer, int apduLength)
where T : IAsduValue, new()
{
var meta = Cache<T>.Meta;
var header = FrameIHeader.Read(buffer, apduLength);
var infoObjects = new InfoObject<T>[header.InfoObjectsCount];
var currOffset = 10;
for (int i = 0; i < header.InfoObjectsCount; i++)
{
int address;
if (header.IsSequence)
{
address = header.CommonAddress + i;
}
else
{
address = buffer[currOffset] | (buffer[currOffset + 1] << 8) | (buffer[currOffset + 2] << 16);
currOffset += 3;
}
var value = new T();
var span = buffer.Slice(currOffset, meta.EncodedLength);
var error = value.TryRead(span);
if (error != ErrorCode.None)
{
return (error, null);
}
currOffset += meta.EncodedLength;
infoObjects[i] = new InfoObject<T>(address, value);
}
return (ErrorCode.None, new FrameI<T>(header, infoObjects));
}
internal static (byte lsb, byte msb) GetBytesFromN(int n)
{
int lsb = 0;
for (var i = 1; i <= 7; i++)
{
if ((n & (1 << (i - 1))) != 0)
{
lsb |= 1 << i;
}
}
int msb = 0;
for (var i = 0; i <= 7; i++)
{
if ((n & (1 << (i + 7))) != 0)
{
msb |= 1 << i;
}
}
return ((byte)lsb, (byte)msb);
}
internal static int GetNFromBytes(byte lsb, byte msb)
{
int n = 0;
for (int i = 1; i <= 7; i++)
{
if ((lsb & (1 << i)) != 0)
{
n |= 1 << (i - 1);
}
}
for (int i = 0; i <= 7; i++)
{
if ((msb & (1 << i)) != 0)
{
n |= 1 << (i + 7);
}
}
return n;
}
}
}
| 32.217105 | 121 | 0.43639 | [
"MIT"
] | jdvor/IEC-60870-5-104 | src/Iec608705104/Bytes.cs | 4,897 | 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("BinShort")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BinShort")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5a9b9d0e-886f-4c8d-8ec7-19e83693b17e")]
// 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.540541 | 84 | 0.743701 | [
"MIT"
] | ivannk0900/Telerik-Academy | C# 2/NumeralSystems/BinShort/Properties/AssemblyInfo.cs | 1,392 | C# |
using UnityEngine;
public static class DebugTransform {
/* draw x and y axes in transform local space */
public static void DrawLocalAxis (this Transform self, float scale = 3.0f) {
Debug.DrawRay ( self.position, self.up * scale, Color.yellow, 0.2f, false );
Debug.DrawRay ( self.position, self.right * scale, Color.yellow, 0.2f, false );
}
/* draw a ray representing an objects heading or velocity */
public static void DrawHeading (this Transform self, Vector3 heading) {
Debug.DrawRay(self.position, heading * 5f, Color.red);
}
/* draw a line from transform origin to point target */
public static void DrawLineToTarget (this Transform self, Vector3 target) {
Debug.DrawLine(self.position, target);
}
} | 38.45 | 87 | 0.689207 | [
"Unlicense"
] | msawangwan/vector_trig_geometry | Assets/Script/DebugTransform.cs | 771 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace lab_04
{
static class VinogradMultiply
{
public static Matrix Classic(Matrix first, Matrix second)
{
Matrix result = new Matrix(0, 0);
if (first.M == second.N && first.N != 0 && second.M != 0)
{
int n1 = first.N;
int m1 = first.M;
int n2 = second.N;
int m2 = second.M;
result = new Matrix(n1, m2);
int[] mulH = new int[n1];
int[] mulV = new int[m2];
for (int i = 0; i < n1; i++)
{
for (int j = 0; j < m1 / 2; j++)
{
mulH[i] += first[i, j * 2] * first[i, j * 2 + 1];
}
}
for (int i = 0; i < m2; i++)
{
for (int j = 0; j < n2 / 2; j++)
{
mulV[i] += second[j * 2, i] * second[j * 2 + 1, i];
}
}
for (int i = 0; i < n1; i++)
{
for (int j = 0; j < m2; j++)
{
result[i, j] = -mulH[i] - mulV[j];
for (int k = 0; k < m1 / 2; k++)
{
result[i, j] += (first[i, 2 * k + 1] + second[2 * k, j]) * (first[i, 2 * k] + second[2 * k + 1, j]);
}
}
}
if (m1 % 2 == 1)
{
for (int i = 0; i < n1; i++)
{
for (int j = 0; j < m2; j++)
{
result[i, j] += first[i, m1 - 1] * second[m1 - 1, j];
}
}
}
}
return result;
}
// параллелится и mulh и mulv одновременно, потом паралл на главную и параллел на последнюю
public static Matrix ParallelFirst(Matrix first, Matrix second, int threadsCount)
{
Matrix result = new Matrix(0, 0);
if (threadsCount <= 1)
{
result = Classic(first, second);
}
else if (first.M == second.N && first.N != 0 && second.M != 0)
{
int n1 = first.N;
int m1 = first.M;
int n2 = second.N;
int m2 = second.M;
result = new Matrix(n1, m2);
int[] mulH = new int[n1];
int[] mulV = new int[m2];
Thread[] threads = new Thread[threadsCount];
int threadsHalfing = threadsCount / 2;
// mulH
int threadWork = threadsHalfing;
int step = n1 / threadWork;
if (threadWork / n1 >= 1)
{
step = 1;
threadWork = n1;
threadsHalfing = threadWork;
}
int start = 0;
for (int i = 0; i < threadWork - 1; i++)
{
threads[i] = new Thread(CountMulH);
threads[i].Start(new ParametersForMul(first, mulH, start, start + step, m1));
start += step;
}
threads[threadWork - 1] = new Thread(CountMulH);
threads[threadWork - 1].Start(new ParametersForMul(first, mulH, start, n1, m1));
// MulV
threadWork = (threadsCount - threadsHalfing);
step = m2 / threadWork;
if (threadWork / m2 >= 1)
{
step = 1;
threadWork = m2;
}
start = 0;
for (int i = threadsHalfing; i < threadsHalfing + threadWork - 1; i++)
{
threads[i] = new Thread(CountMulV);
threads[i].Start(new ParametersForMul(second, mulV, start, start + step, n2));
start += step;
}
threads[threadsHalfing + threadWork - 1] = new Thread(CountMulV);
threads[threadsHalfing + threadWork - 1].Start(new ParametersForMul(second, mulV, start, m2, n2));
//sync
for (int i = 0; i < threadWork + threadsHalfing; i++)
{
threads[i].Join();
}
//Main
step = n1 / threadsCount;
threadWork = threadsCount;
if (threadsCount / n1 >= 1)
{
step = 1;
threadWork = n1;
}
start = 0;
for (int i = 0; i < threadWork - 1; i++)
{
threads[i] = new Thread(CountMain);
threads[i].Start(new ParametersForMain(result, first, second, mulV, mulH, start, start + step, m2, m1));
start += step;
}
threads[threadWork - 1] = new Thread(CountMain);
threads[threadWork - 1].Start(new ParametersForMain(result, first, second, mulV, mulH, start, n1, m2, m1));
// sync
for (int i = 0; i < threadWork; i++)
{
threads[i].Join();
}
// end
if (m1 % 2 == 1)
{
start = 0;
for (int i = 0; i < threadWork - 1; i++)
{
threads[i] = new Thread(CountTail);
threads[i].Start(new ParametersForMain(result, first, second, mulV, mulH, start, start + step, m2, m1));
start += step;
}
threads[threadWork - 1] = new Thread(CountTail);
threads[threadWork - 1].Start(new ParametersForMain(result, first, second, mulV, mulH, start, n1, m2, m1));
// sync
for (int i = 0; i < threadWork; i++)
{
threads[i].Join();
}
}
}
return result;
}
// параллелится только main
public static Matrix ParallelSecond(Matrix first, Matrix second, int threadsCount)
{
Matrix result = new Matrix(0, 0);
if (threadsCount <= 1)
{
result = Classic(first, second);
}
else if (first.M == second.N && first.N != 0 && second.M != 0)
{
int n1 = first.N;
int m1 = first.M;
int n2 = second.N;
int m2 = second.M;
result = new Matrix(n1, m2);
int[] mulH = new int[n1];
int[] mulV = new int[m2];
for (int i = 0; i < n1; i++)
{
for (int j = 0; j < m1 / 2; j++)
{
mulH[i] += first[i, j * 2] * first[i, j * 2 + 1];
}
}
for (int i = 0; i < m2; i++)
{
for (int j = 0; j < n2 / 2; j++)
{
mulV[i] += second[j * 2, i] * second[j * 2 + 1, i];
}
}
//Main
Thread[] threads = new Thread[threadsCount];
int step = n1 / threadsCount;
int threadWork = threadsCount;
if (threadsCount / n1 >= 1)
{
step = 1;
threadWork = n1;
}
int start = 0;
for (int i = 0; i < threadWork - 1; i++)
{
threads[i] = new Thread(CountMain);
threads[i].Start(new ParametersForMain(result, first, second, mulV, mulH, start, start + step, m2, m1));
start += step;
}
threads[threadWork - 1] = new Thread(CountMain);
threads[threadWork - 1].Start(new ParametersForMain(result, first, second, mulV, mulH, start, n1, m2, m1));
// sync
for (int i = 0; i < threadWork; i++)
{
threads[i].Join();
}
// end
if (m1 % 2 == 1)
{
for (int i = 0; i < n1; i++)
{
for (int j = 0; j < m2; j++)
{
result[i, j] += first[i, m1 - 1] * second[m1 - 1, j];
}
}
}
}
return result;
}
private static void CountMulH(object paramsObj)
{
ParametersForMul paramses = (ParametersForMul)paramsObj;
int start = paramses.start,
end = paramses.end,
secondBorder = paramses.secondBorder;
Matrix matrix = paramses.matrix;
int[] mul = paramses.array;
for (int i = start; i < end; i++)
{
for (int j = 0; j < secondBorder / 2; j++)
{
mul[i] += matrix[i, j * 2] * matrix[i, j * 2 + 1];
}
}
}
private static void CountMulV(object paramsObj)
{
ParametersForMul paramses = (ParametersForMul)paramsObj;
int start = paramses.start,
end = paramses.end,
secondBorder = paramses.secondBorder;
Matrix matrix = paramses.matrix;
int[] mul = paramses.array;
for (int i = start; i < end; i++)
{
for (int j = 0; j < secondBorder / 2; j++)
{
mul[i] += matrix[j * 2, i] * matrix[j * 2 + 1, i];
}
}
}
private static void CountMain(object paramsObj)
{
ParametersForMain paramses = (ParametersForMain)paramsObj;
Matrix result = paramses.result,
first = paramses.first,
second = paramses.second;
int[] mulH = paramses.mulH,
mulV = paramses.mulV;
int start = paramses.start,
end = paramses.end,
m2 = paramses.m2,
m1 = paramses.m1;
for (int i = start; i < end; i++)
{
for (int j = 0; j < m2; j++)
{
result[i, j] = -mulH[i] - mulV[j];
for (int k = 0; k < m1 / 2; k++)
{
result[i, j] += (first[i, 2 * k + 1] + second[2 * k, j]) * (first[i, 2 * k] + second[2 * k + 1, j]);
}
}
}
}
private static void CountTail(object paramsObj)
{
ParametersForMain paramses = (ParametersForMain)paramsObj;
Matrix result = paramses.result,
first = paramses.first,
second = paramses.second;
int start = paramses.start,
end = paramses.end,
m2 = paramses.m2,
m1 = paramses.m1;
for (int i = start; i < end; i++)
{
for (int j = 0; j < m2; j++)
{
result[i, j] += first[i, m1 - 1] * second[m1 - 1, j];
}
}
}
}
class ParametersForMul
{
public Matrix matrix;
public int[] array;
public int start, end, secondBorder;
public ParametersForMul(Matrix matrix, int[] array, int start, int end, int secondBorder)
{
this.matrix = matrix;
this.array = array;
this.start = start;
this.end = end;
this.secondBorder = secondBorder;
}
}
class ParametersForMain
{
public Matrix first, second, result;
public int[] mulH, mulV;
public int start, end, m2, m1;
public ParametersForMain(Matrix result, Matrix first, Matrix second,
int[] mulV, int[] mulH,
int start, int end, int m2, int m1)
{
this.first = first;
this.second = second;
this.result = result;
this.mulH = mulH;
this.mulV = mulV;
this.start = start;
this.end = end;
this.m1 = m1;
this.m2 = m2;
}
}
} | 34.724138 | 132 | 0.376747 | [
"MIT"
] | DeaLoic/bmstu-AA | lab_04/source/VinogradMultiply.cs | 13,177 | C# |
/*
* CryptoWeather
*
* The CryptoWeather API allows for access to all of the cryptocurrency data and market forecast services provided. There are two primary categories of routes, `public` and `private`, where `public` routes are accessible to the general public and do not require API authentication, and `private` routes, which require API authentication. ## General Overview 1. All API methods adhere to RESTful best practices as closely as possible. As such, all API calls will be made via the standard HTTP protocol using the GET/POST/PUT/DELETE request types. 2. Every request returns the status as a JSON response with the following: - success, true if it was successful - code, the http status code (also in the response header) - 200 if response is successful - 400 if bad request - 401 if authorization JWT is wrong or limit exceeded - 404 wrong route - 500 for any internal errors - status, the status of the request, default **success** - errors, an array of any relevant error details 3. For any requests that are not successful an error message is specified and returned as an array for the **errors** key in the JSON response. 4. All authentication uses JSON Web Tokens (JWT), which is set as the **Authorization** entry in the header, see the following for more details. - http://jwt.io - https://scotch.io/tutorials/the-anatomy-of-a-json-web-token ## Code Example The following is a code example in Python, which demonstrates using the [Python Requests library](https://requests.readthedocs.io/en/master/) for both the `public` and `private` API routes. ``` import requests HOST = \"https://api.cryptoweather.ai/v1\" # Your API key (JWT) API_KEY = \"<YOUR API KEY>\" # Example public request, no API key required. requests.get(\"{}/public/symbols\".format(HOST)).json() # Get the current btc price using the public route requests.get(\"{}/public/price-current/{}\".format(HOST, \"btc\")).json() # Example private request, API key required. Get the btc hourly forecasts headers = {\"Authorization\": \"Bearer {}\".format(API_KEY)} requests.get(\"{}/private/forecast/{}/{}\".format(HOST, \"btc\", \"1h\"), headers=headers).json() ```
*
*
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter;
namespace IO.Swagger.Model
{
/// <summary>
/// TrendRoute
/// </summary>
[DataContract]
public partial class TrendRoute : IEquatable<TrendRoute>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="TrendRoute" /> class.
/// </summary>
[JsonConstructorAttribute]
public TrendRoute()
{
}
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class TrendRoute {\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as TrendRoute);
}
/// <summary>
/// Returns true if TrendRoute instances are equal
/// </summary>
/// <param name="input">Instance of TrendRoute to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(TrendRoute input)
{
if (input == null)
return false;
return false;
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 48.027273 | 2,219 | 0.638274 | [
"MIT"
] | Investabit/investabit-csharp-sdk | src/IO.Swagger/Model/TrendRoute.cs | 5,283 | C# |
namespace GTA
{
public enum Control
{
NextCamera,
LookLeftRight,
LookUpDown,
LookUpOnly,
LookDownOnly,
LookLeftOnly,
LookRightOnly,
CinematicSlowMo,
FlyUpDown,
FlyLeftRight,
ScriptedFlyZUp,
ScriptedFlyZDown,
WeaponWheelUpDown,
WeaponWheelLeftRight,
WeaponWheelNext,
WeaponWheelPrev,
SelectNextWeapon,
SelectPrevWeapon,
SkipCutscene,
CharacterWheel,
MultiplayerInfo,
Sprint,
Jump,
Enter,
Attack,
Aim,
LookBehind,
Phone,
SpecialAbility,
SpecialAbilitySecondary,
MoveLeftRight,
MoveUpDown,
MoveUpOnly,
MoveDownOnly,
MoveLeftOnly,
MoveRightOnly,
Duck,
SelectWeapon,
Pickup,
SniperZoom,
SniperZoomInOnly,
SniperZoomOutOnly,
SniperZoomInSecondary,
SniperZoomOutSecondary,
Cover,
Reload,
Talk,
Detonate,
HUDSpecial,
Arrest,
AccurateAim,
Context,
ContextSecondary,
WeaponSpecial,
WeaponSpecial2,
Dive,
DropWeapon,
DropAmmo,
ThrowGrenade,
VehicleMoveLeftRight,
VehicleMoveUpDown,
VehicleMoveUpOnly,
VehicleMoveDownOnly,
VehicleMoveLeftOnly,
VehicleMoveRightOnly,
VehicleSpecial,
VehicleGunLeftRight,
VehicleGunUpDown,
VehicleAim,
VehicleAttack,
VehicleAttack2,
VehicleAccelerate,
VehicleBrake,
VehicleDuck,
VehicleHeadlight,
VehicleExit,
VehicleHandbrake,
VehicleHotwireLeft,
VehicleHotwireRight,
VehicleLookBehind,
VehicleCinCam,
VehicleNextRadio,
VehiclePrevRadio,
VehicleNextRadioTrack,
VehiclePrevRadioTrack,
VehicleRadioWheel,
VehicleHorn,
VehicleFlyThrottleUp,
VehicleFlyThrottleDown,
VehicleFlyYawLeft,
VehicleFlyYawRight,
VehiclePassengerAim,
VehiclePassengerAttack,
VehicleSpecialAbilityFranklin,
VehicleStuntUpDown,
VehicleCinematicUpDown,
VehicleCinematicUpOnly,
VehicleCinematicDownOnly,
VehicleCinematicLeftRight,
VehicleSelectNextWeapon,
VehicleSelectPrevWeapon,
VehicleRoof,
VehicleJump,
VehicleGrapplingHook,
VehicleShuffle,
VehicleDropProjectile,
VehicleMouseControlOverride,
VehicleFlyRollLeftRight,
VehicleFlyRollLeftOnly,
VehicleFlyRollRightOnly,
VehicleFlyPitchUpDown,
VehicleFlyPitchUpOnly,
VehicleFlyPitchDownOnly,
VehicleFlyUnderCarriage,
VehicleFlyAttack,
VehicleFlySelectNextWeapon,
VehicleFlySelectPrevWeapon,
VehicleFlySelectTargetLeft,
VehicleFlySelectTargetRight,
VehicleFlyVerticalFlightMode,
VehicleFlyDuck,
VehicleFlyAttackCamera,
VehicleFlyMouseControlOverride,
VehicleSubTurnLeftRight,
VehicleSubTurnLeftOnly,
VehicleSubTurnRightOnly,
VehicleSubPitchUpDown,
VehicleSubPitchUpOnly,
VehicleSubPitchDownOnly,
VehicleSubThrottleUp,
VehicleSubThrottleDown,
VehicleSubAscend,
VehicleSubDescend,
VehicleSubTurnHardLeft,
VehicleSubTurnHardRight,
VehicleSubMouseControlOverride,
VehiclePushbikePedal,
VehiclePushbikeSprint,
VehiclePushbikeFrontBrake,
VehiclePushbikeRearBrake,
MeleeAttackLight,
MeleeAttackHeavy,
MeleeAttackAlternate,
MeleeBlock,
ParachuteDeploy,
ParachuteDetach,
ParachuteTurnLeftRight,
ParachuteTurnLeftOnly,
ParachuteTurnRightOnly,
ParachutePitchUpDown,
ParachutePitchUpOnly,
ParachutePitchDownOnly,
ParachuteBrakeLeft,
ParachuteBrakeRight,
ParachuteSmoke,
ParachutePrecisionLanding,
Map,
SelectWeaponUnarmed,
SelectWeaponMelee,
SelectWeaponHandgun,
SelectWeaponShotgun,
SelectWeaponSmg,
SelectWeaponAutoRifle,
SelectWeaponSniper,
SelectWeaponHeavy,
SelectWeaponSpecial,
SelectCharacterMichael,
SelectCharacterFranklin,
SelectCharacterTrevor,
SelectCharacterMultiplayer,
SaveReplayClip,
SpecialAbilityPC,
PhoneUp,
PhoneDown,
PhoneLeft,
PhoneRight,
PhoneSelect,
PhoneCancel,
PhoneOption,
PhoneExtraOption,
PhoneScrollForward,
PhoneScrollBackward,
PhoneCameraFocusLock,
PhoneCameraGrid,
PhoneCameraSelfie,
PhoneCameraDOF,
PhoneCameraExpression,
FrontendDown,
FrontendUp,
FrontendLeft,
FrontendRight,
FrontendRdown,
FrontendRup,
FrontendRleft,
FrontendRright,
FrontendAxisX,
FrontendAxisY,
FrontendRightAxisX,
FrontendRightAxisY,
FrontendPause,
FrontendPauseAlternate,
FrontendAccept,
FrontendCancel,
FrontendX,
FrontendY,
FrontendLb,
FrontendRb,
FrontendLt,
FrontendRt,
FrontendLs,
FrontendRs,
FrontendLeaderboard,
FrontendSocialClub,
FrontendSocialClubSecondary,
FrontendDelete,
FrontendEndscreenAccept,
FrontendEndscreenExpand,
FrontendSelect,
ScriptLeftAxisX,
ScriptLeftAxisY,
ScriptRightAxisX,
ScriptRightAxisY,
ScriptRUp,
ScriptRDown,
ScriptRLeft,
ScriptRRight,
ScriptLB,
ScriptRB,
ScriptLT,
ScriptRT,
ScriptLS,
ScriptRS,
ScriptPadUp,
ScriptPadDown,
ScriptPadLeft,
ScriptPadRight,
ScriptSelect,
CursorAccept,
CursorCancel,
CursorX,
CursorY,
CursorScrollUp,
CursorScrollDown,
EnterCheatCode,
InteractionMenu,
MpTextChatAll,
MpTextChatTeam,
MpTextChatFriends,
MpTextChatCrew,
PushToTalk,
CreatorLS,
CreatorRS,
CreatorLT,
CreatorRT,
CreatorMenuToggle,
CreatorAccept,
CreatorDelete,
Attack2,
RappelJump,
RappelLongJump,
RappelSmashWindow,
PrevWeapon,
NextWeapon,
MeleeAttack1,
MeleeAttack2,
Whistle,
MoveLeft,
MoveRight,
MoveUp,
MoveDown,
LookLeft,
LookRight,
LookUp,
LookDown,
SniperZoomIn,
SniperZoomOut,
SniperZoomInAlternate,
SniperZoomOutAlternate,
VehicleMoveLeft,
VehicleMoveRight,
VehicleMoveUp,
VehicleMoveDown,
VehicleGunLeft,
VehicleGunRight,
VehicleGunUp,
VehicleGunDown,
VehicleLookLeft,
VehicleLookRight,
ReplayStartStopRecording,
ReplayStartStopRecordingSecondary,
ScaledLookLeftRight,
ScaledLookUpDown,
ScaledLookUpOnly,
ScaledLookDownOnly,
ScaledLookLeftOnly,
ScaledLookRightOnly,
ReplayMarkerDelete,
ReplayClipDelete,
ReplayPause,
ReplayRewind,
ReplayFfwd,
ReplayNewmarker,
ReplayRecord,
ReplayScreenshot,
ReplayHidehud,
ReplayStartpoint,
ReplayEndpoint,
ReplayAdvance,
ReplayBack,
ReplayTools,
ReplayRestart,
ReplayShowhotkey,
ReplayCycleMarkerLeft,
ReplayCycleMarkerRight,
ReplayFOVIncrease,
ReplayFOVDecrease,
ReplayCameraUp,
ReplayCameraDown,
ReplaySave,
ReplayToggletime,
ReplayToggletips,
ReplayPreview,
ReplayToggleTimeline,
ReplayTimelinePickupClip,
ReplayTimelineDuplicateClip,
ReplayTimelinePlaceClip,
ReplayCtrl,
ReplayTimelineSave,
ReplayPreviewAudio,
VehicleDriveLook,
VehicleDriveLook2,
VehicleFlyAttack2,
RadioWheelUpDown,
RadioWheelLeftRight,
VehicleSlowMoUpDown,
VehicleSlowMoUpOnly,
VehicleSlowMoDownOnly,
MapPointOfInterest,
ReplaySnapmaticPhoto,
VehicleCarJump,
VehicleRocketBoost,
VehicleParachute,
}
}
| 19.097421 | 36 | 0.792348 | [
"MIT"
] | GTANetworkDev/platform | Shv.NET/source/scripting/Control.cs | 6,665 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace UrlHandling.API.ViewModel
{
public class UrlLinkResponse
{
public Guid id { get; set; }
public string ShortUrl { get; set; }
public string OriginalUrl { get; set; }
public DateTime RegistrationDate { get; set; }
public bool Active { get; set; }
}
}
| 24.117647 | 54 | 0.656098 | [
"MIT"
] | edmarssk/Urlhandling | src/UrlHandling.API/ViewModel/UrlLinkResponse.cs | 412 | C# |
using GenericEntity.Abstractions;
using GenericEntity.Extensions;
using System;
using System.IO;
using System.Text.Json;
using GenericEntity;
using System.Linq;
using System.Reflection;
namespace GenericEntity.CLI
{
class Program
{
static void Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine($"Syntax: {Assembly.GetExecutingAssembly().GetName().Name}.exe $schema");
return;
}
string schema = args[0];
//Initialization of the schema repository
ISchemaRepository schemaRepository = new JsonFileSchemaRepository("Schemas");
GenericEntity.DefaultSchemaRepository = schemaRepository;
//Creating address entity
GenericEntity address = new GenericEntity(schema, schemaRepository);
ReadFromConsole(address);
PrintToConsole(address);
}
private static void ReadFromConsole(GenericEntity genericEntity)
{
Console.WriteLine($@"Please type generic entity ""{genericEntity.Schema.Name}"" fields values:");
//Enumerating fields and setting the string value (which is validated and converted into proper field type)
foreach (IField field in genericEntity.Fields)
{
while (true)
{
Console.Write($"{field.Definition.DisplayName} ({field.Definition.Type}): ");
string value = Console.ReadLine();
try
{
field.SetString(value);
break;
}
catch (Exception exc)
{
Console.WriteLine(@$"Can't set ""{value}"" into ""{field.Definition.Type}"" field type.");
}
}
}
Console.WriteLine("Reading completed." + Environment.NewLine);
}
private static void PrintToConsole(GenericEntity genericEntity)
{
int[] columnWidths = new int[] { 15, 20, 15, 15 };
Console.WriteLine($@"Printing generic entity ""{genericEntity.Schema.Name}"" fields:");
int i = 0;
Console.WriteLine($"{"Name".PadRight(columnWidths[i++])}{"DisplayName".PadRight(columnWidths[i++])}{"Type".PadRight(columnWidths[i++])}{"NET Type".PadRight(columnWidths[i++])}{"Value"}");
Console.WriteLine($"{"-".PadRight(columnWidths.Sum() + 5, '-')}");
//Enumerating fields and getting value as string (such conversion is safe for all field types)
foreach (IField field in genericEntity.Fields)
{
i = 0;
Console.WriteLine($"{field.Definition.Name.PadRight(columnWidths[i++])}{field.Definition.DisplayName.PadRight(columnWidths[i++])}{field.Definition.Type.PadRight(columnWidths[i++])}{field.DataType.ToString().PadRight(columnWidths[i++])}{field.GetString()}");
}
Console.WriteLine();
}
}
}
| 38.160494 | 273 | 0.570366 | [
"MIT"
] | mguoth/GenericEntity | CSharp/GenericEntity.TestConsole/Program.cs | 3,093 | C# |
using UncommonSense.CBreeze.Core.Code.Variable;
using UncommonSense.CBreeze.Core.Contracts;
using UncommonSense.CBreeze.Core.Property.Implementation;
using UncommonSense.CBreeze.Core.Property.Type;
namespace UncommonSense.CBreeze.Core.Table.Field.Properties
{
public class TableFilterTableFieldProperties : Property.Properties
{
#if NAV2015
private AccessByPermissionProperty accessByPermission = new AccessByPermissionProperty("AccessByPermission");
#endif
private MultiLanguageProperty captionML = new MultiLanguageProperty("CaptionML");
private StringProperty description = new StringProperty("Description");
private TriggerProperty onLookup = new TriggerProperty("OnLookup");
private TriggerProperty onValidate = new TriggerProperty("OnValidate");
private StringProperty tableIDExpr = new StringProperty("TableIDExpr");
internal TableFilterTableFieldProperties(TableFilterTableField field)
{
Field = field;
innerList.Add(onValidate);
innerList.Add(onLookup);
innerList.Add(tableIDExpr);
#if NAV2015
innerList.Add(accessByPermission);
#endif
innerList.Add(captionML);
innerList.Add(description);
}
public TableFilterTableField Field { get; protected set; }
public override INode ParentNode => Field;
#if NAV2015
public AccessByPermission AccessByPermission
{
get
{
return accessByPermission.Value;
}
}
#endif
public MultiLanguageValue CaptionML
{
get
{
return this.captionML.Value;
}
}
public string Description
{
get
{
return this.description.Value;
}
set
{
this.description.Value = value;
}
}
public Trigger OnLookup
{
get
{
return this.onLookup.Value;
}
}
public Trigger OnValidate
{
get
{
return this.onValidate.Value;
}
}
public string TableIDExpr
{
get
{
return this.tableIDExpr.Value;
}
set
{
this.tableIDExpr.Value = value;
}
}
}
}
| 26.020833 | 117 | 0.567254 | [
"MIT"
] | FSharpCSharp/UncommonSense.CBreeze | CBreeze/UncommonSense.CBreeze.Core/Table/Field/Properties/TableFilterTableFieldProperties.cs | 2,498 | C# |
/*
* Copyright 2018 JDCLOUD.COM
*
* 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.
*
* back source configuration openapi
* back source configuration openapi
*
* OpenAPI spec version: v1
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace JDCloudSDK.Ossopenapi.Model
{
/// <summary>
/// 回源地址
/// </summary>
public class BackSourceAddress
{
///<summary>
/// 地址协议, 如http
///</summary>
public string Protocol{ get; set; }
///<summary>
/// 域名
///</summary>
public string HostName{ get; set; }
///<summary>
/// 将前缀替换为指定的内容
///</summary>
public string ReplaceKeyPrefixWith{ get; set; }
///<summary>
/// 将key替换为指定内容
///</summary>
public string ReplaceKeyWith{ get; set; }
///<summary>
/// 将后缀替换为指定的内容
///</summary>
public string ReplaceKeySuffixWith{ get; set; }
}
}
| 25.532258 | 76 | 0.628553 | [
"Apache-2.0"
] | jdcloud-api/jdcloud-sdk-net | sdk/src/Service/Ossopenapi/Model/BackSourceAddress.cs | 1,665 | C# |
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
namespace EventOrganizer.Data
{
/* This is used if database provider does't define
* IEventOrganizerDbSchemaMigrator implementation.
*/
public class NullEventOrganizerDbSchemaMigrator : IEventOrganizerDbSchemaMigrator, ITransientDependency
{
public Task MigrateAsync()
{
return Task.CompletedTask;
}
}
} | 27.0625 | 107 | 0.711316 | [
"MIT"
] | 271943794/abp-samples | EventOrganizer/src/EventOrganizer.Domain/Data/NullEventOrganizerDbSchemaMigrator.cs | 435 | C# |
//-----------------------------------------------------------------------
// <copyright file="Shape.cs" company="Akka.NET Project">
// Copyright (C) 2009-2018 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2018 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Akka.Streams.Implementation;
namespace Akka.Streams
{
/// <summary>
/// An input port of a <see cref="IModule"/>. This type logically belongs
/// into the impl package but must live here due to how sealed works.
/// It is also used in the Java DSL for "untyped Inlets" as a work-around
/// for otherwise unreasonable existential types.
/// </summary>
public abstract class InPort
{
/// <summary>
/// TBD
/// </summary>
internal int Id = -1;
}
/// <summary>
/// An output port of a StreamLayout.Module. This type logically belongs
/// into the impl package but must live here due to how sealed works.
/// It is also used in the Java DSL for "untyped Outlets" as a work-around
/// for otherwise unreasonable existential types.
/// </summary>
public abstract class OutPort
{
/// <summary>
/// TBD
/// </summary>
internal int Id = -1;
}
/// <summary>
/// An Inlet is a typed input to a Shape. Its partner in the Module view
/// is the InPort(which does not bear an element type because Modules only
/// express the internal structural hierarchy of stream topologies).
/// </summary>
public abstract class Inlet : InPort
{
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T">TBD</typeparam>
/// <param name="inlet">TBD</param>
/// <returns>TBD</returns>
public static Inlet<T> Create<T>(Inlet inlet) => inlet as Inlet<T> ?? new Inlet<T>(inlet.Name);
/// <summary>
/// TBD
/// </summary>
/// <param name="name">TBD</param>
/// <exception cref="ArgumentException">
/// This exception is thrown when the specified <paramref name="name"/> is undefined.
/// </exception>
protected Inlet(string name)
{
if (name is null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_Inletname_IsNull); }
Name = name;
}
/// <summary>
/// TBD
/// </summary>
public readonly string Name;
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public abstract Inlet CarbonCopy();
/// <inheritdoc/>
public sealed override string ToString() => Name;
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T">TBD</typeparam>
public sealed class Inlet<T> : Inlet
{
/// <summary>
/// TBD
/// </summary>
/// <param name="name">TBD</param>
public Inlet(string name) : base(name) { }
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TOther">TBD</typeparam>
/// <returns>TBD</returns>
internal Inlet<TOther> As<TOther>() => Create<TOther>(this);
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override Inlet CarbonCopy() => new Inlet<T>(Name);
}
/// <summary>
/// An Outlet is a typed output to a Shape. Its partner in the Module view
/// is the OutPort(which does not bear an element type because Modules only
/// express the internal structural hierarchy of stream topologies).
/// </summary>
public abstract class Outlet : OutPort
{
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T">TBD</typeparam>
/// <param name="outlet">TBD</param>
/// <returns>TBD</returns>
public static Outlet<T> Create<T>(Outlet outlet) => outlet as Outlet<T> ?? new Outlet<T>(outlet.Name);
/// <summary>
/// TBD
/// </summary>
/// <param name="name">TBD</param>
protected Outlet(string name) => Name = name;
/// <summary>
/// TBD
/// </summary>
public readonly string Name;
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public abstract Outlet CarbonCopy();
/// <inheritdoc/>
public sealed override string ToString() => Name;
}
/// <summary>
/// TBD
/// </summary>
public sealed class Outlet<T> : Outlet
{
/// <summary>
/// TBD
/// </summary>
/// <param name="name">TBD</param>
public Outlet(string name) : base(name) { }
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TOther">TBD</typeparam>
/// <returns>TBD</returns>
internal Outlet<TOther> As<TOther>() => Create<TOther>(this);
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override Outlet CarbonCopy() => new Outlet<T>(Name);
}
/// <summary>
/// A Shape describes the inlets and outlets of a <see cref="IGraph{TShape}"/>. In keeping with the
/// philosophy that a Graph is a freely reusable blueprint, everything that
/// matters from the outside are the connections that can be made with it,
/// otherwise it is just a black box.
/// </summary>
public abstract class Shape
#if CLONEABLE
: ICloneable
#endif
{
/// <summary>
/// Gets list of all input ports.
/// </summary>
public abstract ImmutableArray<Inlet> Inlets { get; }
/// <summary>
/// Gets list of all output ports.
/// </summary>
public abstract ImmutableArray<Outlet> Outlets { get; }
/// <summary>
/// Create a copy of this Shape object, returning the same type as the
/// original; this constraint can unfortunately not be expressed in the
/// type system.
/// </summary>
/// <returns>TBD</returns>
public abstract Shape DeepCopy();
/// <summary>
/// Create a copy of this Shape object, returning the same type as the
/// original but containing the ports given within the passed-in Shape.
/// </summary>
/// <param name="inlets">TBD</param>
/// <param name="outlets">TBD</param>
/// <returns>TBD</returns>
public abstract Shape CopyFromPorts(ImmutableArray<Inlet> inlets, ImmutableArray<Outlet> outlets);
/// <summary>
/// Compare this to another shape and determine whether the set of ports is the same (ignoring their ordering).
/// </summary>
/// <param name="shape">TBD</param>
/// <returns>TBD</returns>
public bool HasSamePortsAs(Shape shape)
{
var inlets = new HashSet<Inlet>(Inlets);
var outlets = new HashSet<Outlet>(Outlets);
return inlets.SetEquals(shape.Inlets) && outlets.SetEquals(shape.Outlets);
}
/// <summary>
/// Compare this to another shape and determine whether the arrangement of ports is the same (including their ordering).
/// </summary>
/// <param name="shape">TBD</param>
/// <returns>TBD</returns>
public bool HasSamePortsAndShapeAs(Shape shape) => Inlets.Equals(shape.Inlets) && Outlets.Equals(shape.Outlets);
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public object Clone() => DeepCopy();
/// <inheritdoc/>
public sealed override string ToString() => $"{GetType().Name}([{string.Join(", ", Inlets)}] [{string.Join(", ", Outlets)}])";
}
/// <summary>
/// This <see cref="Shape"/> is used for graphs that have neither open inputs nor open
/// outputs. Only such a <see cref="IGraph{TShape,TMaterializer}"/> can be materialized by a <see cref="IMaterializer"/>.
/// </summary>
public class ClosedShape : Shape, ISingletonMessage
{
/// <summary>
/// TBD
/// </summary>
public static readonly ClosedShape Instance = new ClosedShape();
private ClosedShape() { }
/// <summary>
/// TBD
/// </summary>
public override ImmutableArray<Inlet> Inlets => ImmutableArray<Inlet>.Empty;
/// <summary>
/// TBD
/// </summary>
public override ImmutableArray<Outlet> Outlets => ImmutableArray<Outlet>.Empty;
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override Shape DeepCopy() => this;
/// <summary>
/// TBD
/// </summary>
/// <param name="inlets">TBD</param>
/// <param name="outlets">TBD</param>
/// <exception cref="ArgumentException">
/// This exception is thrown when the size of the specified <paramref name="inlets"/> array is zero
/// or the size of the specified <paramref name="outlets"/> array is zero.
/// </exception>
/// <returns>TBD</returns>
public override Shape CopyFromPorts(ImmutableArray<Inlet> inlets, ImmutableArray<Outlet> outlets)
{
if (0u < (uint)inlets.Length) ThrowHelper.ThrowArgumentException_FitClosedShape(ExceptionArgument.inlets);
if (0u < (uint)outlets.Length) ThrowHelper.ThrowArgumentException_FitClosedShape(ExceptionArgument.outlets);
return this;
}
}
/// <summary>
/// This type of <see cref="Shape"/> can express any number of inputs and outputs at the
/// expense of forgetting about their specific types. It is used mainly in the
/// implementation of the <see cref="IGraph{TShape,TMaterializer}"/> builders and typically replaced by a more
/// meaningful type of Shape when the building is finished.
/// </summary>
public class AmorphousShape : Shape
{
/// <summary>
/// TBD
/// </summary>
/// <param name="inlets">TBD</param>
/// <param name="outlets">TBD</param>
public AmorphousShape(ImmutableArray<Inlet> inlets, ImmutableArray<Outlet> outlets)
{
Inlets = inlets;
Outlets = outlets;
}
/// <summary>
/// TBD
/// </summary>
public override ImmutableArray<Inlet> Inlets { get; }
/// <summary>
/// TBD
/// </summary>
public override ImmutableArray<Outlet> Outlets { get; }
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override Shape DeepCopy()
=> new AmorphousShape(Inlets.Select(i => i.CarbonCopy()).ToImmutableArray(), Outlets.Select(o => o.CarbonCopy()).ToImmutableArray());
/// <summary>
/// TBD
/// </summary>
/// <param name="inlets">TBD</param>
/// <param name="outlets">TBD</param>
/// <returns>TBD</returns>
public override Shape CopyFromPorts(ImmutableArray<Inlet> inlets, ImmutableArray<Outlet> outlets)
=> new AmorphousShape(inlets, outlets);
}
/// <summary>
/// A Source <see cref="Shape"/> has exactly one output and no inputs, it models a source of data.
/// </summary>
/// <typeparam name="TOut">TBD</typeparam>
public sealed class SourceShape<TOut> : Shape
{
/// <summary>
/// TBD
/// </summary>
/// <param name="outlet">TBD</param>
/// <exception cref="ArgumentNullException">TBD</exception>
public SourceShape(Outlet<TOut> outlet)
{
if (outlet is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.outlet); }
Outlet = outlet;
Outlets = ImmutableArray.Create<Outlet>(outlet);
}
/// <summary>
/// TBD
/// </summary>
public readonly Outlet<TOut> Outlet;
/// <summary>
/// TBD
/// </summary>
public override ImmutableArray<Inlet> Inlets => ImmutableArray<Inlet>.Empty;
/// <summary>
/// TBD
/// </summary>
public override ImmutableArray<Outlet> Outlets { get; }
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override Shape DeepCopy() => new SourceShape<TOut>((Outlet<TOut>)Outlet.CarbonCopy());
/// <summary>
/// TBD
/// </summary>
/// <param name="inlets">TBD</param>
/// <param name="outlets">TBD</param>
/// <exception cref="ArgumentException">
/// This exception is thrown when the size of the specified <paramref name="inlets"/> array is zero
/// or the size of the specified <paramref name="outlets"/> array is one.
/// </exception>
/// <returns>TBD</returns>
public override Shape CopyFromPorts(ImmutableArray<Inlet> inlets, ImmutableArray<Outlet> outlets)
{
if (inlets.Length != 0) ThrowHelper.ThrowArgumentException_FitSourceShape(ExceptionArgument.inlets);
if (outlets.Length != 1) ThrowHelper.ThrowArgumentException_FitSourceShape(ExceptionArgument.outlets);
return new SourceShape<TOut>(outlets[0] as Outlet<TOut>);
}
/// <inheritdoc/>
public override bool Equals(object obj)
{
if (obj is null)
return false;
if (ReferenceEquals(this, obj))
return true;
return obj is SourceShape<TOut> shape && Equals(shape);
}
/// <inheritdoc/>
private bool Equals(SourceShape<TOut> other) => Outlet.Equals(other.Outlet);
/// <inheritdoc/>
public override int GetHashCode() => Outlet.GetHashCode();
}
/// <summary>
/// TBD
/// </summary>
public interface IFlowShape
{
/// <summary>
/// TBD
/// </summary>
Inlet Inlet { get; }
/// <summary>
/// TBD
/// </summary>
Outlet Outlet { get; }
}
/// <summary>
/// A Flow <see cref="Shape"/> has exactly one input and one output, it looks from the
/// outside like a pipe (but it can be a complex topology of streams within of course).
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
public sealed class FlowShape<TIn, TOut> : Shape, IFlowShape
{
/// <summary>
/// TBD
/// </summary>
/// <param name="inlet">TBD</param>
/// <param name="outlet">TBD</param>
/// <exception cref="ArgumentNullException">
/// This exception is thrown when either the specified <paramref name="inlet"/> or <paramref name="outlet"/> is undefined.
/// </exception>
public FlowShape(Inlet<TIn> inlet, Outlet<TOut> outlet)
{
if (inlet is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.inlet, ExceptionResource.ArgumentNull_FlowShape_Inlet); }
if (outlet is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.outlet, ExceptionResource.ArgumentNull_FlowShape_Outlet); }
Inlet = inlet;
Outlet = outlet;
Inlets = ImmutableArray.Create<Inlet>(inlet);
Outlets = ImmutableArray.Create<Outlet>(outlet);
}
Inlet IFlowShape.Inlet => Inlet;
Outlet IFlowShape.Outlet => Outlet;
/// <summary>
/// TBD
/// </summary>
public Inlet<TIn> Inlet { get; }
/// <summary>
/// TBD
/// </summary>
public Outlet<TOut> Outlet { get; }
/// <summary>
/// TBD
/// </summary>
public override ImmutableArray<Inlet> Inlets { get; }
/// <summary>
/// TBD
/// </summary>
public override ImmutableArray<Outlet> Outlets { get; }
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override Shape DeepCopy()
=> new FlowShape<TIn, TOut>((Inlet<TIn>)Inlet.CarbonCopy(), (Outlet<TOut>)Outlet.CarbonCopy());
/// <summary>
/// TBD
/// </summary>
/// <param name="inlets">TBD</param>
/// <param name="outlets">TBD</param>
/// <exception cref="ArgumentException">
/// This exception is thrown when the size of the specified <paramref name="inlets"/> array is one
/// or the size of the specified <paramref name="outlets"/> array is one.
/// </exception>
/// <returns>TBD</returns>
public override Shape CopyFromPorts(ImmutableArray<Inlet> inlets, ImmutableArray<Outlet> outlets)
{
if (inlets.Length != 1) ThrowHelper.ThrowArgumentException_FitFlowShape(ExceptionArgument.inlets);
if (outlets.Length != 1) ThrowHelper.ThrowArgumentException_FitFlowShape(ExceptionArgument.outlets);
return new FlowShape<TIn, TOut>(inlets[0] as Inlet<TIn>, outlets[0] as Outlet<TOut>);
}
}
/// <summary>
/// A Sink <see cref="Shape"/> has exactly one input and no outputs, it models a data sink.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
public sealed class SinkShape<TIn> : Shape
{
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<TIn> Inlet;
/// <summary>
/// TBD
/// </summary>
/// <param name="inlet">TBD</param>
/// <exception cref="ArgumentNullException">
/// This exception is thrown when the specified <paramref name="inlet"/> is undefined.
/// </exception>
public SinkShape(Inlet<TIn> inlet)
{
if (inlet is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.inlet, ExceptionResource.ArgumentNull_SinkShape_Inlet); }
Inlet = inlet;
Inlets = ImmutableArray.Create<Inlet>(inlet);
}
/// <summary>
/// TBD
/// </summary>
public override ImmutableArray<Inlet> Inlets { get; }
/// <summary>
/// TBD
/// </summary>
public override ImmutableArray<Outlet> Outlets => ImmutableArray<Outlet>.Empty;
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override Shape DeepCopy() => new SinkShape<TIn>((Inlet<TIn>)Inlet.CarbonCopy());
/// <summary>
/// TBD
/// </summary>
/// <param name="inlets">TBD</param>
/// <param name="outlets">TBD</param>
/// <exception cref="ArgumentException">
/// This exception is thrown when the size of the specified <paramref name="inlets"/> array is zero
/// or the size of the specified <paramref name="outlets"/> array is one.
/// </exception>
/// <returns>TBD</returns>
public override Shape CopyFromPorts(ImmutableArray<Inlet> inlets, ImmutableArray<Outlet> outlets)
{
if (outlets.Length != 0) ThrowHelper.ThrowArgumentException_FitSinkShape(ExceptionArgument.outlets);
if (inlets.Length != 1) ThrowHelper.ThrowArgumentException_FitSinkShape(ExceptionArgument.inlets);
return new SinkShape<TIn>(inlets[0] as Inlet<TIn>);
}
/// <inheritdoc/>
public override bool Equals(object obj)
{
if (obj is null)
return false;
if (ReferenceEquals(this, obj))
return true;
return obj is SinkShape<TIn> shape && Equals(shape);
}
private bool Equals(SinkShape<TIn> other) => Equals(Inlet, other.Inlet);
/// <inheritdoc/>
public override int GetHashCode() => Inlet.GetHashCode();
}
/// <summary>
/// A bidirectional flow of elements that consequently has two inputs and two outputs.
/// </summary>
/// <typeparam name="TIn1">TBD</typeparam>
/// <typeparam name="TOut1">TBD</typeparam>
/// <typeparam name="TIn2">TBD</typeparam>
/// <typeparam name="TOut2">TBD</typeparam>
public sealed class BidiShape<TIn1, TOut1, TIn2, TOut2> : Shape
{
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<TIn1> Inlet1;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<TIn2> Inlet2;
/// <summary>
/// TBD
/// </summary>
public readonly Outlet<TOut1> Outlet1;
/// <summary>
/// TBD
/// </summary>
public readonly Outlet<TOut2> Outlet2;
/// <summary>
/// TBD
/// </summary>
/// <param name="in1">TBD</param>
/// <param name="out1">TBD</param>
/// <param name="in2">TBD</param>
/// <param name="out2">TBD</param>
/// <exception cref="ArgumentNullException">
/// This exception is thrown when either the specified <paramref name="in1"/>, <paramref name="out1"/>,
/// <paramref name="in2"/>, or <paramref name="out2"/> is undefined.
/// </exception>
public BidiShape(Inlet<TIn1> in1, Outlet<TOut1> out1, Inlet<TIn2> in2, Outlet<TOut2> out2)
{
if (in1 is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.in1); }
if (in2 is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.in2); }
if (out1 is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.out1); }
if (out2 is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.out2); }
Inlet1 = in1;
Inlet2 = in2;
Outlet1 = out1;
Outlet2 = out2;
Inlets = ImmutableArray.Create<Inlet>(Inlet1, Inlet2);
Outlets = ImmutableArray.Create<Outlet>(Outlet1, Outlet2);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="top">TBD</param>
/// <param name="bottom">TBD</param>
public BidiShape(FlowShape<TIn1, TOut1> top, FlowShape<TIn2, TOut2> bottom)
: this(top.Inlet, top.Outlet, bottom.Inlet, bottom.Outlet)
{
}
/// <summary>
/// TBD
/// </summary>
public override ImmutableArray<Inlet> Inlets { get; }
/// <summary>
/// TBD
/// </summary>
public override ImmutableArray<Outlet> Outlets { get; }
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override Shape DeepCopy()
{
return new BidiShape<TIn1, TOut1, TIn2, TOut2>(
(Inlet<TIn1>)Inlet1.CarbonCopy(),
(Outlet<TOut1>)Outlet1.CarbonCopy(),
(Inlet<TIn2>)Inlet2.CarbonCopy(),
(Outlet<TOut2>)Outlet2.CarbonCopy());
}
/// <summary>
/// TBD
/// </summary>
/// <param name="inlets">TBD</param>
/// <param name="outlets">TBD</param>
/// <exception cref="ArgumentException">
/// This exception is thrown when the size of the specified <paramref name="inlets"/> array is two
/// or the size of the specified <paramref name="outlets"/> array is two.
/// </exception>
/// <returns>TBD</returns>
public override Shape CopyFromPorts(ImmutableArray<Inlet> inlets, ImmutableArray<Outlet> outlets)
{
if (inlets.Length != 2) ThrowHelper.ThrowArgumentException_ProposedInlets(inlets);
if (outlets.Length != 2) ThrowHelper.ThrowArgumentException_ProposedOutlets(outlets);
return new BidiShape<TIn1, TOut1, TIn2, TOut2>((Inlet<TIn1>)inlets[0], (Outlet<TOut1>)outlets[0], (Inlet<TIn2>)inlets[1], (Outlet<TOut2>)outlets[1]);
}
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public Shape Reversed() => new BidiShape<TIn2, TOut2, TIn1, TOut1>(Inlet2, Outlet2, Inlet1, Outlet1);
}
/// <summary>
/// TBD
/// </summary>
public static class BidiShape
{
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn1">TBD</typeparam>
/// <typeparam name="TOut1">TBD</typeparam>
/// <typeparam name="TIn2">TBD</typeparam>
/// <typeparam name="TOut2">TBD</typeparam>
/// <param name="top">TBD</param>
/// <param name="bottom">TBD</param>
/// <returns>TBD</returns>
public static BidiShape<TIn1, TOut1, TIn2, TOut2> FromFlows<TIn1, TOut1, TIn2, TOut2>(
FlowShape<TIn1, TOut1> top, FlowShape<TIn2, TOut2> bottom)
=> new BidiShape<TIn1, TOut1, TIn2, TOut2>(top.Inlet, top.Outlet, bottom.Inlet, bottom.Outlet);
}
}
| 35.340395 | 161 | 0.562448 | [
"Apache-2.0"
] | cuteant/akka.net | src/Akka.Streams/Shape.cs | 25,023 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FlowChart.Controller;
using FlowChart.Models;
using FlowChart.Entities;
using FlowChart.Utility;
using FlowChart.Visitors;
using System.Windows.Forms;
using FlowChart.Views;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace FlowChart.Tools
{
internal class DefaultInputTool:BaseInputTool
{
private float maxTop = 0;
private float minTop = 0;
private float maxLeft = 0;
private float minLeft = 0;
private float zoom = 1;
private readonly float zoomLimit = 25;
private readonly int offSet = 25;
private PointF lastPoint = new PointF();
public override float ZoomFactor
{
get
{
return base.ZoomFactor;
}
set
{
base.ZoomFactor = value;
if (this.View != null)
{
float delta = (601 * ZoomFactor - this.View.Width);
Zoom(delta, (int)lastPoint.X, (int)lastPoint.Y);
this.View.Invalidate();
/*if (this.Resize != null)
{
this.Resize();
}*/
}
}
}
public ScrollableControl View
{
get;
private set;
}
public FlowChartModel Model
{
get;
set;
}
internal DefaultInputTool(FlowChartModel model, FlowChartPage view)
{
this.Model = model;
this.View = view;
View.MouseDown += new System.Windows.Forms.MouseEventHandler(View_MouseDown);
View.MouseUp += new System.Windows.Forms.MouseEventHandler(View_MouseUp);
View.MouseMove += new System.Windows.Forms.MouseEventHandler(View_MouseMove);
View.KeyDown += new System.Windows.Forms.KeyEventHandler(View_KeyDown);
View.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(View_MouseDoubleClick);
View.MouseWheel += new MouseEventHandler(View_MouseWheel);
view.DragMouse += new Action<float, float>(view_DragMouse);
}
private void Zoom(float delta, int focusX, int focusY)
{
float oX = View.Left + focusX;
float oY = View.Top + focusY;
float nWidth = View.Width + delta;
float nHeight = View.Height + delta;
float newX = (focusX * nWidth) / View.Width;
float newY = (focusY * nHeight) / View.Height;
View.Width = (int)Math.Round(nWidth);
View.Height = (int)Math.Round(nHeight);
View.Left = (int)Math.Round(oX - newX);
View.Top = (int)Math.Round(oY - newY);
}
internal void ResetView(float maxTop, float minTop, float maxLeft, float minLeft)
{
this.maxTop = maxTop;
this.minTop = minTop;
this.maxLeft = maxLeft;
this.minLeft = minLeft;
}
void view_DragMouse(float x, float y)
{
float nTop = View.Top + y;
float nLeft = View.Left + x;
if (nLeft > minLeft && nLeft <= maxLeft)
{
View.Left += (int)x;
}
if (nTop > minTop && nTop <= maxTop)
{
View.Top += (int)y;
}
}
void View_MouseWheel(object sender, MouseEventArgs e)
{
MouseEventArgs p = BacktrackMouse(e);
if ((Control.ModifierKeys & Keys.Control) != Keys.None)
{
float f = 1.1f;
if ((e.Delta / 120) < 0) f = 1 / f;
this.lastPoint.X = p.X;
this.lastPoint.Y = p.Y;
this.OnZoom(f, p.X, p.Y);
}
else
{
float nTop = View.Top + e.Delta / 10;
if (nTop > minTop && nTop <= maxTop)
{
View.Top += (int)e.Delta / 10;
}
this.OnScroll(e.Delta/10, p.X, p.Y);
}
}
void View_MouseDoubleClick(object sender, System.Windows.Forms.MouseEventArgs e)
{
this.MouseDoubleClick(BacktrackMouse(e));
}
void View_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
this.KeyDown(e);
}
void View_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
this.MouseMove(BacktrackMouse(e));
}
void View_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
this.MouseUp(BacktrackMouse(e));
}
void View_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
this.MouseDown(BacktrackMouse(e));
}
private void SaveInstance()
{
System.Windows.Forms.Clipboard.SetText(Util.GetJSONString(SelectedComponent.GetComponent()));
}
private void LoadInstance()
{
try
{
FlowChartComponent fc = Util.ConvertFromJSON<FlowChartComponent>(System.Windows.Forms.Clipboard.GetText());
BaseComponent c = (BaseComponent)Activator.CreateInstance(Type.GetType(fc.Type));
c.SetComponent(fc);
c.ID = Util.GetUniqueID();
c.Accept(new ObjectCreateVisitor(Model, fc));
this.OnAdd(c);
}
catch
{
}
}
protected override void KeyDown(System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == System.Windows.Forms.Keys.Delete)
{
if (SelectedComponent != null)
{
this.OnDelete(SelectedComponent);
this.View.Invalidate();
}
}
else if (e.KeyCode == System.Windows.Forms.Keys.C && e.Control)
{
if (SelectedComponent != null)
{
SaveInstance();
}
}
else if (e.KeyCode == System.Windows.Forms.Keys.V && e.Control)
{
LoadInstance();
}
}
protected override void MouseDown(System.Windows.Forms.MouseEventArgs e)
{
if (SelectedComponent != null)
{
if (SelectedComponent.HitTest(e.X, e.Y))
{
if ((Control.ModifierKeys & Keys.Shift) != Keys.None)
{
SaveInstance();
LoadInstance();
BaseComponent addedCmp = SelectedComponent;
if (addedCmp.HitTest(e.X, e.Y))
{
OnSelect(addedCmp);
addedCmp.MouseDown(e);
}
return;
}
else
{
SelectedComponent.MouseDown(e);
return;
}
}
else
{
OnSelect(null);
}
}
foreach (BaseComponent x in Model.Items)
{
x.MouseState = Entities.MouseState.None;
x.IsSelected = false;
if (x.HitTest(e.X, e.Y))
{
OnSelect(x);
x.MouseDown(e);
break;
}
}
this.View.Invalidate();
}
protected override void MouseMove(System.Windows.Forms.MouseEventArgs e)
{
if (SelectedComponent != null)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
if (SelectedComponent.MouseState == MouseState.Resize)
{
SelectedComponent.MouseMove(e);
this.View.Invalidate();
}
else if (SelectedComponent.MouseState == MouseState.Move)
{
SelectedComponent.Move(e);
this.View.Invalidate();
}
}
}
}
protected override void MouseUp(System.Windows.Forms.MouseEventArgs e)
{
if (SelectedComponent != null)
{
SelectedComponent.MouseUp(e);
this.View.Invalidate();
}
}
protected override void MouseDoubleClick(System.Windows.Forms.MouseEventArgs e)
{
if (SelectedComponent != null)
{
MouseEventArgs p = BacktrackMouse(e);
this.OnDblClick(p.X, p.Y);
}
}
protected MouseEventArgs BacktrackMouse(MouseEventArgs e)
{
float zoom = this.ZoomFactor;
Matrix mx = new Matrix(zoom, 0, 0, zoom, 0, 0);
mx.Translate(View.AutoScrollPosition.X * (1.0f / zoom), View.AutoScrollPosition.Y * (1.0f / zoom));
mx.Invert();
Point[] pa = new Point[] { new Point(e.X, e.Y) };
mx.TransformPoints(pa);
return new MouseEventArgs(e.Button, e.Clicks, pa[0].X, pa[0].Y, e.Delta);
}
}
}
| 32.737542 | 123 | 0.466511 | [
"BSD-3-Clause"
] | JackWangCUMT/FlowChart | Tools/DefaultInputTool.cs | 9,856 | C# |
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace LinkyLink.Models
{
/// <summary>
/// This class coordinates Entity Framework Core functionality (Create, Read, Update, Delete) for the LinkBundle data model.
/// </summary>
public class LinksContext : DbContext
{
private readonly string cosmosContainerName;
public LinksContext(DbContextOptions<LinksContext> options, IConfiguration configuration) : base(options)
{
cosmosContainerName = configuration.GetSection("CosmosSettings")["ContainerName"];
}
public DbSet<LinkBundle> LinkBundle { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<LinkBundle>().Property(p => p.Id).ValueGeneratedOnAdd();
modelBuilder.Entity<LinkBundle>().OwnsMany<Link>(p => p.Links);
modelBuilder.Entity<LinkBundle>().HasPartitionKey(o => o.UserId);
modelBuilder.HasDefaultContainer(cosmosContainerName);
modelBuilder.Entity<LinkBundle>().HasNoDiscriminator();
}
}
}
| 39.551724 | 128 | 0.687881 | [
"MIT"
] | aluong/openhack-production | api/src/LinkyLink/Models/LinksContext.cs | 1,149 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using AdaptiveExpressions.Properties;
using Newtonsoft.Json;
using Microsoft.Bot.Builder.Dialogs;
using Octokit;
using System.ComponentModel.DataAnnotations;
namespace GitHubClient.Oauth
{
/// <summary>
/// Action to call GitHubClient.Oauth.GetGitHubLoginUrl() API.
/// </summary>
public class GetGitHubLoginUrl : GitHubAction
{
/// <summary>
/// Class identifier.
/// </summary>
[JsonProperty("$kind")]
public const string Kind = "GitHub.Oauth.GetGitHubLoginUrl";
/// <summary>
/// Initializes a new instance of the <see cref="GetGitHubLoginUrl"/> class.
/// </summary>
/// <param name="callerPath">Optional, source file full path.</param>
/// <param name="callerLine">Optional, line number in source file.</param>
public GetGitHubLoginUrl([CallerFilePath] string callerPath = "", [CallerLineNumber] int callerLine = 0)
{
this.RegisterSourceLocation(callerPath, callerLine);
}
/// <summary>
/// (REQUIRED) Gets or sets the expression for api argument request.
/// </summary>
/// <value>
/// The value or expression to bind to the value for the argument.
/// </value>
[Required()]
[JsonProperty("request")]
public ObjectExpression<Octokit.OauthLoginRequest> Request { get; set; }
/// <inheritdoc/>
protected override async Task<object> CallGitHubApi(DialogContext dc, Octokit.GitHubClient gitHubClient, CancellationToken cancellationToken = default(CancellationToken))
{
if (Request != null)
{
var requestValue = Request.GetValue(dc.State);
return gitHubClient.Oauth.GetGitHubLoginUrl(requestValue);
}
throw new ArgumentNullException("Required [request] arguments missing for GitHubClient.Oauth.GetGitHubLoginUrl");
}
}
}
| 35.779661 | 178 | 0.64756 | [
"MIT"
] | coldplaying42/iciclecreek.bot | source/Libraries/Iciclecreek.Bot.Builder.Dialogs.Adaptive.GitHub/Actions/Oauth/GetGitHubLoginUrl.cs | 2,111 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Gov.Lclb.Cllb.Interfaces.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Microsoft.Dynamics.CRM.bulkoperationlog
/// </summary>
public partial class MicrosoftDynamicsCRMbulkoperationlog
{
/// <summary>
/// Initializes a new instance of the
/// MicrosoftDynamicsCRMbulkoperationlog class.
/// </summary>
public MicrosoftDynamicsCRMbulkoperationlog()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the
/// MicrosoftDynamicsCRMbulkoperationlog class.
/// </summary>
public MicrosoftDynamicsCRMbulkoperationlog(string additionalinfo = default(string), string _owningteamValue = default(string), string owningbusinessunit = default(string), int? utcconversiontimezonecode = default(int?), System.DateTimeOffset? overriddencreatedon = default(System.DateTimeOffset?), string bulkoperationlogid = default(string), int? errornumber = default(int?), string owninguser = default(string), string _createdobjectidValue = default(string), string _regardingobjectidValue = default(string), string _bulkoperationidValue = default(string), int? importsequencenumber = default(int?), string versionnumber = default(string), string _owneridValue = default(string), string name = default(string), int? timezoneruleversionnumber = default(int?), MicrosoftDynamicsCRMteam owningteam = default(MicrosoftDynamicsCRMteam), IList<MicrosoftDynamicsCRMsyncerror> bulkoperationlogSyncErrors = default(IList<MicrosoftDynamicsCRMsyncerror>), IList<MicrosoftDynamicsCRMteam> bulkoperationlogTeams = default(IList<MicrosoftDynamicsCRMteam>), IList<MicrosoftDynamicsCRMmailboxtrackingfolder> bulkoperationlogMailboxTrackingFolders = default(IList<MicrosoftDynamicsCRMmailboxtrackingfolder>), IList<MicrosoftDynamicsCRMprincipalobjectattributeaccess> bulkoperationlogPrincipalObjectAttributeAccesses = default(IList<MicrosoftDynamicsCRMprincipalobjectattributeaccess>), MicrosoftDynamicsCRMactivitypointer createdobjectidActivitypointer = default(MicrosoftDynamicsCRMactivitypointer), MicrosoftDynamicsCRMcontact createdobjectidContact = default(MicrosoftDynamicsCRMcontact), IList<MicrosoftDynamicsCRMbulkdeletefailure> bulkOperationLogBulkDeleteFailures = default(IList<MicrosoftDynamicsCRMbulkdeletefailure>), MicrosoftDynamicsCRMbulkoperation bulkoperationid = default(MicrosoftDynamicsCRMbulkoperation), MicrosoftDynamicsCRMaccount createdobjectidAccount = default(MicrosoftDynamicsCRMaccount), MicrosoftDynamicsCRMaccount regardingobjectidAccount = default(MicrosoftDynamicsCRMaccount), MicrosoftDynamicsCRMactivitypointer bulkoperationidActivitypointer = default(MicrosoftDynamicsCRMactivitypointer), MicrosoftDynamicsCRMlead createdobjectidLead = default(MicrosoftDynamicsCRMlead), MicrosoftDynamicsCRMopportunity createdobjectidOpportunity = default(MicrosoftDynamicsCRMopportunity), MicrosoftDynamicsCRMcontact regardingobjectidContact = default(MicrosoftDynamicsCRMcontact), IList<MicrosoftDynamicsCRMasyncoperation> bulkOperationLogAsyncOperations = default(IList<MicrosoftDynamicsCRMasyncoperation>), MicrosoftDynamicsCRMlead regardingobjectidLead = default(MicrosoftDynamicsCRMlead))
{
Additionalinfo = additionalinfo;
this._owningteamValue = _owningteamValue;
Owningbusinessunit = owningbusinessunit;
Utcconversiontimezonecode = utcconversiontimezonecode;
Overriddencreatedon = overriddencreatedon;
Bulkoperationlogid = bulkoperationlogid;
Errornumber = errornumber;
Owninguser = owninguser;
this._createdobjectidValue = _createdobjectidValue;
this._regardingobjectidValue = _regardingobjectidValue;
this._bulkoperationidValue = _bulkoperationidValue;
Importsequencenumber = importsequencenumber;
Versionnumber = versionnumber;
this._owneridValue = _owneridValue;
Name = name;
Timezoneruleversionnumber = timezoneruleversionnumber;
Owningteam = owningteam;
BulkoperationlogSyncErrors = bulkoperationlogSyncErrors;
BulkoperationlogTeams = bulkoperationlogTeams;
BulkoperationlogMailboxTrackingFolders = bulkoperationlogMailboxTrackingFolders;
BulkoperationlogPrincipalObjectAttributeAccesses = bulkoperationlogPrincipalObjectAttributeAccesses;
CreatedobjectidActivitypointer = createdobjectidActivitypointer;
CreatedobjectidContact = createdobjectidContact;
BulkOperationLogBulkDeleteFailures = bulkOperationLogBulkDeleteFailures;
Bulkoperationid = bulkoperationid;
CreatedobjectidAccount = createdobjectidAccount;
RegardingobjectidAccount = regardingobjectidAccount;
BulkoperationidActivitypointer = bulkoperationidActivitypointer;
CreatedobjectidLead = createdobjectidLead;
CreatedobjectidOpportunity = createdobjectidOpportunity;
RegardingobjectidContact = regardingobjectidContact;
BulkOperationLogAsyncOperations = bulkOperationLogAsyncOperations;
RegardingobjectidLead = regardingobjectidLead;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "additionalinfo")]
public string Additionalinfo { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_owningteam_value")]
public string _owningteamValue { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "owningbusinessunit")]
public string Owningbusinessunit { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "utcconversiontimezonecode")]
public int? Utcconversiontimezonecode { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "overriddencreatedon")]
public System.DateTimeOffset? Overriddencreatedon { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "bulkoperationlogid")]
public string Bulkoperationlogid { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "errornumber")]
public int? Errornumber { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "owninguser")]
public string Owninguser { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_createdobjectid_value")]
public string _createdobjectidValue { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_regardingobjectid_value")]
public string _regardingobjectidValue { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_bulkoperationid_value")]
public string _bulkoperationidValue { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "importsequencenumber")]
public int? Importsequencenumber { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "versionnumber")]
public string Versionnumber { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_ownerid_value")]
public string _owneridValue { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "timezoneruleversionnumber")]
public int? Timezoneruleversionnumber { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "owningteam")]
public MicrosoftDynamicsCRMteam Owningteam { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "bulkoperationlog_SyncErrors")]
public IList<MicrosoftDynamicsCRMsyncerror> BulkoperationlogSyncErrors { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "bulkoperationlog_Teams")]
public IList<MicrosoftDynamicsCRMteam> BulkoperationlogTeams { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "bulkoperationlog_MailboxTrackingFolders")]
public IList<MicrosoftDynamicsCRMmailboxtrackingfolder> BulkoperationlogMailboxTrackingFolders { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "bulkoperationlog_PrincipalObjectAttributeAccesses")]
public IList<MicrosoftDynamicsCRMprincipalobjectattributeaccess> BulkoperationlogPrincipalObjectAttributeAccesses { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "createdobjectid_activitypointer")]
public MicrosoftDynamicsCRMactivitypointer CreatedobjectidActivitypointer { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "createdobjectid_contact")]
public MicrosoftDynamicsCRMcontact CreatedobjectidContact { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "BulkOperationLog_BulkDeleteFailures")]
public IList<MicrosoftDynamicsCRMbulkdeletefailure> BulkOperationLogBulkDeleteFailures { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "bulkoperationid")]
public MicrosoftDynamicsCRMbulkoperation Bulkoperationid { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "createdobjectid_account")]
public MicrosoftDynamicsCRMaccount CreatedobjectidAccount { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "regardingobjectid_account")]
public MicrosoftDynamicsCRMaccount RegardingobjectidAccount { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "bulkoperationid_activitypointer")]
public MicrosoftDynamicsCRMactivitypointer BulkoperationidActivitypointer { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "createdobjectid_lead")]
public MicrosoftDynamicsCRMlead CreatedobjectidLead { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "createdobjectid_opportunity")]
public MicrosoftDynamicsCRMopportunity CreatedobjectidOpportunity { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "regardingobjectid_contact")]
public MicrosoftDynamicsCRMcontact RegardingobjectidContact { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "BulkOperationLog_AsyncOperations")]
public IList<MicrosoftDynamicsCRMasyncoperation> BulkOperationLogAsyncOperations { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "regardingobjectid_lead")]
public MicrosoftDynamicsCRMlead RegardingobjectidLead { get; set; }
}
}
| 48.731405 | 2,608 | 0.69448 | [
"Apache-2.0"
] | brianorwhatever/jag-lcrb-carla-public | cllc-interfaces/Dynamics-Autorest/Models/MicrosoftDynamicsCRMbulkoperationlog.cs | 11,793 | C# |
using System;
using MongoDB.Bson;
namespace Core.Module.MongoDb.Entities
{
public abstract class MongoDBAbstractEntity : IMongoDBEntity
{
public ObjectId Id { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
public bool isDeleted { get; set; }
}
} | 25.538462 | 64 | 0.650602 | [
"Unlicense"
] | MoHcTpUk/Core | Core.Module.MongoDb/Entities/MongoDBAbstractEntity.cs | 334 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Nsxt.Inputs
{
public sealed class PolicyServiceTagGetArgs : Pulumi.ResourceArgs
{
[Input("scope")]
public Input<string>? Scope { get; set; }
[Input("tag")]
public Input<string>? Tag { get; set; }
public PolicyServiceTagGetArgs()
{
}
}
}
| 24.615385 | 88 | 0.657813 | [
"ECL-2.0",
"Apache-2.0"
] | nvpnathan/pulumi-nsxt | sdk/dotnet/Inputs/PolicyServiceTagGetArgs.cs | 640 | C# |
using System;
namespace FirebaseDotNetCore
{
public interface IFirebaseApp : IDisposable
{
void GoOnline();
void GoOffline();
IFirebase Child(string path);
}
} | 17.909091 | 47 | 0.634518 | [
"Apache-2.0"
] | trevonmckay/FirebaseDotNetCore | Interfaces/IFirebaseApp.cs | 199 | C# |
using System;
namespace PriorityQueue;
/// <summary>
/// 最大-最小堆。
/// </summary>
/// <typeparam name="TKey">最大最小堆中保存的元素。</typeparam>
public class MinMaxPq<TKey> : IMaxPq<TKey>, IMinPq<TKey> where TKey : IComparable<TKey>
{
/// <summary>
/// 最大-最小堆中的数据结点。
/// </summary>
private sealed class MinMaxNode : IComparable<MinMaxNode>
{
/// <summary>
/// 结点的值。
/// </summary>
/// <value>结点的值。</value>
public TKey Key { get; set; }
/// <summary>
/// 结点在当前数组中的下标。
/// </summary>
/// <value>结点在当前数组中的下标。</value>
public readonly int Index;
/// <summary>
/// 指向孪生结点的引用。
/// </summary>
/// <value>指向孪生结点的引用。</value>
public MinMaxNode Pair { get; set; }
/// <summary>
/// 这个类不能在外部实例化。
/// </summary>
private MinMaxNode(TKey key, int index)
{
Key = key;
Index = index;
}
/// <summary>
/// 工厂方法,建立两个孪生的结点。
/// </summary>
/// <param name="key">结点中的元素。</param>
/// <param name="index">索引。</param>
/// <param name="minNode">准备放到最小堆中的结点。</param>
/// <param name="maxNode">准备放到最大堆中的结点。</param>
public static void GetNodes(TKey key, int index, out MinMaxNode minNode, out MinMaxNode maxNode)
{
minNode = new MinMaxNode(key, index);
maxNode = new MinMaxNode(key, index);
minNode.Pair = maxNode;
maxNode.Pair = minNode;
}
/// <summary>
/// 比较两个元素的大小。
/// </summary>
/// <param name="other">需要与之比较的另一个元素。</param>
/// <returns>如果 <paramref name="other"/> 比较小则返回正数,否则返回负数。</returns>
public int CompareTo(MinMaxNode other)
{
return Key.CompareTo(other.Key);
}
}
/// <summary>
/// 对 <see cref="MinMaxNode"/> 偏特化的最大堆。
/// </summary>
private sealed class MaxPq : MaxPq<MinMaxNode>
{
/// <summary>
/// 建立指定大小的最大堆。
/// </summary>
/// <param name="capacity">最大堆的容量。</param>
public MaxPq(int capacity) : base(capacity) { }
/// <summary>
/// 利用指定的结点建立最大堆。
/// </summary>
/// <param name="nodes">用于建立最大堆的结点。</param>
public MaxPq(MinMaxNode[] nodes) : base(nodes) { }
/// <summary>
/// 重写的 Exch 方法,只交换元素和指针。
/// </summary>
/// <param name="i">要交换的下标。</param>
/// <param name="j">要交换的下标。</param>
protected override void Exch(int i, int j)
{
Pq[i].Pair.Pair = Pq[j];
Pq[j].Pair.Pair = Pq[i];
var swapNode = Pq[i].Pair;
var swapKey = Pq[i].Key;
Pq[i].Key = Pq[j].Key;
Pq[i].Pair = Pq[j].Pair;
Pq[j].Key = swapKey;
Pq[j].Pair = swapNode;
}
}
/// <summary>
/// 对 <see cref="MinMaxNode"/> 偏特化的最小堆。
/// </summary>
private sealed class MinPq : MinPq<MinMaxNode>
{
/// <summary>
/// 建立指定大小的最小堆。
/// </summary>
/// <param name="capacity">最小堆的容量。</param>
public MinPq(int capacity) : base(capacity) { }
/// <summary>
/// 利用指定的结点建立最小堆。
/// </summary>
/// <param name="nodes">用于建立最小堆的结点。</param>
public MinPq(MinMaxNode[] nodes) : base(nodes) { }
/// <summary>
/// 重写的 Exch 方法,只交换元素和指针。
/// </summary>
/// <param name="i">要交换的下标。</param>
/// <param name="j">要交换的下标。</param>
protected override void Exch(int i, int j)
{
Pq[i].Pair.Pair = Pq[j];
Pq[j].Pair.Pair = Pq[i];
var swapNode = Pq[i].Pair;
var swapKey = Pq[i].Key;
Pq[i].Key = Pq[j].Key;
Pq[i].Pair = Pq[j].Pair;
Pq[j].Key = swapKey;
Pq[j].Pair = swapNode;
}
}
/// <summary>
/// 最小堆。
/// </summary>
/// <value>最小堆。</value>
private readonly MinPq _minPq;
/// <summary>
/// 最大堆。
/// </summary>
/// <value>最大堆。</value>
private readonly MaxPq _maxPq;
/// <summary>
/// 堆的大小。
/// </summary>
/// <value>堆的大小。</value>
private int _n;
/// <summary>
/// 构造一个最大-最小堆。
/// </summary>
public MinMaxPq() : this(1) { }
/// <summary>
/// 构造一个指定容量的最大-最小堆。
/// </summary>
/// <param name="capacity">堆的大小。</param>
public MinMaxPq(int capacity)
{
_minPq = new MinPq(capacity);
_maxPq = new MaxPq(capacity);
_n = 0;
}
/// <summary>
/// 根据已有元素建立一个最大-最小堆。(O(n))
/// </summary>
/// <param name="keys">需要建堆的元素。</param>
public MinMaxPq(TKey[] keys)
{
_n = keys.Length;
var minNodes = new MinMaxNode[keys.Length];
var maxNodes = new MinMaxNode[keys.Length];
for (var i = 0; i < _n; i++)
{
MinMaxNode.GetNodes(keys[i], i + 1, out minNodes[i], out maxNodes[i]);
}
_minPq = new MinPq(minNodes);
_maxPq = new MaxPq(maxNodes);
}
/// <summary>
/// 删除并返回最大值。
/// </summary>
/// <returns>最大元素。</returns>
public TKey DelMax()
{
// ⬇ 不可以交换操作顺序 ⬇
_minPq.Remove(_maxPq.Max().Pair.Index);
var key = _maxPq.Max().Key;
_maxPq.DelMax();
// ⬆ 不可以交换操作顺序 ⬆
_n--;
return key;
}
/// <summary>
/// 删除并返回最小值。
/// </summary>
/// <returns>最小值。</returns>
public TKey DelMin()
{
// ⬇ 不可以交换操作顺序 ⬇
_maxPq.Remove(_minPq.Min().Pair.Index);
var key = _minPq.Min().Key;
_minPq.DelMin();
// ⬆ 不可以交换操作顺序 ⬆
_n--;
return key;
}
/// <summary>
/// 插入一个新的值。
/// </summary>
/// <param name="v">待插入的新值。</param>
public void Insert(TKey v)
{
_n++;
MinMaxNode.GetNodes(v, _n, out var minNode, out var maxNode);
_maxPq.Insert(maxNode);
_minPq.Insert(minNode);
}
/// <summary>
/// 判断堆是否为空。
/// </summary>
/// <returns>若堆为空则返回 <c>true</c>,否则返回 <c>false</c>。</returns>
public bool IsEmpty() => _n == 0;
/// <summary>
/// 获得堆中的最大值。
/// </summary>
/// <returns>堆的最大值。</returns>
public TKey Max() => _maxPq.Max().Key;
/// <summary>
/// 获得堆中的最小值。
/// </summary>
/// <returns>堆的最小值。</returns>
public TKey Min() => _minPq.Min().Key;
/// <summary>
/// 获得堆的大小。
/// </summary>
/// <returns>堆的大小。</returns>
public int Size() => _n;
} | 25.74902 | 104 | 0.48675 | [
"MIT"
] | Higurashi-kagome/Algorithms-4th-Edition-in-Csharp | 2 Sorting/2.4/PriorityQueue/MinMaxPQ.cs | 7,722 | C# |
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Repository.Pattern.UnitOfWork;
using Repository.Pattern.Infrastructure;
using Z.EntityFramework.Plus;
using TrackableEntities;
using WebApp.Models;
using WebApp.Services;
using WebApp.Repositories;
using Microsoft.Ajax.Utilities;
namespace WebApp.Controllers
{
/// <summary>
/// File: AttachmentsController.cs
/// Purpose:主数据管理/附件管理
/// Created Date: 2020/5/20 20:49:55
/// Author: neo.zhu
/// Tools: SmartCode MVC5 Scaffolder for Visual Studio 2017
/// TODO: Registers the type mappings with the Unity container(Mvc.UnityConfig.cs)
/// <![CDATA[
/// container.RegisterType<IRepositoryAsync<Attachment>, Repository<Attachment>>();
/// container.RegisterType<IAttachmentService, AttachmentService>();
/// ]]>
/// Copyright (c) 2012-2018 All Rights Reserved
/// </summary>
[Authorize]
[RoutePrefix("Attachments")]
public class AttachmentsController : Controller
{
private readonly IAttachmentService attachmentService;
private readonly IUnitOfWorkAsync unitOfWork;
private readonly NLog.ILogger logger;
public AttachmentsController (
IAttachmentService attachmentService,
IUnitOfWorkAsync unitOfWork,
NLog.ILogger logger
)
{
this.attachmentService = attachmentService;
this.unitOfWork = unitOfWork;
this.logger = logger;
}
//GET: Attachments/Index
//[OutputCache(Duration = 60, VaryByParam = "none")]
[Route("Index", Name = "附件管理", Order = 1)]
public ActionResult Index() => this.View();
//接收上传文件
public async Task<ActionResult> Upload() {
var file = this.Request.Files[0];
var user = ViewBag.GivenName;
try
{
var tags = this.Request.Form["tags"];
var name = this.Request.Form["name"];
var folder = this.Server.MapPath("~/UploadFiles");
var relpath = "~/UploadFiles";
await this.attachmentService.SaveFile(file, tags, folder, relpath, name, user);
await this.unitOfWork.SaveChangesAsync();
return Content($"{file.FileName}:上传成功", "text/plain");
}
catch (Exception e) {
throw e;
}
}
//重命名
public async Task<JsonResult> Rename(string fileid, string newfilename) {
try
{
if (!string.IsNullOrEmpty(newfilename))
{
await this.attachmentService.Rename(fileid, newfilename);
await this.unitOfWork.SaveChangesAsync();
}
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
return Json(new { success = false,err=e.GetBaseException().Message }, JsonRequestBehavior.AllowGet);
}
}
//Get :Attachments/GetData
//For Index View datagrid datasource url
[HttpGet]
//[OutputCache(Duration = 10, VaryByParam = "*")]
public async Task<JsonResult> GetData(int page = 1, int rows = 10, string sort = "Id", string order = "asc", string filterRules = "")
{
var filters = JsonConvert.DeserializeObject<IEnumerable<filterRule>>(filterRules);
var pagerows = (await this.attachmentService
.Query(new AttachmentQuery().Withfilter(filters))
.OrderBy(n=>n.OrderBy(sort,order))
.SelectPageAsync(page, rows, out var totalCount))
.Select( n => new {
Id = n.Id,
FileName = n.FileName,
FileId = n.FileId,
Ext = n.Ext,
FilePath = n.FilePath,
n.RelativePath,
n.Size,
n.Tags,
RefKey = n.RefKey,
Owner = n.Owner,
Upload = n.Upload.ToString("yyyy-MM-dd HH:mm:ss")
}).ToList();
var pagelist = new { total = totalCount, rows = pagerows };
return Json(pagelist, JsonRequestBehavior.AllowGet);
}
//easyui datagrid post acceptChanges
[HttpPost]
public async Task<JsonResult> SaveData(Attachment[] attachments)
{
if (attachments == null)
{
throw new ArgumentNullException(nameof(attachments));
}
if (ModelState.IsValid)
{
try{
foreach (var item in attachments)
{
this.attachmentService.ApplyChanges(item);
}
var result = await this.unitOfWork.SaveChangesAsync();
return Json(new {success=true,result}, JsonRequestBehavior.AllowGet);
}
catch (System.Data.Entity.Validation.DbEntityValidationException e)
{
var errormessage = string.Join(",", e.EntityValidationErrors.Select(x => x.ValidationErrors.FirstOrDefault()?.PropertyName + ":" + x.ValidationErrors.FirstOrDefault()?.ErrorMessage));
return Json(new { success = false, err = errormessage }, JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
return Json(new { success = false, err = e.GetBaseException().Message }, JsonRequestBehavior.AllowGet);
}
}
else
{
var modelStateErrors = string.Join(",", ModelState.Keys.SelectMany(key => ModelState[key].Errors.Select(n => n.ErrorMessage)));
return Json(new { success = false, err = modelStateErrors }, JsonRequestBehavior.AllowGet);
}
}
//GET: Attachments/Details/:id
public ActionResult Details(int id)
{
var attachment = this.attachmentService.Find(id);
if (attachment == null)
{
return HttpNotFound();
}
return View(attachment);
}
//GET: Attachments/GetItem/:id
[HttpGet]
public async Task<JsonResult> GetItem(int id) {
var attachment = await this.attachmentService.FindAsync(id);
return Json(attachment,JsonRequestBehavior.AllowGet);
}
//GET: Attachments/Create
public ActionResult Create()
{
var attachment = new Attachment();
//set default value
return View(attachment);
}
//POST: Attachments/Create
//To protect from overposting attacks, please enable the specific properties you want to bind to, for more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(Attachment attachment)
{
if (attachment == null)
{
throw new ArgumentNullException(nameof(attachment));
}
if (ModelState.IsValid)
{
try{
this.attachmentService.Insert(attachment);
var result = await this.unitOfWork.SaveChangesAsync();
return Json(new { success = true,result }, JsonRequestBehavior.AllowGet);
}
catch (System.Data.Entity.Validation.DbEntityValidationException e)
{
var errormessage = string.Join(",", e.EntityValidationErrors.Select(x => x.ValidationErrors.FirstOrDefault()?.PropertyName + ":" + x.ValidationErrors.FirstOrDefault()?.ErrorMessage));
return Json(new { success = false, err = errormessage }, JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
return Json(new { success = false, err = e.GetBaseException().Message }, JsonRequestBehavior.AllowGet);
}
//DisplaySuccessMessage("Has update a attachment record");
}
else {
var modelStateErrors =string.Join(",", this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors.Select(n=>n.ErrorMessage)));
return Json(new { success = false, err = modelStateErrors }, JsonRequestBehavior.AllowGet);
//DisplayErrorMessage(modelStateErrors);
}
//return View(attachment);
}
//新增对象初始化
[HttpGet]
public async Task<JsonResult> NewItem() {
var attachment = await Task.Run(() => {
return new Attachment();
});
return Json(attachment, JsonRequestBehavior.AllowGet);
}
//GET: Attachments/Edit/:id
public ActionResult Edit(int id)
{
var attachment = this.attachmentService.Find(id);
if (attachment == null)
{
return HttpNotFound();
}
return View(attachment);
}
//POST: Attachments/Edit/:id
//To protect from overposting attacks, please enable the specific properties you want to bind to, for more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(Attachment attachment)
{
if (attachment == null)
{
throw new ArgumentNullException(nameof(attachment));
}
if (ModelState.IsValid)
{
attachment.TrackingState = TrackingState.Modified;
try{
this.attachmentService.Update(attachment);
var result = await this.unitOfWork.SaveChangesAsync();
return Json(new { success = true,result = result }, JsonRequestBehavior.AllowGet);
}
catch (System.Data.Entity.Validation.DbEntityValidationException e)
{
var errormessage = string.Join(",", e.EntityValidationErrors.Select(x => x.ValidationErrors.FirstOrDefault()?.PropertyName + ":" + x.ValidationErrors.FirstOrDefault()?.ErrorMessage));
return Json(new { success = false, err = errormessage }, JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
return Json(new { success = false, err = e.GetBaseException().Message }, JsonRequestBehavior.AllowGet);
}
//DisplaySuccessMessage("Has update a Attachment record");
//return RedirectToAction("Index");
}
else {
var modelStateErrors =string.Join(",", this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors.Select(n=>n.ErrorMessage)));
return Json(new { success = false, err = modelStateErrors }, JsonRequestBehavior.AllowGet);
//DisplayErrorMessage(modelStateErrors);
}
//return View(attachment);
}
//删除当前记录
//GET: Attachments/Delete/:id
[HttpGet]
public async Task<ActionResult> Delete(int id)
{
try{
await this.attachmentService.Queryable().Where(x => x.Id == id).DeleteAsync();
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
catch (System.Data.Entity.Validation.DbEntityValidationException e)
{
var errormessage = string.Join(",", e.EntityValidationErrors.Select(x => x.ValidationErrors.FirstOrDefault()?.PropertyName + ":" + x.ValidationErrors.FirstOrDefault()?.ErrorMessage));
return Json(new { success = false, err = errormessage }, JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
return Json(new { success = false, err = e.GetBaseException().Message }, JsonRequestBehavior.AllowGet);
}
}
//删除选中的记录
[HttpPost]
public async Task<JsonResult> DeleteChecked(int[] id) {
if (id == null)
{
throw new ArgumentNullException(nameof(id));
}
try{
await this.attachmentService.Delete(id);
await this.unitOfWork.SaveChangesAsync();
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
catch (System.Data.Entity.Validation.DbEntityValidationException e)
{
var errormessage = string.Join(",", e.EntityValidationErrors.Select(x => x.ValidationErrors.FirstOrDefault()?.PropertyName + ":" + x.ValidationErrors.FirstOrDefault()?.ErrorMessage));
return Json(new { success = false, err = errormessage }, JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
return Json(new { success = false, err = e.GetBaseException().Message }, JsonRequestBehavior.AllowGet);
}
}
//导出Excel
[HttpPost]
public async Task<ActionResult> ExportExcel( string filterRules = "",string sort = "Id", string order = "asc")
{
var fileName = "attachments_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
var stream = await this.attachmentService.ExportExcelAsync(filterRules,sort, order );
return File(stream, "application/vnd.ms-excel", fileName);
}
private void DisplaySuccessMessage(string msgText) => TempData["SuccessMessage"] = msgText;
private void DisplayErrorMessage(string msgText) => TempData["ErrorMessage"] = msgText;
}
}
| 38.770393 | 203 | 0.621601 | [
"Apache-2.0"
] | neozhu/bms | src/BMS.Solution/Web/WebApp/Controllers/AttachmentsController.cs | 12,931 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.