content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
using System;
namespace sat_dal_mock
{
public class Class1
{
}
}
| 8.777778 | 23 | 0.620253 | [
"MIT"
] | WorthyD/steam-achievement-tracker | tests/sat-dal-mock/Class1.cs | 81 | C# |
var date = new DateTime(2000, 6, 1);
date.ShouldBe(new DateTime(2000, 6, 1, 1, 0, 1), TimeSpan.FromHours(1)); | 54.5 | 72 | 0.678899 | [
"BSD-3-Clause"
] | Lisa3x3x3/shouldly | src/DocumentationExamples/CodeExamples/ShouldBeExamples.DateTime.codeSample.approved.cs | 109 | C# |
using System;
namespace AdventOfCode.Y2021;
class SplashScreenImpl : SplashScreen {
public void Show() {
var color = Console.ForegroundColor;
Write(0xcc00, false, " ▄█▄ ▄▄█ ▄ ▄ ▄▄▄ ▄▄ ▄█▄ ▄▄▄ ▄█ ▄▄ ▄▄▄ ▄▄█ ▄▄▄\n █▄█ █ █ █ █ █▄█ █ █ █ █ █ █▄ ");
Write(0xcc00, false, " █ █ █ █ █ █▄█\n █ █ █▄█ ▀▄▀ █▄▄ █ █ █▄ █▄█ █ █▄ █▄█ █▄█ █▄▄ // 2021\n \n ");
Write(0xcc00, false, " ");
Write(0x666666, false, "~~~~~~~~~~~~~~~~~~~");
Write(0xc8ff, false, "~");
Write(0x666666, false, "~~");
Write(0xc8ff, false, "~");
Write(0x666666, false, "~");
Write(0xc8ff, false, "~");
Write(0x666666, false, "~");
Write(0xc8ff, false, "~~");
Write(0x666666, false, "~");
Write(0xc8ff, false, "~~~~~~~~~~~~~~~~~~~~ ");
Write(0xcccccc, false, " 1 ");
Write(0xffff66, false, "**\n ");
Write(0x666666, false, "'... . . . . .. ' . . .. . ");
Write(0xa47a4d, false, "..'''' ");
Write(0xcccccc, false, " 2 ");
Write(0xffff66, false, "**\n ");
Write(0x666666, false, " . . . . .. . ' ");
Write(0xa47a4d, false, ": ");
Write(0xcccccc, false, " 3 ");
Write(0xffff66, false, "**\n ");
Write(0x666666, false, ". ' ' . .'... .' ....' ");
Write(0xcccccc, false, " 4 ");
Write(0xffff66, false, "*");
Write(0x666666, false, "*\n . ' .~ ' . . ..|\\..'' ");
Write(0xcccccc, false, " 5 ");
Write(0xffff66, false, "*");
Write(0x666666, false, "*\n . . : ");
Write(0xcccccc, false, " 6 ");
Write(0xffff66, false, "*");
Write(0x666666, false, "*\n . . . . .~ . . . :' ");
Write(0xcccccc, false, " 7 ");
Write(0xffff66, false, "*");
Write(0x666666, false, "*\n . ' ' . '. '''''..... .... ");
Write(0xcccccc, false, " 8 ");
Write(0xffff66, false, "*");
Write(0x666666, false, "*\n .. . . ~ :'.. .. '' ': ");
Write(0xcccccc, false, " 9 ");
Write(0xffff66, false, "*");
Write(0x666666, false, "*\n . . .. : '' ''''.. '. ");
Write(0xcccccc, false, "10 ");
Write(0xffff66, false, "*");
Write(0x666666, false, "*\n . . . : '..'. : ");
Write(0xcccccc, false, "11 ");
Write(0xffff66, false, "*");
Write(0x666666, false, "*\n . .. .. : :'''.. ..' : ");
Write(0xcccccc, false, "12 ");
Write(0xffff66, false, "*");
Write(0x666666, false, "*\n . .' ..'' ''' ...: ");
Write(0xcccccc, false, "13 ");
Write(0xffff66, false, "*");
Write(0x666666, false, "*\n . . : ...'' ..': ....' ");
Write(0xcccccc, false, "14 ");
Write(0xffff66, false, "*");
Write(0x666666, false, "*\n . .. . :' ...''' ''' ");
Write(0xcccccc, false, "15 ");
Write(0xffff66, false, "*");
Write(0x666666, false, "*\n '.'. . '. :'. ....' ");
Write(0xcccccc, false, "16 ");
Write(0xffff66, false, "*");
Write(0x666666, false, "*\n : . : ' ");
Write(0xcccccc, false, "17 ");
Write(0xffff66, false, "*");
Write(0x666666, false, "*\n ");
Write(0x333333, false, " : ..' ");
Write(0x666666, false, "18\n 19\n ");
Write(0x666666, false, " 20\n 21\n ");
Write(0x666666, false, " 22\n ");
Write(0x666666, false, " 23\n 24\n ");
Write(0x666666, false, " 25\n \n");
Console.ForegroundColor = color;
Console.WriteLine();
}
private static void Write(int rgb, bool bold, string text){
Console.Write($"\u001b[38;2;{(rgb>>16)&255};{(rgb>>8)&255};{rgb&255}{(bold ? ";1" : "")}m{text}");
}
}
| 56.521739 | 141 | 0.309423 | [
"MIT"
] | cotenoni/adventofcode | 2021/SplashScreen.cs | 5,374 | C# |
namespace OAuthServer.IdentityServer.Quickstart
{
public class JsonClaim
{
public string Type { get; set; }
public string Value { get; set; }
}
} | 21.75 | 48 | 0.626437 | [
"MIT"
] | yetanotherchris/OAuthServerDocker | OAuthServer.IdentityServer/src/Quickstart/JsonClaim.cs | 176 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PageLayout.Core
{
/// <summary>
/// Represents a double card. It consists of two cards or, in other words, of
/// two double pages. It contains four single pages. Two on the front and
/// two on the back.
/// </summary>
class DoubleCard
{
DoublePage topPage;
DoublePage bottomPage;
private int index;
public DoubleCard(int index, int allPageNumber)
{
this.index = index;
topPage = new DoublePage(index * 2, allPageNumber);
bottomPage = new DoublePage(index * 2 + 1, allPageNumber);
}
public Page FirstLeftPage
{
get { return bottomPage.LeftPage; }
}
public Page SecondLeftPage
{
get { return topPage.LeftPage; }
}
public Page FirstRightPage
{
get { return bottomPage.RightPage; }
}
public Page SecondRightPage
{
get { return topPage.RightPage; }
}
internal void AddTopPageNumbers(List<int> list)
{
list.Add(SecondLeftPage.PageNumber);
list.Add(SecondRightPage.PageNumber);
}
internal void AddBottomPageNumbers(List<int> list)
{
list.Add(FirstRightPage.PageNumber);
list.Add(FirstLeftPage.PageNumber);
}
}
}
| 24.881356 | 81 | 0.572888 | [
"MIT"
] | jns300/PageLayout | PageLayout/Core/DoubleCard.cs | 1,470 | C# |
using System;
using System.Collections.Generic;
using OalSoft.NET.OpenALSharp;
namespace OalSoft.NET
{
/// <summary>
/// Managed wrapper for an OpenAL Context. A context is attached to a single device. It owns a collection of
/// sources that can be played on the device.
/// </summary>
public sealed class AlContext : IDisposable
{
internal IntPtr Handle { get; private set; }
private readonly List<AlSource> _sources;
/// <summary>
/// Get this context's <see cref="AlDevice"/>.
/// </summary>
public AlDevice Device { get; }
internal AlContext(AlDevice device, IntPtr handle)
{
Device = device;
Handle = handle;
_sources = new List<AlSource>();
}
/// <summary>
/// Create an <see cref="AlStreamingSource"/> for this context.
/// </summary>
public AlStreamingSource CreateStreamingSource()
{
ALC10.alcMakeContextCurrent(Handle);
AL10.alGenSources(1, out var name);
AlHelper.AlAlwaysCheckError("Call to alGenSources failed.");
var source = new AlStreamingSource(name, this);
_sources.Add(source);
return source;
}
/// <summary>
/// Create an <see cref="AlStaticSource"/> for this context.
/// </summary>
public AlStaticSource CreateStaticSource()
{
ALC10.alcMakeContextCurrent(Handle);
AL10.alGenSources(1, out var name);
AlHelper.AlAlwaysCheckError("Call to alGenSources failed.");
var source = new AlStaticSource(name, this);
_sources.Add(source);
return source;
}
internal void DeleteSource(AlSource source)
{
if (!_sources.Remove(source))
throw new InvalidOperationException("Context does not own the given source.");
AL10.alDeleteSources(1, ref source.Name);
AlHelper.AlCheckError("Call to alDeleteSources failed.");
_sources.Remove(source);
}
internal void MakeCurrent()
{
ALC10.alcMakeContextCurrent(Handle);
}
internal void Destroy()
{
// notify all sources first
foreach (var source in _sources)
source.OnContextDestroyed();
ALC10.alcDestroyContext(Handle);
}
private void ReleaseUnmanagedResources()
{
Device.DestroyContext(this);
}
public void Dispose()
{
ReleaseUnmanagedResources();
GC.SuppressFinalize(this);
}
~AlContext()
{
ReleaseUnmanagedResources();
}
}
}
| 29.935484 | 112 | 0.56717 | [
"MIT"
] | Jjagg/OalSoft.NET | AlContext.cs | 2,786 | C# |
using System;
using System.Threading.Tasks;
using Coravel.Mailer.Mail.Interfaces;
using Microsoft.AspNetCore.Mvc;
using TestMvcApp.Mailables;
using TestMvcApp.Models;
namespace TestMvcApp.Controllers
{
[Route("Mail")]
public class MailController : Controller
{
private IMailer _mailer;
public MailController(IMailer mailer)
{
this._mailer = mailer;
}
[Route("WithHtml")]
public async Task<IActionResult> WithHtml()
{
UserModel user = new UserModel()
{
Email = "FromUserModel@test.com",
Name = "Coravel Test Person"
};
await this._mailer.SendAsync(new WelcomeUserMailable(user));
return Ok();
}
[Route("RenderHtml")]
public async Task<IActionResult> RenderHtml()
{
UserModel user = new UserModel()
{
Email = "FromUserModel@test.com",
Name = "Coravel Test Person"
};
string message = await this._mailer.RenderAsync(new WelcomeUserMailable(user));
return Content(message, "text/html");
}
[Route("WithView")]
public async Task<IActionResult> WithView()
{
UserModel user = new UserModel()
{
Email = "FromUserModel@test.com",
Name = "Coravel Test Person"
};
await this._mailer.SendAsync(new NewUserViewMail(user));
return Ok();
}
[Route("RenderView")]
public async Task<IActionResult> RenderView()
{
UserModel user = new UserModel()
{
Email = "FromUserModel@test.com",
Name = "Coravel Test Person"
};
string message = await this._mailer.RenderAsync(new NewUserViewMail(user));
return Content(message, "text/html");
}
}
} | 24.85 | 91 | 0.538732 | [
"MIT"
] | Blinke/coravel | Src/IntegrationTests/TestMvcApp/Controllers/MailController.cs | 1,988 | C# |
using System;
using Newtonsoft.Json;
using StoryLine.Rest.Expectations.Services.Expectations;
using StoryLine.Rest.Expectations.Services.Json;
namespace StoryLine.Rest.Expectations.Builders
{
public class JsonBodyExpectationBuilder
{
private readonly HttpResponse _builder;
public JsonBodyExpectationBuilder(HttpResponse builder)
{
_builder = builder ?? throw new ArgumentNullException(nameof(builder));
}
public HttpResponse MatchesObject(object content, params string[] propertiesToIgnore)
{
return MatchesObject(content, Config.DefaultJsonSerializerSettings, propertiesToIgnore);
}
public HttpResponse MatchesObject(object content, JsonSerializerSettings settings, params string[] propertiesToIgnore)
{
if (content == null)
throw new ArgumentNullException(nameof(content));
if (settings == null)
throw new ArgumentNullException(nameof(settings));
return Matches(JsonConvert.SerializeObject(content, settings), propertiesToIgnore);
}
public HttpResponse Matches(string expectedContent, params string[] propertiesToIgnore)
{
if (propertiesToIgnore == null)
throw new ArgumentNullException(nameof(propertiesToIgnore));
if (string.IsNullOrEmpty(expectedContent))
throw new ArgumentException("Value cannot be null or empty.", nameof(expectedContent));
var config = new JsonVerifierSettings
{
IgnoredProperties = propertiesToIgnore
};
_builder.RequestExpectation(
new BodyContentExpectation(
expectedContent,
Config.JsonVerifierFactory(config)));
return _builder;
}
public JsonResourceBodyExpectationBuilder Matches()
{
return new JsonResourceBodyExpectationBuilder(_builder);
}
}
} | 35.45614 | 126 | 0.653142 | [
"BSD-3-Clause"
] | DiamondDragon/StoryLine.Rest | StoryLine.Rest/Expectations/Builders/JsonBodyExpectationBuilder.cs | 2,021 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using App.Metrics;
using App.Metrics.Meter;
using MetricsCollector.Abstractions;
using IMeter = MetricsCollector.Abstractions.IMeter;
namespace CodeGeneration.Roslyn.MetricsCollector.AppMetrics
{
public abstract class MetricsCollectorBase
{
private readonly IMetrics _metrics;
private readonly Dictionary<Type, IGrouping<Type, IMetricsExceptionRenderer>> _metricsExceptionRenderers;
protected MetricsCollectorBase(IMetrics metrics, IEnumerable<IMetricsExceptionRenderer> exceptionRenderers)
{
_metrics = metrics;
_metricsExceptionRenderers = exceptionRenderers.GroupBy(_=>_.ExceptionType).ToDictionary(_=>_.Key);
}
// private static MetricTags GetMetricTags(IInvocation invocation)
// {
// var tagKeys = invocation.Method.GetParameters().Select(parameter => parameter.Name).ToArray();
// var tagValues = invocation.Arguments.Select(argument => argument?.ToString() ?? "n/a").ToArray();
// return new MetricTags(tagKeys, tagValues);
// }
protected string RenderException(Exception exception)
{
if (_metricsExceptionRenderers.TryGetValue(exception.GetType(), out var renderers) && renderers.Any())
{
var sb = new StringBuilder(exception.GetType().Name); //TODO Use Spans
foreach (var renderer in renderers)
{
sb.Append("|" + renderer.Render(exception));
}
}
return exception.GetType().Name;
}
protected IMeter CreateMeter(string contextName, string name, bool suppressExportMetrics, MetricTags tags)
{
var meterOptions = new MeterOptions
{
Context = contextName,
Name = name,
ReportSetItems = !suppressExportMetrics
};
return new Meter(_metrics.Provider.Meter, _metrics.Measure.Meter, meterOptions, tags);
}
}
} | 33.388889 | 109 | 0.75208 | [
"MIT"
] | as-ivanov/AppBlocks | src/CodeGeneration.Roslyn.MetricsCollector.AppMetrics/MetricsCollectorBase.cs | 1,803 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Reflection.PortableExecutable;
namespace Microsoft.CodeAnalysis.BinaryParsers.PortableExecutable
{
public abstract class ImageHeader
{
internal SafePointer m_pHeader;
public ImageHeader(PEHeader parentHeader, SafePointer sp)
{
ParentHeader = parentHeader;
m_pHeader = sp;
}
public PEHeader ParentHeader { get; private set; }
public abstract ImageHeader Create(PEHeader parentHeader, SafePointer sp);
public object GetField(int n)
{
object res;
ImageFieldData fi = GetFieldInfo(n);
int count = fi.Count;
int offset = GetFieldOffset(n); ;
Object o;
int len;
SafePointer sp = m_pHeader + offset;
if (fi.VarLen)
{
// this assumes we can not have varlen arrays of headers
count = GetFieldSize(n) / fi.GetTypeLen();
}
if (count == 1)
return sp.SafePointerToType(fi);
// if a negative count is provided we tread it as an offset of
// the field where to find the real count
if (count < 0)
count = Convert.ToInt32(GetField(n + count));
res = new object[count];
for (int i = 0; i < count; i++)
{
o = sp.SafePointerToType(fi);
((object[])res)[i] = o;
len = (o is ImageHeader)
? ((ImageHeader)o).Size
: fi.GetTypeLen();
sp = sp + len;
}
return res;
}
public object GetField(object o)
{
return GetField((int)o);
}
public ImageFieldData GetFieldInfo(int n)
{
return GetFields()[n];
}
public int GetFieldSize(int n)
{
ImageFieldData fi = GetFieldInfo(n);
int count = fi.Count;
int padding = fi.PadTo;
int size;
int len;
if (fi.VarLen)
{
SafePointer field_start = m_pHeader + GetFieldOffset(n);
SafePointer field_end = field_start;
while ((byte)field_end != fi.TrailingByte) field_end++;
// if we have a VarLen and a PadTo specified we will make sure
// we only skip up to PadTo trailing bytes
padding = (padding != 0)
? padding - (field_end.Address - m_pHeader.Address) % padding
: -1;
while (((byte)field_end == fi.TrailingByte) && (padding-- != 0))
{
field_end++;
}
return field_end - field_start;
}
if (fi.Type == Type.HEADER)
{
object o = GetField(n);
len = (o is Array)
? ((ImageHeader)((object[])o)[0]).Size
: ((ImageHeader)o).Size;
}
else
len = fi.GetTypeLen();
if (count == 1)
return len;
// if a negative count is provided we tread it as an offset of
// the field where to find the real count
if (count < 0)
count = Convert.ToInt32(GetField(n + count));
size = len * count;
// We don't pad is the size is already a multiple of padding
if ((padding != 0) && (size % padding != 0))
size += padding - (size % padding);
return size;
}
public int GetFieldOffset(int n)
{
ImageFieldData fi = GetFieldInfo(n);
int offset = fi.Offset;
if (offset >= 0) return offset;
return GetFieldOffset(n + offset) + GetFieldSize(n + offset);
}
protected abstract ImageFieldData[] GetFields();
public int NumberOfFields
{
get { return GetFields().Length; }
}
public static int ShiftOffset(ImageFieldData[] fields, int n)
{
if ((fields[n].Offset < 0) || (fields[n].Count < 0)) return -1;
return fields[n].Offset + fields[n].Count * fields[n].GetTypeLen();
}
public int Size
{
get
{
int n = GetFields().Length - 1;
return GetFieldOffset(n) + GetFieldSize(n);
}
}
}
}
| 29.48125 | 101 | 0.48781 | [
"MIT"
] | C3rooks/binskim | src/BinaryParsers/PEBinary/PortableExecutable/ImageHeader.cs | 4,719 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WishHeroes.ViewModels;
namespace WishHeroes.Repository.Interfaces
{
public interface IProfile
{
}
}
| 15.8 | 42 | 0.767932 | [
"MIT"
] | TechnicallyWilliams/CoderCamps | WishHeroes/WishHeroes.Repository/Interfaces/IProfile.cs | 239 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.DocumentDB.V20210315.Outputs
{
/// <summary>
/// Cosmos DB Cassandra table partition key
/// </summary>
[OutputType]
public sealed class CassandraPartitionKeyResponse
{
/// <summary>
/// Name of the Cosmos DB Cassandra table partition key
/// </summary>
public readonly string? Name;
[OutputConstructor]
private CassandraPartitionKeyResponse(string? name)
{
Name = name;
}
}
}
| 26.16129 | 81 | 0.657213 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/DocumentDB/V20210315/Outputs/CassandraPartitionKeyResponse.cs | 811 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Query.Expressions;
namespace Microsoft.EntityFrameworkCore.Query.ExpressionTranslators.Internal
{
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public class SqlServerStringReplaceTranslator : IMethodCallTranslator
{
private static readonly MethodInfo _methodInfo = typeof(string).GetTypeInfo()
.GetDeclaredMethods(nameof(string.Replace))
.Single(m => m.GetParameters()[0].ParameterType == typeof(string));
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public virtual Expression Translate(MethodCallExpression methodCallExpression)
=> methodCallExpression.Method == _methodInfo
? new SqlFunctionExpression(
"REPLACE",
methodCallExpression.Type,
new[] { methodCallExpression.Object }.Concat(methodCallExpression.Arguments))
: null;
}
}
| 45.735294 | 111 | 0.681029 | [
"Apache-2.0"
] | hqywork/EntityFramework | src/Microsoft.EntityFrameworkCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerStringReplaceTranslator.cs | 1,555 | C# |
// ReSharper disable InheritdocConsiderUsage
namespace SqlExecuteTests
{
using System;
using System.Collections;
using System.Diagnostics;
using Firefly.SqlCmdParser;
using Firefly.SqlCmdParser.Client;
/// <summary>
/// Concrete argument class for these tests
/// </summary>
/// <seealso cref="Firefly.SqlCmdParser.Client.ISqlExecuteArguments" />
internal class TestArguments : ISqlExecuteArguments
{
private string[] inputFile;
/// <summary>
/// Gets or sets a value indicating whether [abort on error].
/// </summary>
/// <value>
/// <c>true</c> if [abort on error]; otherwise, <c>false</c>.
/// </value>
public bool AbortOnErrorSet { get; set; } = false;
/// <summary>
/// Gets or sets the connected event handler.
/// </summary>
/// <value>
/// The connected.
/// </value>
public EventHandler<ConnectEventArgs> Connected { get; set; } = (sender, args) => { };
/// <summary>
/// Gets or sets the connection string.
/// </summary>
/// <value>
/// The connection string.
/// </value>
public string[] ConnectionString { get; set; }
/// <summary>
/// Gets the current directory resolver.
/// </summary>
/// <value>
/// The current directory resolver. If <c>null</c> then <see cref="M:System.IO.Directory.GetCurrentDirectory" /> is used.
/// </value>
public ICurrentDirectoryResolver CurrentDirectoryResolver => null;
/// <summary>
/// Gets a value indicating whether to disable interactive commands, startup script, and environment variables.
/// </summary>
/// <value>
/// <c>true</c> if [disable commands]; otherwise, <c>false</c>.
/// </value>
public bool DisableCommandsSet => false;
/// <summary>
/// Gets a value indicating whether [disable variables].
/// </summary>
/// <value>
/// <c>true</c> if [disable variables]; otherwise, <c>false</c>.
/// </value>
public bool DisableVariablesSet => false;
public bool RunParallel { get; }
/// <summary>
/// Gets or sets the exit code.
/// </summary>
/// <value>
/// The exit code.
/// </value>
public int ExitCode { get; set; } = 0;
/// <summary>
/// Gets or sets the initial variables.
/// </summary>
/// <value>
/// The initial variables.
/// </value>
public IDictionary InitialVariables { get; set; } = null;
string[] ISqlExecuteArguments.InputFile => this.inputFile;
/// <summary>
/// Gets or sets the input file.
/// </summary>
/// <value>
/// The input file.
/// </value>
public string InputFile { get; set; } = null;
/// <summary>
/// Gets the maximum length of binary data to return.
/// </summary>
public int MaxBinaryLength => 4096;
/// <summary>
/// Gets the maximum length of character data to return.
/// </summary>
/// <value>
/// The maximum length of the character.
/// </value>
public int MaxCharLength => 4000;
/// <summary>
/// Gets the results as.
/// </summary>
/// <value>
/// The results as.
/// </value>
public OutputAs OutputAs => OutputAs.DataRows;
/// <summary>
/// Gets the output file.
/// </summary>
/// <value>
/// The output file.
/// </value>
public string OutputFile => null;
/// <summary>
/// Gets or sets the output message event handler.
/// </summary>
/// <value>
/// The output message.
/// </value>
public EventHandler<OutputMessageEventArgs> OutputMessage { get; set; } = (sender, args) =>
{
switch (args.OutputDestination)
{
case OutputDestination.StdOut:
Debug.WriteLine($"INFO : {args.Message}");
break;
case OutputDestination.StdError:
Debug.WriteLine($"ERROR: {args.Message}");
break;
case OutputDestination.File:
Debug.WriteLine($"FILE : {args.Message}");
break;
}
};
/// <summary>
/// Gets or sets the output result event handler.
/// </summary>
/// <value>
/// The output result.
/// </value>
public EventHandler<OutputResultEventArgs> OutputResult { get; set; } = (sender, args) => { };
/// <summary>
/// Gets or sets the console/file result event handler.
/// </summary>
/// <value>
/// The output result.
/// </value>
public EventHandler<OutputResultEventArgs> OutputTextResult { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [override script variables].
/// </summary>
/// <value>
/// <c>true</c> if [override script variables]; otherwise, <c>false</c>.
/// </value>
public bool OverrideScriptVariablesSet { get; set; } = false;
/// <summary>
/// Gets a value indicating whether parse only (no execute) run should be performed.
/// </summary>
/// <value>
/// <c>true</c> if [parse only]; otherwise, <c>false</c>.
/// </value>
public bool ParseOnly => false;
/// <summary>
/// Gets or sets the query.
/// </summary>
/// <value>
/// The query.
/// </value>
public string Query { get; set; }
/// <summary>
/// Gets or sets the query timeout.
/// </summary>
/// <value>
/// The query timeout.
/// </value>
public int QueryTimeout { get; set; } = 0;
/// <summary>
/// Gets or sets the number of times to retry a retryable error (e.g. timed-out queries).
/// </summary>
/// <value>
/// The retry count.
/// </value>
public int RetryCount { get; set; } = 0;
}
} | 31.038647 | 129 | 0.503969 | [
"MIT"
] | fireflycons/Invoke-SqlExecute | SqlExecuteTests/TestArguments.cs | 6,427 | C# |
using System;
namespace nats_ui.Data.Scripts
{
public interface IScriptCommand : ICheckable
{
string Name { get; }
string ParamName1 { get; }
string ParamName2 { get; }
string Param1 { get; set; }
string Param2 { get; set; }
ExecutionStatus Status { get; set; }
public string Result { get; set; }
public DateTime TimeStamp { get; set; }
public TimeSpan Duration { get; set; }
string Execute(NatsService natsService, ExecutorService executorService);
}
} | 25 | 81 | 0.612727 | [
"Unlicense"
] | fremag/nats-ui | Data/Scripts/IScriptCommand.cs | 550 | C# |
namespace DBMS_G15
{
partial class ContractForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ContractForm));
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
this.panel2 = new System.Windows.Forms.Panel();
this.btnDelete = new System.Windows.Forms.Button();
this.btnSave = new System.Windows.Forms.Button();
this.btnAdd = new System.Windows.Forms.Button();
this.panelNavigator = new System.Windows.Forms.Panel();
this.searchBox = new System.Windows.Forms.TextBox();
this.btnNext = new System.Windows.Forms.Button();
this.btnPrevious = new System.Windows.Forms.Button();
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.panelDetails = new System.Windows.Forms.Panel();
this.expirationDateLabel = new System.Windows.Forms.Label();
this.beginDateLabel = new System.Windows.Forms.Label();
this.departmentIDLabel = new System.Windows.Forms.Label();
this.productNameLabel = new System.Windows.Forms.Label();
this.idLabel = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.tbDepartmentID = new System.Windows.Forms.TextBox();
this.tbName = new System.Windows.Forms.TextBox();
this.tbID = new System.Windows.Forms.TextBox();
this.partnerIDLabel = new System.Windows.Forms.Label();
this.tbPartnerID = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.tbRepresentativeName = new System.Windows.Forms.TextBox();
this.beginDate = new System.Windows.Forms.DateTimePicker();
this.expirationDate = new System.Windows.Forms.DateTimePicker();
this.commissionLabel = new System.Windows.Forms.Label();
this.tbCommission = new System.Windows.Forms.TextBox();
this.activationComboBox = new System.Windows.Forms.ComboBox();
this.activationLabel = new System.Windows.Forms.Label();
this.panel2.SuspendLayout();
this.panelNavigator.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.panelDetails.SuspendLayout();
this.SuspendLayout();
//
// panel2
//
this.panel2.BackColor = System.Drawing.Color.WhiteSmoke;
this.panel2.Controls.Add(this.btnDelete);
this.panel2.Controls.Add(this.btnSave);
this.panel2.Controls.Add(this.btnAdd);
this.panel2.Dock = System.Windows.Forms.DockStyle.Right;
this.panel2.Location = new System.Drawing.Point(736, 0);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(72, 583);
this.panel2.TabIndex = 7;
//
// btnDelete
//
this.btnDelete.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnDelete.Dock = System.Windows.Forms.DockStyle.Top;
this.btnDelete.FlatAppearance.BorderSize = 0;
this.btnDelete.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(128)))));
this.btnDelete.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
this.btnDelete.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnDelete.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnDelete.Image = ((System.Drawing.Image)(resources.GetObject("btnDelete.Image")));
this.btnDelete.Location = new System.Drawing.Point(0, 380);
this.btnDelete.Name = "btnDelete";
this.btnDelete.Size = new System.Drawing.Size(72, 190);
this.btnDelete.TabIndex = 21;
this.btnDelete.Text = "Xóa";
this.btnDelete.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this.btnDelete.UseVisualStyleBackColor = true;
//
// btnSave
//
this.btnSave.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnSave.Dock = System.Windows.Forms.DockStyle.Top;
this.btnSave.FlatAppearance.BorderSize = 0;
this.btnSave.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(255)))), ((int)(((byte)(255)))));
this.btnSave.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(255)))));
this.btnSave.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnSave.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnSave.Image = ((System.Drawing.Image)(resources.GetObject("btnSave.Image")));
this.btnSave.Location = new System.Drawing.Point(0, 190);
this.btnSave.Name = "btnSave";
this.btnSave.Size = new System.Drawing.Size(72, 190);
this.btnSave.TabIndex = 20;
this.btnSave.Text = "Lưu";
this.btnSave.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
this.btnSave.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this.btnSave.UseVisualStyleBackColor = true;
//
// btnAdd
//
this.btnAdd.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnAdd.Dock = System.Windows.Forms.DockStyle.Top;
this.btnAdd.FlatAppearance.BorderSize = 0;
this.btnAdd.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(255)))), ((int)(((byte)(128)))));
this.btnAdd.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
this.btnAdd.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnAdd.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnAdd.Image = ((System.Drawing.Image)(resources.GetObject("btnAdd.Image")));
this.btnAdd.Location = new System.Drawing.Point(0, 0);
this.btnAdd.Name = "btnAdd";
this.btnAdd.Size = new System.Drawing.Size(72, 190);
this.btnAdd.TabIndex = 19;
this.btnAdd.Text = "Thêm";
this.btnAdd.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this.btnAdd.UseVisualStyleBackColor = true;
//
// panelNavigator
//
this.panelNavigator.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(39)))), ((int)(((byte)(67)))), ((int)(((byte)(138)))));
this.panelNavigator.Controls.Add(this.searchBox);
this.panelNavigator.Controls.Add(this.btnNext);
this.panelNavigator.Controls.Add(this.btnPrevious);
this.panelNavigator.Dock = System.Windows.Forms.DockStyle.Bottom;
this.panelNavigator.Location = new System.Drawing.Point(0, 513);
this.panelNavigator.Name = "panelNavigator";
this.panelNavigator.Size = new System.Drawing.Size(736, 70);
this.panelNavigator.TabIndex = 9;
//
// searchBox
//
this.searchBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)));
this.searchBox.Location = new System.Drawing.Point(293, 25);
this.searchBox.Name = "searchBox";
this.searchBox.Size = new System.Drawing.Size(150, 20);
this.searchBox.TabIndex = 2;
//
// btnNext
//
this.btnNext.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnNext.BackColor = System.Drawing.Color.WhiteSmoke;
this.btnNext.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnNext.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnNext.Location = new System.Drawing.Point(522, 11);
this.btnNext.Name = "btnNext";
this.btnNext.Size = new System.Drawing.Size(100, 50);
this.btnNext.TabIndex = 1;
this.btnNext.Text = ">";
this.btnNext.UseVisualStyleBackColor = false;
//
// btnPrevious
//
this.btnPrevious.BackColor = System.Drawing.Color.WhiteSmoke;
this.btnPrevious.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnPrevious.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnPrevious.Location = new System.Drawing.Point(114, 10);
this.btnPrevious.Name = "btnPrevious";
this.btnPrevious.Size = new System.Drawing.Size(100, 50);
this.btnPrevious.TabIndex = 0;
this.btnPrevious.Text = "<";
this.btnPrevious.UseVisualStyleBackColor = false;
//
// dataGridView1
//
this.dataGridView1.AllowUserToAddRows = false;
this.dataGridView1.AllowUserToDeleteRows = false;
this.dataGridView1.AllowUserToResizeColumns = false;
this.dataGridView1.AllowUserToResizeRows = false;
this.dataGridView1.BackgroundColor = System.Drawing.Color.Gainsboro;
dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle1.BackColor = System.Drawing.Color.WhiteSmoke;
dataGridViewCellStyle1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.GradientActiveCaption;
dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.dataGridView1.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1;
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.dataGridView1.GridColor = System.Drawing.Color.Gainsboro;
this.dataGridView1.Location = new System.Drawing.Point(0, 190);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.ReadOnly = true;
this.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dataGridView1.Size = new System.Drawing.Size(736, 323);
this.dataGridView1.TabIndex = 10;
//
// panelDetails
//
this.panelDetails.BackColor = System.Drawing.Color.Gainsboro;
this.panelDetails.Controls.Add(this.activationLabel);
this.panelDetails.Controls.Add(this.activationComboBox);
this.panelDetails.Controls.Add(this.commissionLabel);
this.panelDetails.Controls.Add(this.tbCommission);
this.panelDetails.Controls.Add(this.expirationDate);
this.panelDetails.Controls.Add(this.beginDate);
this.panelDetails.Controls.Add(this.label2);
this.panelDetails.Controls.Add(this.tbRepresentativeName);
this.panelDetails.Controls.Add(this.partnerIDLabel);
this.panelDetails.Controls.Add(this.tbPartnerID);
this.panelDetails.Controls.Add(this.expirationDateLabel);
this.panelDetails.Controls.Add(this.beginDateLabel);
this.panelDetails.Controls.Add(this.departmentIDLabel);
this.panelDetails.Controls.Add(this.productNameLabel);
this.panelDetails.Controls.Add(this.idLabel);
this.panelDetails.Controls.Add(this.label1);
this.panelDetails.Controls.Add(this.tbDepartmentID);
this.panelDetails.Controls.Add(this.tbName);
this.panelDetails.Controls.Add(this.tbID);
this.panelDetails.Dock = System.Windows.Forms.DockStyle.Fill;
this.panelDetails.Location = new System.Drawing.Point(0, 0);
this.panelDetails.Name = "panelDetails";
this.panelDetails.Size = new System.Drawing.Size(736, 190);
this.panelDetails.TabIndex = 11;
//
// expirationDateLabel
//
this.expirationDateLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.expirationDateLabel.AutoSize = true;
this.expirationDateLabel.Location = new System.Drawing.Point(621, 47);
this.expirationDateLabel.Name = "expirationDateLabel";
this.expirationDateLabel.Size = new System.Drawing.Size(79, 13);
this.expirationDateLabel.TabIndex = 10;
this.expirationDateLabel.Text = "Ngày Kết Thúc";
//
// beginDateLabel
//
this.beginDateLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.beginDateLabel.AutoSize = true;
this.beginDateLabel.Location = new System.Drawing.Point(493, 47);
this.beginDateLabel.Name = "beginDateLabel";
this.beginDateLabel.Size = new System.Drawing.Size(74, 13);
this.beginDateLabel.TabIndex = 9;
this.beginDateLabel.Text = "Ngày Bắt Đầu";
//
// departmentIDLabel
//
this.departmentIDLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)));
this.departmentIDLabel.AutoSize = true;
this.departmentIDLabel.Location = new System.Drawing.Point(285, 47);
this.departmentIDLabel.Name = "departmentIDLabel";
this.departmentIDLabel.Size = new System.Drawing.Size(75, 13);
this.departmentIDLabel.TabIndex = 8;
this.departmentIDLabel.Text = "Mã Chi Nhánh";
//
// productNameLabel
//
this.productNameLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)));
this.productNameLabel.AutoSize = true;
this.productNameLabel.Location = new System.Drawing.Point(285, 92);
this.productNameLabel.Name = "productNameLabel";
this.productNameLabel.Size = new System.Drawing.Size(66, 13);
this.productNameLabel.TabIndex = 7;
this.productNameLabel.Text = "Mã Số Thuế";
//
// idLabel
//
this.idLabel.AutoSize = true;
this.idLabel.Location = new System.Drawing.Point(53, 100);
this.idLabel.Name = "idLabel";
this.idLabel.Size = new System.Drawing.Size(74, 13);
this.idLabel.TabIndex = 6;
this.idLabel.Text = "Mã Hợp Đồng";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 18F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(48, 21);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(133, 58);
this.label1.TabIndex = 5;
this.label1.Text = "Thông Tin\r\nHợp Đồng";
//
// tbDepartmentID
//
this.tbDepartmentID.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)));
this.tbDepartmentID.Location = new System.Drawing.Point(282, 111);
this.tbDepartmentID.Name = "tbDepartmentID";
this.tbDepartmentID.Size = new System.Drawing.Size(161, 20);
this.tbDepartmentID.TabIndex = 3;
//
// tbName
//
this.tbName.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)));
this.tbName.Location = new System.Drawing.Point(282, 63);
this.tbName.Name = "tbName";
this.tbName.Size = new System.Drawing.Size(161, 20);
this.tbName.TabIndex = 1;
//
// tbID
//
this.tbID.Location = new System.Drawing.Point(53, 119);
this.tbID.Name = "tbID";
this.tbID.Size = new System.Drawing.Size(161, 20);
this.tbID.TabIndex = 0;
//
// partnerIDLabel
//
this.partnerIDLabel.AutoSize = true;
this.partnerIDLabel.Location = new System.Drawing.Point(53, 145);
this.partnerIDLabel.Name = "partnerIDLabel";
this.partnerIDLabel.Size = new System.Drawing.Size(63, 13);
this.partnerIDLabel.TabIndex = 12;
this.partnerIDLabel.Text = "Mã Đối Tác";
//
// tbPartnerID
//
this.tbPartnerID.Location = new System.Drawing.Point(53, 164);
this.tbPartnerID.Name = "tbPartnerID";
this.tbPartnerID.Size = new System.Drawing.Size(161, 20);
this.tbPartnerID.TabIndex = 11;
//
// label2
//
this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)));
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(285, 145);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(79, 13);
this.label2.TabIndex = 14;
this.label2.Text = "Người Đại Diện";
//
// tbRepresentativeName
//
this.tbRepresentativeName.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)));
this.tbRepresentativeName.Location = new System.Drawing.Point(282, 164);
this.tbRepresentativeName.Name = "tbRepresentativeName";
this.tbRepresentativeName.Size = new System.Drawing.Size(161, 20);
this.tbRepresentativeName.TabIndex = 13;
//
// beginDate
//
this.beginDate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.beginDate.Format = System.Windows.Forms.DateTimePickerFormat.Short;
this.beginDate.Location = new System.Drawing.Point(496, 63);
this.beginDate.Name = "beginDate";
this.beginDate.Size = new System.Drawing.Size(100, 20);
this.beginDate.TabIndex = 15;
//
// expirationDate
//
this.expirationDate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.expirationDate.Format = System.Windows.Forms.DateTimePickerFormat.Short;
this.expirationDate.Location = new System.Drawing.Point(624, 63);
this.expirationDate.Name = "expirationDate";
this.expirationDate.Size = new System.Drawing.Size(100, 20);
this.expirationDate.TabIndex = 16;
//
// commissionLabel
//
this.commissionLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.commissionLabel.AutoSize = true;
this.commissionLabel.Location = new System.Drawing.Point(493, 95);
this.commissionLabel.Name = "commissionLabel";
this.commissionLabel.Size = new System.Drawing.Size(80, 13);
this.commissionLabel.TabIndex = 18;
this.commissionLabel.Text = "Tiền Hoa Hồng";
//
// tbCommission
//
this.tbCommission.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.tbCommission.Location = new System.Drawing.Point(496, 111);
this.tbCommission.Name = "tbCommission";
this.tbCommission.Size = new System.Drawing.Size(161, 20);
this.tbCommission.TabIndex = 17;
//
// activationComboBox
//
this.activationComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.activationComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.activationComboBox.FormattingEnabled = true;
this.activationComboBox.Items.AddRange(new object[] {
"Vô Hiệu",
"Có Hiệu Lực"});
this.activationComboBox.Location = new System.Drawing.Point(496, 164);
this.activationComboBox.Name = "activationComboBox";
this.activationComboBox.Size = new System.Drawing.Size(161, 21);
this.activationComboBox.TabIndex = 19;
//
// activationLabel
//
this.activationLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.activationLabel.AutoSize = true;
this.activationLabel.Location = new System.Drawing.Point(493, 148);
this.activationLabel.Name = "activationLabel";
this.activationLabel.Size = new System.Drawing.Size(50, 13);
this.activationLabel.TabIndex = 20;
this.activationLabel.Text = "Hiệu Lực";
//
// ContractForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.Gainsboro;
this.ClientSize = new System.Drawing.Size(808, 583);
this.Controls.Add(this.panelDetails);
this.Controls.Add(this.dataGridView1);
this.Controls.Add(this.panelNavigator);
this.Controls.Add(this.panel2);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Name = "ContractForm";
this.Text = "ContractForm";
this.panel2.ResumeLayout(false);
this.panelNavigator.ResumeLayout(false);
this.panelNavigator.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
this.panelDetails.ResumeLayout(false);
this.panelDetails.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Button btnDelete;
private System.Windows.Forms.Button btnSave;
private System.Windows.Forms.Button btnAdd;
private System.Windows.Forms.Panel panelNavigator;
private System.Windows.Forms.TextBox searchBox;
private System.Windows.Forms.Button btnNext;
private System.Windows.Forms.Button btnPrevious;
private System.Windows.Forms.DataGridView dataGridView1;
private System.Windows.Forms.Panel panelDetails;
private System.Windows.Forms.Label expirationDateLabel;
private System.Windows.Forms.Label beginDateLabel;
private System.Windows.Forms.Label departmentIDLabel;
private System.Windows.Forms.Label productNameLabel;
private System.Windows.Forms.Label idLabel;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox tbDepartmentID;
private System.Windows.Forms.TextBox tbName;
private System.Windows.Forms.TextBox tbID;
private System.Windows.Forms.Label partnerIDLabel;
private System.Windows.Forms.TextBox tbPartnerID;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox tbRepresentativeName;
private System.Windows.Forms.DateTimePicker expirationDate;
private System.Windows.Forms.DateTimePicker beginDate;
private System.Windows.Forms.Label commissionLabel;
private System.Windows.Forms.TextBox tbCommission;
private System.Windows.Forms.ComboBox activationComboBox;
private System.Windows.Forms.Label activationLabel;
}
} | 57.961207 | 179 | 0.630996 | [
"MIT"
] | HCMUS-Eakan/DBMS-Course | Application/Code/DBMS_G15/DBMS_G15/ContractForm.Designer.cs | 26,957 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Compilation;
namespace Artem.Data.Access.Build {
/// <summary>
///
/// </summary>
public class DalBuildProvider : BuildProvider {
#region Methods /////////////////////////////////////////////////////////////////
/// <summary>
/// Generates source code for the virtual path of the build provider, and adds the source code to a specified assembly builder.
/// </summary>
/// <param name="assemblyBuilder">The assembly builder that references the source code generated by the build provider.</param>
public override void GenerateCode(AssemblyBuilder assemblyBuilder) {
using (DalGenerator gen = new DalGenerator(this.VirtualPath, true)) {
assemblyBuilder.AddCodeCompileUnit(this, gen.Generate());
//CodeHelper.BuildCodeTreeFromMapFile(this.VirtualPath, true));
}
}
#endregion
}
}
| 35.413793 | 135 | 0.599805 | [
"MIT"
] | velio/dotnet-data-access | src/Artem.Data.Access/Build/DalBuildProvider.cs | 1,027 | C# |
using Xamarin.Forms;
using Xamarin.Forms.Internals;
using Xamarin.Forms.Xaml;
namespace Xlet.Mobile.Views.Dashboard
{
/// <summary>
/// Page to show the health care details.
/// </summary>
[Preserve(AllMembers = true)]
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class HealthCarePage : ContentPage
{
/// <summary>
/// Initializes a new instance of the <see cref="HealthCarePage" /> class.
/// </summary>
public HealthCarePage()
{
InitializeComponent();
}
}
}
| 24.956522 | 82 | 0.621951 | [
"MIT"
] | MattPearce/xlet | Xlet.Mobile/Xlet.Mobile/Xlet.Mobile/Views/Dashboard/HealthCarePage.xaml.cs | 576 | C# |
#pragma checksum "TestFiles/IntegrationTests/CodeGenerationIntegrationTest/DuplicateAttributeTagHelpers.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "4dc2ea6fc4bd045c34a90867a6a72183a3d01323"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(Microsoft.AspNetCore.Razor.Language.IntegrationTests.TestFiles.TestFiles_IntegrationTests_CodeGenerationIntegrationTest_DuplicateAttributeTagHelpers_Runtime), @"default", @"/TestFiles/IntegrationTests/CodeGenerationIntegrationTest/DuplicateAttributeTagHelpers.cshtml")]
namespace Microsoft.AspNetCore.Razor.Language.IntegrationTests.TestFiles
{
#line hidden
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"4dc2ea6fc4bd045c34a90867a6a72183a3d01323", @"/TestFiles/IntegrationTests/CodeGenerationIntegrationTest/DuplicateAttributeTagHelpers.cshtml")]
public class TestFiles_IntegrationTests_CodeGenerationIntegrationTest_DuplicateAttributeTagHelpers_Runtime
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", "button", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("TYPE", new global::Microsoft.AspNetCore.Html.HtmlString("checkbox"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", new global::Microsoft.AspNetCore.Html.HtmlString("checkbox"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("checked", new global::Microsoft.AspNetCore.Html.HtmlString("false"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", "button", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.SingleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("checked", new global::Microsoft.AspNetCore.Html.HtmlString("true"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.SingleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("checked", new global::Microsoft.AspNetCore.Html.HtmlString("true"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_7 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("AGE", new global::Microsoft.AspNetCore.Html.HtmlString("40"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_8 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("Age", new global::Microsoft.AspNetCore.Html.HtmlString("500"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::TestNamespace.PTagHelper __TestNamespace_PTagHelper;
private global::TestNamespace.InputTagHelper __TestNamespace_InputTagHelper;
private global::TestNamespace.InputTagHelper2 __TestNamespace_InputTagHelper2;
#pragma warning disable 1998
public async System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral("\r\n");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => {
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => {
}
);
__TestNamespace_InputTagHelper = CreateTagHelper<global::TestNamespace.InputTagHelper>();
__tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper);
__TestNamespace_InputTagHelper2 = CreateTagHelper<global::TestNamespace.InputTagHelper2>();
__tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2);
__TestNamespace_InputTagHelper.Type = (string)__tagHelperAttribute_0.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0);
__TestNamespace_InputTagHelper2.Type = (string)__tagHelperAttribute_0.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => {
}
);
__TestNamespace_InputTagHelper = CreateTagHelper<global::TestNamespace.InputTagHelper>();
__tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper);
__TestNamespace_InputTagHelper2 = CreateTagHelper<global::TestNamespace.InputTagHelper2>();
__tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2);
__TestNamespace_InputTagHelper.Type = (string)__tagHelperAttribute_0.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0);
__TestNamespace_InputTagHelper2.Type = (string)__tagHelperAttribute_0.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0);
#nullable restore
#line 5 "TestFiles/IntegrationTests/CodeGenerationIntegrationTest/DuplicateAttributeTagHelpers.cshtml"
__TestNamespace_InputTagHelper2.Checked = true;
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("checked", __TestNamespace_InputTagHelper2.Checked, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => {
}
);
__TestNamespace_InputTagHelper = CreateTagHelper<global::TestNamespace.InputTagHelper>();
__tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper);
__TestNamespace_InputTagHelper2 = CreateTagHelper<global::TestNamespace.InputTagHelper2>();
__tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2);
__TestNamespace_InputTagHelper.Type = (string)__tagHelperAttribute_4.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4);
__TestNamespace_InputTagHelper2.Type = (string)__tagHelperAttribute_4.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4);
#nullable restore
#line 6 "TestFiles/IntegrationTests/CodeGenerationIntegrationTest/DuplicateAttributeTagHelpers.cshtml"
__TestNamespace_InputTagHelper2.Checked = true;
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("checked", __TestNamespace_InputTagHelper2.Checked, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_5);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_6);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n");
}
);
__TestNamespace_PTagHelper = CreateTagHelper<global::TestNamespace.PTagHelper>();
__tagHelperExecutionContext.Add(__TestNamespace_PTagHelper);
#nullable restore
#line 3 "TestFiles/IntegrationTests/CodeGenerationIntegrationTest/DuplicateAttributeTagHelpers.cshtml"
__TestNamespace_PTagHelper.Age = 3;
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("age", __TestNamespace_PTagHelper.Age, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_7);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_8);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
}
#pragma warning restore 1998
}
}
#pragma warning restore 1591
| 82.366013 | 357 | 0.75734 | [
"Apache-2.0"
] | benaadams/AspNetCore-Tooling | src/Razor/test/RazorLanguage.Test/TestFiles/IntegrationTests/CodeGenerationIntegrationTest/DuplicateAttributeTagHelpers_Runtime.codegen.cs | 12,602 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using Microsoft.Extensions.Logging;
using NBitcoin;
using NBitcoin.BuilderExtensions;
using Stratis.Bitcoin.AsyncWork;
using Stratis.Bitcoin.Configuration;
using Stratis.Bitcoin.Features.Wallet;
using Stratis.Bitcoin.Features.Wallet.Interfaces;
using Stratis.Bitcoin.Features.Wallet.Models;
using Stratis.Bitcoin.Interfaces;
using Stratis.Bitcoin.Utilities;
[assembly: InternalsVisibleTo("Stratis.Bitcoin.Features.ColdStaking.Tests")]
[assembly: InternalsVisibleTo("Stratis.Bitcoin.IntegrationTests")]
namespace Stratis.Bitcoin.Features.ColdStaking
{
/// <summary>
/// The manager class for implementing cold staking as covered in more detail in the remarks of
/// the <see cref="ColdStakingFeature"/> class.
/// This class provides the methods used by the <see cref="Controllers.ColdStakingController"/>
/// which in turn provides the API methods for accessing this functionality.
/// </summary>
/// <remarks>
/// The following functionality is implemented in this class:
/// <list type="bullet">
/// <item><description>Generating cold staking address via the <see cref="GetFirstUnusedColdStakingAddress"/> method. These
/// addresses are used for generating the cold staking setup.</description></item>
/// <item><description>Creating a build context for generating the cold staking setup via the <see
/// cref="GetColdStakingSetupTransaction"/> method.</description></item>
/// </list>
/// </remarks>
public class ColdStakingManager : WalletManager, IWalletManager
{
private static Func<HdAccount, bool> coldStakingAccounts = a => a.Index >= Wallet.Wallet.SpecialPurposeAccountIndexesStart;
/// <summary>The account index of the cold wallet account.</summary>
internal const int ColdWalletAccountIndex = Wallet.Wallet.SpecialPurposeAccountIndexesStart + 0;
/// <summary>The account name of the cold wallet account.</summary>
internal const string ColdWalletAccountName = "coldStakingColdAddresses";
/// <summary>The account index of the hot wallet account.</summary>
internal const int HotWalletAccountIndex = Wallet.Wallet.SpecialPurposeAccountIndexesStart + 1;
/// <summary>The account name of the hot wallet account.</summary>
internal const string HotWalletAccountName = "coldStakingHotAddresses";
/// <summary>Instance logger.</summary>
private readonly ILogger logger;
/// <summary>Provider of time functions.</summary>
private readonly IDateTimeProvider dateTimeProvider;
/// <summary>
/// Constructs the cold staking manager which is used by the cold staking controller.
/// </summary>
/// <param name="network">The network that the manager is running on.</param>
/// <param name="chainIndexer">Thread safe class representing a chain of headers from genesis.</param>
/// <param name="walletSettings">The wallet settings.</param>
/// <param name="dataFolder">Contains path locations to folders and files on disk.</param>
/// <param name="walletFeePolicy">The wallet fee policy.</param>
/// <param name="asyncProvider">Factory for creating and also possibly starting application defined tasks inside async loop.</param>
/// <param name="nodeLifeTime">Allows consumers to perform cleanup during a graceful shutdown.</param>
/// <param name="scriptAddressReader">A reader for extracting an address from a <see cref="Script"/>.</param>
/// <param name="loggerFactory">The logger factory to use to create the custom logger.</param>
/// <param name="dateTimeProvider">Provider of time functions.</param>
/// <param name="broadcasterManager">The broadcaster manager.</param>
public ColdStakingManager(
Network network,
ChainIndexer chainIndexer,
WalletSettings walletSettings,
DataFolder dataFolder,
IWalletFeePolicy walletFeePolicy,
IAsyncProvider asyncProvider,
INodeLifetime nodeLifeTime,
IScriptAddressReader scriptAddressReader,
ILoggerFactory loggerFactory,
IDateTimeProvider dateTimeProvider,
IWalletRepository walletRepository,
IBroadcasterManager broadcasterManager = null) : base(
loggerFactory,
network,
chainIndexer,
walletSettings,
dataFolder,
walletFeePolicy,
dateTimeProvider,
walletRepository)
{
Guard.NotNull(loggerFactory, nameof(loggerFactory));
Guard.NotNull(dateTimeProvider, nameof(dateTimeProvider));
this.logger = loggerFactory.CreateLogger(this.GetType().FullName);
this.dateTimeProvider = dateTimeProvider;
}
/// <summary>
/// Overrides the default <see cref="WalletManager.CreateAddressFromScriptLookup"/>.
/// </summary>
/// <returns>A new <see cref="ColdStakingAddressLookup"/> object for use by this class.</returns>
protected override ScriptToAddressLookup CreateAddressFromScriptLookup()
{
return new ColdStakingAddressLookup(this.network);
}
/// <inheritdoc />
public override Dictionary<string, ScriptTemplate> GetValidStakingTemplates()
{
Dictionary<string, ScriptTemplate> templates = base.GetValidStakingTemplates();
templates["ColdStaking"] = ColdStakingScriptTemplate.Instance;
return templates;
}
// <inheritdoc />
public override IEnumerable<BuilderExtension> GetTransactionBuilderExtensionsForStaking()
{
return base.GetTransactionBuilderExtensionsForStaking().Concat(new List<BuilderExtension> { new ColdStakingBuilderExtension(true) });
}
/// <summary>
/// Gets all the unspent transactions in a wallet from the accounts participating in staking.
/// </summary>
/// <param name="walletName">Name of the wallet to get the transactions from.</param>
/// <param name="confirmations">Number of confirmation required.</param>
/// <returns>An enumeration of <see cref="UnspentOutputReference"/> objects.</returns>
public override IEnumerable<UnspentOutputReference> GetSpendableTransactionsInWalletForStaking(string walletName, int confirmations = 0)
{
return this.GetUnspentTransactionsInWallet(walletName, confirmations,
a => (a.Index < Wallet.Wallet.SpecialPurposeAccountIndexesStart) || (a.Index == ColdStakingManager.HotWalletAccountIndex));
}
/// <summary>
/// Returns information related to cold staking.
/// </summary>
/// <param name="walletName">The wallet to return the information for.</param>
/// <returns>A <see cref="Models.GetColdStakingInfoResponse"/> object containing the information.</returns>
internal Models.GetColdStakingInfoResponse GetColdStakingInfo(string walletName)
{
Wallet.Wallet wallet = this.GetWallet(walletName);
var response = new Models.GetColdStakingInfoResponse()
{
ColdWalletAccountExists = this.GetColdStakingAccount(wallet, true) != null,
HotWalletAccountExists = this.GetColdStakingAccount(wallet, false) != null
};
this.logger.LogTrace("(-):'{0}'", response);
return response;
}
/// <summary>
/// Gets a cold staking account.
/// </summary>
/// <remarks>
/// <para>In order to keep track of cold staking addresses and balances we are using <see cref="HdAccount"/>'s
/// with indexes starting from the value defined in <see cref="Wallet.SpecialPurposeAccountIndexesStart"/>.
/// </para><para>
/// We are using two such accounts, one when the wallet is in the role of cold wallet, and another one when
/// the wallet is in the role of hot wallet. For this reason we specify the required account when calling this
/// method.
/// </para></remarks>
/// <param name="wallet">The wallet where we wish to create the account.</param>
/// <param name="isColdWalletAccount">Indicates whether we need the cold wallet account (versus the hot wallet account).</param>
/// <returns>The cold staking account or <c>null</c> if the account does not exist.</returns>
internal HdAccount GetColdStakingAccount(Wallet.Wallet wallet, bool isColdWalletAccount)
{
HdAccount account = wallet.GetAccount(isColdWalletAccount ? ColdWalletAccountName : HotWalletAccountName);
if (account == null)
{
this.logger.LogTrace("(-)[ACCOUNT_DOES_NOT_EXIST]:null");
return null;
}
this.logger.LogTrace("(-):'{0}'", account.Name);
return account;
}
/// <summary>
/// Creates a cold staking account and ensures that it has at least one address.
/// If the account already exists then the existing account is returned.
/// </summary>
/// <remarks>
/// <para>In order to keep track of cold staking addresses and balances we are using <see cref="HdAccount"/>'s
/// with indexes starting from the value defined in <see cref="Wallet.SpecialPurposeAccountIndexesStart"/>.
/// </para><para>
/// We are using two such accounts, one when the wallet is in the role of cold wallet, and another one when
/// the wallet is in the role of hot wallet. For this reason we specify the required account when calling this
/// method.
/// </para></remarks>
/// <param name="walletName">The name of the wallet where we wish to create the account.</param>
/// <param name="isColdWalletAccount">Indicates whether we need the cold wallet account (versus the hot wallet account).</param>
/// <param name="walletPassword">The wallet password which will be used to create the account.</param>
/// <returns>The new or existing cold staking account.</returns>
internal HdAccount GetOrCreateColdStakingAccount(string walletName, bool isColdWalletAccount, string walletPassword, ExtPubKey extPubKey)
{
Wallet.Wallet wallet = this.GetWallet(walletName);
HdAccount account = this.GetColdStakingAccount(wallet, isColdWalletAccount);
if (account != null)
{
this.logger.LogTrace("(-)[ACCOUNT_ALREADY_EXIST]:'{0}'", account.Name);
return account;
}
this.logger.LogDebug("The {0} wallet account for '{1}' does not exist and will now be created.", isColdWalletAccount ? "cold" : "hot", wallet.Name);
int accountIndex;
string accountName;
if (isColdWalletAccount)
{
accountIndex = ColdWalletAccountIndex;
accountName = ColdWalletAccountName;
}
else
{
accountIndex = HotWalletAccountIndex;
accountName = HotWalletAccountName;
}
if (extPubKey == null)
account = wallet.AddNewAccount(walletPassword, accountIndex, accountName, this.dateTimeProvider.GetTimeOffset());
else
account = wallet.AddNewAccount(extPubKey, accountIndex, accountName, this.dateTimeProvider.GetTimeOffset());
this.logger.LogTrace("(-):'{0}'", account.Name);
return account;
}
/// <summary>
/// Gets the first unused cold staking address. Creates a new address if required.
/// </summary>
/// <param name="walletName">The name of the wallet providing the cold staking address.</param>
/// <param name="isColdWalletAddress">Indicates whether we need the cold wallet address (versus the hot wallet address).</param>
/// <returns>The cold staking address or <c>null</c> if the required account does not exist.</returns>
internal HdAddress GetFirstUnusedColdStakingAddress(string walletName, bool isColdWalletAddress)
{
Guard.NotNull(walletName, nameof(walletName));
Wallet.Wallet wallet = this.GetWallet(walletName);
HdAccount account = this.GetColdStakingAccount(wallet, isColdWalletAddress);
if (account == null)
{
this.logger.LogTrace("(-)[ACCOUNT_DOES_NOT_EXIST]:null");
return null;
}
HdAddress address = account.GetFirstUnusedReceivingAddress();
if (address == null)
{
this.logger.LogDebug("No unused address exists on account '{0}'. Adding new address.", account.Name);
// TODO:
/*
IEnumerable<HdAddress> newAddresses = account.CreateAddresses(wallet.Network, 1);
this.UpdateKeysLookupLocked(newAddresses);
address = newAddresses.First();
*/
}
this.logger.LogTrace("(-):'{0}'", address.Address);
return address;
}
/// <summary>
/// Creates cold staking setup <see cref="Transaction"/>.
/// </summary>
/// <remarks>
/// The <paramref name="coldWalletAddress"/> and <paramref name="hotWalletAddress"/> would be expected to be
/// from different wallets and typically also different physical machines under normal circumstances. The following
/// rules are enforced by this method and would lead to a <see cref="WalletException"/> otherwise:
/// <list type="bullet">
/// <item><description>The cold and hot wallet addresses are expected to belong to different wallets.</description></item>
/// <item><description>Either the cold or hot wallet address must belong to a cold staking account in the wallet identified
/// by <paramref name="walletName"/></description></item>
/// <item><description>The account specified in <paramref name="walletAccount"/> can't be a cold staking account.</description></item>
/// </list>
/// </remarks>
/// <param name="walletTransactionHandler">The wallet transaction handler. Contains the <see cref="WalletTransactionHandler.BuildTransaction"/> method.</param>
/// <param name="coldWalletAddress">The cold wallet address generated by <see cref="GetColdStakingAddress"/>.</param>
/// <param name="hotWalletAddress">The hot wallet address generated by <see cref="GetColdStakingAddress"/>.</param>
/// <param name="walletName">The name of the wallet.</param>
/// <param name="walletAccount">The wallet account.</param>
/// <param name="walletPassword">The wallet password.</param>
/// <param name="amount">The amount to cold stake.</param>
/// <param name="feeAmount">The fee to pay for the cold staking setup transaction.</param>
/// <param name="subtractFeeFromAmount">Whether the transaction fee should be subtracted from the amount being transferred into the cold staking account.</param>
/// <param name="offline">Whether the transaction should be left unsigned so that it can be transferred to an offline wallet for signing.</param>
/// <param name="splitCount">The number of UTXOs of similar value the setup transaction will be split into. Defaults to 1.</param>
/// <param name="useSegwitChangeAddress">Use a segwit style change address.</param>
/// <returns>The <see cref="Transaction"/> for setting up cold staking.</returns>
/// <exception cref="WalletException">Thrown if any of the rules listed in the remarks section of this method are broken.</exception>
internal (Transaction, TransactionBuildContext) GetColdStakingSetupTransaction(IWalletTransactionHandler walletTransactionHandler,
string coldWalletAddress, string hotWalletAddress, string walletName, string walletAccount,
string walletPassword, Money amount, Money feeAmount, bool subtractFeeFromAmount, bool offline, int splitCount, bool useSegwitChangeAddress = false)
{
TransactionBuildContext context = this.GetSetupTransactionBuildContext(walletTransactionHandler, coldWalletAddress, hotWalletAddress, walletName, walletAccount,
walletPassword, amount, feeAmount, subtractFeeFromAmount, offline, useSegwitChangeAddress, splitCount);
context.Sign = !offline;
// Build the transaction.
Transaction transaction = walletTransactionHandler.BuildTransaction(context);
this.logger.LogTrace("(-)");
return (transaction, context);
}
private TransactionBuildContext GetSetupTransactionBuildContext(IWalletTransactionHandler walletTransactionHandler,
string coldWalletAddress, string hotWalletAddress, string walletName, string walletAccount,
string walletPassword, Money amount, Money feeAmount, bool subtractFeeFromAmount, bool offline, bool useSegwitChangeAddress, int splitCount, ExtPubKey extPubKey = null)
{
Guard.NotNull(walletTransactionHandler, nameof(walletTransactionHandler));
Guard.NotEmpty(coldWalletAddress, nameof(coldWalletAddress));
Guard.NotEmpty(hotWalletAddress, nameof(hotWalletAddress));
Guard.NotEmpty(walletName, nameof(walletName));
Guard.NotEmpty(walletAccount, nameof(walletAccount));
Guard.NotNull(amount, nameof(amount));
Wallet.Wallet wallet = this.GetWallet(walletName);
KeyId hotPubKeyHash = null;
KeyId coldPubKeyHash = null;
if (!offline)
{
// Get/create the cold staking accounts.
HdAccount coldAccount = this.GetOrCreateColdStakingAccount(walletName, true, walletPassword, extPubKey);
HdAccount hotAccount = this.GetOrCreateColdStakingAccount(walletName, false, walletPassword, extPubKey);
HdAddress coldAddress = coldAccount?.ExternalAddresses.FirstOrDefault(s => s.Address == coldWalletAddress || s.Bech32Address == coldWalletAddress);
HdAddress hotAddress = hotAccount?.ExternalAddresses.FirstOrDefault(s => s.Address == hotWalletAddress || s.Bech32Address == hotWalletAddress);
bool thisIsColdWallet = coldAddress != null;
bool thisIsHotWallet = hotAddress != null;
this.logger.LogDebug("Local wallet '{0}' does{1} contain cold wallet address '{2}' and does{3} contain hot wallet address '{4}'.",
walletName, thisIsColdWallet ? "" : " NOT", coldWalletAddress, thisIsHotWallet ? "" : " NOT", hotWalletAddress);
if (thisIsColdWallet && thisIsHotWallet)
{
this.logger.LogTrace("(-)[COLDSTAKE_BOTH_HOT_AND_COLD]");
throw new WalletException("You can't use this wallet as both the hot wallet and cold wallet.");
}
if (!thisIsColdWallet && !thisIsHotWallet)
{
this.logger.LogTrace("(-)[COLDSTAKE_ADDRESSES_NOT_IN_ACCOUNTS]");
throw new WalletException("The hot and cold wallet addresses could not be found in the corresponding accounts.");
}
// Check if this is a segwit address.
if (coldAddress?.Bech32Address == coldWalletAddress || hotAddress?.Bech32Address == hotWalletAddress)
{
hotPubKeyHash = new BitcoinWitPubKeyAddress(hotWalletAddress, wallet.Network).Hash.AsKeyId();
coldPubKeyHash = new BitcoinWitPubKeyAddress(coldWalletAddress, wallet.Network).Hash.AsKeyId();
}
else
{
hotPubKeyHash = new BitcoinPubKeyAddress(hotWalletAddress, wallet.Network).Hash;
coldPubKeyHash = new BitcoinPubKeyAddress(coldWalletAddress, wallet.Network).Hash;
}
}
else
{
// In offline mode we relax all the restrictions to enable simpler setup. The user should ensure they are using separate wallets, or the cold private key could be inadvertently loaded on the online node.
IDestination hot = BitcoinAddress.Create(hotWalletAddress, this.network);
IDestination cold = BitcoinAddress.Create(coldWalletAddress, this.network);
if (hot is BitcoinPubKeyAddress && cold is BitcoinPubKeyAddress)
{
hotPubKeyHash = new BitcoinPubKeyAddress(hotWalletAddress, wallet.Network).Hash;
coldPubKeyHash = new BitcoinPubKeyAddress(coldWalletAddress, wallet.Network).Hash;
}
if (hot is BitcoinWitPubKeyAddress && cold is BitcoinWitPubKeyAddress)
{
hotPubKeyHash = new BitcoinWitPubKeyAddress(hotWalletAddress, wallet.Network).Hash.AsKeyId();
coldPubKeyHash = new BitcoinWitPubKeyAddress(coldWalletAddress, wallet.Network).Hash.AsKeyId();
}
}
if (hotPubKeyHash == null || coldPubKeyHash == null)
{
this.logger.LogTrace("(-)[PUBKEYHASH_NOT_AVAILABLE]");
throw new WalletException($"Unable to compute the needed hashes from the given addresses.");
}
Script destination = ColdStakingScriptTemplate.Instance.GenerateScriptPubKey(hotPubKeyHash, coldPubKeyHash);
// Only normal accounts should be allowed.
if (!this.GetAccounts(walletName).Any(a => a.Name == walletAccount))
{
this.logger.LogTrace("(-)[COLDSTAKE_ACCOUNT_NOT_FOUND]");
throw new WalletException($"Can't find wallet account '{walletAccount}'.");
}
List<Recipient> recipients = GetRecipients(destination, amount, subtractFeeFromAmount, splitCount);
var context = new TransactionBuildContext(wallet.Network)
{
AccountReference = new WalletAccountReference(walletName, walletAccount),
TransactionFee = feeAmount,
MinConfirmations = 0,
Shuffle = false,
UseSegwitChangeAddress = useSegwitChangeAddress,
WalletPassword = walletPassword,
Recipients = recipients
};
// Register the cold staking builder extension with the transaction builder.
context.TransactionBuilder.Extensions.Add(new ColdStakingBuilderExtension(false));
return context;
}
private List<Recipient> GetRecipients(Script destination, Money overallAmount, bool subtractFeeFromAmount, int splitCount)
{
var recipients = new List<Recipient>();
Money moneyPerRecipient = overallAmount / splitCount;
while (recipients.Count < splitCount)
{
recipients.Add(new Recipient
{
Amount = moneyPerRecipient,
ScriptPubKey = destination,
SubtractFeeFromAmount = false
});
}
if (recipients.Count == 0)
throw new WalletException($"Couldn't construct recipients list.");
recipients.Last().SubtractFeeFromAmount = subtractFeeFromAmount;
return recipients;
}
internal Money EstimateSetupTransactionFee(IWalletTransactionHandler walletTransactionHandler,
string coldWalletAddress, string hotWalletAddress, string walletName, string walletAccount,
string walletPassword, Money amount, bool subtractFeeFromAmount, bool offline, bool useSegwitChangeAddress, int splitCount)
{
TransactionBuildContext context = this.GetSetupTransactionBuildContext(walletTransactionHandler, coldWalletAddress, hotWalletAddress, walletName, walletAccount,
walletPassword, amount, null, subtractFeeFromAmount, offline, useSegwitChangeAddress, splitCount);
Money estimatedFee = walletTransactionHandler.EstimateFee(context);
return estimatedFee;
}
/// <summary>
/// Builds an unsigned transaction template for a cold staking withdrawal transaction.
/// This requires specialised logic due to the lack of a private key for the cold account.
/// </summary>
public BuildOfflineSignResponse BuildOfflineColdStakingWithdrawalRequest(IWalletTransactionHandler walletTransactionHandler, string receivingAddress,
string walletName, string accountName, Money amount, Money feeAmount, bool subtractFeeFromAmount)
{
TransactionBuildContext context = this.GetOfflineWithdrawalBuildContext(receivingAddress, walletName, accountName, amount, feeAmount, subtractFeeFromAmount);
Transaction transactionResult = walletTransactionHandler.BuildTransaction(context);
var utxos = new List<UtxoDescriptor>();
var addresses = new List<AddressDescriptor>();
foreach (ICoin coin in context.TransactionBuilder.FindSpentCoins(transactionResult))
{
utxos.Add(new UtxoDescriptor()
{
Amount = coin.TxOut.Value.ToUnit(MoneyUnit.BTC).ToString(),
TransactionId = coin.Outpoint.Hash.ToString(),
Index = coin.Outpoint.N.ToString(),
ScriptPubKey = coin.TxOut.ScriptPubKey.ToHex()
});
// We do not include address descriptors as the cold staking scripts are not really regarded as having addresses in the conventional sense.
// There is also typically only a single script involved so the keypath hinting is of little use.
}
var hotAccountReference = new WalletAccountReference(walletName, accountName);
// Return transaction hex and UTXO list.
return new BuildOfflineSignResponse()
{
WalletName = hotAccountReference.WalletName,
WalletAccount = hotAccountReference.AccountName,
Fee = context.TransactionFee.ToUnit(MoneyUnit.BTC).ToString(),
UnsignedTransaction = transactionResult.ToHex(),
Utxos = utxos,
Addresses = addresses
};
}
public Money EstimateOfflineWithdrawalFee(IWalletTransactionHandler walletTransactionHandler, string receivingAddress,
string walletName, string accountName, Money amount, bool subtractFeeFromAmount)
{
TransactionBuildContext context = this.GetOfflineWithdrawalBuildContext(receivingAddress, walletName, accountName, amount, null, subtractFeeFromAmount);
context.TransactionBuilder.Extensions.Add(new ColdStakingBuilderExtension(false));
return walletTransactionHandler.EstimateFee(context);
}
private TransactionBuildContext GetOfflineWithdrawalBuildContext(string receivingAddress, string walletName, string accountName, Money amount, Money feeAmount, bool subtractFeeFromAmount)
{
// We presume that the amount given by the user is accurate and optimistically pass it to the build context.
var recipient = new List<Recipient>() { new Recipient() { Amount = amount, ScriptPubKey = BitcoinAddress.Create(receivingAddress, this.network).ScriptPubKey, SubtractFeeFromAmount = subtractFeeFromAmount } };
var hotAccountReference = new WalletAccountReference(walletName, accountName);
// As a simplification, the change address is defaulted to be the same cold staking script the UTXOs originate from.
UnspentOutputReference coldStakingUtxo = this.GetSpendableTransactionsInAccount(hotAccountReference, 0).FirstOrDefault();
if (coldStakingUtxo == null)
{
throw new WalletException("No unspent transactions found in cold staking hot account.");
}
var context = new TransactionBuildContext(this.network)
{
AccountReference = hotAccountReference,
TransactionFee = feeAmount,
MinConfirmations = 0,
Shuffle = true, // We shuffle transaction outputs by default as it's better for anonymity.
Recipients = recipient,
ChangeScript = coldStakingUtxo.Transaction.ScriptPubKey, // We specifically use this instead of ChangeAddress.
Sign = false
};
// As we don't actually know when the signed offline transaction will be broadcast, give it the highest chance of success if no fee was specified.
if (context.TransactionFee == null)
{
context.FeeType = FeeType.High;
}
return context;
}
/// <summary>
/// Creates a cold staking withdrawal <see cref="Transaction"/>.
/// </summary>
/// <remarks>
/// Cold staking withdrawal is performed on the wallet that is in the role of the cold staking cold wallet.
/// </remarks>
/// <param name="walletTransactionHandler">The wallet transaction handler used to build the transaction.</param>
/// <param name="receivingAddress">The address that will receive the withdrawal.</param>
/// <param name="walletName">The name of the wallet in the role of cold wallet.</param>
/// <param name="walletPassword">The wallet password.</param>
/// <param name="amount">The amount to remove from cold staking.</param>
/// <param name="feeAmount">The fee to pay for cold staking transaction withdrawal.</param>
/// <returns>The <see cref="Transaction"/> for cold staking withdrawal.</returns>
/// <exception cref="WalletException">Thrown if the receiving address is in a cold staking account in this wallet.</exception>
/// <exception cref="ArgumentNullException">Thrown if the receiving address is invalid.</exception>
internal Transaction GetColdStakingWithdrawalTransaction(IWalletTransactionHandler walletTransactionHandler, string receivingAddress,
string walletName, string walletPassword, Money amount, Money feeAmount, bool subtractFeeFromAmount)
{
(TransactionBuildContext context, HdAccount coldAccount, Script destination) = this.GetWithdrawalTransactionBuildContext(receivingAddress, walletName, amount, feeAmount, subtractFeeFromAmount);
// Build the withdrawal transaction according to the settings recorded in the context.
Transaction transaction = walletTransactionHandler.BuildTransaction(context);
// Map OutPoint to UnspentOutputReference.
var accountReference = new WalletAccountReference(walletName, coldAccount.Name);
Dictionary<OutPoint, UnspentOutputReference> mapOutPointToUnspentOutput = this.GetSpendableTransactionsInAccount(accountReference)
.ToDictionary(unspent => unspent.ToOutPoint(), unspent => unspent);
// Set the cold staking scriptPubKey on the change output.
TxOut changeOutput = transaction.Outputs.SingleOrDefault(output => (output.ScriptPubKey != destination) && (output.Value != 0));
if (changeOutput != null)
{
// Find the largest input.
TxIn largestInput = transaction.Inputs.OrderByDescending(input => mapOutPointToUnspentOutput[input.PrevOut].Transaction.Amount).Take(1).Single();
// Set the scriptPubKey of the change output to the scriptPubKey of the largest input.
changeOutput.ScriptPubKey = mapOutPointToUnspentOutput[largestInput.PrevOut].Transaction.ScriptPubKey;
}
Wallet.Wallet wallet = this.GetWallet(walletName);
// Add keys for signing inputs. This takes time so only add keys for distinct addresses.
foreach (HdAddress address in transaction.Inputs.Select(i => mapOutPointToUnspentOutput[i.PrevOut].Address).Distinct())
{
context.TransactionBuilder.AddKeys(wallet.GetExtendedPrivateKeyForAddress(walletPassword, address));
}
// Sign the transaction.
context.TransactionBuilder.SignTransactionInPlace(transaction);
this.logger.LogTrace("(-):'{0}'", transaction.GetHash());
return transaction;
}
private (TransactionBuildContext, HdAccount, Script) GetWithdrawalTransactionBuildContext(string receivingAddress, string walletName, Money amount, Money feeAmount, bool subtractFeeFromAmount)
{
Guard.NotEmpty(receivingAddress, nameof(receivingAddress));
Guard.NotEmpty(walletName, nameof(walletName));
Guard.NotNull(amount, nameof(amount));
Wallet.Wallet wallet = this.GetWallet(walletName);
// Get the cold staking account.
HdAccount coldAccount = this.GetColdStakingAccount(wallet, true);
if (coldAccount == null)
{
this.logger.LogTrace("(-)[COLDSTAKE_ACCOUNT_DOES_NOT_EXIST]");
throw new WalletException("The cold wallet account does not exist.");
}
// Prevent reusing cold stake addresses as regular withdrawal addresses.
if (coldAccount.ExternalAddresses.Concat(coldAccount.InternalAddresses).Any(s => s.Address == receivingAddress || s.Bech32Address == receivingAddress))
{
this.logger.LogTrace("(-)[COLDSTAKE_INVALID_COLD_WALLET_ADDRESS_USAGE]");
throw new WalletException("You can't send the money to a cold staking cold wallet account.");
}
HdAccount hotAccount = this.GetColdStakingAccount(wallet, false);
if (hotAccount != null && hotAccount.ExternalAddresses.Concat(hotAccount.InternalAddresses).Any(s => s.Address == receivingAddress || s.Bech32Address == receivingAddress))
{
this.logger.LogTrace("(-)[COLDSTAKE_INVALID_HOT_WALLET_ADDRESS_USAGE]");
throw new WalletException("You can't send the money to a cold staking hot wallet account.");
}
Script destination = null;
if (BitcoinWitPubKeyAddress.IsValid(receivingAddress, this.network, out Exception _))
{
destination = new BitcoinWitPubKeyAddress(receivingAddress, wallet.Network).ScriptPubKey;
}
else
{
// Send the money to the receiving address.
destination = BitcoinAddress.Create(receivingAddress, wallet.Network).ScriptPubKey;
}
// Create the transaction build context (used in BuildTransaction).
var accountReference = new WalletAccountReference(walletName, coldAccount.Name);
var context = new TransactionBuildContext(wallet.Network)
{
AccountReference = accountReference,
// Specify a dummy change address to prevent a change (internal) address from being created.
// Will be changed after the transaction is built and before it is signed.
ChangeAddress = coldAccount.ExternalAddresses.First(),
TransactionFee = feeAmount,
MinConfirmations = 0,
Shuffle = false,
Sign = false,
Recipients = new[] { new Recipient { Amount = amount, ScriptPubKey = destination, SubtractFeeFromAmount = subtractFeeFromAmount } }.ToList()
};
// Register the cold staking builder extension with the transaction builder.
context.TransactionBuilder.Extensions.Add(new ColdStakingBuilderExtension(false));
// Avoid script errors due to missing scriptSig.
context.TransactionBuilder.StandardTransactionPolicy.ScriptVerify = null;
return (context, coldAccount, destination);
}
internal Money EstimateWithdrawalTransactionFee(IWalletTransactionHandler walletTransactionHandler, string receivingAddress,
string walletName, Money amount, bool subtractFeeFromAmount)
{
(TransactionBuildContext context, _, _) = this.GetWithdrawalTransactionBuildContext(receivingAddress, walletName, amount, null, subtractFeeFromAmount);
Money estimatedFee = walletTransactionHandler.EstimateFee(context);
return estimatedFee;
}
/// <summary>
/// Gets the spendable transactions associated with cold wallet addresses.
/// </summary>
/// <param name="walletName">The name of the wallet.</param>
/// <param name="isColdWalletAccount">The cold staking account to get the transactions for.</param>
/// <param name="confirmations">The number of confirmations.</param>
/// <returns>An enumeration of <see cref="UnspentOutputReference"/> items.</returns>
public IEnumerable<UnspentOutputReference> GetSpendableTransactionsInColdWallet(string walletName, bool isColdWalletAccount, int confirmations = 0)
{
Guard.NotEmpty(walletName, nameof(walletName));
Wallet.Wallet wallet = this.GetWallet(walletName);
UnspentOutputReference[] res = null;
lock (this.lockObject)
{
res = wallet.GetAllSpendableTransactions(this.ChainIndexer.Tip.Height, confirmations,
a => a.Index == (isColdWalletAccount ? ColdWalletAccountIndex : HotWalletAccountIndex)).ToArray();
}
this.logger.LogTrace("(-):*.Count={0}", res.Count());
return res;
}
}
}
| 54.748924 | 220 | 0.65566 | [
"MIT"
] | StratisIain/StratisFullNode | src/Stratis.Bitcoin.Features.ColdStaking/ColdStakingManager.cs | 38,162 | C# |
/*
* The MIT License (MIT)
*
* Copyright (c) 2020 Alistair Leslie-Hughes
*
* 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 Microsoft.DirectX.DirectPlay;
using System;
namespace Microsoft.DirectX.DirectPlay
{
public sealed class PlayerRemovedFromGroupEventArgs : EventArgs
{
public RemovePlayerFromGroupMessage Message;
public PlayerRemovedFromGroupEventArgs(RemovePlayerFromGroupMessage dpMessage)
{
}
}
}
| 40.27027 | 84 | 0.755034 | [
"MIT"
] | alesliehughes/monoDX | Microsoft.DirectX.DirectPlay/Microsoft.DirectX.DirectPlay/PlayerRemovedFromGroupEventArgs.cs | 1,490 | C# |
#pragma warning disable SA1310 // Field names should not contain underscore
namespace WinSW.Native
{
internal static class Errors
{
internal const int ERROR_ACCESS_DENIED = 5;
internal const int ERROR_INVALID_HANDLE = 6;
internal const int ERROR_INVALID_PARAMETER = 7;
internal const int ERROR_CANCELLED = 1223;
}
}
| 27.846154 | 76 | 0.70442 | [
"MIT"
] | Create-it-cn/winsw | src/Core/WinSWCore/Native/Errors.cs | 364 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace luval.rpa.navigator
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
//Comment: Showing to the team
//Added a new line
}
}
}
| 23.08 | 65 | 0.618718 | [
"MIT"
] | Niavart/rpa-navigator | code/luval.rpa.navigator/Program.cs | 579 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.Devices.E2ETests.Helpers;
using Microsoft.Azure.Devices.E2ETests.Helpers.Templates;
using Microsoft.Azure.Devices.E2ETests.Messaging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.Azure.Devices.E2ETests
{
public partial class FaultInjectionPoolAmqpTests
{
private readonly string MessageReceive_DevicePrefix = $"MessageReceiveFaultInjectionPoolAmqpTests";
// TODO: #943 - Honor different pool sizes for different connection pool settings.
[Ignore]
[LoggedTestMethod]
public async Task Message_DeviceSak_TcpConnectionLossReceiveRecovery_SingleConnection_Amqp()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.SingleConnection_PoolSize,
PoolingOverAmqp.SingleConnection_DevicesCount,
FaultInjection.FaultType_Tcp,
FaultInjection.FaultCloseReason_Boom)
.ConfigureAwait(false);
}
// TODO: #943 - Honor different pool sizes for different connection pool settings.
[Ignore]
[LoggedTestMethod]
public async Task Message_DeviceSak_TcpConnectionLossReceiveRecovery_SingleConnection_AmqpWs()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.SingleConnection_PoolSize,
PoolingOverAmqp.SingleConnection_DevicesCount,
FaultInjection.FaultType_Tcp,
FaultInjection.FaultCloseReason_Boom)
.ConfigureAwait(false);
}
// TODO: #943 - Honor different pool sizes for different connection pool settings.
[Ignore]
[LoggedTestMethod]
public async Task Message_IoTHubSak_TcpConnectionLossReceiveRecovery_SingleConnection_Amqp()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.SingleConnection_PoolSize,
PoolingOverAmqp.SingleConnection_DevicesCount,
FaultInjection.FaultType_Tcp,
FaultInjection.FaultCloseReason_Boom,
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
// TODO: #943 - Honor different pool sizes for different connection pool settings.
[Ignore]
[LoggedTestMethod]
public async Task Message_IoTHubSak_TcpConnectionLossReceiveRecovery_SingleConnection_AmqpWs()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.SingleConnection_PoolSize,
PoolingOverAmqp.SingleConnection_DevicesCount,
FaultInjection.FaultType_Tcp,
FaultInjection.FaultCloseReason_Boom,
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
// TODO: #943 - Honor different pool sizes for different connection pool settings.
[Ignore]
[LoggedTestMethod]
public async Task Message_DeviceSak_AmqpConnectionLossReceiveRecovery_SingleConnection_Amqp()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.SingleConnection_PoolSize,
PoolingOverAmqp.SingleConnection_DevicesCount,
FaultInjection.FaultType_AmqpConn,
"")
.ConfigureAwait(false);
}
// TODO: #943 - Honor different pool sizes for different connection pool settings.
[Ignore]
[LoggedTestMethod]
public async Task Message_DeviceSak_AmqpConnectionLossReceiveRecovery_SingleConnection_AmqpWs()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.SingleConnection_PoolSize,
PoolingOverAmqp.SingleConnection_DevicesCount,
FaultInjection.FaultType_AmqpConn,
"")
.ConfigureAwait(false);
}
// TODO: #943 - Honor different pool sizes for different connection pool settings.
[Ignore]
[LoggedTestMethod]
public async Task Message_IotHubSak_AmqpConnectionLossReceiveRecovery_SingleConnection_Amqp()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.SingleConnection_PoolSize,
PoolingOverAmqp.SingleConnection_DevicesCount,
FaultInjection.FaultType_AmqpConn,
"",
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
// TODO: #943 - Honor different pool sizes for different connection pool settings.
[Ignore]
[LoggedTestMethod]
public async Task Message_IoTHubSak_AmqpConnectionLossReceiveRecovery_SingleConnection_AmqpWs()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.SingleConnection_PoolSize,
PoolingOverAmqp.SingleConnection_DevicesCount,
FaultInjection.FaultType_AmqpConn,
"",
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
// TODO: #943 - Honor different pool sizes for different connection pool settings.
// TODO: #950 - Link/session faults for message send/ method/ twin operations closes the connection.
[Ignore]
[LoggedTestMethod]
public async Task Message_DeviceSak_AmqpSessionLossReceiveRecovery_SingleConnection_Amqp()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.SingleConnection_PoolSize,
PoolingOverAmqp.SingleConnection_DevicesCount,
FaultInjection.FaultType_AmqpSess,
"")
.ConfigureAwait(false);
}
// TODO: #943 - Honor different pool sizes for different connection pool settings.
// TODO: #950 - Link/session faults for message send/ method/ twin operations closes the connection.
[Ignore]
[LoggedTestMethod]
public async Task Message_DeviceSak_AmqpSessionLossReceiveRecovery_SingleConnection_AmqpWs()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.SingleConnection_PoolSize,
PoolingOverAmqp.SingleConnection_DevicesCount,
FaultInjection.FaultType_AmqpSess,
"")
.ConfigureAwait(false);
}
// TODO: #943 - Honor different pool sizes for different connection pool settings.
// TODO: #950 - Link/session faults for message send/ method/ twin operations closes the connection.
[Ignore]
[LoggedTestMethod]
public async Task Message_IoTHubSak_AmqpSessionLossReceiveRecovery_SingleConnection_Amqp()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.SingleConnection_PoolSize,
PoolingOverAmqp.SingleConnection_DevicesCount,
FaultInjection.FaultType_AmqpSess,
"",
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
// TODO: #943 - Honor different pool sizes for different connection pool settings.
// TODO: #950 - Link/session faults for message send/ method/ twin operations closes the connection.
[Ignore]
[LoggedTestMethod]
public async Task Message_IoTHubSak_AmqpSessionLossReceiveRecovery_SingleConnection_AmqpWs()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.SingleConnection_PoolSize,
PoolingOverAmqp.SingleConnection_DevicesCount,
FaultInjection.FaultType_AmqpSess,
"",
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
// TODO: #943 - Honor different pool sizes for different connection pool settings.
[Ignore]
[LoggedTestMethod]
public async Task Message_DeviceSak_AmqpC2DLinkDropReceiveRecovery_SingleConnection_Amqp()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.SingleConnection_PoolSize,
PoolingOverAmqp.SingleConnection_DevicesCount,
FaultInjection.FaultType_AmqpC2D,
FaultInjection.FaultCloseReason_Boom)
.ConfigureAwait(false);
}
// TODO: #943 - Honor different pool sizes for different connection pool settings.
[Ignore]
[LoggedTestMethod]
public async Task Message_DeviceSak_AmqpC2DLinkDropReceiveRecovery_SingleConnection_AmqpWs()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.SingleConnection_PoolSize,
PoolingOverAmqp.SingleConnection_DevicesCount,
FaultInjection.FaultType_AmqpC2D,
FaultInjection.FaultCloseReason_Boom)
.ConfigureAwait(false);
}
// TODO: #943 - Honor different pool sizes for different connection pool settings.
[Ignore]
[LoggedTestMethod]
public async Task Message_IoTHubSak_AmqpC2DLinkDropReceiveRecovery_SingleConnection_Amqp()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.SingleConnection_PoolSize,
PoolingOverAmqp.SingleConnection_DevicesCount,
FaultInjection.FaultType_AmqpC2D,
FaultInjection.FaultCloseReason_Boom,
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
// TODO: #943 - Honor different pool sizes for different connection pool settings.
[Ignore]
[LoggedTestMethod]
public async Task Message_IoTHubSak_AmqpC2DLinkDropReceiveRecovery_SingleConnection_AmqpWs()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.SingleConnection_PoolSize,
PoolingOverAmqp.SingleConnection_DevicesCount,
FaultInjection.FaultType_AmqpC2D,
FaultInjection.FaultCloseReason_Boom,
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
// TODO: #943 - Honor different pool sizes for different connection pool settings.
[Ignore]
[LoggedTestMethod]
public async Task Message_DeviceSak_GracefulShutdownReceiveRecovery_SingleConnection_Amqp()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.SingleConnection_PoolSize,
PoolingOverAmqp.SingleConnection_DevicesCount,
FaultInjection.FaultType_GracefulShutdownAmqp,
FaultInjection.FaultCloseReason_Bye)
.ConfigureAwait(false);
}
// TODO: #943 - Honor different pool sizes for different connection pool settings.
[Ignore]
[LoggedTestMethod]
public async Task Message_DeviceSak_GracefulShutdownReceiveRecovery_SingleConnection_AmqpWs()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.SingleConnection_PoolSize,
PoolingOverAmqp.SingleConnection_DevicesCount,
FaultInjection.FaultType_GracefulShutdownAmqp,
FaultInjection.FaultCloseReason_Bye)
.ConfigureAwait(false);
}
// TODO: #943 - Honor different pool sizes for different connection pool settings.
[Ignore]
[LoggedTestMethod]
public async Task Message_IoTHubSak_GracefulShutdownReceiveRecovery_SingleConnection_Amqp()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.SingleConnection_PoolSize,
PoolingOverAmqp.SingleConnection_DevicesCount,
FaultInjection.FaultType_GracefulShutdownAmqp,
FaultInjection.FaultCloseReason_Bye,
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
// TODO: #943 - Honor different pool sizes for different connection pool settings.
[Ignore]
[LoggedTestMethod]
public async Task Message_IoTHubSak_GracefulShutdownReceiveRecovery_SingleConnection_AmqpWs()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.SingleConnection_PoolSize,
PoolingOverAmqp.SingleConnection_DevicesCount,
FaultInjection.FaultType_GracefulShutdownAmqp,
FaultInjection.FaultCloseReason_Bye,
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_DeviceSak_TcpConnectionLossReceiveRecovery_MultipleConnections_Amqp()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_Tcp,
FaultInjection.FaultCloseReason_Boom)
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_DeviceSak_TcpConnectionLossReceiveRecovery_MultipleConnections_AmqpWs()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_Tcp,
FaultInjection.FaultCloseReason_Boom)
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_IoTHubSak_TcpConnectionLossReceiveRecovery_MultipleConnections_Amqp()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_Tcp,
FaultInjection.FaultCloseReason_Boom,
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_IoTHubSak_TcpConnectionLossReceiveRecovery_MultipleConnections_AmqpWs()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_Tcp,
FaultInjection.FaultCloseReason_Boom,
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_DeviceSak_AmqpConnectionLossReceiveRecovery_MultipleConnections_Amqp()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_AmqpConn,
"")
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_DeviceSak_AmqpConnectionLossReceiveRecovery_MultipleConnections_AmqpWs()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_AmqpConn,
"")
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_IotHubSak_AmqpConnectionLossReceiveRecovery_MultipleConnections_Amqp()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_AmqpConn,
"",
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_IoTHubSak_AmqpConnectionLossReceiveRecovery_MultipleConnections_AmqpWs()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_AmqpConn,
"",
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
// TODO: #950 - Link/session faults for message send/ method/ twin operations closes the connection.
[LoggedTestMethod]
public async Task Message_DeviceSak_AmqpSessionLossReceiveRecovery_MultipleConnections_Amqp()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_AmqpSess,
"")
.ConfigureAwait(false);
}
// TODO: #950 - Link/session faults for message send/ method/ twin operations closes the connection.
[LoggedTestMethod]
public async Task Message_DeviceSak_AmqpSessionLossReceiveRecovery_MultipleConnections_AmqpWs()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_AmqpSess,
"")
.ConfigureAwait(false);
}
// TODO: #950 - Link/session faults for message send/ method/ twin operations closes the connection.
[LoggedTestMethod]
public async Task Message_IoTHubSak_AmqpSessionLossReceiveRecovery_MultipleConnections_Amqp()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_AmqpSess,
"",
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
// TODO: #950 - Link/session faults for message send/ method/ twin operations closes the connection.
[LoggedTestMethod]
public async Task Message_IoTHubSak_AmqpSessionLossReceiveRecovery_MultipleConnections_AmqpWs()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_AmqpSess,
"",
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
[LoggedTestMethod]
[TestCategory("LongRunning")]
public async Task Message_DeviceSak_AmqpC2DLinkDropReceiveRecovery_MultipleConnections_Amqp()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_AmqpC2D,
FaultInjection.FaultCloseReason_Boom)
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_DeviceSak_AmqpC2DLinkDropReceiveRecovery_MultipleConnections_AmqpWs()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_AmqpC2D,
FaultInjection.FaultCloseReason_Boom)
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_IoTHubSak_AmqpC2DLinkDropReceiveRecovery_MultipleConnections_Amqp()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_AmqpC2D,
FaultInjection.FaultCloseReason_Boom,
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_IoTHubSak_AmqpC2DLinkDropReceiveRecovery_MultipleConnections_AmqpWs()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_AmqpC2D,
FaultInjection.FaultCloseReason_Boom,
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_DeviceSak_GracefulShutdownReceiveRecovery_MultipleConnections_Amqp()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_GracefulShutdownAmqp,
FaultInjection.FaultCloseReason_Bye)
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_DeviceSak_GracefulShutdownReceiveRecovery_MultipleConnections_AmqpWs()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_GracefulShutdownAmqp,
FaultInjection.FaultCloseReason_Bye)
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_IoTHubSak_GracefulShutdownReceiveRecovery_MultipleConnections_Amqp()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_GracefulShutdownAmqp,
FaultInjection.FaultCloseReason_Bye,
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_IoTHubSak_GracefulShutdownReceiveRecovery_MultipleConnections_AmqpWs()
{
await ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_GracefulShutdownAmqp,
FaultInjection.FaultCloseReason_Bye,
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_DeviceSak_TcpConnectionLossReceiveUsingCallbackRecovery_MultipleConnections_Amqp()
{
await ReceiveMessageUsingCallbackRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_Tcp,
FaultInjection.FaultCloseReason_Boom)
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_DeviceSak_TcpConnectionLossReceiveUsingCallbackRecovery_MultipleConnections_AmqpWs()
{
await ReceiveMessageUsingCallbackRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_Tcp,
FaultInjection.FaultCloseReason_Boom)
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_IoTHubSak_TcpConnectionLossReceiveUsingCallbackRecovery_MultipleConnections_Amqp()
{
await ReceiveMessageUsingCallbackRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_Tcp,
FaultInjection.FaultCloseReason_Boom,
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_IoTHubSak_TcpConnectionLossReceiveUsingCallbackRecovery_MultipleConnections_AmqpWs()
{
await ReceiveMessageUsingCallbackRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_Tcp,
FaultInjection.FaultCloseReason_Boom,
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_DeviceSak_AmqpConnectionLossReceiveUsingCallbackRecovery_MultipleConnections_Amqp()
{
await ReceiveMessageUsingCallbackRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_AmqpConn,
"")
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_DeviceSak_AmqpConnectionLossReceiveUsingCallbackRecovery_MultipleConnections_AmqpWs()
{
await ReceiveMessageUsingCallbackRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_AmqpConn,
"")
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_IotHubSak_AmqpConnectionLossReceiveUsingCallbackRecovery_MultipleConnections_Amqp()
{
await ReceiveMessageUsingCallbackRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_AmqpConn,
"",
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_IoTHubSak_AmqpConnectionLossReceiveUsingCallbackRecovery_MultipleConnections_AmqpWs()
{
await ReceiveMessageUsingCallbackRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_AmqpConn,
"",
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
// TODO: #950 - Link/session faults for message send/ method/ twin operations closes the connection.
[LoggedTestMethod]
public async Task Message_DeviceSak_AmqpSessionLossReceiveUsingCallbackRecovery_MultipleConnections_Amqp()
{
await ReceiveMessageUsingCallbackRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_AmqpSess,
"")
.ConfigureAwait(false);
}
// TODO: #950 - Link/session faults for message send/ method/ twin operations closes the connection.
[LoggedTestMethod]
public async Task Message_DeviceSak_AmqpSessionLossReceiveUsingCallbackRecovery_MultipleConnections_AmqpWs()
{
await ReceiveMessageUsingCallbackRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_AmqpSess,
"")
.ConfigureAwait(false);
}
// TODO: #950 - Link/session faults for message send/ method/ twin operations closes the connection.
[LoggedTestMethod]
public async Task Message_IoTHubSak_AmqpSessionLossReceiveUsingCallbackRecovery_MultipleConnections_Amqp()
{
await ReceiveMessageUsingCallbackRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_AmqpSess,
"",
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
// TODO: #950 - Link/session faults for message send/ method/ twin operations closes the connection.
[LoggedTestMethod]
public async Task Message_IoTHubSak_AmqpSessionLossReceiveUsingCallbackRecovery_MultipleConnections_AmqpWs()
{
await ReceiveMessageUsingCallbackRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_AmqpSess,
"",
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
[LoggedTestMethod]
[TestCategory("LongRunning")]
public async Task Message_DeviceSak_AmqpC2DLinkDropReceiveUsingCallbackRecovery_MultipleConnections_Amqp()
{
await ReceiveMessageUsingCallbackRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_AmqpC2D,
FaultInjection.FaultCloseReason_Boom)
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_DeviceSak_AmqpC2DLinkDropReceiveUsingCallbackRecovery_MultipleConnections_AmqpWs()
{
await ReceiveMessageUsingCallbackRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_AmqpC2D,
FaultInjection.FaultCloseReason_Boom)
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_IoTHubSak_AmqpC2DLinkDropReceiveUsingCallbackRecovery_MultipleConnections_Amqp()
{
await ReceiveMessageUsingCallbackRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_AmqpC2D,
FaultInjection.FaultCloseReason_Boom,
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_IoTHubSak_AmqpC2DLinkDropReceiveUsingCallbackRecovery_MultipleConnections_AmqpWs()
{
await ReceiveMessageUsingCallbackRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_AmqpC2D,
FaultInjection.FaultCloseReason_Boom,
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_DeviceSak_GracefulShutdownReceiveUsingCallbackRecovery_MultipleConnections_Amqp()
{
await ReceiveMessageUsingCallbackRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_GracefulShutdownAmqp,
FaultInjection.FaultCloseReason_Bye)
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_DeviceSak_GracefulShutdownReceiveUsingCallbackRecovery_MultipleConnections_AmqpWs()
{
await ReceiveMessageUsingCallbackRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_GracefulShutdownAmqp,
FaultInjection.FaultCloseReason_Bye)
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_IoTHubSak_GracefulShutdownReceiveUsingCallbackRecovery_MultipleConnections_Amqp()
{
await ReceiveMessageUsingCallbackRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_Tcp_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_GracefulShutdownAmqp,
FaultInjection.FaultCloseReason_Bye,
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
[LoggedTestMethod]
public async Task Message_IoTHubSak_GracefulShutdownReceiveUsingCallbackRecovery_MultipleConnections_AmqpWs()
{
await ReceiveMessageUsingCallbackRecoveryPoolOverAmqpAsync(
TestDeviceType.Sasl,
Client.TransportType.Amqp_WebSocket_Only,
PoolingOverAmqp.MultipleConnections_PoolSize,
PoolingOverAmqp.MultipleConnections_DevicesCount,
FaultInjection.FaultType_GracefulShutdownAmqp,
FaultInjection.FaultCloseReason_Bye,
authScope: ConnectionStringAuthScope.IoTHub)
.ConfigureAwait(false);
}
private async Task ReceiveMessageRecoveryPoolOverAmqpAsync(
TestDeviceType type,
Client.TransportType transport,
int poolSize,
int devicesCount,
string faultType,
string reason,
int delayInSec = FaultInjection.DefaultDelayInSec,
int durationInSec = FaultInjection.DefaultDurationInSec,
ConnectionStringAuthScope authScope = ConnectionStringAuthScope.Device,
string proxyAddress = null)
{
// Initialize the service client
var serviceClient = ServiceClient.CreateFromConnectionString(Configuration.IoTHub.ConnectionString);
async Task TestOperationAsync(DeviceClient deviceClient, TestDevice testDevice, TestDeviceCallbackHandler _)
{
(Message msg, string payload, string p1Value) = MessageReceiveE2ETests.ComposeC2dTestMessage(Logger);
Logger.Trace($"{nameof(FaultInjectionPoolAmqpTests)}: Sending message to device {testDevice.Id}: payload='{payload}' p1Value='{p1Value}'");
await serviceClient.SendAsync(testDevice.Id, msg)
.ConfigureAwait(false);
Logger.Trace($"{nameof(FaultInjectionPoolAmqpTests)}: Preparing to receive message for device {testDevice.Id}");
await deviceClient.OpenAsync()
.ConfigureAwait(false);
await MessageReceiveE2ETests.VerifyReceivedC2DMessageAsync(transport, deviceClient, testDevice.Id, msg, payload, Logger)
.ConfigureAwait(false);
}
async Task CleanupOperationAsync(IList<DeviceClient> deviceClients)
{
await serviceClient.CloseAsync()
.ConfigureAwait(false);
serviceClient.Dispose();
foreach (DeviceClient deviceClient in deviceClients)
{
deviceClient.Dispose();
}
}
await FaultInjectionPoolingOverAmqp
.TestFaultInjectionPoolAmqpAsync(
MessageReceive_DevicePrefix,
transport,
proxyAddress,
poolSize,
devicesCount,
faultType,
reason,
delayInSec,
durationInSec,
(d, t, h) => { return Task.FromResult(false); },
TestOperationAsync,
CleanupOperationAsync,
authScope,
Logger)
.ConfigureAwait(false);
}
private async Task ReceiveMessageUsingCallbackRecoveryPoolOverAmqpAsync(
TestDeviceType type,
Client.TransportType transport,
int poolSize,
int devicesCount,
string faultType,
string reason,
int delayInSec = FaultInjection.DefaultDelayInSec,
int durationInSec = FaultInjection.DefaultDurationInSec,
ConnectionStringAuthScope authScope = ConnectionStringAuthScope.Device,
string proxyAddress = null)
{
// Initialize the service client
var serviceClient = ServiceClient.CreateFromConnectionString(Configuration.IoTHub.ConnectionString);
async Task InitOperationAsync(DeviceClient deviceClient, TestDevice testDevice, TestDeviceCallbackHandler testDeviceCallbackHandler)
{
await testDeviceCallbackHandler.SetMessageReceiveCallbackHandlerAsync().ConfigureAwait(false);
}
async Task TestOperationAsync(DeviceClient deviceClient, TestDevice testDevice, TestDeviceCallbackHandler testDeviceCallbackHandler)
{
var timeout = TimeSpan.FromSeconds(20);
using var cts = new CancellationTokenSource(timeout);
(Message msg, string payload, string p1Value) = MessageReceiveE2ETests.ComposeC2dTestMessage(Logger);
testDeviceCallbackHandler.ExpectedMessageSentByService = msg;
await serviceClient.SendAsync(testDevice.Id, msg).ConfigureAwait(false);
Logger.Trace($"{nameof(FaultInjectionPoolAmqpTests)}: Sent message to device {testDevice.Id}: payload='{payload}' p1Value='{p1Value}'");
Client.Message receivedMessage = await deviceClient.ReceiveAsync(timeout).ConfigureAwait(false);
await testDeviceCallbackHandler.WaitForReceiveMessageCallbackAsync(cts.Token).ConfigureAwait(false);
receivedMessage.Should().BeNull();
}
async Task CleanupOperationAsync(IList<DeviceClient> deviceClients)
{
await serviceClient.CloseAsync().ConfigureAwait(false);
serviceClient.Dispose();
foreach (DeviceClient deviceClient in deviceClients)
{
deviceClient.Dispose();
}
}
await FaultInjectionPoolingOverAmqp
.TestFaultInjectionPoolAmqpAsync(
MessageReceive_DevicePrefix,
transport,
proxyAddress,
poolSize,
devicesCount,
faultType,
reason,
delayInSec,
durationInSec,
InitOperationAsync,
TestOperationAsync,
CleanupOperationAsync,
authScope,
Logger)
.ConfigureAwait(false);
}
}
}
| 46.988131 | 155 | 0.628123 | [
"MIT"
] | isabella232/azure-iot-sdk-csharp | e2e/test/iothub/messaging/FaultInjectionPoolAmqpTests.MessageReceiveFaultInjectionPoolAmqpTests.cs | 47,507 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.FunctionalTests
{
public class ApplicationModelTest : IClassFixture<MvcTestFixture<ApplicationModelWebSite.Startup>>
{
public ApplicationModelTest(MvcTestFixture<ApplicationModelWebSite.Startup> fixture)
{
Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact]
public async Task ControllerModel_CustomizedWithAttribute()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/CoolController/GetControllerName");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal("CoolController", body);
}
[Fact]
public async Task ActionModel_CustomizedWithAttribute()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/ActionModel/ActionName");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal("ActionName", body);
}
[Fact]
public async Task ParameterModel_CustomizedWithAttribute()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/ParameterModel/GetParameterMetadata");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal("CoolMetadata", body);
}
[Fact]
public async Task ApplicationModel_AddPropertyToActionDescriptor_FromApplicationModel()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/Home/GetCommonDescription");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal("Common Application Description", body);
}
[Fact]
public async Task ApplicationModel_AddPropertyToActionDescriptor_ControllerModelOverwritesCommonApplicationProperty()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/ApplicationModel/GetControllerDescription");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal("Common Controller Description", body);
}
[Fact]
public async Task ApplicationModel_ProvidesMetadataToActionDescriptor_ActionModelOverwritesControllerModelProperty()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/ApplicationModel/GetActionSpecificDescription");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal("Specific Action Description", body);
}
[Fact]
public async Task ApplicationModelExtensions_AddsConventionToAllControllers()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/License/GetLicense");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal("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.", body);
}
[Fact]
public async Task ApplicationModelExtensions_AddsConventionToAllActions()
{
// Arrange
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Home/GetHelloWorld");
request.Headers.Add("helloWorld", "HelloWorld");
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal("From Header - HelloWorld", body);
}
[Fact]
public async Task ActionModelSuppressedForPathMatching_CannotBeRouted()
{
// Arrange & Act
var response = await Client.GetAsync("Home/CannotBeRouted");
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task ActionModelNotSuppressedForPathMatching_CanBeRouted()
{
// Arrange & Act
var response = await Client.GetStringAsync("Home/CanBeRouted");
// Assert
Assert.Equal("Hello world", response);
}
[Fact]
public async Task ActionModelSuppressedForLinkGeneration_CannotBeLinked()
{
// Act & Assert
var ex = await Assert.ThrowsAsync<InvalidOperationException>(
() => Client.GetStringAsync("Home/RouteToSuppressLinkGeneration"));
Assert.Equal("No route matches the supplied values.", ex.Message);
}
[Fact]
public async Task ActionModelSuppressedForPathMatching_CanBeLinked()
{
// Arrange & Act
var response = await Client.GetAsync("Home/RouteToSuppressPathMatching");
// Assert
Assert.Equal("/Home/CannotBeRouted", response.Headers.Location.ToString());
}
[Theory]
[InlineData("Products", "Products View")]
[InlineData("Services", "Services View")]
[InlineData("Manage", "Manage View")]
public async Task ApplicationModel_CanDuplicateController_InMultipleAreas(string areaName, string expectedContent)
{
// Arrange & Act
var response = await Client.GetAsync(areaName + "/MultipleAreas/Index");
var content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains(expectedContent, content);
}
[Theory]
[InlineData("Help", "This is the help page")]
[InlineData("MoreHelp", "This is the more help page")]
public async Task ControllerModel_CanDuplicateActions_RoutesToDifferentNames(string actionName, string expectedContent)
{
// Arrange & Act
var response = await Client.GetAsync("ActionModel/" + actionName);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var body = await response.Content.ReadAsStringAsync();
Assert.Contains(expectedContent, body);
}
}
} | 36.45 | 127 | 0.62332 | [
"Apache-2.0"
] | aneequrrehman/Mvc | test/Microsoft.AspNetCore.Mvc.FunctionalTests/ApplicationModelTest.cs | 7,290 | C# |
namespace AuroraScript.Exceptions
{
public class AuroraScriptException : Exception
{
internal AuroraScriptException(String message) : base(message)
{
}
}
}
| 16.25 | 70 | 0.641026 | [
"MIT"
] | vblegend/AuroraScript | AuroraScript/Exceptions/AuroraScriptException.cs | 197 | C# |
// Copyright 2017-2018 Dirk Lemstra (https://github.com/dlemstra/line-bot-sdk-dotnet)
//
// Dirk Lemstra 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:
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Line.Tests
{
[TestClass]
public class MessageTests
{
private const string AudioJson = "Events/Messages/Audio.json";
private const string ImageJson = "Events/Messages/Image.json";
private const string InvalidJson = "Events/Invalid.json";
private const string InvalidMesssageJson = "Events/Messages/InvalidMessage.json";
private const string LocationJson = "Events/Messages/Location.json";
private const string MessageEventWithoutMessageJson = "Events/Messages/MessageEventWithoutMessage.json";
private const string StickerJson = "Events/Messages/Sticker.json";
private const string TextJson = "Events/Messages/Text.json";
private const string VideoJson = "Events/Messages/Video.json";
[TestMethod]
[DeploymentItem(MessageEventWithoutMessageJson)]
public async Task GetEvents_RequestWithoutMessage_MessageIsNull()
{
ILineBot bot = TestConfiguration.CreateBot();
TestHttpRequest request = new TestHttpRequest(MessageEventWithoutMessageJson);
IEnumerable<ILineEvent> events = await bot.GetEvents(request);
Assert.IsNotNull(events);
Assert.AreEqual(1, events.Count());
ILineEvent lineEvent = events.First();
Assert.AreEqual(LineEventType.Message, lineEvent.EventType);
Assert.IsNull(lineEvent.Message);
}
[TestMethod]
[DeploymentItem(InvalidMesssageJson)]
public async Task GetEvents_InvalidMessageType_MessageTypeIsUnknown()
{
ILineBot bot = TestConfiguration.CreateBot();
TestHttpRequest request = new TestHttpRequest(InvalidMesssageJson);
IEnumerable<ILineEvent> events = await bot.GetEvents(request);
Assert.AreEqual(1, events.Count());
ILineEvent lineEvent = events.First();
Assert.IsNotNull(lineEvent.Message);
Assert.AreEqual(MessageType.Unknown, lineEvent.Message.MessageType);
}
[TestMethod]
[DeploymentItem(InvalidJson)]
public async Task GetEvents_InvalidRequest_MessageIsNull()
{
ILineBot bot = TestConfiguration.CreateBot();
TestHttpRequest request = new TestHttpRequest(InvalidJson);
IEnumerable<ILineEvent> events = await bot.GetEvents(request);
Assert.AreEqual(1, events.Count());
ILineEvent lineEvent = events.First();
Assert.IsNull(lineEvent.Message);
}
[TestMethod]
[DeploymentItem(AudioJson)]
public async Task Group_MessageTypeIsAudio_ReturnsMessage()
{
ILineBot bot = TestConfiguration.CreateBot();
TestHttpRequest request = new TestHttpRequest(AudioJson);
IEnumerable<ILineEvent> events = await bot.GetEvents(request);
Assert.AreEqual(1, events.Count());
ILineEvent lineEvent = events.First();
IEventSource source = lineEvent.Source;
Assert.IsNotNull(source);
Assert.AreEqual(EventSourceType.User, source.SourceType);
Assert.AreEqual("U206d25c2ea6bd87c17655609a1c37cb8", source.User.Id);
Assert.AreEqual("nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", lineEvent.ReplyToken);
Assert.IsNotNull(lineEvent.Message);
Assert.AreEqual("325708", lineEvent.Message.Id);
Assert.IsNull(lineEvent.Message.Location);
Assert.AreEqual(MessageType.Audio, lineEvent.Message.MessageType);
Assert.AreEqual("nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", lineEvent.Message.ReplyToken);
Assert.IsNull(lineEvent.Message.Sticker);
Assert.IsNull(lineEvent.Message.Text);
}
[TestMethod]
[DeploymentItem(ImageJson)]
public async Task Group_MessageTypeIsImage_ReturnsMessage()
{
ILineBot bot = TestConfiguration.CreateBot();
TestHttpRequest request = new TestHttpRequest(ImageJson);
IEnumerable<ILineEvent> events = await bot.GetEvents(request);
Assert.AreEqual(1, events.Count());
ILineEvent lineEvent = events.First();
IEventSource source = lineEvent.Source;
Assert.IsNotNull(source);
Assert.AreEqual(EventSourceType.User, source.SourceType);
Assert.AreEqual("U206d25c2ea6bd87c17655609a1c37cb8", source.User.Id);
Assert.AreEqual("nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", lineEvent.ReplyToken);
Assert.IsNotNull(lineEvent.Message);
Assert.AreEqual("325708", lineEvent.Message.Id);
Assert.IsNull(lineEvent.Message.Location);
Assert.AreEqual(MessageType.Image, lineEvent.Message.MessageType);
Assert.AreEqual("nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", lineEvent.Message.ReplyToken);
Assert.IsNull(lineEvent.Message.Sticker);
Assert.IsNull(lineEvent.Message.Text);
}
[TestMethod]
[DeploymentItem(LocationJson)]
public async Task Group_MessageTypeIsLocation_ReturnsMessage()
{
ILineBot bot = TestConfiguration.CreateBot();
TestHttpRequest request = new TestHttpRequest(LocationJson);
IEnumerable<ILineEvent> events = await bot.GetEvents(request);
Assert.AreEqual(1, events.Count());
ILineEvent lineEvent = events.First();
IEventSource source = lineEvent.Source;
Assert.IsNotNull(source);
Assert.AreEqual(EventSourceType.User, source.SourceType);
Assert.AreEqual("U206d25c2ea6bd87c17655609a1c37cb8", source.User.Id);
Assert.AreEqual("nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", lineEvent.ReplyToken);
Assert.IsNotNull(lineEvent.Message);
Assert.AreEqual("325708", lineEvent.Message.Id);
Assert.AreEqual(MessageType.Location, lineEvent.Message.MessageType);
Assert.AreEqual("nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", lineEvent.Message.ReplyToken);
Assert.IsNull(lineEvent.Message.Text);
Assert.IsNull(lineEvent.Message.Sticker);
ILocation location = lineEvent.Message.Location;
Assert.IsNotNull(location);
Assert.AreEqual("〒150-0002 東京都渋谷区渋谷2丁目21−1", location.Address);
Assert.AreEqual(35.65910807942215m, location.Latitude);
Assert.AreEqual(139.70372892916203m, location.Longitude);
Assert.AreEqual("my location", location.Title);
}
[TestMethod]
[DeploymentItem(StickerJson)]
public async Task Group_MessageTypeIsSticker_ReturnsMessage()
{
ILineBot bot = TestConfiguration.CreateBot();
TestHttpRequest request = new TestHttpRequest(StickerJson);
IEnumerable<ILineEvent> events = await bot.GetEvents(request);
Assert.AreEqual(1, events.Count());
ILineEvent lineEvent = events.First();
IEventSource source = lineEvent.Source;
Assert.IsNotNull(source);
Assert.AreEqual(EventSourceType.User, source.SourceType);
Assert.AreEqual("U206d25c2ea6bd87c17655609a1c37cb8", source.User.Id);
Assert.AreEqual("nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", lineEvent.ReplyToken);
Assert.IsNotNull(lineEvent.Message);
Assert.AreEqual("325708", lineEvent.Message.Id);
Assert.IsNull(lineEvent.Message.Location);
Assert.AreEqual(MessageType.Sticker, lineEvent.Message.MessageType);
Assert.AreEqual("nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", lineEvent.Message.ReplyToken);
Assert.IsNull(lineEvent.Message.Text);
ISticker sticker = lineEvent.Message.Sticker;
Assert.IsNotNull(sticker);
Assert.AreEqual("1", sticker.PackageId);
Assert.AreEqual("2", sticker.StickerId);
}
[TestMethod]
[DeploymentItem(TextJson)]
public async Task Group_MessageTypeIsText_ReturnsMessage()
{
ILineBot bot = TestConfiguration.CreateBot();
TestHttpRequest request = new TestHttpRequest(TextJson);
IEnumerable<ILineEvent> events = await bot.GetEvents(request);
Assert.AreEqual(1, events.Count());
ILineEvent lineEvent = events.First();
IEventSource source = lineEvent.Source;
Assert.IsNotNull(source);
Assert.AreEqual(EventSourceType.User, source.SourceType);
Assert.AreEqual("U206d25c2ea6bd87c17655609a1c37cb8", source.User.Id);
Assert.AreEqual("nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", lineEvent.ReplyToken);
Assert.IsNotNull(lineEvent.Message);
Assert.AreEqual("325708", lineEvent.Message.Id);
Assert.IsNull(lineEvent.Message.Location);
Assert.AreEqual(MessageType.Text, lineEvent.Message.MessageType);
Assert.AreEqual("nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", lineEvent.Message.ReplyToken);
Assert.IsNull(lineEvent.Message.Sticker);
Assert.AreEqual("Hello, world", lineEvent.Message.Text);
}
[TestMethod]
[DeploymentItem(VideoJson)]
public async Task Group_MessageTypeIsVideo_ReturnsMessage()
{
ILineBot bot = TestConfiguration.CreateBot();
TestHttpRequest request = new TestHttpRequest(VideoJson);
IEnumerable<ILineEvent> events = await bot.GetEvents(request);
Assert.AreEqual(1, events.Count());
ILineEvent lineEvent = events.First();
IEventSource source = lineEvent.Source;
Assert.IsNotNull(source);
Assert.AreEqual(EventSourceType.User, source.SourceType);
Assert.AreEqual("U206d25c2ea6bd87c17655609a1c37cb8", source.User.Id);
Assert.AreEqual("nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", lineEvent.ReplyToken);
Assert.IsNotNull(lineEvent.Message);
Assert.AreEqual("325708", lineEvent.Message.Id);
Assert.IsNull(lineEvent.Message.Location);
Assert.AreEqual(MessageType.Video, lineEvent.Message.MessageType);
Assert.AreEqual("nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", lineEvent.Message.ReplyToken);
Assert.IsNull(lineEvent.Message.Sticker);
Assert.IsNull(lineEvent.Message.Text);
}
}
}
| 42.755725 | 112 | 0.66747 | [
"Apache-2.0"
] | Ben67366/line-bot-sdk-dotnet | tests/LineBot.Tests/Events/Messages/MessageTests.cs | 11,236 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the directconnect-2012-10-25.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.DirectConnect.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.DirectConnect.Model.Internal.MarshallTransformations
{
/// <summary>
/// AllocatePrivateVirtualInterface Request Marshaller
/// </summary>
public class AllocatePrivateVirtualInterfaceRequestMarshaller : IMarshaller<IRequest, AllocatePrivateVirtualInterfaceRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((AllocatePrivateVirtualInterfaceRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(AllocatePrivateVirtualInterfaceRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.DirectConnect");
string target = "OvertureService.AllocatePrivateVirtualInterface";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.HttpMethod = "POST";
string uriResourcePath = "/";
request.ResourcePath = uriResourcePath;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetConnectionId())
{
context.Writer.WritePropertyName("connectionId");
context.Writer.Write(publicRequest.ConnectionId);
}
if(publicRequest.IsSetNewPrivateVirtualInterfaceAllocation())
{
context.Writer.WritePropertyName("newPrivateVirtualInterfaceAllocation");
context.Writer.WriteObjectStart();
var marshaller = NewPrivateVirtualInterfaceAllocationMarshaller.Instance;
marshaller.Marshall(publicRequest.NewPrivateVirtualInterfaceAllocation, context);
context.Writer.WriteObjectEnd();
}
if(publicRequest.IsSetOwnerAccount())
{
context.Writer.WritePropertyName("ownerAccount");
context.Writer.Write(publicRequest.OwnerAccount);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
}
} | 38.085714 | 177 | 0.644911 | [
"Apache-2.0"
] | Bynder/aws-sdk-net | sdk/src/Services/DirectConnect/Generated/Model/Internal/MarshallTransformations/AllocatePrivateVirtualInterfaceRequestMarshaller.cs | 3,999 | C# |
// Copyright (c) Christof Senn. All rights reserved. See license.txt in the project root for license information.
namespace Remote.Linq
{
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
public interface IAsyncRemoteQueryProvider : IRemoteQueryProvider
{
Task<TResult> ExecuteAsync<TResult>(Expression expression, CancellationToken cancellationToken);
}
}
| 30.5 | 114 | 0.75644 | [
"MIT"
] | mrmandrake/maoui | Remote.Linq/IAsyncRemoteQueryProvider.cs | 429 | C# |
namespace YKToolkit.Controls
{
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shell;
/// <summary>
/// YKToolkit.Controls のテーマに則った Window コントロールを表します。
/// </summary>
[TemplatePart(Name = PART_IconButton, Type = typeof(Button))]
[TemplatePart(Name = PART_CloseButton, Type = typeof(Button))]
[TemplatePart(Name = PART_RestoreButton, Type = typeof(Button))]
[TemplatePart(Name = PART_MaximizeButton, Type = typeof(Button))]
[TemplatePart(Name = PART_MinimizeButton, Type = typeof(Button))]
[TemplatePart(Name = PART_TopmostButton, Type = typeof(Button))]
[TemplatePart(Name = PART_ChangeThemeButton, Type = typeof(Button))]
public class Window : System.Windows.Window
{
#region TemplatePart
private const string PART_IconButton = "PART_IconButton";
private const string PART_CloseButton = "PART_CloseButton";
private const string PART_RestoreButton = "PART_RestoreButton";
private const string PART_MaximizeButton = "PART_MaximizeButton";
private const string PART_MinimizeButton = "PART_MinimizeButton";
private const string PART_TopmostButton = "PART_TopmostButton";
private const string PART_ChangeThemeButton = "PART_ChangeThemeButton";
private Button _iconButton;
private Button IconButton
{
get { return _iconButton; }
set
{
if (_iconButton != null)
{
_iconButton.MouseDoubleClick -= IconButtonDoubleClick;
}
_iconButton = value;
if (_iconButton != null)
{
_iconButton.MouseDoubleClick += IconButtonDoubleClick;
}
}
}
private Button _closeButton;
private Button CloseButton
{
get { return _closeButton; }
set
{
if (_closeButton != null)
{
_closeButton.Click -= CloseButtonClick;
}
_closeButton = value;
if (_closeButton != null)
{
_closeButton.Click += CloseButtonClick;
}
}
}
private Button _restoreButton;
private Button RestoreButton
{
get { return _restoreButton; }
set
{
if (_restoreButton != null)
{
_restoreButton.Click -= RestoreButtonClick;
}
_restoreButton = value;
if (_restoreButton != null)
{
_restoreButton.Click += RestoreButtonClick;
}
}
}
private Button _maximizeButton;
private Button MaximizeButton
{
get { return _maximizeButton; }
set
{
if (_maximizeButton != null)
{
_maximizeButton.Click -= MaximizeButtonClick;
}
_maximizeButton = value;
if (_maximizeButton != null)
{
_maximizeButton.Click += MaximizeButtonClick;
}
}
}
private Button _minimizeButton;
private Button MinimizeButton
{
get { return _minimizeButton; }
set
{
if (_minimizeButton != null)
{
_minimizeButton.Click -= MinimizeButtonClick;
}
_minimizeButton = value;
if (_minimizeButton != null)
{
_minimizeButton.Click += MinimizeButtonClick;
}
}
}
private Button _topmostButton;
private Button TopmostButton
{
get { return _topmostButton; }
set
{
if (_topmostButton != null)
{
_topmostButton.Click -= TopmostButtonClick;
}
_topmostButton = value;
if (_topmostButton != null)
{
_topmostButton.Click += TopmostButtonClick;
}
}
}
private Button _changeThemeButton;
private Button ChangeThemeButton
{
get { return _changeThemeButton; }
set
{
if (_changeThemeButton != null)
{
_changeThemeButton.Click -= ChangeThemeButtonClick;
}
_changeThemeButton = value;
if (_changeThemeButton != null)
{
_changeThemeButton.Click += ChangeThemeButtonClick;
}
}
}
/// <summary>
/// テンプレート適用時の処理
/// </summary>
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
this.IconButton = this.Template.FindName(PART_IconButton, this) as Button;
this.CloseButton = this.Template.FindName(PART_CloseButton, this) as Button;
this.RestoreButton = this.Template.FindName(PART_RestoreButton, this) as Button;
this.MaximizeButton = this.Template.FindName(PART_MaximizeButton, this) as Button;
this.MinimizeButton = this.Template.FindName(PART_MinimizeButton, this) as Button;
this.TopmostButton = this.Template.FindName(PART_TopmostButton, this) as Button;
this.ChangeThemeButton = this.Template.FindName(PART_ChangeThemeButton, this) as Button;
UpdateResizeBorderThickness();
}
#endregion TemplatePart
#region CaptionFontSize プロパティ
/// <summary>
/// CaptionFontSize 依存関係プロパティの定義
/// </summary>
public static readonly DependencyProperty CaptionFontSizeProperty = DependencyProperty.Register("CaptionFontSize", typeof(double?), typeof(Window), new PropertyMetadata(16.0));
/// <summary>
/// キャプションバーに表示するキャプションのフォントサイズを取得または設定します。
/// </summary>
public double? CaptionFontSize
{
get { return (double?)GetValue(CaptionFontSizeProperty); }
set { SetValue(CaptionFontSizeProperty, value); }
}
#endregion CaptionFontSize プロパティ
#region CaptionLeftContent プロパティ
/// <summary>
/// CaptionLeftContent 依存関係プロパティの定義
/// </summary>
public static readonly DependencyProperty CaptionLeftContentProperty = DependencyProperty.Register("CaptionLeftContent", typeof(object), typeof(Window), new PropertyMetadata(null));
/// <summary>
/// キャプションバーに表示するコンテンツを取得または設定します。
/// </summary>
public object CaptionLeftContent
{
get { return GetValue(CaptionLeftContentProperty); }
set { SetValue(CaptionLeftContentProperty, value); }
}
#endregion CaptionLeftContent プロパティ
#region CaptionRightContent プロパティ
/// <summary>
/// CaptionRightContent 依存関係プロパティの定義
/// </summary>
public static readonly DependencyProperty CaptionRightContentProperty = DependencyProperty.Register("CaptionRightContent", typeof(object), typeof(Window), new PropertyMetadata(null));
/// <summary>
/// キャプションバーに表示するコンテンツを取得または設定します。
/// </summary>
public object CaptionRightContent
{
get { return GetValue(CaptionRightContentProperty); }
set { SetValue(CaptionRightContentProperty, value); }
}
#endregion CaptionRightContent プロパティ
#region SystemMenuContent プロパティ
/// <summary>
/// SystemMenuContent 依存関係プロパティの定義
/// </summary>
public static readonly DependencyProperty SystemMenuContentProperty = DependencyProperty.Register("SystemMenuContent", typeof(object), typeof(Window), new PropertyMetadata(null));
/// <summary>
/// システムメニューとして表示するコンテンツを取得または設定します。
/// </summary>
public object SystemMenuContent
{
get { return GetValue(SystemMenuContentProperty); }
set { SetValue(SystemMenuContentProperty, value); }
}
#endregion SystemMenuContent プロパティ
#region IsClosingConfirmationEnabled プロパティ
/// <summary>
/// IsClosingConfirmationEnabled 依存関係プロパティの定義
/// </summary>
public static readonly DependencyProperty IsClosingConfirmationEnabledProperty = DependencyProperty.Register("IsClosingConfirmationEnabled", typeof(bool), typeof(Window), new PropertyMetadata(true));
/// <summary>
/// ウィンドウを閉じることを確認するかどうかを取得または設定します。
/// </summary>
public bool IsClosingConfirmationEnabled
{
get { return (bool)GetValue(IsClosingConfirmationEnabledProperty); }
set { SetValue(IsClosingConfirmationEnabledProperty, value); }
}
#endregion IsClosingConfirmationEnabled プロパティ
#region ClosingConfirmationMessage プロパティ
/// <summary>
/// ClosingConfirmationMessage 依存関係プロパティの定義
/// </summary>
public static readonly DependencyProperty ClosingConfirmationMessageProperty = DependencyProperty.Register("ClosingConfirmationMessage", typeof(string), typeof(Window), new PropertyMetadata("Do you really want to exit this application?"));
/// <summary>
/// ウィンドウを閉じることを確認するかどうかを取得または設定します。
/// </summary>
public string ClosingConfirmationMessage
{
get { return (string)GetValue(ClosingConfirmationMessageProperty); }
set { SetValue(ClosingConfirmationMessageProperty, value); }
}
#endregion ClosingConfirmationMessage プロパティ
#region ClosingConfirmationTitle プロパティ
/// <summary>
/// ClosingConfirmationTitle 依存関係プロパティの定義
/// </summary>
public static readonly DependencyProperty ClosingConfirmationTitleProperty = DependencyProperty.Register("ClosingConfirmationTitle", typeof(string), typeof(Window), new PropertyMetadata("Confirmation"));
/// <summary>
/// ウィンドウを閉じることを確認するかどうかを取得または設定します。
/// </summary>
public string ClosingConfirmationTitle
{
get { return (string)GetValue(ClosingConfirmationTitleProperty); }
set { SetValue(ClosingConfirmationTitleProperty, value); }
}
#endregion ClosingConfirmationTitle プロパティ
#region IsCloseButtonEnabled プロパティ
/// <summary>
/// IsClosingConfirmationEnabled 依存関係プロパティの定義
/// </summary>
public static readonly DependencyProperty IsCloseButtonEnabledProperty = DependencyProperty.Register("IsCloseButtonEnabled", typeof(bool), typeof(Window), new PropertyMetadata(true));
/// <summary>
/// 閉じるボタンが有効かどうかを取得または設定します。
/// </summary>
public bool IsCloseButtonEnabled
{
get { return (bool)GetValue(IsCloseButtonEnabledProperty); }
set { SetValue(IsCloseButtonEnabledProperty, value); }
}
#endregion IsCloseButtonEnabled プロパティ
#region IsRestoreButtonEnabled プロパティ
/// <summary>
/// IsRestoreButtonEnabled 依存関係プロパティの定義
/// </summary>
public static readonly DependencyProperty IsRestoreButtonEnabledProperty = DependencyProperty.Register("IsRestoreButtonEnabled", typeof(bool), typeof(Window), new PropertyMetadata(true));
/// <summary>
/// 元に戻すボタンが有効かどうかを取得または設定します。
/// </summary>
public bool IsRestoreButtonEnabled
{
get { return (bool)GetValue(IsRestoreButtonEnabledProperty); }
set { SetValue(IsRestoreButtonEnabledProperty, value); }
}
#endregion IsRestoreButtonEnabled プロパティ
#region IsMaximizeButtonEnabled プロパティ
/// <summary>
/// IsMaximizeButtonEnabled 依存関係プロパティの定義
/// </summary>
public static readonly DependencyProperty IsMaximizeButtonEnabledProperty = DependencyProperty.Register("IsMaximizeButtonEnabled", typeof(bool), typeof(Window), new PropertyMetadata(true));
/// <summary>
/// 最大化ボタンが有効かどうかを取得または設定します。
/// </summary>
public bool IsMaximizeButtonEnabled
{
get { return (bool)GetValue(IsMaximizeButtonEnabledProperty); }
set { SetValue(IsMaximizeButtonEnabledProperty, value); }
}
#endregion IsMaximizeButtonEnabled プロパティ
#region IsMinimizeButtonEnabled プロパティ
/// <summary>
/// IsMinimizeButtonEnabled 依存関係プロパティの定義
/// </summary>
public static readonly DependencyProperty IsMinimizeButtonEnabledProperty = DependencyProperty.Register("IsMinimizeButtonEnabled", typeof(bool), typeof(Window), new PropertyMetadata(true));
/// <summary>
/// 最小化ボタンが有効かどうかを取得または設定します。
/// </summary>
public bool IsMinimizeButtonEnabled
{
get { return (bool)GetValue(IsMinimizeButtonEnabledProperty); }
set { SetValue(IsMinimizeButtonEnabledProperty, value); }
}
#endregion IsMinimizeButtonEnabled プロパティ
#region IsTopmostButtonEnabled プロパティ
/// <summary>
/// IsTopmostButtonEnabled 依存関係プロパティの定義
/// </summary>
public static readonly DependencyProperty IsTopmostButtonEnabledProperty = DependencyProperty.Register("IsTopmostButtonEnabled", typeof(bool), typeof(Window), new PropertyMetadata(true));
/// <summary>
/// 常に手前に表示ボタンが有効かどうかを取得または設定します。
/// </summary>
public bool IsTopmostButtonEnabled
{
get { return (bool)GetValue(IsTopmostButtonEnabledProperty); }
set { SetValue(IsTopmostButtonEnabledProperty, value); }
}
#endregion IsTopmostButtonEnabled プロパティ
#region IsChangeThemeButtonEnabled プロパティ
/// <summary>
/// IsChangeThemeButtonEnabled 依存関係プロパティの定義
/// </summary>
public static readonly DependencyProperty IsChangeThemeButtonEnabledProperty = DependencyProperty.Register("IsChangeThemeButtonEnabled", typeof(bool), typeof(Window), new PropertyMetadata(true));
/// <summary>
/// テーマ切替ボタンが有効かどうかを取得または設定します。
/// </summary>
public bool IsChangeThemeButtonEnabled
{
get { return (bool)GetValue(IsChangeThemeButtonEnabledProperty); }
set { SetValue(IsChangeThemeButtonEnabledProperty, value); }
}
#endregion IsChangeThemeButtonEnabled プロパティ
#region IconVisibility プロパティ
/// <summary>
/// IconVisibility 依存関係プロパティの定義
/// </summary>
public static readonly DependencyProperty IconVisibilityProperty = DependencyProperty.Register("IconVisibility", typeof(Visibility), typeof(Window), new PropertyMetadata(Visibility.Visible));
/// <summary>
/// アイコンの視認性を取得または設定します。
/// </summary>
public Visibility IconVisibility
{
get { return (Visibility)GetValue(IconVisibilityProperty); }
set { SetValue(IconVisibilityProperty, value); }
}
#endregion IconVisibility プロパティ
#region CloseButtonVisibility プロパティ
/// <summary>
/// CloseButtonVisibility 依存関係プロパティの定義
/// </summary>
public static readonly DependencyProperty CloseButtonVisibilityProperty = DependencyProperty.Register("CloseButtonVisibility", typeof(Visibility), typeof(Window), new PropertyMetadata(Visibility.Visible));
/// <summary>
/// 閉じるボタンの視認性を取得または設定します。
/// </summary>
public Visibility CloseButtonVisibility
{
get { return (Visibility)GetValue(CloseButtonVisibilityProperty); }
set { SetValue(CloseButtonVisibilityProperty, value); }
}
#endregion CloseButtonVisibility プロパティ
#region RestoreButtonVisibility プロパティ
/// <summary>
/// RestoreButtonVisibility 依存関係プロパティの定義
/// </summary>
public static readonly DependencyProperty RestoreButtonVisibilityProperty = DependencyProperty.Register("RestoreButtonVisibility", typeof(Visibility), typeof(Window), new PropertyMetadata(Visibility.Visible));
/// <summary>
/// 元に戻すボタンの視認性を取得または設定します。
/// </summary>
public Visibility RestoreButtonVisibility
{
get { return (Visibility)GetValue(RestoreButtonVisibilityProperty); }
set { SetValue(RestoreButtonVisibilityProperty, value); }
}
#endregion RestoreButtonVisibility プロパティ
#region MaximizeButtonVisibility プロパティ
/// <summary>
/// MaximizeButtonVisibility 依存関係プロパティの定義
/// </summary>
public static readonly DependencyProperty MaximizeButtonVisibilityProperty = DependencyProperty.Register("MaximizeButtonVisibility", typeof(Visibility), typeof(Window), new PropertyMetadata(Visibility.Visible));
/// <summary>
/// 最大化ボタンの視認性を取得または設定します。
/// </summary>
public Visibility MaximizeButtonVisibility
{
get { return (Visibility)GetValue(MaximizeButtonVisibilityProperty); }
set { SetValue(MaximizeButtonVisibilityProperty, value); }
}
#endregion MaximizeButtonVisibility プロパティ
#region MinimizeButtonVisibility プロパティ
/// <summary>
/// MinimizeButtonVisibility 依存関係プロパティの定義
/// </summary>
public static readonly DependencyProperty MinimizeButtonVisibilityProperty = DependencyProperty.Register("MinimizeButtonVisibility", typeof(Visibility), typeof(Window), new PropertyMetadata(Visibility.Visible));
/// <summary>
/// 最小化ボタンの視認性を取得または設定します。
/// </summary>
public Visibility MinimizeButtonVisibility
{
get { return (Visibility)GetValue(MinimizeButtonVisibilityProperty); }
set { SetValue(MinimizeButtonVisibilityProperty, value); }
}
#endregion MinimizeButtonVisibility プロパティ
#region TopmostButtonVisibility プロパティ
/// <summary>
/// TopmostButtonVisibility 依存関係プロパティの定義
/// </summary>
public static readonly DependencyProperty TopmostButtonVisibilityProperty = DependencyProperty.Register("TopmostButtonVisibility", typeof(Visibility), typeof(Window), new PropertyMetadata(Visibility.Visible));
/// <summary>
/// 常に手前に表示ボタンの視認性を取得または設定します。
/// </summary>
public Visibility TopmostButtonVisibility
{
get { return (Visibility)GetValue(TopmostButtonVisibilityProperty); }
set { SetValue(TopmostButtonVisibilityProperty, value); }
}
#endregion TopmostButtonVisibility プロパティ
#region ChangeThemeButtonVisibility プロパティ
/// <summary>
/// ChangeThemeButtonVisibility 依存関係プロパティの定義
/// </summary>
public static readonly DependencyProperty ChangeThemeButtonVisibilityProperty = DependencyProperty.Register("ChangeThemeButtonVisibility", typeof(Visibility), typeof(Window), new PropertyMetadata(Visibility.Visible));
/// <summary>
/// テーマ切替ボタンの視認性を取得または設定します。
/// </summary>
public Visibility ChangeThemeButtonVisibility
{
get { return (Visibility)GetValue(ChangeThemeButtonVisibilityProperty); }
set { SetValue(ChangeThemeButtonVisibilityProperty, value); }
}
#endregion ChangeThemeButtonVisibility プロパティ
#region ResizeMode プロパティ
/// <summary>
/// ResizeMode 依存関係プロパティの定義
/// </summary>
public static readonly new DependencyProperty ResizeModeProperty = DependencyProperty.Register("ResizeMode", typeof(ResizeMode), typeof(Window), new PropertyMetadata(ResizeMode.CanResize, OnResizeModePropertyChanged));
/// <summary>
/// ウィンドウのリサイズモードを取得または設定します。
/// </summary>
public new ResizeMode ResizeMode
{
get => (ResizeMode)GetValue(ResizeModeProperty);
set => SetValue(ResizeModeProperty, value);
}
#endregion ResizeMode プロパティ
#region ContentBackground プロパティ
/// <summary>
/// ContentBackground 依存関係プロパティの定義
/// </summary>
public static readonly DependencyProperty ContentBackgroundProperty = DependencyProperty.Register("ContentBackground", typeof(Brush), typeof(Window), new PropertyMetadata(null));
/// <summary>
/// コンテンツ部の背景色を取得または設定します。
/// </summary>
public Brush ContentBackground
{
get { return (Brush)GetValue(ContentBackgroundProperty); }
set { SetValue(ContentBackgroundProperty, value); }
}
#endregion ContentBackground プロパティ
#region CaptionBorderThickness プロパティ
/// <summary>
/// CaptionBorderThickness 依存関係プロパティの定義
/// </summary>
public static readonly DependencyProperty CaptionBorderThicknessProperty = DependencyProperty.Register("CaptionBorderThickness", typeof(double), typeof(Window), new PropertyMetadata(0.0));
/// <summary>
/// 非クライアント領域とクライアント領域の境界線の太さを取得または設定します。
/// </summary>
public double CaptionBorderThickness
{
get { return (double)GetValue(CaptionBorderThicknessProperty); }
set { SetValue(CaptionBorderThicknessProperty, value); }
}
#endregion CaptionBorderThickness プロパティ
#region ClosingFunction プロパティ
/// <summary>
/// ClosingFunction 依存関係プロパティの定義
/// </summary>
public static readonly DependencyProperty ClosingFunctionProperty = DependencyProperty.Register("ClosingFunction", typeof(Func<bool>), typeof(Window), new PropertyMetadata(null));
/// <summary>
/// ウィンドウを閉じる前に実行する処理を取得または設定します。
/// </summary>
public Func<bool> ClosingFunction
{
get { return (Func<bool>)GetValue(ClosingFunctionProperty); }
set { SetValue(ClosingFunctionProperty, value); }
}
#endregion ClosingFunction プロパティ
/// <summary>
/// 静的なコンストラクタ
/// </summary>
static Window()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(Window), new FrameworkPropertyMetadata(typeof(Window)));
// テーマを初期化する
YKToolkit.Controls.ThemeManager.Instance.Initialize();
// Popup の表示を右利き/左利き設定に依存させないようにする
EnsureStandardPopupAlignment();
SystemParameters.StaticPropertyChanged += SystemParameters_StaticPropertyChanged;
}
/// <summary>
/// SystemParameters のプロパティ変更イベントハンドラ
/// </summary>
/// <param name="sender">イベント発行元</param>
/// <param name="e">イベント引数</param>
static void SystemParameters_StaticPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "MenuDropAlignment")
EnsureStandardPopupAlignment();
}
/// <summary>
/// 右利き設定とする
/// </summary>
private static void EnsureStandardPopupAlignment()
{
var _menuDropAlignmentField = typeof(SystemParameters).GetField("_menuDropAlignment", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
// MenuDropAlignment が true なら false に書き換える
if (SystemParameters.MenuDropAlignment && (_menuDropAlignmentField != null))
{
_menuDropAlignmentField.SetValue(null, false);
}
}
/// <summary>
/// 新しいインスタンスを生成します。
/// </summary>
public Window()
{
this.Closing += OnWindowClosing;
this.StateChanged += OnStateChanged;
}
/// <summary>
/// ResizeMode プロパティ変更イベントハンドラ
/// </summary>
/// <param name="sender">イベント発行元</param>
/// <param name="e">イベント引数</param>
private static void OnResizeModePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var w = sender as Window;
w.UpdateResizeBorderThickness();
}
/// <summary>
/// ResizeBorderThickness を更新します。
/// </summary>
private void UpdateResizeBorderThickness()
{
var chrome = WindowChrome.GetWindowChrome(this);
if (chrome != null)
{
chrome.ResizeBorderThickness = this.ResizeMode == ResizeMode.NoResize ? new Thickness(0) : SystemParameters.WindowResizeBorderThickness;
}
}
/// <summary>
/// Window Closing イベントハンドラ
/// </summary>
/// <param name="sender">イベント発行元</param>
/// <param name="e">イベント引数</param>
private void OnWindowClosing(object sender, CancelEventArgs e)
{
/* ウィンドゥ終了時のメッセージボックス
if ((this.ClosingFunction == null) || this.ClosingFunction())
{
if (this.IsClosingConfirmationEnabled)
{
var result = MessageBox.Show(this, this.ClosingConfirmationMessage, this.ClosingConfirmationTitle, MessageBoxButton.OKCancel, MessageBoxImage.Question);
if (result == MessageBoxResult.Cancel)
e.Cancel = true;
}
}
else
{
e.Cancel = true;
}
*/
}
/// <summary>
/// WindowState プロパティ変更イベントハンドラ
/// </summary>
/// <param name="sender">イベント発行元</param>
/// <param name="e">イベント引数</param>
private void OnStateChanged(object sender, EventArgs e)
{
if (this.MaximizeButtonVisibility == System.Windows.Visibility.Collapsed)
{
var w = sender as Window;
if (w.WindowState == System.Windows.WindowState.Maximized)
{
w.WindowState = System.Windows.WindowState.Normal;
}
}
}
/// <summary>
/// IconButton ダブルクリックイベントハンドラ
/// </summary>
/// <param name="sender">イベント発行元</param>
/// <param name="e">イベント引数</param>
private void IconButtonDoubleClick(object sender, MouseButtonEventArgs e)
{
if (this.IsCloseButtonEnabled)
{
this.Close();
}
}
/// <summary>
/// CloseButton クリックイベントハンドラ
/// </summary>
/// <param name="sender">イベント発行元</param>
/// <param name="e">イベント引数</param>
private void CloseButtonClick(object sender, RoutedEventArgs e)
{
this.Close();
}
/// <summary>
/// RestoreButton クリックイベントハンドラ
/// </summary>
/// <param name="sender">イベント発行元</param>
/// <param name="e">イベント引数</param>
private void RestoreButtonClick(object sender, RoutedEventArgs e)
{
this.WindowState = WindowState.Normal;
}
/// <summary>
/// MaximizeButton クリックイベントハンドラ
/// </summary>
/// <param name="sender">イベント発行元</param>
/// <param name="e">イベント引数</param>
private void MaximizeButtonClick(object sender, RoutedEventArgs e)
{
this.WindowState = WindowState.Maximized;
}
/// <summary>
/// MinimizeButton クリックイベントハンドラ
/// </summary>
/// <param name="sender">イベント発行元</param>
/// <param name="e">イベント引数</param>
private void MinimizeButtonClick(object sender, RoutedEventArgs e)
{
this.WindowState = WindowState.Minimized;
}
/// <summary>
/// TopmostButton クリックイベントハンドラ
/// </summary>
/// <param name="sender">イベント発行元</param>
/// <param name="e">イベント引数</param>
private void TopmostButtonClick(object sender, RoutedEventArgs e)
{
this.Topmost = !this.Topmost;
}
/// <summary>
/// ChangeThemeButton クリックイベントハンドラ
/// </summary>
/// <param name="sender">イベント発行元</param>
/// <param name="e">イベント引数</param>
private void ChangeThemeButtonClick(object sender, RoutedEventArgs e) => ThemeManager.Instance.ChangeNextTheme();
}
}
| 39.412081 | 248 | 0.594987 | [
"MIT"
] | Remon-7L/YKToolkit.Controls | YKToolkit.Controls/Themes/Generic.Window.xaml.cs | 32,566 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using CsSystem = System;
using Fox;
namespace Fox.PartsBuilder
{
public partial class PartDescription : Fox.Core.Data
{
// Properties
public Fox.Core.DynamicArray<Fox.Core.EntityLink> depends = new Fox.Core.DynamicArray<Fox.Core.EntityLink>();
public Fox.String partName;
public Fox.String buildType;
// PropertyInfo
private static Fox.EntityInfo classInfo;
public static new Fox.EntityInfo ClassInfo
{
get
{
return classInfo;
}
}
public override Fox.EntityInfo GetClassEntityInfo()
{
return classInfo;
}
static PartDescription()
{
classInfo = new Fox.EntityInfo("PartDescription", new Fox.Core.Data(0, 0, 0).GetClassEntityInfo(), 0, "PartsBuilder", 2);
classInfo.StaticProperties.Insert("depends", new Fox.Core.PropertyInfo(Fox.Core.PropertyInfo.PropertyType.EntityLink, 120, 1, Fox.Core.PropertyInfo.ContainerType.DynamicArray, Fox.Core.PropertyInfo.PropertyExport.EditorAndGame, Fox.Core.PropertyInfo.PropertyExport.EditorAndGame, null, null, Fox.Core.PropertyInfo.PropertyStorage.Instance));
classInfo.StaticProperties.Insert("partName", new Fox.Core.PropertyInfo(Fox.Core.PropertyInfo.PropertyType.String, 136, 1, Fox.Core.PropertyInfo.ContainerType.StaticArray, Fox.Core.PropertyInfo.PropertyExport.EditorAndGame, Fox.Core.PropertyInfo.PropertyExport.EditorAndGame, null, null, Fox.Core.PropertyInfo.PropertyStorage.Instance));
classInfo.StaticProperties.Insert("buildType", new Fox.Core.PropertyInfo(Fox.Core.PropertyInfo.PropertyType.String, 144, 1, Fox.Core.PropertyInfo.ContainerType.StaticArray, Fox.Core.PropertyInfo.PropertyExport.EditorAndGame, Fox.Core.PropertyInfo.PropertyExport.EditorAndGame, null, null, Fox.Core.PropertyInfo.PropertyStorage.Instance));
}
// Constructor
public PartDescription(ulong address, ushort idA, ushort idB) : base(address, idA, idB) { }
public override void SetProperty(string propertyName, Fox.Value value)
{
switch(propertyName)
{
case "partName":
this.partName = value.GetValueAsString();
return;
case "buildType":
this.buildType = value.GetValueAsString();
return;
default:
base.SetProperty(propertyName, value);
return;
}
}
public override void SetPropertyElement(string propertyName, ushort index, Fox.Value value)
{
switch(propertyName)
{
case "depends":
while(this.depends.Count <= index) { this.depends.Add(default(Fox.Core.EntityLink)); }
this.depends[index] = value.GetValueAsEntityLink();
return;
default:
base.SetPropertyElement(propertyName, index, value);
return;
}
}
public override void SetPropertyElement(string propertyName, string key, Fox.Value value)
{
switch(propertyName)
{
default:
base.SetPropertyElement(propertyName, key, value);
return;
}
}
}
} | 41.956522 | 344 | 0.586528 | [
"MIT"
] | Joey35233/FoxKit-3 | FoxKit/Assets/FoxKit/Fox/Generated/Fox/PartsBuilder/PartDescription.generated.cs | 3,860 | C# |
//------------------------------------------------------------------------------
// <copyright file="LocateFolderCommand.cs" company="Company">
// Copyright (c) Company. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Globalization;
using System.Linq;
using EnvDTE;
using EnvDTE80;
using LocateFolder.Utilities;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
namespace LocateFolder
{
/// <summary>
/// Command handler
/// </summary>
internal sealed class LocateFolderCommand
{
/// <summary>
/// Command ID.
/// </summary>
public const int CommandId = 0x0100;
/// <summary>
/// Command menu group (command set GUID).
/// </summary>
public static readonly Guid CommandSet = new Guid("031046af-15f9-44ab-9b2a-3f6cad1a89e3");
/// <summary>
/// VS Package that provides this command, not null.
/// </summary>
private readonly Package package;
/// <summary>
/// Initializes a new instance of the <see cref="LocateFolderCommand"/> class.
/// Adds our command handlers for menu (commands must exist in the command table file)
/// </summary>
/// <param name="package">Owner package, not null.</param>
private LocateFolderCommand(Package package)
{
if (package == null)
{
throw new ArgumentNullException("package");
}
this.package = package;
OleMenuCommandService commandService = this.ServiceProvider.GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
if (commandService != null)
{
var menuCommandID = new CommandID(CommandSet, CommandId);
var menuItem = new MenuCommand(this.MenuItemCallback, menuCommandID);
commandService.AddCommand(menuItem);
}
}
/// <summary>
/// Gets the instance of the command.
/// </summary>
public static LocateFolderCommand Instance
{
get;
private set;
}
/// <summary>
/// Gets the service provider from the owner package.
/// </summary>
private IServiceProvider ServiceProvider
{
get
{
return this.package;
}
}
/// <summary>
/// Initializes the singleton instance of the command.
/// </summary>
/// <param name="package">Owner package, not null.</param>
public static void Initialize(Package package)
{
Instance = new LocateFolderCommand(package);
}
/// <summary>
/// This function is the callback used to execute the command when the menu item is clicked.
/// See the constructor to see how the menu item is associated with this function using
/// OleMenuCommandService service and MenuCommand class.
/// </summary>
/// <param name="sender">Event sender.</param>
/// <param name="e">Event args.</param>
private void MenuItemCallback(object sender, EventArgs e)
{
var selectedItems = ((UIHierarchy)((DTE2)this.ServiceProvider.GetService(typeof(DTE))).Windows.Item("{3AE79031-E1BC-11D0-8F78-00A0C9110057}").Object).SelectedItems as object[];
if (selectedItems != null)
{
LocateFile.FilesOrFolders((IEnumerable<string>)(from t in selectedItems
where (t as UIHierarchyItem)?.Object is ProjectItem
select ((ProjectItem)((UIHierarchyItem)t).Object).FileNames[1]));
}
}
}
}
| 36.036036 | 188 | 0.5525 | [
"Apache-2.0"
] | akhilmittal/LocateFileInWindowsExplorer | LocateFolder/Commands/LocateFolderCommand.cs | 4,002 | C# |
using UnityEngine;
public class Background : MonoBehaviour
{
// スクロールするスピード
public float speed = 0.1f;
void Update ()
{
// 時間によってYの値が0から1に変化していく。1になったら0に戻り、繰り返す。
float y = Mathf.Repeat (Time.time * speed, 1);
// Yの値がずれていくオフセットを作成
Vector2 offset = new Vector2 (0, y);
// マテリアルにオフセットを設定する
GetComponent<Renderer>().sharedMaterial.SetTextureOffset ("_MainTex", offset);
}
}
| 19.6 | 80 | 0.709184 | [
"MIT"
] | z-ohnami/Shooting_sample | Assets/Scripts/Background.cs | 546 | C# |
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
namespace R5T.Plymouth
{
public static class IWebHostExtensions
{
public static async Task Run(this Task<IWebHost> gettingWebHost)
{
var webHost = await gettingWebHost;
await webHost.RunAsync();
}
}
}
| 18.210526 | 72 | 0.650289 | [
"MIT"
] | SafetyCone/R5T.Plymouth | source/R5T.Plymouth.WebHost/Code/Extensions/IWebHostExtensions.cs | 348 | C# |
using System;
using System.Collections.Generic;
using JetBrains.Metadata.Reader.API;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Plugins.Unity.ShaderLab.ProjectModel;
using JetBrains.ReSharper.Plugins.Unity.ShaderLab.Psi;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.ExtensionsAPI;
using JetBrains.ReSharper.Psi.Modules;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.ReSharper.TestFramework;
using JetBrains.TestFramework.Utils;
using JetBrains.Text;
using JetBrains.Util;
using NUnit.Framework;
namespace JetBrains.ReSharper.Plugins.Unity.Tests.ShaderLab.Psi.Parsing
{
public class ParseBuiltinShadersTests : ThirdPartyShaderTests
{
// NOTE: Requires downloading builtin shaders from Unity, and copying to
// test\data\psi\shaderLab\parsing\external\bultin_shaders-5.6.2f1
protected override string ShaderFolderName => "builtin_shaders-5.6.2f1";
}
public class ParseMixedRealityToolkitShadersTests : ThirdPartyShaderTests
{
// NOTE: Requires cloning - https://github.com/Microsoft/MixedRealityToolkit-Unity
// File names might be too long for Windows to handle. If so, just copy .shader
// files into `test\data\psi\shaderLab\parsing\external\MixedRealityToolkit-Unity`
protected override string ShaderFolderName => "MixedRealityToolkit-Unity";
}
[Explicit]
[TestUnity]
[TestFileExtension(ShaderLabProjectFileType.SHADERLAB_EXTENSION)]
public abstract class ThirdPartyShaderTests : BaseTestWithSingleProject
{
// NOTE: Requires downloading the built in shaders from Unity
protected override string RelativeTestDataPath => @"ShaderLab\Psi\Parsing\External\" + ShaderFolderName;
protected abstract string ShaderFolderName { get; }
[TestCaseSource(nameof(ThirdPartyShadersSource))]
public void TestThirdPartyShaders(string name) => DoOneTest(name);
public IEnumerable<string> ThirdPartyShadersSource
{
get
{
TestUtil.SetHomeDir(GetType().Assembly);
var path = TestDataPath2;
foreach (var file in path.GetChildFiles("*.shader", PathSearchFlags.RecurseIntoSubdirectories))
yield return file.MakeRelativeTo(path).ChangeExtension(string.Empty).FullPath;
}
}
protected override void DoTest(IProject testProject)
{
var projectFile = testProject.GetAllProjectFiles().FirstNotNull();
Assert.NotNull(projectFile);
var text = projectFile.Location.ReadAllText2();
var buffer = new StringBuffer(text.Text);
var languageService = ShaderLabLanguage.Instance.LanguageService().NotNull();
var lexer = languageService.GetPrimaryLexerFactory().CreateLexer(buffer);
var psiModule = Solution.PsiModules().GetPrimaryPsiModule(testProject, TargetFrameworkId.Default);
var parser = languageService.CreateParser(lexer, psiModule, null);
var psiFile = parser.ParseFile().NotNull();
if (DebugUtil.HasErrorElements(psiFile))
{
DebugUtil.DumpPsi(Console.Out, psiFile);
Assert.Fail("File contains error elements");
}
Assert.AreEqual(text.Text, psiFile.GetText(), "Reconstructed text mismatch");
CheckRange(text.Text, psiFile);
}
private static void CheckRange(string documentText, ITreeNode node)
{
Assert.AreEqual(node.GetText(), documentText.Substring(node.GetTreeStartOffset().Offset, node.GetTextLength()), "node range text mismatch");
for (var child = node.FirstChild; child != null; child = child.NextSibling)
CheckRange(documentText, child);
}
}
} | 42.555556 | 152 | 0.694778 | [
"Apache-2.0"
] | mfilippov/resharper-unity | resharper/test/src/ShaderLab/Psi/Parsing/ParseThirdPartyShaderTests.cs | 3,830 | C# |
namespace Mapbox.Editor
{
using System.Collections.Generic;
using UnityEngine;
using UnityEditor.SceneManagement;
using UnityEditor;
using System.IO;
using System.Collections;
using Mapbox.Unity;
using Mapbox.Tokens;
using Mapbox.Json;
using Mapbox.Unity.Utilities;
using Mapbox.Unity.Utilities.DebugTools;
using UnityEditor.Callbacks;
using System;
public class MapboxConfigurationWindow : EditorWindow
{
public static MapboxConfigurationWindow instance;
static MapboxConfiguration _mapboxConfig;
static MapboxTokenStatus _currentTokenStatus;
static MapboxAccess _mapboxAccess;
static bool _waitingToLoad = false;
//default mapboxconfig
static string _configurationFile;
static string _accessToken = "";
[Range(0, 1000)]
static int _memoryCacheSize = 500;
[Range(0, 3000)]
static int _mbtilesCacheSize = 2000;
static int _webRequestTimeout = 30;
//mapbox access callbacks
static bool _listeningForTokenValidation = false;
static bool _validating = false;
static string _lastValidatedToken;
//gui flags
bool _showConfigurationFoldout;
bool _showChangelogFoldout;
Vector2 _scrollPosition;
//samples
static int _selectedSample;
static ScenesList _sceneList;
static GUIContent[] _sampleContent;
string _sceneToOpen;
//styles
GUISkin _skin;
Color _defaultContentColor;
Color _defaultBackgroundColor;
GUIStyle _titleStyle;
GUIStyle _bodyStyle;
GUIStyle _linkStyle;
GUIStyle _textFieldStyle;
GUIStyle _submitButtonStyle;
GUIStyle _checkingButtonStyle;
GUIStyle _validFieldStyle;
GUIStyle _validButtonStyle;
Color _validContentColor;
Color _validBackgroundColor;
GUIStyle _invalidFieldStyle;
GUIStyle _invalidButtonStyle;
Color _invalidContentColor;
Color _invalidBackgroundColor;
GUIStyle _errorStyle;
GUIStyle _verticalGroup;
GUIStyle _horizontalGroup;
GUIStyle _scrollViewStyle;
GUIStyle _sampleButtonStyle;
[DidReloadScripts]
public static void ShowWindowOnImport()
{
if (ShouldShowConfigurationWindow())
{
PlayerPrefs.SetInt(Constants.Path.DID_PROMPT_CONFIGURATION, 1);
PlayerPrefs.Save();
InitWhenLoaded();
}
}
[MenuItem("Mapbox/Setup")]
static void InitWhenLoaded()
{
if(EditorApplication.isCompiling && !_waitingToLoad)
{
//subscribe to updates
_waitingToLoad = true;
EditorApplication.update += InitWhenLoaded;
return;
}
if(!EditorApplication.isCompiling)
{
//unsubscribe from updates if waiting
if(_waitingToLoad)
{
EditorApplication.update -= InitWhenLoaded;
_waitingToLoad = false;
}
Init();
}
}
static void Init()
{
Runnable.EnableRunnableInEditor();
//verify that the config file exists
_configurationFile = Path.Combine(Unity.Constants.Path.MAPBOX_RESOURCES_ABSOLUTE, Unity.Constants.Path.CONFIG_FILE);
if (!Directory.Exists(Unity.Constants.Path.MAPBOX_RESOURCES_ABSOLUTE))
{
Directory.CreateDirectory(Unity.Constants.Path.MAPBOX_RESOURCES_ABSOLUTE);
}
if (!File.Exists(_configurationFile))
{
_mapboxConfig = new MapboxConfiguration
{
AccessToken = _accessToken,
MemoryCacheSize = (uint)_memoryCacheSize,
MbTilesCacheSize = (uint)_mbtilesCacheSize,
DefaultTimeout = _webRequestTimeout
};
var json = JsonUtility.ToJson(_mapboxConfig);
File.WriteAllText(_configurationFile, json);
AssetDatabase.Refresh();
}
//finish opening the window after the assetdatabase is refreshed.
EditorApplication.delayCall += OpenWindow;
}
static void OpenWindow()
{
EditorApplication.delayCall -= OpenWindow;
//setup mapboxaccess listener
_mapboxAccess = MapboxAccess.Instance;
if (!_listeningForTokenValidation)
{
_mapboxAccess.OnTokenValidation += HandleValidationResponse;
_listeningForTokenValidation = true;
}
//setup local variables from mapbox config file
_mapboxConfig = _mapboxAccess.Configuration;
if (_mapboxConfig != null)
{
_accessToken = _mapboxConfig.AccessToken;
_memoryCacheSize = (int)_mapboxConfig.MemoryCacheSize;
_mbtilesCacheSize = (int)_mapboxConfig.MbTilesCacheSize;
_webRequestTimeout = (int)_mapboxConfig.DefaultTimeout;
}
//validate current config
if (!string.IsNullOrEmpty(_accessToken))
{
SubmitConfiguration();
}
//cache sample scene gui content
GetSceneList();
_selectedSample = -1;
//instantiate the config window
instance = GetWindow(typeof(MapboxConfigurationWindow)) as MapboxConfigurationWindow;
instance.minSize = new Vector2(800, 350);
instance.titleContent = new GUIContent("Mapbox Setup");
instance.Show();
}
static void GetSceneList()
{
_sceneList = Resources.Load<ScenesList>("Mapbox/ScenesList");
//exclude scenes with no image data
var content = new List<SceneData>();
if (_sceneList != null)
{
for (int i = 0; i < _sceneList.SceneList.Length; i++)
{
if (File.Exists(_sceneList.SceneList[i].ScenePath))
{
if (_sceneList.SceneList[i].Image != null)
{
content.Add(_sceneList.SceneList[i]);
}
}
}
}
_sampleContent = new GUIContent[content.Count];
for (int i = 0; i < _sampleContent.Length; i++)
{
_sampleContent[i] = new GUIContent(content[i].Name, content[i].Image, content[i].ScenePath);
}
}
/// <summary>
/// Unity Events
/// </summary>
private void OnDisable() { AssetDatabase.Refresh(); }
private void OnDestroy() { AssetDatabase.Refresh(); }
private void OnLostFocus() { AssetDatabase.Refresh(); }
/// <summary>
/// Mapbox access
/// </summary>
private static void SubmitConfiguration()
{
var mapboxConfiguration = new MapboxConfiguration
{
AccessToken = _accessToken,
MemoryCacheSize = (uint)_memoryCacheSize,
MbTilesCacheSize = (uint)_mbtilesCacheSize,
DefaultTimeout = _webRequestTimeout
};
_mapboxAccess.SetConfiguration(mapboxConfiguration, false);
_validating = true;
}
private static void HandleValidationResponse(MapboxTokenStatus status)
{
_currentTokenStatus = status;
_validating = false;
_lastValidatedToken = _accessToken;
//save the config
_configurationFile = Path.Combine(Unity.Constants.Path.MAPBOX_RESOURCES_ABSOLUTE, Unity.Constants.Path.CONFIG_FILE);
var json = JsonUtility.ToJson(_mapboxAccess.Configuration);
File.WriteAllText(_configurationFile, json);
}
void OnGUI()
{
//only run after init
if (instance == null)
{
//TODO: loading message?
InitWhenLoaded();
return;
}
InitStyles();
_scrollPosition = EditorGUILayout.BeginScrollView(_scrollPosition, _scrollViewStyle);
EditorGUILayout.BeginVertical();
// Access token link.
DrawAccessTokenLink();
// Access token entry and validation.
DrawAccessTokenField();
// Draw the validation error, if one exists
DrawError();
EditorGUILayout.EndVertical();
EditorGUILayout.BeginVertical(_verticalGroup);
// Configuration
DrawConfigurationSettings();
GUILayout.Space(8);
// Changelog
DrawChangelog();
EditorGUILayout.EndVertical();
// Draw Example links if the scenelist asset is where it should be.
if (_sampleContent.Length > 0)
{
EditorGUILayout.BeginVertical(_verticalGroup);
DrawExampleLinks();
EditorGUILayout.EndVertical();
}
EditorGUILayout.EndScrollView();
}
void InitStyles()
{
_defaultContentColor = GUI.contentColor;
_defaultBackgroundColor = GUI.backgroundColor;
_titleStyle = new GUIStyle(GUI.skin.FindStyle("IN TitleText"));
_titleStyle.padding.left = 3;
//_titleStyle.fontSize = 16;
_bodyStyle = new GUIStyle(GUI.skin.FindStyle("WordWrapLabel"));
//_bodyStyle.fontSize = 14;
_linkStyle = new GUIStyle(GUI.skin.FindStyle("PR PrefabLabel"));
//_linkStyle.fontSize = 14;
_linkStyle.padding.left = 0;
_linkStyle.padding.top = -1;
_textFieldStyle = new GUIStyle(GUI.skin.FindStyle("TextField"));
_textFieldStyle.margin.right = 0;
_textFieldStyle.margin.top = 0;
_submitButtonStyle = new GUIStyle(GUI.skin.FindStyle("ButtonRight"));
_submitButtonStyle.padding.top = 0;
_submitButtonStyle.margin.top = 0;
_submitButtonStyle.fixedWidth = 200;
_checkingButtonStyle = new GUIStyle(_submitButtonStyle);
_validFieldStyle = new GUIStyle(_textFieldStyle);
_validButtonStyle = new GUIStyle(GUI.skin.FindStyle("LODSliderRange"));
_validButtonStyle.alignment = TextAnchor.MiddleCenter;
_validButtonStyle.padding = new RectOffset(0, 0, 0, 0);
_validButtonStyle.border = new RectOffset(0, 0, 5, -2);
_validButtonStyle.fixedWidth = 60;
_validContentColor = new Color(1, 1, 1, .7f);
_validBackgroundColor = new Color(.2f, .8f, .2f, 1);
_invalidContentColor = new Color(1, 1, 1, .7f);
_invalidBackgroundColor = new Color(.8f, .2f, .2f, 1);
_errorStyle = new GUIStyle(GUI.skin.FindStyle("ErrorLabel"));
_errorStyle.padding.left = 5;
_verticalGroup = new GUIStyle();
_verticalGroup.margin = new RectOffset(0, 0, 0, 35);
_horizontalGroup = new GUIStyle();
_horizontalGroup.padding = new RectOffset(0, 0, 4, 4);
_scrollViewStyle = new GUIStyle(GUI.skin.FindStyle("scrollview"));
_scrollViewStyle.padding = new RectOffset(20, 20, 40, 0);
_sampleButtonStyle = new GUIStyle(GUI.skin.FindStyle("button"));
_sampleButtonStyle.imagePosition = ImagePosition.ImageAbove;
_sampleButtonStyle.padding = new RectOffset(0, 0, 5, 5);
_sampleButtonStyle.fontStyle = FontStyle.Bold;
}
void DrawAccessTokenLink()
{
EditorGUILayout.LabelField("Access Token", _titleStyle);
EditorGUILayout.BeginHorizontal(_horizontalGroup);
if (string.IsNullOrEmpty(_accessToken))
{
//fit box to text to create an 'inline link'
GUIContent labelContent = new GUIContent("Copy your free token from");
GUIContent linkContent = new GUIContent("mapbox.com");
EditorGUILayout.LabelField(labelContent, _bodyStyle, GUILayout.Width(_bodyStyle.CalcSize(labelContent).x));
if (GUILayout.Button(linkContent, _linkStyle))
{
Application.OpenURL("https://www.mapbox.com/studio/account/tokens/");
}
//create link cursor
var rect = GUILayoutUtility.GetLastRect();
rect.width = _linkStyle.CalcSize(new GUIContent(linkContent)).x;
EditorGUIUtility.AddCursorRect(rect, MouseCursor.Link);
GUILayout.FlexibleSpace();
}
else
{
GUIContent labelContent = new GUIContent("Manage your tokens at");
GUIContent linkContent = new GUIContent("mapbox.com/studio/accounts/tokens/");
EditorGUILayout.LabelField(labelContent, _bodyStyle, GUILayout.Width(_bodyStyle.CalcSize(labelContent).x));
if (GUILayout.Button(linkContent, _linkStyle))
{
Application.OpenURL("https://www.mapbox.com/studio/account/tokens/");
}
//create link cursor
var rect = GUILayoutUtility.GetLastRect();
rect.width = _linkStyle.CalcSize(new GUIContent(linkContent)).x;
EditorGUIUtility.AddCursorRect(rect, MouseCursor.Link);
GUILayout.FlexibleSpace();
}
EditorGUILayout.EndHorizontal();
}
void DrawAccessTokenField()
{
EditorGUILayout.BeginHorizontal(_horizontalGroup);
//_accessToken is empty
if (string.IsNullOrEmpty(_accessToken))
{
_accessToken = EditorGUILayout.TextField("", _accessToken, _textFieldStyle);
EditorGUI.BeginDisabledGroup(true);
GUILayout.Button("Submit", _submitButtonStyle);
EditorGUI.EndDisabledGroup();
}
else
{
//_accessToken is being validated
if (_validating)
{
EditorGUI.BeginDisabledGroup(true);
_accessToken = EditorGUILayout.TextField("", _accessToken, _textFieldStyle);
GUILayout.Button("Checking", _submitButtonStyle);
EditorGUI.EndDisabledGroup();
}
//_accessToken is the same as the already submitted token
else if (string.Equals(_lastValidatedToken, _accessToken))
{
//valid token
if (_currentTokenStatus == MapboxTokenStatus.TokenValid)
{
GUI.backgroundColor = _validBackgroundColor;
GUI.contentColor = _validContentColor;
_accessToken = EditorGUILayout.TextField("", _accessToken, _textFieldStyle);
GUILayout.Button("Valid", _validButtonStyle);
GUI.contentColor = _defaultContentColor;
GUI.backgroundColor = _defaultBackgroundColor;
}
//invalid token
else
{
GUI.contentColor = _invalidContentColor;
GUI.backgroundColor = _invalidBackgroundColor;
_accessToken = EditorGUILayout.TextField("", _accessToken, _textFieldStyle);
GUILayout.Button("Invalid", _validButtonStyle);
GUI.contentColor = _defaultContentColor;
GUI.backgroundColor = _defaultBackgroundColor;
}
//Submit button
if (GUILayout.Button("Submit", _submitButtonStyle))
{
SubmitConfiguration();
}
}
//_accessToken is a new, unsubmitted token.
else
{
_accessToken = EditorGUILayout.TextField("", _accessToken, _textFieldStyle);
if (GUILayout.Button("Submit", _submitButtonStyle))
{
SubmitConfiguration();
}
}
}
EditorGUILayout.EndHorizontal();
}
void DrawError()
{
//draw the error message, if one exists
EditorGUILayout.BeginHorizontal(_horizontalGroup);
if (_currentTokenStatus != MapboxTokenStatus.TokenValid
&& _currentTokenStatus != MapboxTokenStatus.StatusNotYetSet
&& string.Equals(_lastValidatedToken, _accessToken)
&& !_validating)
{
EditorGUILayout.LabelField(_currentTokenStatus.ToString(), _errorStyle);
}
else
{
//EditorGUILayout.LabelField("", _errorStyle);
}
EditorGUILayout.EndHorizontal();
}
void DrawChangelog()
{
//_showChangelogFoldout = EditorGUILayout.Foldout(_showChangelogFoldout, "v" + Constants.SDK_VERSION + " Changelog", true);
//if (_showChangelogFoldout)
//{
EditorGUI.indentLevel = 2;
//EditorGUILayout.BeginHorizontal(_horizontalGroup);
// GUIContent labelContent = new GUIContent("SDK version " + Constants.SDK_VERSION + " changelog, and learn how to contribute at");
GUIContent linkContent = new GUIContent("v" + Constants.SDK_VERSION + " changelog");
// EditorGUILayout.LabelField(labelContent, _bodyStyle, GUILayout.Width(_bodyStyle.CalcSize(labelContent).x));
if (GUILayout.Button(linkContent, _linkStyle))
{
Application.OpenURL("https://www.mapbox.com/mapbox-unity-sdk/docs/05-changelog.html");
}
// GUILayout.FlexibleSpace();
//EditorGUILayout.EndHorizontal();
EditorGUI.indentLevel = 0;
//}
}
void DrawConfigurationSettings()
{
_showConfigurationFoldout = EditorGUILayout.Foldout(_showConfigurationFoldout, "Configuration", true);
if (_showConfigurationFoldout)
{
EditorGUIUtility.labelWidth = 240f;
EditorGUI.indentLevel = 2;
_memoryCacheSize = EditorGUILayout.IntSlider("Mem Cache Size (# of tiles)", _memoryCacheSize, 0, 1000);
_mbtilesCacheSize = EditorGUILayout.IntSlider("MBTiles Cache Size (# of tiles)", _mbtilesCacheSize, 0, 3000);
_webRequestTimeout = EditorGUILayout.IntField("Default Web Request Timeout (s)", _webRequestTimeout);
EditorGUILayout.BeginHorizontal(_horizontalGroup);
GUILayout.Space(35f);
if (GUILayout.Button("Save"))
{
SubmitConfiguration();
}
EditorGUI.indentLevel = 0;
EditorGUIUtility.labelWidth = 0f;
EditorGUILayout.EndHorizontal();
}
}
void DrawExampleLinks()
{
EditorGUI.BeginDisabledGroup(_currentTokenStatus != MapboxTokenStatus.TokenValid
|| _validating);
if (_currentTokenStatus == MapboxTokenStatus.TokenValid)
{
EditorGUILayout.LabelField("Sample Scenes", _titleStyle);
}
else
{
EditorGUILayout.LabelField("Sample Scenes", "Paste your mapbox access token to get started", _titleStyle);
}
int rowCount = 2;
EditorGUILayout.BeginHorizontal(_horizontalGroup);
_selectedSample = GUILayout.SelectionGrid(-1, _sampleContent, rowCount, _sampleButtonStyle);
if (_selectedSample != -1)
{
EditorApplication.isPaused = false;
EditorApplication.isPlaying = false;
_sceneToOpen = _sampleContent[_selectedSample].tooltip;
EditorApplication.update += OpenAndPlayScene;
}
EditorGUILayout.EndHorizontal();
EditorGUI.EndDisabledGroup();
}
private void OpenAndPlayScene()
{
if( EditorApplication.isPlaying)
{
return;
}
EditorApplication.update -= OpenAndPlayScene;
if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
{
EditorSceneManager.OpenScene(_sceneToOpen);
EditorApplication.isPlaying = true;
var editorWindow = GetWindow(typeof(MapboxConfigurationWindow));
editorWindow.Close();
}
else
{
_sceneToOpen = null;
_selectedSample = -1;
}
}
static bool ShouldShowConfigurationWindow()
{
if (!PlayerPrefs.HasKey(Constants.Path.DID_PROMPT_CONFIGURATION))
{
PlayerPrefs.SetInt(Constants.Path.DID_PROMPT_CONFIGURATION, 0);
}
return PlayerPrefs.GetInt(Constants.Path.DID_PROMPT_CONFIGURATION) == 0;
}
}
} | 27.690438 | 134 | 0.720339 | [
"Apache-2.0"
] | Anderson-RC/GGJ2018 | Assets/Mapbox/Unity/Editor/MapboxConfigurationWindow.cs | 17,085 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Autofac;
using FluentValidation;
using FluentValidation.Results;
using SmartStore.OfflinePayment.Models;
using SmartStore.OfflinePayment.Settings;
using SmartStore.OfflinePayment.Validators;
using SmartStore.Services;
using SmartStore.Services.Payments;
using SmartStore.Web.Framework.Controllers;
using SmartStore.Web.Framework.Security;
using SmartStore.Web.Framework.Settings;
namespace SmartStore.OfflinePayment.Controllers
{
public class OfflinePaymentController : PaymentControllerBase
{
private readonly IComponentContext _ctx;
private readonly HttpContextBase _httpContext;
public OfflinePaymentController(
HttpContextBase httpContext,
IComponentContext ctx)
{
_httpContext = httpContext;
_ctx = ctx;
}
#region Global
private List<SelectListItem> GetTransactModes()
{
var list = new List<SelectListItem>
{
new SelectListItem { Text = T("Enums.SmartStore.Core.Domain.Payments.PaymentStatus.Pending"), Value = ((int)TransactMode.Pending).ToString() },
new SelectListItem { Text = T("Enums.SmartStore.Core.Domain.Payments.PaymentStatus.Authorized"), Value = ((int)TransactMode.Authorize).ToString() },
new SelectListItem { Text = T("Enums.SmartStore.Core.Domain.Payments.PaymentStatus.Paid"), Value = ((int)TransactMode.Paid).ToString() }
};
return list;
}
[NonAction]
private TModel ConfigureGet<TModel, TSetting>(Action<TModel, TSetting> fn = null)
where TModel : ConfigurationModelBase, new()
where TSetting : PaymentSettingsBase, new()
{
var model = new TModel();
int storeScope = this.GetActiveStoreScopeConfiguration(Services.StoreService, Services.WorkContext);
var settings = Services.Settings.LoadSetting<TSetting>(storeScope);
model.DescriptionText = settings.DescriptionText;
model.AdditionalFee = settings.AdditionalFee;
model.AdditionalFeePercentage = settings.AdditionalFeePercentage;
if (fn != null)
{
fn(model, settings);
}
var storeDependingSettingHelper = new StoreDependingSettingHelper(ViewData);
storeDependingSettingHelper.GetOverrideKeys(settings, model, storeScope, Services.Settings);
return model;
}
[NonAction]
private void ConfigurePost<TModel, TSetting>(TModel model, FormCollection form, Action<TSetting> fn = null)
where TModel : ConfigurationModelBase, new()
where TSetting : PaymentSettingsBase, new()
{
ModelState.Clear();
var storeDependingSettingHelper = new StoreDependingSettingHelper(ViewData);
int storeScope = this.GetActiveStoreScopeConfiguration(Services.StoreService, Services.WorkContext);
var settings = Services.Settings.LoadSetting<TSetting>(storeScope);
settings.DescriptionText = model.DescriptionText;
settings.AdditionalFee = model.AdditionalFee;
settings.AdditionalFeePercentage = model.AdditionalFeePercentage;
if (fn != null)
{
fn(settings);
}
storeDependingSettingHelper.UpdateSettings(settings, form, storeScope, Services.Settings);
NotifySuccess(Services.Localization.GetResource("Admin.Common.DataSuccessfullySaved"));
}
[NonAction]
private TModel PaymentInfoGet<TModel, TSetting>(Action<TModel, TSetting> fn = null)
where TModel : PaymentInfoModelBase, new()
where TSetting : PaymentSettingsBase, new()
{
var settings = _ctx.Resolve<TSetting>();
var model = new TModel();
model.DescriptionText = GetLocalizedText(settings.DescriptionText);
if (fn != null)
{
fn(model, settings);
}
return model;
}
private string GetLocalizedText(string text)
{
if (text.EmptyNull().StartsWith("@"))
{
return T(text.Substring(1));
}
return text;
}
[NonAction]
public override IList<string> ValidatePaymentForm(FormCollection form)
{
var warnings = new List<string>();
IValidator validator;
ValidationResult validationResult = null;
string type = form["OfflinePaymentMethodType"].NullEmpty();
if (type.HasValue())
{
if (type == "Manual")
{
validator = new ManualPaymentInfoValidator(Services.Localization);
var model = new ManualPaymentInfoModel
{
CardholderName = form["CardholderName"],
CardNumber = form["CardNumber"],
CardCode = form["CardCode"]
};
validationResult = validator.Validate(model);
}
else if (type == "DirectDebit")
{
validator = new DirectDebitPaymentInfoValidator(Services.Localization);
var model = new DirectDebitPaymentInfoModel
{
EnterIBAN = form["EnterIBAN"],
DirectDebitAccountHolder = form["DirectDebitAccountHolder"],
DirectDebitAccountNumber = form["DirectDebitAccountNumber"],
DirectDebitBankCode = form["DirectDebitBankCode"],
DirectDebitCountry = form["DirectDebitCountry"],
DirectDebitBankName = form["DirectDebitBankName"],
DirectDebitIban = form["DirectDebitIban"],
DirectDebitBic = form["DirectDebitBic"]
};
validationResult = validator.Validate(model);
}
if (validationResult != null && !validationResult.IsValid)
{
validationResult.Errors.Each(x => warnings.Add(x.ErrorMessage));
}
}
return warnings;
}
[NonAction]
public override ProcessPaymentRequest GetPaymentInfo(FormCollection form)
{
var paymentInfo = new ProcessPaymentRequest();
string type = form["OfflinePaymentMethodType"].NullEmpty();
if (type.HasValue())
{
if (type == "Manual")
{
paymentInfo.CreditCardType = form["CreditCardType"];
paymentInfo.CreditCardName = form["CardholderName"];
paymentInfo.CreditCardNumber = form["CardNumber"];
paymentInfo.CreditCardExpireMonth = int.Parse(form["ExpireMonth"]);
paymentInfo.CreditCardExpireYear = int.Parse(form["ExpireYear"]);
paymentInfo.CreditCardCvv2 = form["CardCode"];
}
else if (type == "DirectDebit")
{
paymentInfo.DirectDebitAccountHolder = form["DirectDebitAccountHolder"];
paymentInfo.DirectDebitAccountNumber = form["DirectDebitAccountNumber"];
paymentInfo.DirectDebitBankCode = form["DirectDebitBankCode"];
paymentInfo.DirectDebitBankName = form["DirectDebitBankName"];
paymentInfo.DirectDebitBic = form["DirectDebitBic"];
paymentInfo.DirectDebitCountry = form["DirectDebitCountry"];
paymentInfo.DirectDebitIban = form["DirectDebitIban"];
}
else if (type == "PurchaseOrderNumber")
{
paymentInfo.PurchaseOrderNumber = form["PurchaseOrderNumber"];
}
}
return paymentInfo;
}
[NonAction]
public override string GetPaymentSummary(FormCollection form)
{
string type = form["OfflinePaymentMethodType"].NullEmpty();
if (type.HasValue())
{
if (type == "Manual")
{
var number = form["CardNumber"];
return "{0}, {1}, {2}".FormatCurrent(
form["CreditCardType"],
form["CardholderName"],
number.Mask(4)
);
}
else if (type == "DirectDebit")
{
if (form["DirectDebitAccountNumber"].HasValue() && (form["DirectDebitBankCode"].HasValue()) && form["DirectDebitAccountHolder"].HasValue())
{
var number = form["DirectDebitAccountNumber"];
return "{0}, {1}, {2}".FormatCurrent(
form["DirectDebitAccountHolder"],
form["DirectDebitBankName"].NullEmpty() ?? form["DirectDebitBankCode"],
number.Mask(4)
);
}
else if (form["DirectDebitIban"].HasValue())
{
var number = form["DirectDebitIban"];
return number.Mask(8);
}
}
else if (type == "PurchaseOrderNumber")
{
return form["PurchaseOrderNumber"];
}
}
return null;
}
#endregion
#region CashOnDelivery
[AdminAuthorize, ChildActionOnly]
public ActionResult CashOnDeliveryConfigure()
{
var model = ConfigureGet<CashOnDeliveryConfigurationModel, CashOnDeliveryPaymentSettings>();
return View("GenericConfigure", model);
}
[HttpPost, AdminAuthorize, ChildActionOnly, ValidateInput(false)]
public ActionResult CashOnDeliveryConfigure(CashOnDeliveryConfigurationModel model, FormCollection form)
{
if (!ModelState.IsValid)
return CashOnDeliveryConfigure();
ConfigurePost<CashOnDeliveryConfigurationModel, CashOnDeliveryPaymentSettings>(model, form);
return CashOnDeliveryConfigure();
}
public ActionResult CashOnDeliveryPaymentInfo()
{
var model = PaymentInfoGet<CashOnDeliveryPaymentInfoModel, CashOnDeliveryPaymentSettings>();
return PartialView("GenericPaymentInfo", model);
}
#endregion
#region Invoice
[ChildActionOnly, AdminAuthorize]
public ActionResult InvoiceConfigure()
{
var model = ConfigureGet<InvoiceConfigurationModel, InvoicePaymentSettings>();
return View("GenericConfigure", model);
}
[HttpPost, AdminAuthorize, ChildActionOnly, ValidateInput(false)]
public ActionResult InvoiceConfigure(InvoiceConfigurationModel model, FormCollection form)
{
if (!ModelState.IsValid)
return InvoiceConfigure();
ConfigurePost<InvoiceConfigurationModel, InvoicePaymentSettings>(model, form);
return InvoiceConfigure();
}
public ActionResult InvoicePaymentInfo()
{
var model = PaymentInfoGet<InvoicePaymentInfoModel, InvoicePaymentSettings>();
return PartialView("GenericPaymentInfo", model);
}
#endregion
#region PayInStore
[ChildActionOnly, AdminAuthorize]
public ActionResult PayInStoreConfigure()
{
var model = ConfigureGet<PayInStoreConfigurationModel, PayInStorePaymentSettings>();
return View("GenericConfigure", model);
}
[HttpPost, AdminAuthorize, ChildActionOnly, ValidateInput(false)]
public ActionResult PayInStoreConfigure(PayInStoreConfigurationModel model, FormCollection form)
{
if (!ModelState.IsValid)
return PayInStoreConfigure();
ConfigurePost<PayInStoreConfigurationModel, PayInStorePaymentSettings>(model, form);
return PayInStoreConfigure();
}
public ActionResult PayInStorePaymentInfo()
{
var model = PaymentInfoGet<PayInStorePaymentInfoModel, PayInStorePaymentSettings>();
return PartialView("GenericPaymentInfo", model);
}
#endregion
#region Prepayment
[AdminAuthorize, ChildActionOnly]
public ActionResult PrepaymentConfigure()
{
var model = ConfigureGet<PrepaymentConfigurationModel, PrepaymentPaymentSettings>();
return View("GenericConfigure", model);
}
[HttpPost, AdminAuthorize, ChildActionOnly, ValidateInput(false)]
public ActionResult PrepaymentConfigure(PrepaymentConfigurationModel model, FormCollection form)
{
if (!ModelState.IsValid)
return PrepaymentConfigure();
ConfigurePost<PrepaymentConfigurationModel, PrepaymentPaymentSettings>(model, form);
return PrepaymentConfigure();
}
public ActionResult PrepaymentPaymentInfo()
{
var model = PaymentInfoGet<PrepaymentPaymentInfoModel, PrepaymentPaymentSettings>();
return PartialView("GenericPaymentInfo", model);
}
#endregion
#region DirectDebit
[AdminAuthorize, ChildActionOnly]
public ActionResult DirectDebitConfigure()
{
var model = ConfigureGet<DirectDebitConfigurationModel, DirectDebitPaymentSettings>();
return View("GenericConfigure", model);
}
[HttpPost, AdminAuthorize, ChildActionOnly, ValidateInput(false)]
public ActionResult DirectDebitConfigure(DirectDebitConfigurationModel model, FormCollection form)
{
if (!ModelState.IsValid)
return DirectDebitConfigure();
ConfigurePost<DirectDebitConfigurationModel, DirectDebitPaymentSettings>(model, form);
return DirectDebitConfigure();
}
public ActionResult DirectDebitPaymentInfo()
{
var model = PaymentInfoGet<DirectDebitPaymentInfoModel, DirectDebitPaymentSettings>();
var paymentData = _httpContext.GetCheckoutState().PaymentData;
model.DirectDebitAccountHolder = (string)paymentData.Get("DirectDebitAccountHolder");
model.DirectDebitAccountNumber = (string)paymentData.Get("DirectDebitAccountNumber");
model.DirectDebitBankCode = (string)paymentData.Get("DirectDebitBankCode");
model.DirectDebitBankName = (string)paymentData.Get("DirectDebitBankName");
model.DirectDebitBic = (string)paymentData.Get("DirectDebitBic");
model.DirectDebitCountry = (string)paymentData.Get("DirectDebitCountry");
model.DirectDebitIban = (string)paymentData.Get("DirectDebitIban");
return PartialView(model);
}
#endregion
#region Manual
[AdminAuthorize, ChildActionOnly]
public ActionResult ManualConfigure()
{
var model = ConfigureGet<ManualConfigurationModel, ManualPaymentSettings>((m, s) =>
{
m.TransactMode = s.TransactMode;
m.TransactModeValues = GetTransactModes();
m.ExcludedCreditCards = s.ExcludedCreditCards.SplitSafe(",");
m.AvailableCreditCards = ManualProvider.CreditCardTypes
.Select(x => new SelectListItem
{
Text = x.Text,
Value = x.Value,
Selected = m.ExcludedCreditCards.Contains(x.Value)
})
.ToList();
});
return View(model);
}
[HttpPost, AdminAuthorize, ChildActionOnly, ValidateInput(false)]
public ActionResult ManualConfigure(ManualConfigurationModel model, FormCollection form)
{
if (!ModelState.IsValid)
return ManualConfigure();
ConfigurePost<ManualConfigurationModel, ManualPaymentSettings>(model, form, s =>
{
s.TransactMode = model.TransactMode;
s.ExcludedCreditCards = string.Join(",", model.ExcludedCreditCards ?? new string[0]);
});
return ManualConfigure();
}
public ActionResult ManualPaymentInfo()
{
var model = PaymentInfoGet<ManualPaymentInfoModel, ManualPaymentSettings>((m, s) =>
{
var excludedCreditCards = s.ExcludedCreditCards.SplitSafe(",");
foreach (var creditCard in ManualProvider.CreditCardTypes)
{
if (!excludedCreditCards.Any(x => x.IsCaseInsensitiveEqual(creditCard.Value)))
{
m.CreditCardTypes.Add(new SelectListItem
{
Text = creditCard.Text,
Value = creditCard.Value
});
}
}
});
// years
for (int i = 0; i < 15; i++)
{
string year = Convert.ToString(DateTime.Now.Year + i);
model.ExpireYears.Add(new SelectListItem { Text = year, Value = year });
}
// months
for (int i = 1; i <= 12; i++)
{
string text = (i < 10) ? "0" + i.ToString() : i.ToString();
model.ExpireMonths.Add(new SelectListItem { Text = text, Value = i.ToString() });
}
// set postback values
var paymentData = _httpContext.GetCheckoutState().PaymentData;
model.CardholderName = (string)paymentData.Get("CardholderName");
model.CardNumber = (string)paymentData.Get("CardNumber");
model.CardCode = (string)paymentData.Get("CardCode");
var creditCardType = (string)paymentData.Get("CreditCardType");
var selectedCcType = model.CreditCardTypes.Where(x => x.Value.Equals(creditCardType, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
if (selectedCcType != null)
selectedCcType.Selected = true;
var expireMonth = (string)paymentData.Get("ExpireMonth");
var selectedMonth = model.ExpireMonths.Where(x => x.Value.Equals(expireMonth, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
if (selectedMonth != null)
selectedMonth.Selected = true;
var expireYear = (string)paymentData.Get("ExpireYear");
var selectedYear = model.ExpireYears.Where(x => x.Value.Equals(expireYear, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
if (selectedYear != null)
selectedYear.Selected = true;
return PartialView(model);
}
#endregion
#region PurchaseOrderNumber
[AdminAuthorize]
[ChildActionOnly]
public ActionResult PurchaseOrderNumberConfigure()
{
var model = ConfigureGet<PurchaseOrderNumberConfigurationModel, PurchaseOrderNumberPaymentSettings>();
return View("GenericConfigure", model);
}
[HttpPost, AdminAuthorize, ChildActionOnly, ValidateInput(false)]
public ActionResult PurchaseOrderNumberConfigure(PurchaseOrderNumberConfigurationModel model, FormCollection form)
{
if (!ModelState.IsValid)
return InvoiceConfigure();
ConfigurePost<PurchaseOrderNumberConfigurationModel, InvoicePaymentSettings>(model, form);
return PurchaseOrderNumberConfigure();
}
public ActionResult PurchaseOrderNumberPaymentInfo()
{
var model = PaymentInfoGet<PurchaseOrderNumberPaymentInfoModel, InvoicePaymentSettings>();
var paymentData = _httpContext.GetCheckoutState().PaymentData;
model.PurchaseOrderNumber = (string)paymentData.Get("PurchaseOrderNumber");
return PartialView("PurchaseOrderNumberPaymentInfo", model);
}
#endregion
}
} | 30.870201 | 152 | 0.721308 | [
"MIT"
] | jenmcquade/csharp-snippets | SmartStoreNET-3.x/src/Plugins/SmartStore.OfflinePayment/Controllers/OfflinePaymentController.cs | 16,888 | C# |
namespace JsonToEnum.Export {
public enum DestinyRecordCompletionStatus
{
Incomplete = 0,
Complete = 1,
Redeemed = 2
}
} | 18.625 | 46 | 0.624161 | [
"MIT"
] | nine13tech/Destiny-API-Frameworks | C#/Destiny 1/Enum/bin/debug/enums/DestinyRecordCompletionStatus .cs | 149 | C# |
using System.Data.Entity.ModelConfiguration;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace AdventureWorksModel
{
public class EmployeeMap : EntityTypeConfiguration<Employee>
{
public EmployeeMap()
{
// Primary Key
HasKey(t => t.BusinessEntityID);
// Properties
Property(t => t.NationalIDNumber)
.IsRequired()
.HasMaxLength(15);
Property(t => t.LoginID)
.IsRequired()
.HasMaxLength(256);
Property(t => t.JobTitle)
.IsRequired()
.HasMaxLength(50);
Property(t => t.MaritalStatus)
.IsRequired()
.IsFixedLength()
.HasMaxLength(1);
Property(t => t.Gender)
.IsRequired()
.IsFixedLength()
.HasMaxLength(1);
// Table & Column Mappings
ToTable("Employee", "HumanResources");
Property(t => t.BusinessEntityID).HasColumnName("BusinessEntityID");
Property(t => t.NationalIDNumber).HasColumnName("NationalIDNumber");
Property(t => t.LoginID).HasColumnName("LoginID");
Ignore(t => t.ManagerID);//.HasColumnName("ManagerID");
Property(t => t.JobTitle).HasColumnName("JobTitle");
Property(t => t.DateOfBirth).HasColumnName("BirthDate");
Property(t => t.MaritalStatus).HasColumnName("MaritalStatus");
Property(t => t.Gender).HasColumnName("Gender");
Property(t => t.HireDate).HasColumnName("HireDate");
Property(t => t.Salaried).HasColumnName("SalariedFlag");
Property(t => t.VacationHours).HasColumnName("VacationHours");
Property(t => t.SickLeaveHours).HasColumnName("SickLeaveHours");
Property(t => t.Current).HasColumnName("CurrentFlag");
Property(t => t.rowguid).HasColumnName("rowguid");
Property(t => t.ModifiedDate).HasColumnName("ModifiedDate").IsConcurrencyToken(false);
// Relationships
Ignore(t => t.Manager);
//.WithMany(t => t.DirectReports)
//.HasForeignKey(d => d.ManagerID);
HasOptional(t => t.SalesPerson).WithRequired(t => t.EmployeeDetails);
HasRequired(t => t.PersonDetails).WithOptional(t => t.Employee);
}
}
public static partial class Mapper
{
public static void Map(this EntityTypeBuilder<Employee> builder)
{
builder.HasKey(t => t.BusinessEntityID);
// Properties
builder.Property(t => t.NationalIDNumber)
.IsRequired()
.HasMaxLength(15);
builder.Property(t => t.LoginID)
.IsRequired()
.HasMaxLength(256);
builder.Property(t => t.JobTitle)
.IsRequired()
.HasMaxLength(50);
builder.Property(t => t.MaritalStatus)
.IsRequired()
.IsFixedLength()
.HasMaxLength(1);
builder.Property(t => t.Gender)
.IsRequired()
.IsFixedLength()
.HasMaxLength(1);
// Table & Column Mappings
builder.ToTable("Employee", "HumanResources");
builder.Property(t => t.BusinessEntityID).HasColumnName("BusinessEntityID");
builder.Property(t => t.NationalIDNumber).HasColumnName("NationalIDNumber");
builder.Property(t => t.LoginID).HasColumnName("LoginID");
builder.Property(t => t.JobTitle).HasColumnName("JobTitle");
builder.Property(t => t.DateOfBirth).HasColumnName("BirthDate");
builder.Property(t => t.MaritalStatus).HasColumnName("MaritalStatus");
builder.Property(t => t.Gender).HasColumnName("Gender");
builder.Property(t => t.HireDate).HasColumnName("HireDate");
builder.Property(t => t.Salaried).HasColumnName("SalariedFlag");
builder.Property(t => t.VacationHours).HasColumnName("VacationHours");
builder.Property(t => t.SickLeaveHours).HasColumnName("SickLeaveHours");
builder.Property(t => t.Current).HasColumnName("CurrentFlag");
builder.Property(t => t.rowguid).HasColumnName("rowguid");
builder.Property(t => t.ModifiedDate).HasColumnName("ModifiedDate").IsConcurrencyToken(false);
builder.Ignore(t => t.ManagerID);//.HasColumnName("ManagerID");
// Relationships
builder.Ignore(t => t.Manager);
//.WithMany(t => t.DirectReports)
//.HasForeignKey(d => d.ManagerID);
//builder.HasOne(t => t.SalesPerson).WithOne(t => t.EmployeeDetails);
builder.HasOne(t => t.PersonDetails).WithOne(t => t.Employee);
}
}
}
| 41.032787 | 106 | 0.567119 | [
"Apache-2.0"
] | NakedObjectsGroup/NakedObjectsFramework | Test/AdventureWorksModel/Mapping/EmployeeMap.cs | 5,006 | C# |
#region Copyright
//
// DotNetNuke® - https://www.dnnsoftware.com
// Copyright (c) 2002-2018
// by DotNetNuke Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Web.UI.HtmlControls;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Host;
using DotNetNuke.UI.ControlPanels;
using DotNetNuke.Web.Client;
using DotNetNuke.Web.Client.ClientResourceManagement;
namespace DotNetNuke.UI.Skins.Controls
{
public class ControlPanel : SkinObjectBase
{
public bool IsDockable { get; set; }
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (Request.QueryString["dnnprintmode"] != "true" && !UrlUtils.InPopUp())
{
var objControlPanel = ControlUtilities.LoadControl<ControlPanelBase>(this, Host.ControlPanel);
var objForm = (HtmlForm)Page.FindControl("Form");
if(objControlPanel.IncludeInControlHierarchy)
{
objControlPanel.IsDockable = IsDockable;
if (!Host.ControlPanel.EndsWith("controlbar.ascx", StringComparison.InvariantCultureIgnoreCase))
Controls.Add(objControlPanel);
else
{
if (objForm != null)
{
objForm.Controls.AddAt(0, objControlPanel);
}
else
{
Page.Controls.AddAt(0, objControlPanel);
}
}
//register admin.css
ClientResourceManager.RegisterAdminStylesheet(Page, Globals.HostPath + "admin.css");
}
}
}
}
}
| 40.071429 | 116 | 0.648128 | [
"MIT"
] | Mhtshum/Dnn.Platform | DNN Platform/Library/UI/Skins/Controls/ControlPanel.cs | 2,808 | C# |
using System.Collections.Generic;
using UIForia.Attributes;
using UIForia.Elements;
using UIForia.Layout;
using UIForia.Rendering;
using UIForia.UIInput;
using UnityEngine;
using UnityEngine.PlayerLoop;
namespace SpaceGameDemo.SinglePlayer {
public class ShipData {
public int id;
public string name;
public ShipData(int id, string name) {
this.id = id;
this.name = name;
}
}
public class InventoryItem {
public string name;
public int width;
public int height;
public InventoryItem(string name, int width, int height) {
this.name = name;
this.width = width;
this.height = height;
}
}
public enum TabItem {
Ships, Items, Stats
}
[Template("SpaceGameDemo/SinglePlayer/SinglePlayer.xml")]
public class SinglePlayer : UIElement {
public int selectedShip = 1;
public int selectedPilot = 1;
public List<ShipData> ships;
// Property
public float progress;
// Property
public string progressString;
// Property
public TabItem tab = TabItem.Ships;
// Property
public List<InventoryItem> availableItems;
// Property
public List<InventoryItem> inventoryItems;
// Property
public int upgradePoints = 39;
// Property
public string nickname;
private float speed = 0.1f;
public override void OnUpdate() {
progress += Time.deltaTime * speed;
if (progress > 1) {
progress = 0;
}
progressString = (progress * 100).ToString("F1");
}
public override void OnCreate() {
ships = new List<ShipData>() {
new ShipData(1, "Cruiser"),
new ShipData(2, "Bomber"),
new ShipData(3, "Shuttle"),
new ShipData(4, "Fighter"),
};
availableItems = new List<InventoryItem>() {
new InventoryItem("R1 Rockets", 2, 1),
new InventoryItem("Beam Laser", 2, 1),
new InventoryItem("Drone System", 4, 4),
new InventoryItem("Cool Drinks", 2, 1),
new InventoryItem("Radar", 2, 2),
};
inventoryItems = new List<InventoryItem>();
}
public void SelectShip(int id) {
selectedShip = id;
}
public void SelectPilot(int pilot) {
selectedPilot = pilot;
}
public DragEvent OnDragCreateItem(MouseInputEvent evt, InventoryItem item) {
return new InventoryItemDragEvent(evt, item);
}
public void SelectTab(TabItem tabItem) {
tab = tabItem;
}
public void DropItemIntoList(DragEvent evt) {
if (evt is InventoryItemDragEvent inventoryEvent) {
InventoryItem item = inventoryEvent.item;
if (!availableItems.Contains(item)) {
inventoryItems.Remove(item);
availableItems.Add(item);
}
}
}
public void DropItemIntoInventory(DragEvent evt) {
if (evt is InventoryItemDragEvent inventoryEvent) {
InventoryItem item = inventoryEvent.item;
if (!inventoryItems.Contains(item)) {
inventoryItems.Add(inventoryEvent.item);
availableItems.Remove(inventoryEvent.item);
}
}
}
}
public class InventoryItemDragEvent : DragEvent {
public InventoryItem item;
private UIElement itemElement;
private Vector2 offset;
public InventoryItemDragEvent(MouseInputEvent evt, InventoryItem item) {
this.item = item;
itemElement = evt.element;
offset = evt.MousePosition - itemElement.layoutResult.screenPosition;
itemElement.style.SetAlignmentTargetX(AlignmentTarget.Mouse, StyleState.Normal);
itemElement.style.SetAlignmentTargetY(AlignmentTarget.Mouse, StyleState.Normal);
itemElement.style.SetAlignmentOffsetX(-offset.x, StyleState.Normal);
itemElement.style.SetAlignmentOffsetY(-offset.y, StyleState.Normal);
}
public override void Update() { }
public override void Drop(bool success) {
itemElement.style.SetAlignmentTargetX(AlignmentTarget.Unset, StyleState.Normal);
itemElement.style.SetAlignmentTargetY(AlignmentTarget.Unset, StyleState.Normal);
itemElement.style.SetAlignmentOffsetX(null, StyleState.Normal);
itemElement.style.SetAlignmentOffsetY(null, StyleState.Normal);
}
}
} | 31.082803 | 92 | 0.57623 | [
"MIT"
] | criedel/UIForia | Assets/SpaceGameDemo/SinglePlayer/SinglePlayer.cs | 4,882 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleTetris.Display
{
public class ConsoleScreen
{
private StringBuilder _renderBuffer;
public void Init(int width, int height)
{
// Avoid blinking by optimizing the buffering space in console
// https://stackoverflow.com/questions/28490246/console-clear-blinking
Console.SetWindowSize(2 * width, 2 * height);
Console.SetBufferSize(2 * width + 1, 2 * height + 1);
_renderBuffer = new StringBuilder(width);
}
public void Draw(Scene scene)
{
Console.Clear();
scene.Draw();
// TODO: Colors Console.ForegroundColor = ConsoleColor.Blue;
FrameBuffer frameToDraw = scene.GetCurrentFrame();
PutFrameOnScreen(scene, frameToDraw);
}
public void DrawBye()
{
Console.Clear();
Console.WriteLine("BYE! THANK YOU!");
}
public void DrawDebug(string text)
{
Console.WriteLine(text);
}
private void PutFrameOnScreen(Scene scene, FrameBuffer frameToDraw)
{
List<string> renderPipeline = new List<string>();
int tempW = 0;
for (int i = 0; i < frameToDraw.Pixels.Length; i++)
{
if (tempW == frameToDraw.Width)
{
tempW = 0;
renderPipeline.Add(_renderBuffer.ToString());
_renderBuffer = _renderBuffer.Clear();
}
_renderBuffer.Append(frameToDraw.Pixels[i].Value);
++tempW;
}
renderPipeline.Add(_renderBuffer.ToString());
_renderBuffer = _renderBuffer.Clear();
// Draw
for (int i = 0; i < renderPipeline.Count; i++)
{
Console.WriteLine(renderPipeline[i]);
}
Console.WriteLine("Points earned: " + frameToDraw.PointsEarned.ToString());
}
}
}
| 28.08 | 87 | 0.536562 | [
"Apache-2.0"
] | optiklab/ConsoleTetris | src/Display/ConsoleScreen.cs | 2,108 | C# |
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
// 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("AWSSDK.Rekognition")]
#if BCL35
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Rekognition. AWS Rekognition service does image processing and concept recognition, face detection and identification, face verification, similar face search and face clustering.")]
#elif BCL45
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Amazon Rekognition. AWS Rekognition service does image processing and concept recognition, face detection and identification, face verification, similar face search and face clustering.")]
#elif NETSTANDARD13
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3) - Amazon Rekognition. AWS Rekognition service does image processing and concept recognition, face detection and identification, face verification, similar face search and face clustering.")]
#elif NETSTANDARD20
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - Amazon Rekognition. AWS Rekognition service does image processing and concept recognition, face detection and identification, face verification, similar face search and face clustering.")]
#elif NETCOREAPP3_1
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - Amazon Rekognition. AWS Rekognition service does image processing and concept recognition, face detection and identification, face verification, similar face search and face clustering.")]
#else
#error Unknown platform constant - unable to set correct AssemblyDescription
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[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)]
// 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("3.3")]
[assembly: AssemblyFileVersion("3.5.0.0")]
[assembly: System.CLSCompliant(true)]
#if BCL
[assembly: System.Security.AllowPartiallyTrustedCallers]
#endif | 56.132075 | 277 | 0.784202 | [
"Apache-2.0"
] | sudoudaisuke/aws-sdk-net | sdk/src/Services/Rekognition/Properties/AssemblyInfo.cs | 2,975 | C# |
using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
using Microsoft.Xaml.Behaviors;
namespace Rml.Wpf.Behavior
{
/// <summary>
///
/// </summary>
public class WindowClosingBehavior : Behavior<FrameworkElement>
{
/// <summary>
///
/// </summary>
public static readonly DependencyProperty ClosingProperty = DependencyProperty.Register(
"Closing", typeof(ICommand), typeof(WindowClosingBehavior), new PropertyMetadata(default(ICommand)));
/// <summary>
///
/// </summary>
public ICommand Closing
{
get { return (ICommand) GetValue(ClosingProperty); }
set { SetValue(ClosingProperty, value); }
}
private Window _window;
/// <inheritdoc />
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.Loaded += AssociatedObjectOnLoaded;
}
private void AssociatedObjectOnLoaded(object sender, RoutedEventArgs e)
{
DetachClosing();
_window = AssociatedObject as Window ?? Window.GetWindow(AssociatedObject);
if (_window == null)
{
return;
}
_window.Closing += WindowOnClosing;
}
private void WindowOnClosing(object sender, CancelEventArgs args)
{
if (Closing == null)
{
return;
}
if (Closing.CanExecute(args))
{
Closing.Execute(args);
}
}
private void DetachClosing()
{
if (_window != null)
{
_window.Closing -= WindowOnClosing;
}
_window = null;
}
/// <inheritdoc />
protected override void OnDetaching()
{
DetachClosing();
AssociatedObject.Loaded -= AssociatedObjectOnLoaded;
base.OnDetaching();
}
}
} | 26.036585 | 114 | 0.507728 | [
"MIT"
] | ryo1988/Rml | Rml.Wpf/Behavior/WindowClosingBehavior.cs | 2,137 | C# |
// <copyright file="RealTimeBuildingAI.cs" company="dymanoid">
// Copyright (c) dymanoid. All rights reserved.
// </copyright>
namespace RealTime.CustomAI
{
using System;
using RealTime.Config;
using RealTime.GameConnection;
using RealTime.Simulation;
using static Constants;
/// <summary>
/// A class that incorporates the custom logic for the private buildings.
/// </summary>
internal sealed class RealTimeBuildingAI : IRealTimeBuildingAI
{
private const int ConstructionSpeedPaused = 10880;
private const int ConstructionSpeedMinimum = 1088;
private const int StepMask = 0xFF;
private const int BuildingStepSize = 192;
private static readonly string[] BannedEntertainmentBuildings = { "parking", "garage", "car park" };
private readonly TimeSpan lightStateCheckInterval = TimeSpan.FromSeconds(15);
private readonly RealTimeConfig config;
private readonly ITimeInfo timeInfo;
private readonly IBuildingManagerConnection buildingManager;
private readonly IToolManagerConnection toolManager;
private readonly IWorkBehavior workBehavior;
private readonly ITravelBehavior travelBehavior;
private readonly bool[] lightStates;
private int lastProcessedMinute = -1;
private bool freezeProblemTimers;
private uint lastConfigConstructionSpeedValue;
private double constructionSpeedValue;
private int lightStateCheckFramesInterval;
private int lightStateCheckCounter;
private ushort lightCheckStep;
/// <summary>
/// Initializes a new instance of the <see cref="RealTimeBuildingAI"/> class.
/// </summary>
///
/// <param name="config">The configuration to run with.</param>
/// <param name="timeInfo">The time information source.</param>
/// <param name="buildingManager">A proxy object that provides a way to call the game-specific methods of the <see cref="BuildingManager"/> class.</param>
/// <param name="toolManager">A proxy object that provides a way to call the game-specific methods of the <see cref="ToolManager"/> class.</param>
/// <param name="workBehavior">A behavior that provides simulation info for the citizens' work time.</param>
/// <param name="travelBehavior">A behavior that provides simulation info for the citizens' traveling.</param>
/// <exception cref="ArgumentNullException">Thrown when any argument is null.</exception>
public RealTimeBuildingAI(
RealTimeConfig config,
ITimeInfo timeInfo,
IBuildingManagerConnection buildingManager,
IToolManagerConnection toolManager,
IWorkBehavior workBehavior,
ITravelBehavior travelBehavior)
{
this.config = config ?? throw new ArgumentNullException(nameof(config));
this.timeInfo = timeInfo ?? throw new ArgumentNullException(nameof(timeInfo));
this.buildingManager = buildingManager ?? throw new ArgumentNullException(nameof(buildingManager));
this.toolManager = toolManager ?? throw new ArgumentNullException(nameof(toolManager));
this.workBehavior = workBehavior ?? throw new ArgumentNullException(nameof(workBehavior));
this.travelBehavior = travelBehavior ?? throw new ArgumentNullException(nameof(travelBehavior));
lightStates = new bool[buildingManager.GetMaxBuildingsCount()];
}
/// <summary>
/// Gets the building construction time taking into account the current day time.
/// </summary>
///
/// <returns>The building construction time in game-specific units (0..10880)</returns>
public int GetConstructionTime()
{
if ((toolManager.GetCurrentMode() & ItemClass.Availability.AssetEditor) != 0)
{
return 0;
}
if (config.ConstructionSpeed != lastConfigConstructionSpeedValue)
{
lastConfigConstructionSpeedValue = config.ConstructionSpeed;
double inverted = 101d - lastConfigConstructionSpeedValue;
constructionSpeedValue = inverted * inverted * inverted / 1_000_000d;
}
// This causes the construction to not advance in the night time
return timeInfo.IsNightTime && config.StopConstructionAtNight
? ConstructionSpeedPaused
: (int)(ConstructionSpeedMinimum * constructionSpeedValue);
}
/// <summary>
/// Performs the custom processing of the outgoing problem timer.
/// </summary>
/// <param name="buildingId">The ID of the building to process.</param>
/// <param name="outgoingProblemTimer">The previous value of the outgoing problem timer.</param>
public void ProcessBuildingProblems(ushort buildingId, byte outgoingProblemTimer)
{
// We have only few customers at night - that's an intended behavior.
// To avoid commercial buildings from collapsing due to lack of customers,
// we force the problem timer to pause at night time.
// In the daytime, the timer is running slower.
if (timeInfo.IsNightTime || timeInfo.Now.Minute % ProblemTimersInterval != 0 || freezeProblemTimers)
{
buildingManager.SetOutgoingProblemTimer(buildingId, outgoingProblemTimer);
}
}
/// <summary>
/// Performs the custom processing of the worker problem timer.
/// </summary>
/// <param name="buildingId">The ID of the building to process.</param>
/// <param name="oldValue">The old value of the worker problem timer.</param>
public void ProcessWorkerProblems(ushort buildingId, byte oldValue)
{
// We force the problem timer to pause at night time.
// In the daytime, the timer is running slower.
if (timeInfo.IsNightTime || timeInfo.Now.Minute % ProblemTimersInterval != 0 || freezeProblemTimers)
{
buildingManager.SetWorkersProblemTimer(buildingId, oldValue);
}
}
/// <summary>Initializes the state of the all building lights.</summary>
public void InitializeLightState()
{
for (ushort i = 0; i <= StepMask; i++)
{
UpdateLightState(i, false);
}
}
/// <summary>Re-calculates the duration of a simulation frame.</summary>
public void UpdateFrameDuration()
{
lightStateCheckFramesInterval = (int)(lightStateCheckInterval.TotalHours / timeInfo.HoursPerFrame);
if (lightStateCheckFramesInterval == 0)
{
++lightStateCheckFramesInterval;
}
}
/// <summary>Notifies this simulation object that a new simulation frame is started.
/// The buildings will be processed again from the beginning of the list.</summary>
/// <param name="frameIndex">The simulation frame index to process.</param>
public void ProcessFrame(uint frameIndex)
{
UpdateLightState();
if ((frameIndex & StepMask) != 0)
{
return;
}
int currentMinute = timeInfo.Now.Minute;
if (lastProcessedMinute != currentMinute)
{
lastProcessedMinute = currentMinute;
freezeProblemTimers = false;
}
else
{
freezeProblemTimers = true;
}
}
/// <summary>
/// Determines whether the lights should be switched off in the specified building.
/// </summary>
/// <param name="buildingId">The ID of the building to check.</param>
/// <returns>
/// <c>true</c> if the lights should be switched off in the specified building; otherwise, <c>false</c>.
/// </returns>
public bool ShouldSwitchBuildingLightsOff(ushort buildingId)
{
return config.SwitchOffLightsAtNight && !lightStates[buildingId];
}
/// <summary>
/// Determines whether the building with the specified ID is an entertainment target.
/// </summary>
/// <param name="buildingId">The building ID to check.</param>
/// <returns>
/// <c>true</c> if the building is an entertainment target; otherwise, <c>false</c>.
/// </returns>
public bool IsEntertainmentTarget(ushort buildingId)
{
if (buildingId == 0)
{
return true;
}
string className = buildingManager.GetBuildingClassName(buildingId);
if (string.IsNullOrEmpty(className))
{
return true;
}
for (int i = 0; i < BannedEntertainmentBuildings.Length; ++i)
{
if (className.IndexOf(BannedEntertainmentBuildings[i], 0, StringComparison.OrdinalIgnoreCase) >= 0)
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether the building with the specified <paramref name="buildingId"/> is noise restricted
/// (has NIMBY policy that is active on current time).
/// </summary>
/// <param name="buildingId">The building ID to check.</param>
/// <param name="currentBuildingId">The ID of a building where the citizen starts their journey.
/// Specify 0 if there is no journey in schedule.</param>
/// <returns>
/// <c>true</c> if the building with the specified <paramref name="buildingId"/> has NIMBY policy
/// that is active on current time; otherwise, <c>false</c>.
/// </returns>
public bool IsNoiseRestricted(ushort buildingId, ushort currentBuildingId = 0)
{
if (buildingManager.GetBuildingSubService(buildingId) != ItemClass.SubService.CommercialLeisure)
{
return false;
}
float currentHour = timeInfo.CurrentHour;
if (currentHour >= config.GoToSleepHour || currentHour <= config.WakeUpHour)
{
return buildingManager.IsBuildingNoiseRestricted(buildingId);
}
if (currentBuildingId == 0)
{
return false;
}
float travelTime = travelBehavior.GetEstimatedTravelTime(currentBuildingId, buildingId);
if (travelTime == 0)
{
return false;
}
float arriveHour = (float)timeInfo.Now.AddHours(travelTime).TimeOfDay.TotalHours;
if (arriveHour >= config.GoToSleepHour || arriveHour <= config.WakeUpHour)
{
return buildingManager.IsBuildingNoiseRestricted(buildingId);
}
return false;
}
private void UpdateLightState()
{
if (lightStateCheckCounter > 0)
{
--lightStateCheckCounter;
return;
}
ushort step = lightCheckStep;
lightCheckStep = (ushort)((step + 1) & StepMask);
lightStateCheckCounter = lightStateCheckFramesInterval;
UpdateLightState(step, true);
}
private void UpdateLightState(ushort step, bool updateBuilding)
{
ushort first = (ushort)(step * BuildingStepSize);
ushort last = (ushort)(((step + 1) * BuildingStepSize) - 1);
for (ushort i = first; i <= last; ++i)
{
buildingManager.GetBuildingService(i, out ItemClass.Service service, out ItemClass.SubService subService);
bool lightsOn = !ShouldSwitchBuildingLightsOff(i, service, subService);
if (lightsOn == lightStates[i])
{
continue;
}
lightStates[i] = lightsOn;
if (updateBuilding)
{
buildingManager.UpdateBuildingColors(i);
}
}
}
private bool ShouldSwitchBuildingLightsOff(ushort buildingId, ItemClass.Service service, ItemClass.SubService subService)
{
switch (service)
{
case ItemClass.Service.None:
return false;
case ItemClass.Service.Residential:
float currentHour = timeInfo.CurrentHour;
return currentHour < Math.Min(config.WakeUpHour, EarliestWakeUp) || currentHour >= config.GoToSleepHour;
case ItemClass.Service.Office when buildingManager.GetBuildingLevel(buildingId) != ItemClass.Level.Level1:
return false;
case ItemClass.Service.Commercial when subService == ItemClass.SubService.CommercialLeisure:
return IsNoiseRestricted(buildingId);
case ItemClass.Service.Commercial
when subService == ItemClass.SubService.CommercialHigh && buildingManager.GetBuildingLevel(buildingId) != ItemClass.Level.Level1:
return false;
case ItemClass.Service.Monument:
return false;
default:
return !workBehavior.IsBuildingWorking(service, subService);
}
}
}
}
| 41.478659 | 162 | 0.602132 | [
"MIT"
] | Louuiss/RealTime | src/RealTime/CustomAI/RealTimeBuildingAI.cs | 13,607 | C# |
//---------------------------------------------------------------------
// This file is part of the CLR Managed Debugger (mdbg) Sample.
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//---------------------------------------------------------------------
using System;
using System.Collections;
using Microsoft.Samples.Debugging.CorDebug.NativeApi;
namespace Microsoft.Samples.Debugging.CorDebug
{
/** Exposes an enumerator for Modules. */
internal class CorModuleEnumerator : IEnumerable, IEnumerator, ICloneable
{
private ICorDebugModuleEnum m_enum;
private CorModule m_mod;
internal CorModuleEnumerator (ICorDebugModuleEnum moduleEnumerator)
{
m_enum = moduleEnumerator;
}
//
// ICloneable interface
//
public Object Clone ()
{
ICorDebugEnum clone = null;
m_enum.Clone (out clone);
return new CorModuleEnumerator ((ICorDebugModuleEnum)clone);
}
//
// IEnumerable interface
//
public IEnumerator GetEnumerator ()
{
return this;
}
//
// IEnumerator interface
//
public bool MoveNext ()
{
ICorDebugModule[] a = new ICorDebugModule[1];
uint c = 0;
int r = m_enum.Next ((uint) a.Length, a, out c);
if (r==0 && c==1) // S_OK && we got 1 new element
m_mod = new CorModule (a[0]);
else
m_mod = null;
return m_mod != null;
}
public void Reset ()
{
m_enum.Reset ();
m_mod = null;
}
public Object Current
{
get
{
return m_mod;
}
}
} /* class ModuleEnumerator */
} /* namespace */
| 26.263889 | 77 | 0.483871 | [
"MIT"
] | Inncee81/cs-script.npp | src/Mdbg_v4.0/Mdbg/debugger/corapi/ModuleEnumerator.cs | 1,891 | 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 cloudfront-2020-05-31.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.CloudFront.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using System.Xml;
namespace Amazon.CloudFront.Model.Internal.MarshallTransformations
{
/// <summary>
/// DeleteFieldLevelEncryptionConfig Request Marshaller
/// </summary>
public class DeleteFieldLevelEncryptionConfigRequestMarshaller : IMarshaller<IRequest, DeleteFieldLevelEncryptionConfigRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((DeleteFieldLevelEncryptionConfigRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(DeleteFieldLevelEncryptionConfigRequest publicRequest)
{
var request = new DefaultRequest(publicRequest, "Amazon.CloudFront");
request.HttpMethod = "DELETE";
if(publicRequest.IsSetIfMatch())
request.Headers["If-Match"] = publicRequest.IfMatch;
if (!publicRequest.IsSetId())
throw new AmazonCloudFrontException("Request object does not have required field Id set");
request.AddPathResource("{Id}", StringUtils.FromString(publicRequest.Id));
request.ResourcePath = "/2020-05-31/field-level-encryption/{Id}";
request.MarshallerVersion = 2;
return request;
}
private static DeleteFieldLevelEncryptionConfigRequestMarshaller _instance = new DeleteFieldLevelEncryptionConfigRequestMarshaller();
internal static DeleteFieldLevelEncryptionConfigRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DeleteFieldLevelEncryptionConfigRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 35.811111 | 179 | 0.66708 | [
"Apache-2.0"
] | PureKrome/aws-sdk-net | sdk/src/Services/CloudFront/Generated/Model/Internal/MarshallTransformations/DeleteFieldLevelEncryptionConfigRequestMarshaller.cs | 3,223 | 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.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection.PortableExecutable;
using System.Text;
namespace ILCompiler.Reflection.ReadyToRun
{
/// <summary>
/// Represents the debug information for a single method in the ready-to-run image.
/// See <a href="https://github.com/dotnet/coreclr/blob/master/src/inc/cordebuginfo.h">src\inc\cordebuginfo.h</a> for
/// the fundamental types this is based on.
/// </summary>
public class DebugInfo
{
private List<DebugInfoBoundsEntry> _boundsList = new List<DebugInfoBoundsEntry>();
private List<NativeVarInfo> _variablesList = new List<NativeVarInfo>();
private Machine _machine;
public DebugInfo(byte[] image, int offset, Machine machine)
{
_machine = machine;
// Get the id of the runtime function from the NativeArray
uint lookback = 0;
uint debugInfoOffset = NativeReader.DecodeUnsigned(image, (uint)offset, ref lookback);
if (lookback != 0)
{
System.Diagnostics.Debug.Assert(0 < lookback && lookback < offset);
debugInfoOffset = (uint)offset - lookback;
}
NibbleReader reader = new NibbleReader(image, (int)debugInfoOffset);
uint boundsByteCount = reader.ReadUInt();
uint variablesByteCount = reader.ReadUInt();
int boundsOffset = reader.GetNextByteOffset();
int variablesOffset = (int)(boundsOffset + boundsByteCount);
if (boundsByteCount > 0)
{
ParseBounds(image, boundsOffset);
}
if (variablesByteCount > 0)
{
ParseNativeVarInfo(image, variablesOffset);
}
}
public List<DebugInfoBoundsEntry> BoundsList => _boundsList;
public List<NativeVarInfo> VariablesList => _variablesList;
public Machine Machine => _machine;
/// <summary>
/// Convert a register number in debug info into a machine-specific register
/// </summary>
public static string GetPlatformSpecificRegister(Machine machine, int regnum)
{
switch (machine)
{
case Machine.I386:
return ((x86.Registers)regnum).ToString();
case Machine.Amd64:
return ((Amd64.Registers)regnum).ToString();
case Machine.Arm:
return ((Arm.Registers)regnum).ToString();
case Machine.Arm64:
return ((Arm64.Registers)regnum).ToString();
default:
throw new NotImplementedException($"No implementation for machine type {machine}.");
}
}
private void ParseBounds(byte[] image, int offset)
{
// Bounds info contains (Native Offset, IL Offset, flags)
// - Sorted by native offset (so use a delta encoding for that).
// - IL offsets aren't sorted, but they should be close to each other (so a signed delta encoding)
// They may also include a sentinel value from MappingTypes.
// - flags is 3 indepedent bits.
NibbleReader reader = new NibbleReader(image, offset);
uint boundsEntryCount = reader.ReadUInt();
Debug.Assert(boundsEntryCount > 0);
uint previousNativeOffset = 0;
for (int i = 0; i < boundsEntryCount; ++i)
{
var entry = new DebugInfoBoundsEntry();
previousNativeOffset += reader.ReadUInt();
entry.NativeOffset = previousNativeOffset;
entry.ILOffset = (uint)(reader.ReadUInt() + (int)MappingTypes.MaxMappingValue);
entry.SourceTypes = (SourceTypes)reader.ReadUInt();
_boundsList.Add(entry);
}
}
private void ParseNativeVarInfo(byte[] image, int offset)
{
// Each Varinfo has a:
// - native start +End offset. We can use a delta for the end offset.
// - Il variable number. These are usually small.
// - VarLoc information. This is a tagged variant.
// The entries aren't sorted in any particular order.
NibbleReader reader = new NibbleReader(image, offset);
uint nativeVarCount = reader.ReadUInt();
for (int i = 0; i < nativeVarCount; ++i)
{
var entry = new NativeVarInfo();
entry.StartOffset = reader.ReadUInt();
entry.EndOffset = entry.StartOffset + reader.ReadUInt();
entry.VariableNumber = (uint)(reader.ReadUInt() + (int)ImplicitILArguments.Max);
var varLoc = new VarLoc();
varLoc.VarLocType = (VarLocType)reader.ReadUInt();
switch (varLoc.VarLocType)
{
case VarLocType.VLT_REG:
case VarLocType.VLT_REG_FP:
case VarLocType.VLT_REG_BYREF:
varLoc.Data1 = (int)reader.ReadUInt();
break;
case VarLocType.VLT_STK:
case VarLocType.VLT_STK_BYREF:
varLoc.Data1 = (int)reader.ReadUInt();
varLoc.Data2 = ReadEncodedStackOffset(reader);
break;
case VarLocType.VLT_REG_REG:
varLoc.Data1 = (int)reader.ReadUInt();
varLoc.Data2 = (int)reader.ReadUInt();
break;
case VarLocType.VLT_REG_STK:
varLoc.Data1 = (int)reader.ReadUInt();
varLoc.Data2 = (int)reader.ReadUInt();
varLoc.Data3 = ReadEncodedStackOffset(reader);
break;
case VarLocType.VLT_STK_REG:
varLoc.Data1 = ReadEncodedStackOffset(reader);
varLoc.Data2 = (int)reader.ReadUInt();
varLoc.Data3 = (int)reader.ReadUInt();
break;
case VarLocType.VLT_STK2:
varLoc.Data1 = (int)reader.ReadUInt();
varLoc.Data2 = ReadEncodedStackOffset(reader);
break;
case VarLocType.VLT_FPSTK:
varLoc.Data1 = (int)reader.ReadUInt();
break;
case VarLocType.VLT_FIXED_VA:
varLoc.Data1 = (int)reader.ReadUInt();
break;
default:
throw new BadImageFormatException("Unexpected var loc type");
}
entry.VariableLocation = varLoc;
_variablesList.Add(entry);
}
}
private int ReadEncodedStackOffset(NibbleReader reader)
{
int offset = reader.ReadInt();
if (_machine == Machine.I386)
{
offset *= 4; // sizeof(DWORD)
}
return offset;
}
}
}
| 41.748603 | 121 | 0.543824 | [
"MIT"
] | AArnott/runtime | src/coreclr/src/tools/crossgen2/ILCompiler.Reflection.ReadyToRun/DebugInfo.cs | 7,473 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
namespace Azure.Identity
{
internal class EnvironmentVariables
{
public static string Username => Environment.GetEnvironmentVariable("AZURE_USERNAME");
public static string Password => Environment.GetEnvironmentVariable("AZURE_PASSWORD");
public static string TenantId => Environment.GetEnvironmentVariable("AZURE_TENANT_ID");
public static string ClientId => Environment.GetEnvironmentVariable("AZURE_CLIENT_ID");
public static string ClientSecret => Environment.GetEnvironmentVariable("AZURE_CLIENT_SECRET");
public static string ClientCertificatePath => Environment.GetEnvironmentVariable("AZURE_CLIENT_CERTIFICATE_PATH");
public static string MsiEndpoint => Environment.GetEnvironmentVariable("MSI_ENDPOINT");
public static string MsiSecret => Environment.GetEnvironmentVariable("MSI_SECRET");
}
}
| 47.238095 | 122 | 0.766129 | [
"MIT"
] | ctstone/azure-sdk-for-net | sdk/identity/Azure.Identity/src/EnvironmentVariables.cs | 994 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace Doddle_Defense
{
class Effect
{
Texture2D Sprite;
Vector2 Position;
Rectangle Source;
int Delay = 30;
float Elapsed = 0;
int FrameAct = 0;
int FrameCount;
public bool AnimationDone = false;
float Size = 1f;
SpriteEffects Facing = SpriteEffects.None;
public Effect(Texture2D spr, Vector2 Pos, int FrameC)
{
Sprite = spr;
FrameCount = FrameC;
Position = new Vector2(Pos.X, Pos.Y);
}
public Effect(Texture2D spr, Vector2 Pos, float size, int PFacing, int FrameC)
{
Sprite = spr;
Position = new Vector2(Pos.X, Pos.Y);
if (PFacing == -1)
{
Facing = SpriteEffects.FlipHorizontally;
Position.X -= 15;
}
FrameCount = FrameC;
Size = size;
}
public void Update(GameTime gameTime)
{
Elapsed += (float)gameTime.ElapsedGameTime.Milliseconds;
if (Elapsed > Delay)
{
FrameAct++;
if (FrameAct >= FrameCount)
{
AnimationDone = true;
FrameAct = 0;
}
Elapsed = 0;
}
Source = new Rectangle((int)(FrameAct * (Sprite.Width / FrameCount)), 0, Sprite.Width / FrameCount, Sprite.Height);
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(Sprite, new Rectangle((int)Position.X, (int)Position.Y, (int)(Sprite.Width / FrameCount * Size), (int)(Sprite.Height * Size)), Source, Color.White, 0f, new Vector2(Sprite.Width / (FrameCount * 2), Sprite.Height / 2), Facing, 0);
}
}
} | 26.9125 | 257 | 0.558291 | [
"MIT"
] | Edwardillo/TowerDefenseGame | Doddle Defense/Doddle Defense/Doddle Defense/Effect.cs | 2,155 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.WebJobs.Script.Grpc.Messages;
namespace Microsoft.Azure.WebJobs.Script.Workers.Rpc
{
internal static class RpcMessageExtensionUtilities
{
public static object ConvertFromHttpMessageToExpando(RpcHttp inputMessage)
{
if (inputMessage == null)
{
return null;
}
dynamic expando = new ExpandoObject();
expando.method = inputMessage.Method;
expando.query = inputMessage.Query as IDictionary<string, string>;
expando.statusCode = inputMessage.StatusCode;
expando.headers = inputMessage.Headers.ToDictionary(p => p.Key, p => (object)p.Value);
expando.enableContentNegotiation = inputMessage.EnableContentNegotiation;
expando.cookies = new List<Tuple<string, string, CookieOptions>>();
foreach (RpcHttpCookie cookie in inputMessage.Cookies)
{
expando.cookies.Add(RpcHttpCookieConverter(cookie));
}
if (inputMessage.Body != null)
{
expando.body = inputMessage.Body.ToObject();
}
return expando;
}
public static Tuple<string, string, CookieOptions> RpcHttpCookieConverter(RpcHttpCookie cookie)
{
var cookieOptions = new CookieOptions();
if (cookie.Domain != null)
{
cookieOptions.Domain = cookie.Domain.Value;
}
if (cookie.Path != null)
{
cookieOptions.Path = cookie.Path.Value;
}
if (cookie.Secure != null)
{
cookieOptions.Secure = cookie.Secure.Value;
}
cookieOptions.SameSite = RpcSameSiteEnumConverter(cookie.SameSite);
if (cookie.HttpOnly != null)
{
cookieOptions.HttpOnly = cookie.HttpOnly.Value;
}
if (cookie.Expires != null)
{
cookieOptions.Expires = cookie.Expires.Value.ToDateTimeOffset();
}
if (cookie.MaxAge != null)
{
cookieOptions.MaxAge = TimeSpan.FromSeconds(cookie.MaxAge.Value);
}
return new Tuple<string, string, CookieOptions>(cookie.Name, cookie.Value, cookieOptions);
}
private static SameSiteMode RpcSameSiteEnumConverter(RpcHttpCookie.Types.SameSite sameSite)
{
switch (sameSite)
{
case RpcHttpCookie.Types.SameSite.Strict:
return SameSiteMode.Strict;
case RpcHttpCookie.Types.SameSite.Lax:
return SameSiteMode.Lax;
case RpcHttpCookie.Types.SameSite.None:
return (SameSiteMode)(-1);
default:
return (SameSiteMode)(-1);
}
}
}
} | 33.821053 | 103 | 0.574541 | [
"Apache-2.0",
"MIT"
] | AnatoliB/azure-functions-host | src/WebJobs.Script/Workers/Rpc/MessageExtensions/RpcMessageExtensionUtilities.cs | 3,215 | C# |
using System;
using src.Controllers;
using Xunit;
namespace test
{
public class HelloControllerTest
{
private readonly HomeController _homeController;
public HelloControllerTest()
{
_homeController = new HomeController();
}
[Fact]
public void VerifyHelloWorldGet()
{
var result = _homeController.Get();
Assert.Contains("hello world", result);
}
}
} | 21.565217 | 57 | 0.552419 | [
"Apache-2.0"
] | azazi-sa/hw-dotnetcore | test/HelloControllerTest.cs | 496 | C# |
using System.IO;
using System.Threading.Tasks;
using NUnit.Framework;
using WebViewControl;
namespace Tests.WebView {
public class ResourcesLoading : WebViewTestBase {
[Test(Description = "Html load encoding is well handled")]
public async Task HtmlIsWellEncoded() {
await Run(async () => {
const string BodyContent = "some text and a double byte char '●'";
await Load($"<html><script>;</script><body>{BodyContent}</body></html>");
var body = TargetView.EvaluateScript<string>("document.body.innerText");
Assert.AreEqual(BodyContent, body);
});
}
[Test(Description = "Embedded files are correctly loaded")]
public async Task EmbeddedFilesLoad() {
await Run(async () => {
var embeddedResourceUrl = new ResourceUrl(GetType().Assembly, "Resources", "EmbeddedJavascriptFile.js");
await Load($"<html><script src='{embeddedResourceUrl}'></script></html>");
var embeddedFileLoaded = TargetView.EvaluateScript<bool>("embeddedFileLoaded");
Assert.IsTrue(embeddedFileLoaded);
});
}
[Test(Description = "Embedded files with dashes in the filename are correctly loaded")]
public async Task EmbeddedFilesWithDashesInFilenameLoad() {
await Run(async () => {
var embeddedResourceUrl = new ResourceUrl(GetType().Assembly, "Resources", "dash-folder", "EmbeddedJavascriptFile-With-Dashes.js");
await Load($"<html><script src='{embeddedResourceUrl}'></script></html>");
var embeddedFileLoaded = TargetView.EvaluateScript<bool>("embeddedFileLoaded");
Assert.IsTrue(embeddedFileLoaded);
});
}
[Test(Description = "Avalonia resource files are loaded")]
public async Task ResourceFile() {
await Run(async () => {
var embeddedResourceUrl = new ResourceUrl(GetType().Assembly, "Resources", "ResourceJavascriptFile.js");
await Load($"<html><script src='{embeddedResourceUrl}'></script></html>");
var resourceFileLoaded = TargetView.EvaluateScript<bool>("resourceFileLoaded");
Assert.IsTrue(resourceFileLoaded);
Stream missingResource = null;
Assert.DoesNotThrow(() => missingResource = ResourcesManager.TryGetResourceWithFullPath(GetType().Assembly, new[] { "Resources", "Missing.txt" }));
Assert.IsNull(missingResource);
});
}
}
}
| 44.440678 | 163 | 0.610603 | [
"Apache-2.0"
] | danwalmsley/WebView | Tests.WebView/ResourcesLoading.cs | 2,626 | 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;
using Microsoft.AspNetCore.Builder;
namespace Microsoft.AspNetCore.SpaServices;
internal class DefaultSpaBuilder : ISpaBuilder
{
public IApplicationBuilder ApplicationBuilder { get; }
public SpaOptions Options { get; }
public DefaultSpaBuilder(IApplicationBuilder applicationBuilder, SpaOptions options)
{
ApplicationBuilder = applicationBuilder
?? throw new ArgumentNullException(nameof(applicationBuilder));
Options = options
?? throw new ArgumentNullException(nameof(options));
}
}
| 29.291667 | 88 | 0.74111 | [
"MIT"
] | AndrewTriesToCode/aspnetcore | src/Middleware/Spa/SpaServices.Extensions/src/DefaultSpaBuilder.cs | 705 | C# |
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Drone.Management.AdHoc.TestData;
using Drone.Management.Entities.Interfaces;
using Drone.Management.Migrator.Interfaces;
using Drone.Management.Repository.Interfaces;
using Drone.Management.Repository.Interfaces.RepositoryValues;
using Drone.Management.Settings.Interfaces;
namespace Drone.Management.AdHoc.Migrator.TestDataMigrators
{
public class DroneTestDataMigrator : ITestDataMigrator
{
public int Queue { get; } = 0;
private readonly IRepositoryBuilder RepositoryBuilderField;
private IDroneRepository DroneRepositoryField { get; set; }
private ITestData TestDataField;
public DroneTestDataMigrator(IRepositoryBuilder repositoryBuilder)
{
RepositoryBuilderField = repositoryBuilder;
}
public void SetTestData(ITestData testData)
{
TestDataField = testData;
}
public async Task VerifyMigratedTestData()
{
Console.WriteLine("\r\nExecuting DRONE test data verification\r\n");
await ReadDroneIds();
foreach (var dataSet in TestDataField.DataSets)
{
var drone = dataSet.Item1;
await VerifyDrone(drone);
}
await ReadDroneIds();
}
public async Task DeleteMigratedTestData()
{
Console.WriteLine($"Deleting {TestDataField.DataSets.Count} drones");
foreach (var dataSet in TestDataField.DataSets)
{
var drone = dataSet.Item1;
await DroneRepositoryField.DeleteDrone(drone);
}
}
public async Task Migrate()
{
Console.WriteLine($"Creating {TestDataField.DataSets.Count} drones");
foreach (var dataSet in TestDataField.DataSets)
{
var drone = dataSet.Item1;
await DroneRepositoryField.CreateDrone(drone);
}
}
public async Task Connect()
{
}
public async Task<IMigrator> BuildMigrator(ISettings settings)
{
DroneRepositoryField = RepositoryBuilderField.BuildDroneRepository(settings);
return this;
}
public async Task ReadDroneIds()
{
var droneIds = await DroneRepositoryField.ReadDroneIds();
Console.WriteLine($"Found {droneIds.Count()} drone ids");
}
public async Task VerifyDrone(IDrone drone)
{
var stopWatch = Stopwatch.StartNew();
var cpDrone = await DroneRepositoryField.ReadDrone(drone);
stopWatch.Stop();
if (cpDrone.Id.CompareTo(drone.Id) != 0)
{
throw new Exception("Drone read from DB does not match created drone!");
}
Console.WriteLine($"Read drone {cpDrone.Tag} in {stopWatch.ElapsedMilliseconds} ms");
drone.Tag = $"Updated {drone.Tag}";
await DroneRepositoryField.UpdateDrone(drone);
}
}
}
| 32.247423 | 97 | 0.615409 | [
"MIT"
] | hansehe/Drone.Management | src/Drone.Management.AdHoc/Drone.Management.AdHoc.Migrator/TestDataMigrators/DroneTestDataMigrator.cs | 3,130 | C# |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjetoFinal.ProdutosMarcas.Dominio;
namespace ProjetoFinal.ProdutosMarcas.Persistencia.EF.Context
{
public class ProdutosMarcasDbContext : DbContext
{
public DbSet<Produto> Produtos { get; set; }
public DbSet<Marca> Marcas { get; set; }
public ProdutosMarcasDbContext()
{
Configuration.LazyLoadingEnabled = false;
Configuration.ProxyCreationEnabled = false;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Produto>()
.ToTable("PRODUTOS") //Especificando o nome da tabela
.HasRequired(p => p.Marca) //precisa ter uma marca
.WithMany(p => p.Produtos) //uma marca tem vários produtos
.HasForeignKey(fk => fk.MarcaId) //MarcaId que liga o produto a marca
.WillCascadeOnDelete(false); //Não deletar a marca relacionada quando o produto for
modelBuilder.Entity<Marca>()
.ToTable("MARCAS"); //Especificando o nome da tabela
}
}
}
| 34.5 | 99 | 0.648148 | [
"MIT"
] | ariele-fatima/Projeto_Final_C_Sharp | ProjetoFinal.ProdutosMarcas/ProjetoFinal.ProdutosMarcas.Persistencia.EF/Context/ProdutosMarcasDbContext.cs | 1,246 | C# |
using System.Runtime.Serialization;
using CarHist.Cars;
using CarHist.Cars.Events;
using Elders.Cronus;
using Elders.Cronus.Projections;
namespace CarHist.Projections.AllCarsTenant;
[DataContract(Namespace = BC.CarHist, Name = "3b4f8226-8dfc-4b4e-9ff2-96b2f1b3a300")]
public class AllCarsTenantProjection : ProjectionDefinition<AllCarsTenantProjection.Data, AllCarsByTenantId>, IProjection,
IEventHandler<CarCreated>,
IEventHandler<CarEdited>,
IEventHandler<CarDeleted>
{
public AllCarsTenantProjection()
{
Subscribe<CarCreated>(x => new AllCarsByTenantId(x.Id.Tenant));
Subscribe<CarEdited>(x => new AllCarsByTenantId(x.Id.Tenant));
Subscribe<CarDeleted>(x => new AllCarsByTenantId(x.Id.Tenant));
}
public void Handle(CarCreated @event)
{
State.Cars.Add(new CarData(@event.Id, @event.Make, @event.Model, @event.VIN, @event.EngineType));
}
public void Handle(CarEdited @event)
{
State.Cars.Where(x => x.Id == @event.Id).FirstOrDefault().Make = @event.Make;
State.Cars.Where(x => x.Id == @event.Id).FirstOrDefault().Model = @event.Model;
State.Cars.Where(x => x.Id == @event.Id).FirstOrDefault().VIN = @event.VIN;
State.Cars.Where(x => x.Id == @event.Id).FirstOrDefault().EngineType = @event.EngineType;
}
public void Handle(CarDeleted @event)
{
State.Cars.Where(x => x.Id == @event.Id).FirstOrDefault().DeletedDate = @event.Timestamp;
}
[DataContract(Namespace = BC.CarHist, Name = "3c9d5503-1914-4a56-8018-edb8e3a97494")]
public class Data
{
public Data()
{
Cars = new HashSet<CarData>();
}
[DataMember(Order = 1)]
public HashSet<CarData> Cars { get; private set; }
}
[DataContract(Namespace = BC.CarHist, Name = "e177295a-a6b9-4129-8ee0-3bc16bee2c19")]
public class CarData
{
private CarData() { }
public CarData(CarId id, string make, string model, string vIN, string engineType)
{
Id = id;
Make = make;
Model = model;
VIN = vIN;
EngineType = engineType;
}
[DataMember(Order = 1)]
public CarId Id { get; set; }
[DataMember(Order = 2)]
public string Make { get; set; }
[DataMember(Order = 3)]
public string Model { get; set; }
[DataMember(Order = 4)]
public string VIN { get; set; }
[DataMember(Order = 5)]
public string EngineType { get; set; }
[DataMember(Order = 6)]
public DateTimeOffset DeletedDate { get; set; } = DateTimeOffset.MinValue;
}
}
| 31.423529 | 122 | 0.622988 | [
"MIT"
] | gshukov98/CarHist | src/CarHist/Projections/AllCarsTenant/AllCarsTenantProjection.cs | 2,673 | C# |
using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace DCSoftDotfuscate
{
[ComVisible(false)]
public sealed class GClass286
{
private const string string_0 = "SOFTWARE\\Microsoft\\Internet Explorer";
private const string string_1 = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
private const string string_2 = "Software\\Microsoft\\Internet Explorer";
public static Process smethod_0(string string_3)
{
ProcessStartInfo processStartInfo = new ProcessStartInfo();
processStartInfo.FileName = smethod_2();
processStartInfo.Arguments = "\"" + string_3 + "\"";
return Process.Start(processStartInfo);
}
public static Process smethod_1(string string_3)
{
ProcessStartInfo processStartInfo = new ProcessStartInfo();
processStartInfo.FileName = smethod_2();
processStartInfo.Arguments = "\"file://" + string_3 + "\"";
return Process.Start(processStartInfo);
}
public static string smethod_2()
{
return smethod_13(Registry.LocalMachine, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\IEXPLORE.EXE", null);
}
public static string smethod_3()
{
return smethod_13(Registry.LocalMachine, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", "MinorVersion");
}
public static string smethod_4()
{
return smethod_13(Registry.LocalMachine, "SOFTWARE\\Microsoft\\Internet Explorer", "Build");
}
public static Version smethod_5()
{
string text = smethod_13(Registry.LocalMachine, "SOFTWARE\\Microsoft\\Internet Explorer", "Version");
if (text == null)
{
return new Version();
}
return new Version(text);
}
public static string smethod_6()
{
return smethod_13(Registry.LocalMachine, "SOFTWARE\\Microsoft\\Internet Explorer", "Version");
}
public static Version smethod_7()
{
string text = smethod_13(Registry.LocalMachine, "SOFTWARE\\Microsoft\\Internet Explorer\\Version Vector", "VML");
if (text == null)
{
return new Version();
}
return new Version(text);
}
public static string smethod_8()
{
return smethod_13(Registry.CurrentUser, "Software\\Microsoft\\Internet Explorer\\Main", "Local Page");
}
public static string smethod_9()
{
return smethod_13(Registry.CurrentUser, "Software\\Microsoft\\Internet Explorer\\Main", "Start Page");
}
public static bool smethod_10()
{
return smethod_13(Registry.CurrentUser, "Software\\Microsoft\\Internet Explorer\\Main", "Disable Script Debugger") == "yes";
}
public static string smethod_11()
{
return smethod_13(Registry.CurrentUser, "Software\\Microsoft\\Internet Explorer\\Main", "Window Title");
}
public static string[] smethod_12()
{
string[] array = null;
RegistryKey registryKey = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Internet Explorer\\TypedURLs");
if (registryKey != null)
{
array = registryKey.GetValueNames();
if (array != null)
{
for (int i = 0; i < array.Length; i++)
{
array[i] = Convert.ToString(registryKey.GetValue(array[i]));
}
}
registryKey.Close();
}
return array;
}
private static string smethod_13(RegistryKey registryKey_0, string string_3, string string_4)
{
object obj = smethod_14(registryKey_0, string_3, string_4);
if (obj == null)
{
return null;
}
return Convert.ToString(obj);
}
private static object smethod_14(RegistryKey registryKey_0, string string_3, string string_4)
{
RegistryKey registryKey = registryKey_0.OpenSubKey(string_3);
if (registryKey == null)
{
return null;
}
object value = registryKey.GetValue(string_4);
registryKey.Close();
return value;
}
private GClass286()
{
}
}
}
| 27.18705 | 127 | 0.704684 | [
"MIT"
] | h1213159982/HDF | Example/WinForm/Editor/DCWriter/DCSoft.Writer.Cleaned/DCSoftDotfuscate/GClass286.cs | 3,779 | C# |
namespace Quartz.Impl.AdoJobStore
{
/// <summary>
/// Delegate implementation for Firebird.
/// </summary>
public class FirebirdDelegate : StdAdoDelegate
{
/// <summary>
/// Gets the select next trigger to acquire SQL clause.
/// FireBird version with ROWS support.
/// </summary>
/// <returns></returns>
protected override string GetSelectNextTriggerToAcquireSql(int maxCount)
{
return SqlSelectNextTriggerToAcquire + " ROWS " + maxCount;
}
protected override string GetSelectNextMisfiredTriggersInStateToAcquireSql(int count)
{
if (count != -1)
{
return SqlSelectHasMisfiredTriggersInState + " ROWS " + count;
}
return base.GetSelectNextMisfiredTriggersInStateToAcquireSql(count);
}
}
} | 32.518519 | 93 | 0.604784 | [
"Apache-2.0"
] | 1508553303/quartznet | src/Quartz/Impl/AdoJobStore/FirebirdDelegate.cs | 880 | C# |
using System;
namespace PipeVision.Domain
{
public interface ITest
{
string Name { get; set; }
string Error { get; set; }
string CallStack { get; set; }
int PipelineJobId { get; set; }
TimeSpan Duration { get; set; }
PipelineJob PipelineJob { get; set; }
}
public class Test : ITest
{
public string Name{get;set;}
public string Error{get;set;}
public string CallStack{get;set;}
public int PipelineJobId { get; set; }
public TimeSpan Duration { get; set; }
public virtual PipelineJob PipelineJob{get;set;}
}
}
| 23.740741 | 56 | 0.578783 | [
"MIT"
] | MHanafy/PipeVision | PipeVision.Domain/Test.cs | 641 | C# |
using Microsoft.AspNetCore.Http;
using System.ComponentModel.DataAnnotations;
namespace LINGYUN.Abp.FileManagement
{
public class FileUploadDto : FileCreateDto
{
/// <summary>
/// 常规块大小
/// </summary>
[Required]
public int ChunkSize { get; set; }
/// <summary>
/// 当前块大小
/// </summary>
[Required]
public int CurrentChunkSize { get; set; }
/// <summary>
/// 当前上传中块的索引
/// </summary>
[Required]
public int ChunkNumber { get; set; }
/// <summary>
/// 块总数
/// </summary>
[Required]
public int TotalChunks { get; set; }
/// <summary>
/// 总文件大小
/// </summary>
[Required]
public int TotalSize { get; set; }
public IFormFile File { get; set; }
}
}
| 23.944444 | 49 | 0.5 | [
"MIT"
] | mysharp/abp-vue-admin-element-typescript | aspnet-core/modules/file-management/LINGYUN.Abp.FileManagement.HttpApi/LINGYUN/Abp/FileManagement/FileUploadDto.cs | 918 | C# |
using YandexDnsAPI.Helpers;
namespace YandexDnsAPI.Models.Request
{
public class GetDnsRequestModel
{
/// <summary>
/// Yandex token
/// </summary>
public string Token { get; set; }
/// <summary>
/// Domain name
/// </summary>
public string Domain { get; set; }
public void Validate()
{
ValidationHelper.ThrowIfNullOrEmpty(this.Token);
ValidationHelper.ThrowIfNullOrEmpty(this.Domain);
}
}
}
| 21.75 | 61 | 0.551724 | [
"MIT"
] | Silvochka/yandex-dns-api | YandexDnsAPI/YandexDnsAPI/Models/Request/GetDnsRequestModel.cs | 524 | C# |
#pragma checksum "E:\SE\asp_net_exercise\blog\blog\Views\Texts\Details.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "486120f97e3a53cdeb4b6f1f2a81c7fec6bb4b90"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Texts_Details), @"mvc.1.0.view", @"/Views/Texts/Details.cshtml")]
[assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Views/Texts/Details.cshtml", typeof(AspNetCore.Views_Texts_Details))]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#line 1 "E:\SE\asp_net_exercise\blog\blog\Views\_ViewImports.cshtml"
using blog;
#line default
#line hidden
#line 2 "E:\SE\asp_net_exercise\blog\blog\Views\_ViewImports.cshtml"
using blog.Models;
#line default
#line hidden
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"486120f97e3a53cdeb4b6f1f2a81c7fec6bb4b90", @"/Views/Texts/Details.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"cb75ca75589086f3cd7b7a5e09e52e9d3c84d752", @"/Views/_ViewImports.cshtml")]
public class Views_Texts_Details : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<blog.Models.Text>
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Edit", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Delete", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
BeginContext(25, 2, true);
WriteLiteral("\r\n");
EndContext();
#line 3 "E:\SE\asp_net_exercise\blog\blog\Views\Texts\Details.cshtml"
ViewData["Title"] = Model.Content;
#line default
#line hidden
BeginContext(74, 45, true);
WriteLiteral("\r\n<br />\r\n\r\n<div>\r\n <h1>\r\n ");
EndContext();
BeginContext(120, 37, false);
#line 11 "E:\SE\asp_net_exercise\blog\blog\Views\Texts\Details.cshtml"
Write(Html.DisplayFor(model => model.Title));
#line default
#line hidden
EndContext();
BeginContext(157, 42, true);
WriteLiteral("\r\n </h1>\r\n <p>\r\n ");
EndContext();
BeginContext(200, 43, false);
#line 14 "E:\SE\asp_net_exercise\blog\blog\Views\Texts\Details.cshtml"
Write(Html.DisplayFor(model => model.PublishDate));
#line default
#line hidden
EndContext();
BeginContext(243, 57, true);
WriteLiteral("\r\n </p>\r\n <br />\r\n <p>\r\n ");
EndContext();
BeginContext(301, 39, false);
#line 18 "E:\SE\asp_net_exercise\blog\blog\Views\Texts\Details.cshtml"
Write(Html.DisplayFor(model => model.Content));
#line default
#line hidden
EndContext();
BeginContext(340, 35, true);
WriteLiteral("\r\n </p>\r\n</div>\r\n<div>\r\n ");
EndContext();
BeginContext(375, 52, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ca3a845d296942338359750e4e542ddc", async() => {
BeginContext(421, 2, true);
WriteLiteral("编辑");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_0.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0);
if (__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues == null)
{
throw new InvalidOperationException(InvalidTagHelperIndexerAssignment("asp-route-id", "Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper", "RouteValues"));
}
BeginWriteTagHelperAttribute();
#line 22 "E:\SE\asp_net_exercise\blog\blog\Views\Texts\Details.cshtml"
WriteLiteral(Model.Id);
#line default
#line hidden
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"] = __tagHelperStringValueBuffer;
__tagHelperExecutionContext.AddTagHelperAttribute("asp-route-id", __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(427, 8, true);
WriteLiteral(" |\r\n ");
EndContext();
BeginContext(435, 54, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "16e00b7dcb184ebb822cd5ff0989bbfe", async() => {
BeginContext(483, 2, true);
WriteLiteral("删除");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_1.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1);
if (__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues == null)
{
throw new InvalidOperationException(InvalidTagHelperIndexerAssignment("asp-route-id", "Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper", "RouteValues"));
}
BeginWriteTagHelperAttribute();
#line 23 "E:\SE\asp_net_exercise\blog\blog\Views\Texts\Details.cshtml"
WriteLiteral(Model.Id);
#line default
#line hidden
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"] = __tagHelperStringValueBuffer;
__tagHelperExecutionContext.AddTagHelperAttribute("asp-route-id", __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(489, 10, true);
WriteLiteral("\r\n</div>\r\n");
EndContext();
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<blog.Models.Text> Html { get; private set; }
}
}
#pragma warning restore 1591
| 57.850829 | 299 | 0.704135 | [
"MIT"
] | Dianaaaa/asp_net_exercise | blog/blog/obj/Debug/netcoreapp2.1/Razor/Views/Texts/Details.g.cshtml.cs | 10,479 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using BGE.Forms;
public class ControllableJellyController : CreatureController
{
Boid boid;
public override void Restart()
{
Vector3 newF = Random.insideUnitCircle;
newF.z = newF.y;
newF.y = 0;
boid.transform.forward = newF;
boid.UpdateLocalFromTransform();
}
// Use this for initialization
void Start()
{
boid = Utilities.FindBoidInHierarchy(this.gameObject);
Restart();
}
// Update is called once per frame
void Update () {
}
}
| 19.71875 | 63 | 0.621236 | [
"MIT"
] | skooter500/Forms | Assets/ControllableJellyController.cs | 633 | C# |
using Microsoft.VisualBasic.Activities;
using OpenRPA.Interfaces;
using OpenRPA.Interfaces.Selector;
using System;
using System.Activities;
using System.Activities.Expressions;
using System.Activities.Presentation.Model;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace OpenRPA.Activities
{
public partial class BreakDesigner
{
public BreakDesigner()
{
InitializeComponent();
}
}
} | 23.6 | 43 | 0.761017 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | Mangalya-13/openrpa | OpenRPA/Activities/BreakDesigner.xaml.cs | 592 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace LinqToDB.SqlQuery
{
public class SqlInsertClause : IQueryElement, ISqlExpressionWalkable, ICloneableElement
{
public SqlInsertClause()
{
Items = new List<SqlSetExpression>();
}
public List<SqlSetExpression> Items { get; }
public SqlTable Into { get; set; }
public bool WithIdentity { get; set; }
#region Overrides
#if OVERRIDETOSTRING
public override string ToString()
{
return ((IQueryElement)this).ToString(new StringBuilder(), new Dictionary<IQueryElement,IQueryElement>()).ToString();
}
#endif
#endregion
#region ICloneableElement Members
public ICloneableElement Clone(Dictionary<ICloneableElement, ICloneableElement> objectTree, Predicate<ICloneableElement> doClone)
{
if (!doClone(this))
return this;
var clone = new SqlInsertClause { WithIdentity = WithIdentity };
if (Into != null)
clone.Into = (SqlTable)Into.Clone(objectTree, doClone);
foreach (var item in Items)
clone.Items.Add((SqlSetExpression)item.Clone(objectTree, doClone));
objectTree.Add(this, clone);
return clone;
}
#endregion
#region ISqlExpressionWalkable Members
ISqlExpression ISqlExpressionWalkable.Walk(WalkOptions options, Func<ISqlExpression,ISqlExpression> func)
{
((ISqlExpressionWalkable)Into)?.Walk(options, func);
foreach (var t in Items)
((ISqlExpressionWalkable)t).Walk(options, func);
return null;
}
#endregion
#region IQueryElement Members
public QueryElementType ElementType => QueryElementType.InsertClause;
StringBuilder IQueryElement.ToString(StringBuilder sb, Dictionary<IQueryElement,IQueryElement> dic)
{
sb.Append("VALUES ");
((IQueryElement)Into)?.ToString(sb, dic);
sb.AppendLine();
foreach (var e in Items)
{
sb.Append("\t");
((IQueryElement)e).ToString(sb, dic);
sb.AppendLine();
}
return sb;
}
#endregion
}
}
| 21.815217 | 131 | 0.702541 | [
"MIT"
] | FrancisChung/linq2db | Source/LinqToDB/SqlQuery/SqlInsertClause.cs | 2,009 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Scada.Update
{
class Program
{
public static string GetCurrentPath()
{
string p = Assembly.GetExecutingAssembly().Location;
return Path.GetDirectoryName(p);
}
static void Main(string[] args)
{
// Debug.Assert(false);
if (args.Length == 0)
return;
string binZipPath = args[0];
Updater u = new Updater();
u.ForceReplaceConfigFiles = false;
u.NeedUpdateConfigFiles = false;
if (args.Length > 1)
{
string opt = args[1];
if (opt.StartsWith("--"))
{
if (opt.IndexOf('w') > 0)
{
u.UpdateByWatch = true;
}
}
}
// TODO:
KillProcesses();
bool r = u.UnzipProgramFiles(binZipPath, Path.GetDirectoryName(GetCurrentPath()));
if (!r)
{
Console.WriteLine("Failed to update!");
}
// TODO:
RestoreProcesses();
}
static void KillProcesses()
{
}
static void RestoreProcesses()
{
}
}
}
| 20.5 | 94 | 0.444298 | [
"Apache-2.0"
] | luokk/scada | DAQ/Scada.Update/Program.cs | 1,519 | C# |
namespace PnP.Core.Model.Teams
{
/// <summary>
/// The importance of the chat message.
/// </summary>
public enum ChatMessageImportance
{
/// <summary>
/// Normal importance
/// </summary>
Normal,
/// <summary>
/// High importance
/// </summary>
High,
/// <summary>
/// Urgent importance
/// </summary>
Urgent
}
}
| 18.208333 | 43 | 0.466819 | [
"MIT"
] | DonKirkham/pnpcore | src/sdk/PnP.Core/Model/Teams/Public/Enums/ChatMessageImportance.cs | 439 | C# |
using Microsoft.Extensions.DependencyInjection;
using Castle.Windsor.MsDependencyInjection;
using Abp.Dependency;
using LearningBoilerplate.Identity;
namespace LearningBoilerplate.Migrator.DependencyInjection
{
public static class ServiceCollectionRegistrar
{
public static void Register(IIocManager iocManager)
{
var services = new ServiceCollection();
IdentityRegistrar.Register(services);
WindsorRegistrationHelper.CreateServiceProvider(iocManager.IocContainer, services);
}
}
}
| 27.9 | 95 | 0.743728 | [
"MIT"
] | TobiasVargas/LearningBoilerplate | aspnet-core/src/LearningBoilerplate.Migrator/DependencyInjection/ServiceCollectionRegistrar.cs | 560 | C# |
using System.Collections.Generic;
namespace Microsoft.Msagl.Drawing
{
public interface IViewerGraph
{
Graph DrawingGraph
{
get;
}
IEnumerable<IViewerNode> Nodes();
IEnumerable<IViewerEdge> Edges();
}
}
| 13 | 35 | 0.723982 | [
"MIT"
] | Jmerk523/automatic-graph-layout | Drawing/IViewerGraph.cs | 221 | C# |
/***************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
This code is licensed under the Visual Studio SDK license terms.
THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
***************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
using Microsoft.Samples.VisualStudio.CodeSweep.BuildTask.Properties;
namespace Microsoft.Samples.VisualStudio.CodeSweep.BuildTask
{
class IgnoreInstance : IIgnoreInstance, IComparable<IIgnoreInstance>
{
string _file;
string _lineText;
string _term;
int _column;
/// <summary>
/// Creates an IgnoreInstance object.
/// </summary>
/// <exception cref="System.ArgumentNullException">Thrown if <c>file</c>, <c>lineText</c>, or <c>term</c> is null.</exception>
/// <exception cref="System.ArgumentException">Thrown if <c>file</c>, <c>lineText</c>, or <c>term</c> is empty; or if <c>column</c> is less than zero or greater than or equal to <c>lineText.Length</c>.</exception>
public IgnoreInstance(string file, string lineText, string term, int column)
{
Init(file, lineText, term, column);
}
/// <summary>
/// Creates an IgnoreInstance object from a serialized representation.
/// </summary>
/// <param name="serialization">The file, term, column, and line text, separated by commas.</param>
/// <param name="projectFolderForDerelativization">The project folder used to convert the serialized relative file path to a rooted file path.</param>
/// <exception cref="System.ArgumentNullException">Thrown if <c>serialization</c> or <c>projectFolderForDerelativization</c> is null.</exception>
/// <exception cref="System.ArgumentException">Thrown if <c>serialization</c> does not contain four comma-delimited fields; if any of the string fields is empty; if the column field cannot be parsed; or if the column field is less than zero or greater than or equal to the line text length.</exception>
public IgnoreInstance(string serialization, string projectFolderForDerelativization)
{
if (serialization == null)
{
throw new ArgumentNullException("serialization");
}
IList<string> fields = Utilities.ParseEscaped(serialization, ',');
if (fields.Count != 4)
{
throw new ArgumentException(Resources.InvalidSerializationStringForIgnoreInstance);
}
if (fields[0].Length == 0)
{
throw new ArgumentException(Resources.EmptyFileField);
}
int column;
if (Int32.TryParse(fields[2], out column))
{
Init(Utilities.AbsolutePathFromRelative(fields[0], projectFolderForDerelativization), fields[3], fields[1], column);
}
else
{
throw new ArgumentException(Resources.BadColumnField, "serialization");
}
}
/// <summary>
/// Returns a serialized representation of this object.
/// </summary>
/// <returns>A string containing four fields delimited by commas. Commas within the fields are escaped with backslashes.</returns>
public string Serialize(string projectFolderForRelativization)
{
string relativePath = Utilities.RelativePathFromAbsolute(FilePath, projectFolderForRelativization);
return Utilities.EscapeChar(relativePath, ',') + ',' +
Utilities.EscapeChar(IgnoredTerm, ',') + ',' +
PositionOfIgnoredTerm.ToString(CultureInfo.InvariantCulture) + ',' +
Utilities.EscapeChar(IgnoredLine, ',');
}
#region IIgnoreInstance Members
public string FilePath
{
get { return _file; }
}
public string IgnoredLine
{
get { return _lineText; }
}
public int PositionOfIgnoredTerm
{
get { return _column; }
}
public string IgnoredTerm
{
get { return _term; }
}
#endregion
#region IComparable<IIgnoreInstance> Members
/// <summary>
/// Compares this ignore instance to another, and returns the result.
/// </summary>
/// <exception cref="System.ArgumentNullException">Thrown if <c>other</c> is null.</exception>
/// <remarks>
/// The order of the comparison is largely arbitrary; the important part is whether it
/// returns zero or nonzero.
/// </remarks>
public int CompareTo(IIgnoreInstance other)
{
if (other == null)
{
throw new ArgumentNullException("other");
}
int result = 0;
result = String.Compare(FilePath, other.FilePath, StringComparison.OrdinalIgnoreCase);
if (result != 0)
{
return result;
}
result = String.CompareOrdinal(IgnoredLine, other.IgnoredLine);
if (result != 0)
{
return result;
}
result = String.Compare(IgnoredTerm, other.IgnoredTerm, StringComparison.OrdinalIgnoreCase);
if (result != 0)
{
return result;
}
return PositionOfIgnoredTerm - other.PositionOfIgnoredTerm;
}
#endregion
#region Private Members
private void Init(string file, string lineText, string term, int column)
{
if (file == null)
{
throw new ArgumentNullException("file");
}
if (lineText == null)
{
throw new ArgumentNullException("lineText");
}
if (term == null)
{
throw new ArgumentNullException("term");
}
if (file.Length == 0)
{
throw new ArgumentException(Resources.EmptyString, "file");
}
column -= LeadingWhitespace(lineText);
lineText = lineText.Trim();
if (lineText.Length == 0)
{
throw new ArgumentException(Resources.EmptyString, "lineText");
}
if (term.Length == 0)
{
throw new ArgumentException(Resources.EmptyString, "term");
}
if (column < 0 || column >= lineText.Length)
{
throw new ArgumentOutOfRangeException("column", column, Resources.ColumnOutOfRange);
}
_file = file;
_lineText = lineText;
_term = term;
_column = column;
}
private static int LeadingWhitespace(string text)
{
int count = 0;
for (; count < text.Length && Char.IsWhiteSpace(text[count]); ++count) { };
return count;
}
#endregion
}
}
| 36.873171 | 311 | 0.552322 | [
"Apache-2.0"
] | LiveMirror/Visual-Studio-2010-SDK-Samples | Code Sweep/C#,C++/BuildTask/IgnoreInstance.cs | 7,559 | C# |
#if UNITY_2021_1_OR_NEWER
#define BEE_COMPILATION_PIPELINE
#endif
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Needle.EditorGUIUtility;
using UnityEditor;
using UnityEditor.Build.Player;
using UnityEditor.Compilation;
using UnityEditor.ShortcutManagement;
using UnityEngine;
using UnityEditorInternal;
using Assembly = UnityEditor.Compilation.Assembly;
using PackageInfo = UnityEditor.PackageManager.PackageInfo;
namespace Needle.CompilationVisualizer
{
#if BEE_COMPILATION_PIPELINE
using IterativeCompilationData = CompilationData.IterativeCompilationData;
#else
using CompilationData = CompilationAnalysis.CompilationData;
using IterativeCompilationData = CompilationAnalysis.IterativeCompilationData;
#endif
internal class CompilationTimelineWindow : EditorWindow, IHasCustomMenu
{
[MenuItem("Window/Analysis/Compilation Timeline")]
static void Init() {
var win = GetWindow<CompilationTimelineWindow>();
win.titleContent = new GUIContent("↻ Compilation Timeline");
win.Show();
}
private bool AllowRefresh => !windowLockState.IsLocked;
public EditorWindowLockState windowLockState = new EditorWindowLockState();
public bool compactDrawing = true;
public int threadCountMultiplier = 1;
private IterativeCompilationData data;
private void OnEnable() {
#if UNITY_2019_1_OR_NEWER
CompilationPipeline.compilationFinished += CompilationFinished;
#endif
AssemblyReloadEvents.afterAssemblyReload += AfterAssemblyReload;
CompilationPipeline.assemblyCompilationFinished += AssemblyCompilationFinished;
// Helper: find EditorCompilationInterface
/*
var assemblies = System.AppDomain.CurrentDomain.GetAssemblies();
foreach (var a in assemblies) {
try {
var t = a.GetTypes();
foreach (var t2 in t) {
if(t2.Name.Contains("EditorCompilationInterface")) {
Debug.Log(t2.AssemblyQualifiedName);
break;
}
}
} catch {
// ignore
}
}
*/
windowLockState.lockStateChanged.AddListener(OnLockStateChanged);
if (threadCountMultiplier > 1) {
// EXPERIMENT: set thread count for compilation "UnityEditor.Scripting.ScriptCompilation.EditorCompilationInterface"
var eci = Type.GetType(
"UnityEditor.Scripting.ScriptCompilation.EditorCompilationInterface, UnityEditor, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null");
if (eci != null) {
var instanceProp = eci.GetProperty("Instance", (BindingFlags) (-1));
if (instanceProp != null) {
var instance = instanceProp.GetValue(null);
var setComp = instance.GetType().GetMethod("SetMaxConcurrentCompilers", (BindingFlags) (-1));
setComp?.Invoke(instance, new object[] {SystemInfo.processorCount * threadCountMultiplier});
}
}
}
EditorApplication.delayCall += Refresh;
}
private void OnLockStateChanged(bool locked)
{
if(!locked)
data = CompilationData.GetAll();
}
private bool AllowLogging {
get => CompilationAnalysis.AllowLogging;
set => CompilationAnalysis.AllowLogging = value;
}
private bool ShowAssemblyReloads {
get => CompilationAnalysis.ShowAssemblyReloads;
set => CompilationAnalysis.ShowAssemblyReloads = value;
}
private WindowStyles styles;
private WindowStyles Styles => styles != null && styles.background ? styles : styles = new WindowStyles();
class WindowStyles
{
public readonly Texture2D background;
public readonly GUIStyle miniLabel = EditorStyles.miniLabel;
public readonly GUIStyle overflowMiniLabel = new GUIStyle(EditorStyles.miniLabel) {
clipping = TextClipping.Overflow
};
public readonly GUIStyle rightAlignedLabel = new GUIStyle(EditorStyles.miniLabel) {
clipping = TextClipping.Overflow,
alignment = TextAnchor.UpperRight
};
public readonly GUIStyle lockButton = "IN LockButton";
public WindowStyles()
{
background = new Texture2D(1, 1);
background.SetPixel(0,0,UnityEditor.EditorGUIUtility.isProSkin ? new Color(52/255f,52/255f,52/255f) : new Color(207/255f,207/255f,207/255f));
background.Apply();
connectorColor = UnityEditor.EditorGUIUtility.isProSkin ? new Color(1f, 1f, 0.7f, 0.4f) : new Color(0.3f,0.3f,0.1f,0.4f);
connectorColor2 = UnityEditor.EditorGUIUtility.isProSkin ? new Color(0.7f, 1f, 1f, 0.4f) : new Color(0.1f, 0.3f, 0.3f, 0.4f);
verticalLineColor = UnityEditor.EditorGUIUtility.isProSkin ? new Color(1, 1, 1, 0.1f) : new Color(0,0,0,0.1f);
}
public readonly Color connectorColor;
public readonly Color connectorColor2;
public readonly Color verticalLineColor;
}
private void OnDisable() {
#if UNITY_2019_1_OR_NEWER
CompilationPipeline.compilationFinished -= CompilationFinished;
#endif
AssemblyReloadEvents.afterAssemblyReload -= AfterAssemblyReload;
}
private void Refresh() {
if (AllowRefresh)
{
data = CompilationData.GetAll();
Repaint();
}
}
private void AssemblyCompilationFinished(string arg1, CompilerMessage[] arg2) {
Refresh();
}
private List<Assembly> assemblies = new List<Assembly>();
private List<Assembly> Assemblies {
get {
if (assemblies.Any()) return assemblies;
assemblies = CompilationPipeline.GetAssemblies().ToList();
return assemblies;
}
}
private Dictionary<string, Assembly> assemblyDependencyDict = new Dictionary<string, Assembly>();
private Dictionary<string, Assembly> AssemblyDependencyDict {
get {
if (assemblyDependencyDict.Any()) return assemblyDependencyDict;
assemblyDependencyDict = Assemblies.ToDictionary(x => x.outputPath);
return assemblyDependencyDict;
}
}
private readonly Dictionary<string, List<Assembly>> assemblyDependantDict =
new Dictionary<string, List<Assembly>>();
private Dictionary<string, List<Assembly>> AssemblyDependantDict {
get {
if (assemblyDependantDict.Any()) return assemblyDependantDict;
foreach (var asm in Assemblies) {
if (!assemblyDependantDict.ContainsKey(asm.outputPath))
assemblyDependantDict.Add(asm.outputPath, new List<Assembly>());
}
foreach (var asm in Assemblies) {
foreach (var dep in asm.assemblyReferences) {
assemblyDependantDict[dep.outputPath].Add(asm);
}
}
return assemblyDependantDict;
}
}
private void CompilationFinished(object obj)
{
Refresh();
ClearCaches();
}
private void AfterAssemblyReload()
{
Refresh();
ClearCaches();
}
private void ClearCaches() {
assemblies.Clear();
assemblyDependencyDict.Clear();
assemblyDependantDict.Clear();
// clear selection if not in result data
if (selectedEntry != null && data?.iterations != null && !data.iterations.Any(c => c.compilationData.Any(x => selectedEntry.Equals(x.assembly, StringComparison.Ordinal))))
selectedEntry = null;
}
private float k_LineHeight = 20;
private float k_SkippedHeight = 4;
private float lastTotalHeight = 200;
internal enum ColorMode {
CompilationDuration,
DependantCount,
DependencyCount
}
[SerializeField]
internal ColorMode colorMode = ColorMode.CompilationDuration;
[SerializeField]
internal BuildTarget buildTarget = BuildTarget.StandaloneWindows64;
// private Vector2 normalizedTimeView = new Vector2(0, 1);
// slot ID (height index) to current end time
private static readonly Dictionary<int, float> graphSlots = new Dictionary<int, float>();
private void Clear()
{
// #if !BEE_COMPILATION_PIPELINE
CompilationData.Clear();
data = CompilationData.GetAll();
// #endif
}
public float fromTimeValue = 0f, toTimeValue = 1f;
private float accumulatedDrag = 0f;
private void OnGUI()
{
if (data?.iterations == null || !data.iterations.Any() || data.iterations.First().compilationData == null || !data.iterations.First().compilationData.Any())
data = CompilationData.GetAll();
var gotData = data != null && data.iterations != null && data.iterations.Count > 0;
var gotSelection = !string.IsNullOrEmpty(selectedEntry);
GUILayout.BeginHorizontal(EditorStyles.toolbar);
EditorGUI.BeginDisabledGroup(EditorApplication.isCompiling);
if (GUILayout.Button("Recompile", EditorStyles.toolbarButton))
{
if(AllowRefresh)
Clear();
RecompileEverything();
GUIUtility.ExitGUI();
// TODO recompile separate scripts or AsmDefs or packages by selection, by setting them dirty
}
if (GUILayout.Button("Compile Player Scripts", EditorStyles.toolbarButton))
{
CompilePlayerScripts();
GUIUtility.ExitGUI();
}
var buttonRect = GUILayoutUtility.GetLastRect();
if (EditorGUILayout.DropdownButton(new GUIContent(""), FocusType.Passive, EditorStyles.toolbarDropDown))
{
if (!PlayerScriptsSettingsWindow.ShowAtPosition(buttonRect, this))
return;
GUIUtility.ExitGUI();
}
EditorGUI.EndDisabledGroup();
EditorGUILayout.Space();
compactDrawing = GUILayout.Toggle(compactDrawing, "Compact", EditorStyles.toolbarButton);
AllowLogging = GUILayout.Toggle(AllowLogging, new GUIContent("Logging", "Log additional compilation data to the console on compilation"), EditorStyles.toolbarButton);
ShowAssemblyReloads = GUILayout.Toggle(ShowAssemblyReloads, new GUIContent("Show Reloads", "Show or hide assembly reloads in the timeline."), EditorStyles.toolbarButton);
colorMode = (ColorMode) EditorGUILayout.EnumPopup(colorMode, GUILayout.ExpandWidth(false));
var totalSpan = TimeSpan.Zero;
var totalCompilationSpan = TimeSpan.Zero;
#if UNITY_2021_1_OR_NEWER
var firstToLastAssemblyCompilationSpan = TimeSpan.Zero;
#endif
var totalCompiledAssemblyCount = 0;
GUILayout.FlexibleSpace();
if(gotData && data.iterations.Count > 0)
{
totalSpan = data.iterations.Last().AfterAssemblyReload - data.iterations.First().CompilationStarted;
if (totalSpan.TotalSeconds < -1)
totalSpan = data.iterations.Last().CompilationFinished - data.iterations.First().CompilationStarted;
if (totalSpan.TotalSeconds <= 0) // timespan adjusted during compilation
totalSpan = DateTime.Now - data.iterations.First().CompilationStarted;
// workaround for Editor restart issues where compilation events are not complete
if(totalSpan.TotalSeconds > 1800) {
Clear();
GUIUtility.ExitGUI();
}
totalCompilationSpan = data.iterations
.Select(item => item.CompilationFinished - item.CompilationStarted)
.Aggregate((result, item) => result + item);
if (totalCompilationSpan.TotalSeconds < 0) // timespan adjusted during compilation
totalCompilationSpan = DateTime.Now - data.iterations.First().CompilationStarted;
#if UNITY_2021_1_OR_NEWER
var dataToAggregate= data.iterations
.Where(x => x is {compilationData: { }} && x.compilationData.Any())
.Select(x => x.compilationData.Last().EndTime - x.compilationData.First().StartTime);
firstToLastAssemblyCompilationSpan = dataToAggregate.Any() ? dataToAggregate.Aggregate((result, item) => result + item) : new TimeSpan(0);
#endif
var totalReloadSpan = data.iterations
.Select(item => item.AfterAssemblyReload - item.BeforeAssemblyReload)
.Aggregate((result, item) => result + item);
// another safeguard against broken compilation
if (totalReloadSpan.TotalSeconds > 1800) {
Clear();
GUIUtility.ExitGUI();
}
if(totalReloadSpan.TotalSeconds < 0)
totalReloadSpan = TimeSpan.FromSeconds(0);
totalCompiledAssemblyCount = data.iterations.Select(x => x.compilationData.Count).Sum();
GUILayout.Label("Total: " + totalSpan.TotalSeconds.ToString("F2") + "s");
GUILayout.Label("Compilation: " + totalCompilationSpan.TotalSeconds.ToString("F2") + "s");
#if UNITY_2021_1_OR_NEWER
GUILayout.Label("Csc: " + firstToLastAssemblyCompilationSpan.TotalSeconds.ToString("F2") + "s");
#endif
GUILayout.Label("Reload: " + totalReloadSpan.TotalSeconds.ToString("F2") + "s");
GUILayout.Label("Compiled Assemblies: " + totalCompiledAssemblyCount);
if (data.iterations.Count > 1)
GUILayout.Label("Iterations: " + data.iterations.Count);
GUILayout.FlexibleSpace();
}
GUILayout.EndHorizontal();
if (!gotData || data.iterations.Count == 0)
{
try
{
GUILayout.Label("Waiting for compilation data...", EditorStyles.miniLabel);
}
// Unity being weird
catch (ArgumentException)
{
// ignore
}
return;
}
var yMax = GUILayoutUtility.GetLastRect().yMax;
// start of draw area rect
var rect = new Rect(0, 0, position.width, position.height) {yMin = yMax};
// var totalWidth = rect.width;
var totalSeconds = ShowAssemblyReloads ? totalSpan.TotalSeconds : totalCompilationSpan.TotalSeconds;
var viewRect = rect;
viewRect.yMax = viewRect.yMin + k_LineHeight * totalCompiledAssemblyCount;
viewRect.width -= 15;
var totalWidth = viewRect.width;
if (compactDrawing && graphSlots.Any()) {
viewRect.yMax = viewRect.yMin + k_LineHeight * (graphSlots.Last().Key + 1);
}
else if (!compactDrawing && gotSelection) {
viewRect.yMax = viewRect.yMin + lastTotalHeight;
}
var paintRect = viewRect;
var fromWidth = viewRect.width * fromTimeValue;
var toWidth = viewRect.width * toTimeValue;
paintRect.xMin = Remap(fromWidth, toWidth, 0, viewRect.width, 0);
paintRect.xMax = Remap(fromWidth, toWidth, 0, viewRect.width, viewRect.width);
var isZoomed = !(Mathf.Approximately(fromTimeValue, 0) && Mathf.Approximately(toTimeValue, 1));
if (Event.current.type == EventType.Repaint) {
// draw time header
var backgroundRect = rect;
// not sure why, but Profiler background style is weird pre-New UI
#if !UNITY_2019_3_OR_NEWER
backgroundRect.xMin -= 200;
backgroundRect.width += 200;
#endif
GUI.DrawTexture(backgroundRect, Styles.background);
var timeHeader0 = GUI.color;
var timeHeader1 = GUI.color;
timeHeader1.a = 0.65f;
GUI.color = timeHeader1;
// actual time
DrawTimeHeader(viewRect, scrollPosition, (float) totalSeconds * 1000f);
timeHeader1.a = 1f;
GUI.color = timeHeader1;
// zoomed time
var scaledTimeHeader = paintRect;
scaledTimeHeader.yMin += 40;
DrawTimeHeader(scaledTimeHeader, scrollPosition, (float) totalSeconds * 1000f);
GUI.color = timeHeader0;
}
var sliderRect = viewRect;
sliderRect.width += 15;
sliderRect.yMin += 20;
sliderRect.height = 20;
var c0 = GUI.color;
var c1 = GUI.color;
c1.a = 0.3f;
GUI.color = c1;
EditorGUI.MinMaxSlider(sliderRect, ref fromTimeValue, ref toTimeValue, 0f, 1f);
GUI.color = c0;
rect.yMin += 60;
viewRect.height = Mathf.Max(viewRect.height + k_LineHeight, rect.height); // one extra line for reload indicator
paintRect.height = viewRect.height;
if (gotSelection) {
selectedScrollPosition = GUI.BeginScrollView(rect, selectedScrollPosition, viewRect);
scrollPosition.x = selectedScrollPosition.x; // sync X scroll
}
else {
scrollPosition = GUI.BeginScrollView(rect, scrollPosition, viewRect);
selectedScrollPosition.x = scrollPosition.x; // sync X scroll
}
DrawVerticalLines(paintRect, (float) totalSeconds * 1000f);
// GUI.DrawTexture(rect, Texture2D.whiteTexture);
graphSlots.Clear();
entryRects.Clear();
if (Event.current.type == EventType.MouseDown)
{
accumulatedDrag = 0;
}
if (Event.current.type == EventType.MouseUp)
{
if (accumulatedDrag > 0)
Event.current.Use();
}
// alt + right click resets the view immediately
if (Event.current.type == EventType.MouseDown && Event.current.button == 1)
{
Event.current.Use();
if(Event.current.alt)
{
fromTimeValue = 0;
toTimeValue = 1;
Repaint();
}
}
// need to do this before the entries, otherwise the entry buttons catch drag events.
if (Event.current.type == EventType.MouseDrag)
{
var pixelShift = Event.current.delta.x;
var totalScaledPixelWidth = Remap(fromTimeValue * Screen.width, toTimeValue * Screen.width, 0, Screen.width, Screen.width);
var percentageShift = pixelShift / totalScaledPixelWidth * 0.5f;
// clamp shift
if(fromTimeValue - percentageShift >= 0 && fromTimeValue - percentageShift <= 1 && toTimeValue - percentageShift >= 0 && toTimeValue - percentageShift <= 1)
{
fromTimeValue -= percentageShift;
toTimeValue -= percentageShift;
}
var verticalShift = Event.current.delta.y;
selectedScrollPosition.y -= verticalShift;
scrollPosition.y -= verticalShift;
accumulatedDrag += Event.current.delta.sqrMagnitude;
Repaint();
}
// naive first pass: paint colored textures
int nonSkippedIndex = 0;
float currentHeight = yMax;
DateTime firstCompilationStarted = data.iterations.First().CompilationStarted;
DateTime lastSectionEndTime = firstCompilationStarted;
foreach(var iterationData in data.iterations) {
foreach (var c in iterationData.compilationData) {
bool skip = gotSelection;
// skip in selection mode
if (skip && selectedEntry != null) {
if (selectedEntry == c.assembly) skip = false;
if (skip) {
if (AssemblyDependantDict.TryGetValue(c.assembly, out var dependantAssemblyList)) {
foreach (var a in dependantAssemblyList) {
if (a == null) continue;
if (selectedEntry.Equals(a.outputPath, StringComparison.Ordinal)) {
skip = false;
break;
}
}
}
}
if (skip) {
if (AssemblyDependencyDict.TryGetValue(c.assembly, out var assembly)) {
foreach (var a in assembly.assemblyReferences) {
if (a == null) continue;
if (selectedEntry.Equals(a.outputPath, StringComparison.Ordinal)) {
skip = false;
break;
}
}
}
}
}
// if (skip) continue;
var entryHeight = skip ? k_SkippedHeight : k_LineHeight;
var xSpan = (c.StartTime - iterationData.CompilationStarted) + (lastSectionEndTime - firstCompilationStarted);
var wSpan = c.EndTime - c.StartTime;
// continuous drawing during compilation - looks nicer
if (wSpan.TotalSeconds < 0)
wSpan = DateTime.Now - c.startTime;
var x = (float) (xSpan.TotalSeconds / totalSeconds) * totalWidth;
var w = (float) (wSpan.TotalSeconds / totalSeconds) * totalWidth;
var color = Color.white;
switch (colorMode)
{
case ColorMode.DependantCount:
if (AssemblyDependantDict.TryGetValue(c.assembly, out var dependantAssemblyList)) {
color = ColorFromValue(dependantAssemblyList.Count, 0f, 5f, 0.3f);
}
break;
case ColorMode.DependencyCount:
if (AssemblyDependencyDict.TryGetValue(c.assembly, out var assembly)) {
color = ColorFromValue(assembly.assemblyReferences.Length, 0f, 10f, 0.3f);
}
break;
default:
color = ColorFromValue((float) wSpan.TotalSeconds, 0.5f, 5f, 0.3f);
break;
}
// stacking: find free slots to place entries
var freeSlots = graphSlots.Where(slot => slot.Value + 0 < x).ToList();
int freeSlot;
if (freeSlots.Any()) {
freeSlot = freeSlots.OrderByDescending(slot => x - slot.Value).First().Key;
}
else {
if (graphSlots.Any())
freeSlot = graphSlots.Last().Key + 1;
else
freeSlot = 0;
graphSlots.Add(freeSlot, x + w);
}
graphSlots[freeSlot] = x + w;
// remap x and w
var xEnd = x + w;
x = Remap(fromWidth, toWidth, 0, viewRect.width, x);
w = Remap(fromWidth, toWidth, 0, viewRect.width, xEnd) - x;
var localRect = new Rect(x, k_LineHeight * (compactDrawing ? freeSlot : nonSkippedIndex) + yMax, w,
entryHeight);
if (gotSelection) {
if (compactDrawing) {
if (skip) {
localRect.height = k_SkippedHeight;
localRect.y += k_LineHeight - k_SkippedHeight;
}
}
else
localRect.y = currentHeight;
}
currentHeight += entryHeight;
nonSkippedIndex++;
entryRects[c.assembly] = localRect;
DrawEntry(compilationData: iterationData, c, localRect, color, !compactDrawing || (compactDrawing && gotSelection));
}
var oldLastSection = lastSectionEndTime;
lastSectionEndTime = ShowAssemblyReloads ? iterationData.AfterAssemblyReload : iterationData.CompilationFinished;
// reload indicator at the end of each iteration
var xSpan2 = (iterationData.CompilationFinished - iterationData.CompilationStarted) + (oldLastSection - firstCompilationStarted);
var wSpan2 = lastSectionEndTime - iterationData.CompilationFinished;
var x2 = (float) (xSpan2.TotalSeconds / totalSeconds) * totalWidth;
var w2 = (float) (wSpan2.TotalSeconds / totalSeconds) * totalWidth;
// remap x and w
var xEnd2 = x2 + w2;
x2 = Remap(fromWidth, toWidth, 0, viewRect.width, x2);
w2 = Remap(fromWidth, toWidth, 0, viewRect.width, xEnd2) - x2;
DrawReloadIndicator(viewRect, ShowAssemblyReloads, x2, w2, Mathf.Max(0, (float) (iterationData.AfterAssemblyReload - iterationData.CompilationFinished).TotalSeconds));
}
lastTotalHeight = currentHeight;
foreach(var iterationData in data.iterations)
foreach (var c in iterationData.compilationData) {
if (c.assembly != selectedEntry) continue;
var localRect = entryRects[c.assembly];
DrawConnectors(c, localRect);
}
if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) {
// context click: remove selection
// Debug.Log("context click!");
selectedEntry = null;
Repaint();
}
if (Event.current.type == EventType.ScrollWheel && Event.current.alt)
{
// we want to zoom around the current X position:
var mPosX = Event.current.mousePosition.x;
var scrollDelta = Event.current.delta.y;
var scrollAmount = 1f + scrollDelta / 25f;
var percentageOnPage = Mathf.InverseLerp(0, Screen.width, mPosX);
var valueOnPage = Remap(0, 1, fromTimeValue, toTimeValue, percentageOnPage);
// scale current from and to values around that valueOnPage
fromTimeValue = valueOnPage - (valueOnPage - fromTimeValue) * scrollAmount;
toTimeValue = valueOnPage + (toTimeValue - valueOnPage) * scrollAmount;
fromTimeValue = Mathf.Clamp01(fromTimeValue);
toTimeValue = Mathf.Clamp01(toTimeValue);
Event.current.Use();
Repaint();
}
GUI.EndScrollView();
}
private static float Remap(float srcFrom, float srcTo, float dstFrom, float dstTo, float val)
{
return (val - srcFrom) / (srcTo - srcFrom) * (dstTo - dstFrom) + dstFrom;
}
#if UNITY_2019_1_OR_NEWER
[Shortcut("needle-compilation-visualizer-" + nameof(CompilePlayerScripts))]
#endif
void CompilePlayerScripts()
{
if(AllowRefresh)
Clear();
var settings = new ScriptCompilationSettings
{
group = BuildPipeline.GetBuildTargetGroup(buildTarget),
target = buildTarget,
options = ScriptCompilationOptions.None
};
// Debug.Log("Compiling Player Scripts for " + settings.group + "/" + settings.target);
const string tempDir = "Temp/PlayerScriptCompilation/";
EditorUtility.DisplayProgressBar("Compiling Player Scripts", "Build Target: " + settings.target + " (" + settings.group + ")", 0.1f);
#if BEE_COMPILATION_PIPELINE
try
{
// TODO figure out the right way to clear the compilation cache
// if (Directory.Exists("Library/Bee")) Directory.Delete("Library/Bee");
// if (Directory.Exists("Library/PramData")) Directory.Delete("Library/PramData");
// if (Directory.Exists("Library/BuildPlayerData")) Directory.Delete("Library/BuildPlayerData");
if (Directory.Exists("Library/Bee/artifacts")) Directory.Delete("Library/Bee/artifacts", true);
if (Directory.Exists(tempDir)) Directory.Delete(tempDir);
}
catch (Exception)
{
// ignore
}
#endif
// RequestScriptCompilationOptions.CleanBuildCache?
var results = PlayerBuildInterface.CompilePlayerScripts(settings, tempDir);
// Debug.Log(string.Join("\n", results.assemblies));
EditorUtility.ClearProgressBar();
}
void RecompileEverything()
{
#if UNITY_2021_1_OR_NEWER
CompilationPipeline.RequestScriptCompilation(RequestScriptCompilationOptions.CleanBuildCache);
#elif UNITY_2019_3_OR_NEWER
CompilationPipeline.RequestScriptCompilation();
#elif UNITY_2017_1_OR_NEWER
var editorAssembly = System.Reflection.Assembly.GetAssembly(typeof(Editor));
var editorCompilationInterfaceType = editorAssembly?.GetType("UnityEditor.Scripting.ScriptCompilation.EditorCompilationInterface");
var dirtyAllScriptsMethod = editorCompilationInterfaceType?.GetMethod("DirtyAllScripts", BindingFlags.Static | BindingFlags.Public);
dirtyAllScriptsMethod?.Invoke(editorCompilationInterfaceType, null);
#endif
}
private void DrawReloadIndicator(Rect viewRect, bool showAssemblyReloads, float x, float width, float reloadDuration)
{
if (showAssemblyReloads)
GUI.color = new Color(1, 0, 0, 0.05f);
else
GUI.color = new Color(1, 0, 0, 0.5f);
GUI.DrawTexture(new Rect(x, viewRect.yMin, Mathf.Max(1, width), viewRect.height), Texture2D.whiteTexture);
GUI.color = Color.red;
GUI.Label(new Rect(x - 100, viewRect.yMax - 14, 100, 14), "Reload: " + reloadDuration.ToString("0.###s"), Styles.rightAlignedLabel);
GUI.color = Color.white;
}
void DrawTimeHeader(Rect viewRect, Vector2 scroll, float totalMilliseconds) {
var totalSeconds = totalMilliseconds / 1000f;
var amount = totalSeconds * 1000f / viewRect.width;
var multiplier = 1f;
if (amount < 5)
multiplier = 4f;
if (amount < 2f)
multiplier = 10f;
if (amount < 0.5f)
multiplier = 25f;
if (amount > 50)
multiplier = 0.5f;
if (amount > 100)
multiplier = 0.2f;
if (amount > 500)
multiplier = 0.05f;
var linesPerSecond = 1f * multiplier;
var lineCount = (int) (totalSeconds * linesPerSecond) + 2;
var lineDistance = viewRect.width / (totalSeconds * linesPerSecond);
var vr = viewRect;
vr.x -= scroll.x;
viewRect = vr;
// height: 20
var tenthRect = new Rect(viewRect.x, viewRect.yMin + 17, viewRect.width, 3);
DrawVerticalLines(tenthRect, totalMilliseconds, 10 * multiplier);
var fourthRect = new Rect(viewRect.x, viewRect.yMin + 14, viewRect.width, 3);
DrawVerticalLines(fourthRect, totalMilliseconds, 5f * multiplier);
var onesRect = new Rect(viewRect.x, viewRect.yMin + 0, viewRect.width, 20);
DrawVerticalLines(onesRect, totalMilliseconds, 1f * multiplier);
for (int i = 0; i < lineCount; i++) {
GUI.Label(new Rect(i * lineDistance - 50 + viewRect.xMin, viewRect.yMin, 100, 14),
(i / multiplier).ToString("0.###s"), EditorStyles.centeredGreyMiniLabel);
}
}
void DrawVerticalLines(Rect viewRect, float totalMilliseconds, float linesPerSecond = 1f) {
if (Event.current.type != EventType.Repaint) return;
// just draw a line per second
// left is always 0
var totalSeconds = totalMilliseconds / 1000f;
var lineCount = (int) (totalSeconds * linesPerSecond) + 2;
var lineDistance = viewRect.width / (totalSeconds * linesPerSecond);
var c0 = GUI.color;
var c = styles.verticalLineColor;
c.a *= GUI.color.a;
GUI.color = c;
for (int i = 0; i < lineCount; i++) {
GUI.DrawTexture(new Rect(i * lineDistance + viewRect.xMin, viewRect.yMin, 1, viewRect.height), Texture2D.whiteTexture);
}
GUI.color = c0;
}
Color ColorFromValue(float value, float min = 0.5f, float max = 5f, float hueRange = 0.25f) {
return Color.HSVToRGB(Mathf.InverseLerp(max, min, value) * hueRange, UnityEditor.EditorGUIUtility.isProSkin ? 0.3f : 0.25f, UnityEditor.EditorGUIUtility.isProSkin ? 0.3f : 0.8f);
}
public Vector2 scrollPosition;
public Vector2 selectedScrollPosition;
public string selectedEntry;
readonly Dictionary<string, Rect> entryRects = new Dictionary<string, Rect>();
private void DrawEntry(CompilationData compilationData, AssemblyCompilationData c, Rect localRect, Color color,
bool overflowLabel) {
localRect.xMin += 0.5f;
localRect.xMax -= 0.5f;
localRect.yMin += 0.5f;
localRect.yMax -= 0.5f;
if (Event.current.type == EventType.Repaint) {
GUI.color = color;
GUI.DrawTexture(localRect, Texture2D.whiteTexture);
GUI.color = Color.white;
}
// localRect.width = Mathf.Max(localRect.width, 500); // make space for the label
if (localRect.height > 5 && GUI.Button(localRect, GetGUIContent(compilationData, c),
overflowLabel ? Styles.overflowMiniLabel : Styles.miniLabel)) {
if (!string.IsNullOrEmpty(selectedEntry) &&
selectedEntry.Equals(c.assembly, StringComparison.Ordinal)) {
selectedEntry = null;
return;
}
selectedEntry = c.assembly;
if(AllowLogging) {
try {
var path = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(c.assembly);
var asm = Assemblies.FirstOrDefault(x => x.outputPath == c.assembly);
if (asm == null)
{
Debug.LogError("Assembly is null for " + path + " from " + c.assembly);
return;
}
var asmDefAsset = AssetDatabase.LoadAssetAtPath<AssemblyDefinitionAsset>(path);
var pi = string.IsNullOrEmpty(path)
? null
:
#if UNITY_2019_2_OR_NEWER
PackageInfo.FindForAssetPath(path);
#else
default(PackageInfo);
#endif
var editorPath = Path.GetDirectoryName(EditorApplication.applicationPath) +
Path.DirectorySeparatorChar + "Data" + Path.DirectorySeparatorChar;
var logString = "<b>" + Path.GetFileName(path) + "</b>" + " in " + (pi?.name ?? "Assets") +
"\n\n<i>Assembly References</i>:\n- " +
string.Join("\n- ",
asm.assemblyReferences.Select(x => x.name)
) +
"\n\n<i>Defines</i>:\n- " +
string.Join("\n- ",
asm.defines
.OrderBy(x => x)
) +
"\n\n<i>Compiled Assembly References</i>:\n- " +
string.Join("\n- ",
asm.compiledAssemblyReferences.Select(x =>
Path.GetFileName(x) + " <color=#ffffff" + "55>" +
Path.GetDirectoryName(x)?.Replace(editorPath, "") + "</color>")
);
// Workaround for console log length limitations
const int MaxLogLength = 15000;
if (logString.Length > MaxLogLength)
{
var colorMarker = "</color>";
logString = logString.Substring(0, MaxLogLength);
int substringLength = logString.LastIndexOf(colorMarker, StringComparison.Ordinal) +
colorMarker.Length;
if (substringLength <= logString.Length)
logString = logString.Substring(0, substringLength) + "\n\n<b>(truncated)</b>";
}
Debug.Log(logString, asmDefAsset);
}
catch {
// ignored
}
}
// EditorGUIUtility.PingObject(asmDefAsset);
}
}
private void DrawConnectors(AssemblyCompilationData c,
Rect originalRect) {
void DrawConnector(int i, IList<Assembly> assemblyList, bool alignRight, Color color) {
// target asm
if (entryRects.TryGetValue(assemblyList[i].outputPath, out var referenceRect)) {
float lrp = (i + 0.5f) / assemblyList.Count;
var lineRect = originalRect;
lineRect.yMin = Mathf.Lerp(originalRect.yMin, originalRect.yMax, lrp);
lineRect.yMax = lineRect.yMin + 1;
var mat = GUI.matrix;
var col = GUI.color;
GUI.color = color;
// horizontal line
// randomize X pos along node (makes deps easier to see when there are many)
lineRect.xMin = Mathf.Lerp(referenceRect.xMin, referenceRect.xMax, lrp);
// override for now, we don't need this if we have a selection
lineRect.xMin = referenceRect.xMin;
lineRect.xMax = alignRight ? originalRect.xMax : originalRect.xMin;
GUI.DrawTexture(lineRect, Texture2D.whiteTexture);
// vertical line
lineRect.xMax = lineRect.xMin + 1;
lineRect.yMin = referenceRect.center.y;
GUI.DrawTexture(lineRect, Texture2D.whiteTexture);
// end point
lineRect.width = 5;
lineRect.height = 5;
lineRect.x -= 2f;
lineRect.y -= 2f;
GUI.DrawTexture(lineRect, Texture2D.whiteTexture);
GUI.matrix = mat;
GUI.color = col;
}
/*
else {
stackRect.y += 10;
GUI.DrawTexture(stackRect, Texture2D.whiteTexture);
}
*/
}
if (Event.current.type != EventType.Repaint) return;
// draw connectors
if (AssemblyDependencyDict.TryGetValue(c.assembly, out var assembly)) {
var adjustedRect = originalRect;
adjustedRect.x = adjustedRect.xMin + 1;
adjustedRect.width = adjustedRect.height = 1;
for (int i = 0; i < assembly.assemblyReferences.Length; i++) {
DrawConnector(i, assembly.assemblyReferences, false, styles.connectorColor);
}
}
if (AssemblyDependantDict.TryGetValue(c.assembly, out var dependantList)) {
var adjustedRect = originalRect;
adjustedRect.x = adjustedRect.xMin + 1;
adjustedRect.width = adjustedRect.height = 1;
for (int i = 0; i < dependantList.Count; i++) {
DrawConnector(i, dependantList, true, styles.connectorColor2);
}
}
}
const string FormatString = "HH:mm:ss.fff";
private const string SpanFormatString = "0.###s";
GUIContent GetGUIContent(CompilationData compilationData, AssemblyCompilationData c) {
var shortName = Path.GetFileName(c.assembly);
// var pi = PackageInfo.FindForAssembly()
return new GUIContent(shortName,
shortName + "\n" +
(c.EndTime - c.StartTime).TotalSeconds.ToString(SpanFormatString) + "\n" +
"From " + c.StartTime.ToString(FormatString) + " to " + c.EndTime.ToString(FormatString) + "\n" +
"From " + (c.StartTime - compilationData.CompilationStarted).TotalSeconds.ToString(SpanFormatString) + " to " + (c.EndTime - compilationData.CompilationStarted).TotalSeconds.ToString(SpanFormatString));
}
public void AddItemsToMenu(GenericMenu menu) {
windowLockState.AddItemsToMenu(menu);
#if UNITY_2021_1_OR_NEWER
menu.AddItem(new GUIContent("Fetch Bee Trace"), false, () =>
{
data = CompilationData.GetAll();
});
menu.AddItem(new GUIContent("Open Chrome and Trace File"), false, () =>
{
#if UNITY_2021_2_OR_NEWER
EditorUtility.RevealInFinder("Library/Bee/fullprofile.json");
#endif
// Application.OpenURL("chrome://trace"); // Chrome's built-in viewer; can't open that as URL directly
Application.OpenURL("https://ui.perfetto.dev/v15.0.5/assets/catapult_trace_viewer.html"); // same viewer but as URL
});
#endif
}
protected void ShowButton(Rect r) {
#if !UNITY_2021_1_OR_NEWER // TODO need to figure out how to lock results on 2021+
windowLockState.ShowButton(r, Styles.lockButton);
#endif
}
internal class PlayerScriptsSettingsWindow : EditorWindow
{
internal CompilationTimelineWindow parentWindow;
internal static PlayerScriptsSettingsWindow window;
internal static bool ShowAtPosition(Rect buttonRect, CompilationTimelineWindow parentWindow)
{
Event.current.Use();
if (!window)
{
window = CreateInstance<PlayerScriptsSettingsWindow>();
window.Init(buttonRect, parentWindow);
return true;
}
window.Cancel();
return false;
}
private GUIStyle background;
private void Init(Rect buttonRect, CompilationTimelineWindow parentWnd)
{
background = "grey_border";
#if UNITY_2019_1_OR_NEWER
buttonRect = GUIUtility.GUIToScreenRect(buttonRect);
#endif
parentWindow = parentWnd;
var windowSize = new Vector2(320f, UnityEditor.EditorGUIUtility.singleLineHeight + 2 * 4);
ShowAsDropDown(buttonRect, windowSize);
}
private void Cancel()
{
Close();
GUI.changed = true;
GUIUtility.ExitGUI();
}
private void OnGUI()
{
if (background == null) background = "grey_border";
var wnd = new Rect(0, 0, position.width, position.height);
var innerWnd = wnd;
const int padding = 4;
innerWnd.xMin += padding;
innerWnd.xMax -= padding;
innerWnd.yMin += padding;
innerWnd.yMax -= padding;
var width = UnityEditor.EditorGUIUtility.labelWidth;
UnityEditor.EditorGUIUtility.labelWidth = 90;
parentWindow.buildTarget = (BuildTarget) EditorGUI.EnumPopup(innerWnd, "Build Target", parentWindow.buildTarget);
UnityEditor.EditorGUIUtility.labelWidth = width;
if (Event.current.type == EventType.Repaint)
background.Draw(wnd, GUIContent.none, false, false, false, false);
if (Event.current.type != EventType.KeyDown || Event.current.keyCode != KeyCode.Escape)
return;
Cancel();
}
}
}
} | 44.691729 | 218 | 0.535877 | [
"MIT"
] | needle-tools/com.needle.compilation-analysis | Editor/CompilationTimelineWindow.cs | 47,556 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.AppService.Models;
using Azure.ResourceManager.Core;
namespace Azure.ResourceManager.AppService
{
/// <summary> A Class representing a User along with the instance operations that can be performed on it. </summary>
public partial class User : ArmResource
{
/// <summary> Generate the resource identifier of a <see cref="User"/> instance. </summary>
public static ResourceIdentifier CreateResourceIdentifier()
{
var resourceId = $"/providers/Microsoft.Web/publishingUsers/web";
return new ResourceIdentifier(resourceId);
}
private readonly ClientDiagnostics _clientDiagnostics;
private readonly WebSiteManagementRestOperations _restClient;
private readonly UserData _data;
/// <summary> Initializes a new instance of the <see cref="User"/> class for mocking. </summary>
protected User()
{
}
/// <summary> Initializes a new instance of the <see cref = "User"/> class. </summary>
/// <param name="options"> The client parameters to use in these operations. </param>
/// <param name="data"> The resource that is the target of operations. </param>
internal User(ArmResource options, UserData data) : base(options, data.Id)
{
HasData = true;
_data = data;
Parent = options;
_clientDiagnostics = new ClientDiagnostics(ClientOptions);
ClientOptions.TryGetApiVersion(ResourceType, out string apiVersion);
_restClient = new WebSiteManagementRestOperations(_clientDiagnostics, Pipeline, ClientOptions, BaseUri, apiVersion);
#if DEBUG
ValidateResourceId(Id);
#endif
}
/// <summary> Initializes a new instance of the <see cref="User"/> class. </summary>
/// <param name="options"> The client parameters to use in these operations. </param>
/// <param name="id"> The identifier of the resource that is the target of operations. </param>
internal User(ArmResource options, ResourceIdentifier id) : base(options, id)
{
Parent = options;
_clientDiagnostics = new ClientDiagnostics(ClientOptions);
ClientOptions.TryGetApiVersion(ResourceType, out string apiVersion);
_restClient = new WebSiteManagementRestOperations(_clientDiagnostics, Pipeline, ClientOptions, BaseUri, apiVersion);
#if DEBUG
ValidateResourceId(Id);
#endif
}
/// <summary> Initializes a new instance of the <see cref="User"/> class. </summary>
/// <param name="clientOptions"> The client options to build client context. </param>
/// <param name="credential"> The credential to build client context. </param>
/// <param name="uri"> The uri to build client context. </param>
/// <param name="pipeline"> The pipeline to build client context. </param>
/// <param name="id"> The identifier of the resource that is the target of operations. </param>
internal User(ArmClientOptions clientOptions, TokenCredential credential, Uri uri, HttpPipeline pipeline, ResourceIdentifier id) : base(clientOptions, credential, uri, pipeline, id)
{
_clientDiagnostics = new ClientDiagnostics(ClientOptions);
ClientOptions.TryGetApiVersion(ResourceType, out string apiVersion);
_restClient = new WebSiteManagementRestOperations(_clientDiagnostics, Pipeline, ClientOptions, BaseUri, apiVersion);
#if DEBUG
ValidateResourceId(Id);
#endif
}
/// <summary> Gets the resource type for the operations. </summary>
public static readonly ResourceType ResourceType = "Microsoft.Web/publishingUsers";
/// <summary> Gets whether or not the current instance has data. </summary>
public virtual bool HasData { get; }
/// <summary> Gets the data representing this Feature. </summary>
/// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception>
public virtual UserData Data
{
get
{
if (!HasData)
throw new InvalidOperationException("The current instance does not have data, you must call Get first.");
return _data;
}
}
internal static void ValidateResourceId(ResourceIdentifier id)
{
if (id.ResourceType != ResourceType)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id));
}
/// <summary> Gets the parent resource of this resource. </summary>
public ArmResource Parent { get; }
/// RequestPath: /providers/Microsoft.Web/publishingUsers/web
/// ContextualPath: /providers/Microsoft.Web/publishingUsers/web
/// OperationId: GetPublishingUser
/// <summary> Description for Gets publishing user. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async virtual Task<Response<User>> GetAsync(CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("User.Get");
scope.Start();
try
{
var response = await _restClient.GetPublishingUserAsync(cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false);
return Response.FromValue(new User(this, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// RequestPath: /providers/Microsoft.Web/publishingUsers/web
/// ContextualPath: /providers/Microsoft.Web/publishingUsers/web
/// OperationId: GetPublishingUser
/// <summary> Description for Gets publishing user. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<User> Get(CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("User.Get");
scope.Start();
try
{
var response = _restClient.GetPublishingUser(cancellationToken);
if (response.Value == null)
throw _clientDiagnostics.CreateRequestFailedException(response.GetRawResponse());
return Response.FromValue(new User(this, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Lists all available geo-locations. </summary>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param>
/// <returns> A collection of locations that may take multiple service requests to iterate over. </returns>
public async virtual Task<IEnumerable<AzureLocation>> GetAvailableLocationsAsync(CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("User.GetAvailableLocations");
scope.Start();
try
{
return await ListAvailableLocationsAsync(ResourceType, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Lists all available geo-locations. </summary>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param>
/// <returns> A collection of locations that may take multiple service requests to iterate over. </returns>
public virtual IEnumerable<AzureLocation> GetAvailableLocations(CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("User.GetAvailableLocations");
scope.Start();
try
{
return ListAvailableLocations(ResourceType, cancellationToken);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// RequestPath: /providers/Microsoft.Web/publishingUsers/web
/// ContextualPath: /providers/Microsoft.Web/publishingUsers/web
/// OperationId: UpdatePublishingUser
/// <summary> Description for Updates publishing user. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="userDetails"> Details of publishing user. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="userDetails"/> is null. </exception>
public async virtual Task<UserCreateOrUpdateOperation> CreateOrUpdateAsync(bool waitForCompletion, UserData userDetails, CancellationToken cancellationToken = default)
{
if (userDetails == null)
{
throw new ArgumentNullException(nameof(userDetails));
}
using var scope = _clientDiagnostics.CreateScope("User.CreateOrUpdate");
scope.Start();
try
{
var response = await _restClient.UpdatePublishingUserAsync(userDetails, cancellationToken).ConfigureAwait(false);
var operation = new UserCreateOrUpdateOperation(this, response);
if (waitForCompletion)
await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// RequestPath: /providers/Microsoft.Web/publishingUsers/web
/// ContextualPath: /providers/Microsoft.Web/publishingUsers/web
/// OperationId: UpdatePublishingUser
/// <summary> Description for Updates publishing user. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="userDetails"> Details of publishing user. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="userDetails"/> is null. </exception>
public virtual UserCreateOrUpdateOperation CreateOrUpdate(bool waitForCompletion, UserData userDetails, CancellationToken cancellationToken = default)
{
if (userDetails == null)
{
throw new ArgumentNullException(nameof(userDetails));
}
using var scope = _clientDiagnostics.CreateScope("User.CreateOrUpdate");
scope.Start();
try
{
var response = _restClient.UpdatePublishingUser(userDetails, cancellationToken);
var operation = new UserCreateOrUpdateOperation(this, response);
if (waitForCompletion)
operation.WaitForCompletion(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
}
}
| 47.153846 | 189 | 0.6354 | [
"MIT"
] | BaherAbdullah/azure-sdk-for-net | sdk/websites/Azure.ResourceManager.AppService/src/Generated/User.cs | 12,260 | C# |
using Application;
using AspNetCoreRateLimit;
using Infrastructure;
using MediatR;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Web.OpenAPI;
namespace Web
{
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
.AddWeb(Configuration)
.AddInfrastructure(Configuration)
.AddApplicationRegistry(Configuration)
.AddSwagger()
.AddCors();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(
IApplicationBuilder app,
IWebHostEnvironment env,
ILoggerFactory loggerFactory)
{
loggerFactory.AddSerilogLogging(env);
if (!env.IsDevelopment())
{
app.UseHsts();
app.UseHttpsRedirection();
}
//change this allow only specific origins
app.UseCors(
builder =>
builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.WithExposedHeaders("Token-Expired"));
app.UseSwagger(
c => { c.RouteTemplate = "swagger/{documentName}/swagger.json"; })
.UseSwaggerUI(
x =>
{
x.SwaggerEndpoint("/swagger/v1/swagger.json", "V1");
x.SwaggerEndpoint("/swagger/v2/swagger.json", "V2");
});
app.UseIpRateLimiting();
app.UseErrorHandlingMiddleware();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
}
}
| 31.089744 | 106 | 0.549278 | [
"MIT"
] | simplyvinay/api-starter-template | Web/Startup.cs | 2,425 | 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("Sif.Framework.Demo.Us.Provider")]
[assembly: AssemblyDescription("Provider created to demonstrate SIF 3 Framework usage.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Systemic Pty Ltd")]
[assembly: AssemblyProduct("Sif.Framework.Demo.Us.Provider")]
[assembly: AssemblyCopyright("Copyright © Systemic Pty Ltd 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0538bd5c-72e8-470f-9658-0f80cf10230d")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("3.2.1.11")]
[assembly: AssemblyFileVersion("3.2.1.11")]
| 41.138889 | 89 | 0.756246 | [
"Apache-2.0"
] | Access4Learning/sif3-framework-dotnet | Code/Sif3FrameworkDemo/Sif.Framework.Demo.Us.Provider/Properties/AssemblyInfo.cs | 1,484 | C# |
using DrumbleApp.Shared.Messages.Enums;
using DrumbleApp.Shared.Messages.Base;
using DrumbleApp.Shared.ValueObjects;
namespace DrumbleApp.Shared.Messages.Classes
{
public sealed class TwitterAccessMessage : BaseMessage<TwitterAccessMessage>
{
public TwitterAccessMessageReason Reason { get; private set; }
public TwitterAccess TwitterAccess { get; private set; }
public TwitterAccessMessage(TwitterAccess twitterAccess, TwitterAccessMessageReason reason)
{
this.TwitterAccess = twitterAccess;
this.Reason = reason;
}
private void Send()
{
base.Send(this);
}
public static void Send(TwitterAccess twitterAccess, TwitterAccessMessageReason reason)
{
new TwitterAccessMessage(twitterAccess, reason).Send();
}
}
}
| 29.758621 | 99 | 0.677868 | [
"MIT"
] | CodeObsessed/drumbleapp | DrumbleApp.Shared/Messages/Classes/TwitterAccessMessage.cs | 865 | 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.md file in the project root for more information.
using System;
using System.Linq;
using Microsoft.Build.Construction;
using Xunit;
namespace Microsoft.VisualStudio.Build
{
public class BuildUtilitiesTests
{
[Fact]
public void GetProperty_MissingProperty()
{
string projectXml =
@"<Project>
<PropertyGroup>
<MyProperty>MyPropertyValue</MyProperty>
</PropertyGroup>
</Project>";
var project = ProjectRootElementFactory.Create(projectXml);
var property = BuildUtilities.GetProperty(project, "NonExistentProperty");
Assert.Null(property);
}
[Fact]
public void GetProperty_ExistentProperty()
{
string projectXml =
@"<Project>
<PropertyGroup>
<MyProperty>MyPropertyValue</MyProperty>
</PropertyGroup>
</Project>";
var project = ProjectRootElementFactory.Create(projectXml);
var property = BuildUtilities.GetProperty(project, "MyProperty");
Assert.NotNull(property);
}
[Fact]
public void GetPropertyValues_SingleValue()
{
var values = BuildUtilities.GetPropertyValues("MyPropertyValue");
Assert.Collection(values, firstValue => Assert.Equal("MyPropertyValue", firstValue));
}
[Fact]
public void GetPropertyValues_MultipleValues()
{
var values = BuildUtilities.GetPropertyValues("1;2");
Assert.Collection(values,
firstValue => Assert.Equal("1", firstValue),
secondValue => Assert.Equal("2", secondValue));
}
[Fact]
public void GetPropertyValues_NonDefaultDelimiter()
{
var values = BuildUtilities.GetPropertyValues("1|2", '|');
Assert.Collection(values,
firstValue => Assert.Equal("1", firstValue),
secondValue => Assert.Equal("2", secondValue));
}
[Fact]
public void GetPropertyValues_EmptyValues()
{
var values = BuildUtilities.GetPropertyValues("1; ;;;2");
Assert.Collection(values,
firstValue => Assert.Equal("1", firstValue),
secondValue => Assert.Equal("2", secondValue));
}
[Fact]
public void GetPropertyValues_WhiteSpace()
{
var values = BuildUtilities.GetPropertyValues(" 1; ; ; ; 2 ");
Assert.Collection(values,
firstValue => Assert.Equal("1", firstValue),
secondValue => Assert.Equal("2", secondValue));
}
[Fact]
public void GetPropertyValues_Duplicates()
{
var values = BuildUtilities.GetPropertyValues("1;2;1;1;2;2;2;1");
Assert.Collection(values,
firstValue => Assert.Equal("1", firstValue),
secondValue => Assert.Equal("2", secondValue));
}
[Fact]
public void GetOrAddProperty_NoGroups()
{
var project = ProjectRootElementFactory.Create();
BuildUtilities.GetOrAddProperty(project, "MyProperty");
Assert.Single(project.Properties);
Assert.Collection(project.PropertyGroups,
group => Assert.Collection(group.Properties,
firstProperty => Assert.Equal(string.Empty, firstProperty.Value)));
}
[Fact]
public void GetOrAddProperty_FirstGroup()
{
string projectXml =
@"<Project>
<PropertyGroup/>
<PropertyGroup/>
</Project>";
var project = ProjectRootElementFactory.Create(projectXml);
BuildUtilities.GetOrAddProperty(project, "MyProperty");
Assert.Single(project.Properties);
AssertEx.CollectionLength(project.PropertyGroups, 2);
var group = project.PropertyGroups.First();
Assert.Single(group.Properties);
var property = group.Properties.First();
Assert.Equal(string.Empty, property.Value);
}
[Fact]
public void GetOrAddProperty_ExistingProperty()
{
string projectXml =
@"<Project>
<PropertyGroup>
<MyProperty>1</MyProperty>
</PropertyGroup>
</Project>";
var project = ProjectRootElementFactory.Create(projectXml);
BuildUtilities.GetOrAddProperty(project, "MyProperty");
Assert.Single(project.Properties);
Assert.Single(project.PropertyGroups);
var group = project.PropertyGroups.First();
Assert.Single(group.Properties);
var property = group.Properties.First();
Assert.Equal("1", property.Value);
}
[Fact]
public void AppendPropertyValue_DefaultDelimiter()
{
string projectXml =
@"<Project>
<PropertyGroup>
<MyProperty>1;2</MyProperty>
</PropertyGroup>
</Project>";
var project = ProjectRootElementFactory.Create(projectXml);
BuildUtilities.AppendPropertyValue(project, "1;2", "MyProperty", "3");
var property = BuildUtilities.GetProperty(project, "MyProperty");
Assert.NotNull(property);
Assert.Equal("1;2;3", property!.Value);
}
[Fact]
public void AppendPropertyValue_EmptyProperty()
{
string projectXml =
@"<Project>
<PropertyGroup>
<MyProperty/>
</PropertyGroup>
</Project>";
var project = ProjectRootElementFactory.Create(projectXml);
BuildUtilities.AppendPropertyValue(project, "", "MyProperty", "1");
var property = BuildUtilities.GetProperty(project, "MyProperty");
Assert.NotNull(property);
Assert.Equal("1", property!.Value);
}
[Fact]
public void AppendPropertyValue_InheritedValue()
{
var project = ProjectRootElementFactory.Create();
BuildUtilities.AppendPropertyValue(project, "1;2", "MyProperty", "3");
var property = BuildUtilities.GetProperty(project, "MyProperty");
Assert.NotNull(property);
Assert.Equal("1;2;3", property!.Value);
}
[Fact]
public void AppendPropertyValue_MissingProperty()
{
var project = ProjectRootElementFactory.Create();
BuildUtilities.AppendPropertyValue(project, "", "MyProperty", "1");
var property = BuildUtilities.GetProperty(project, "MyProperty");
Assert.NotNull(property);
Assert.Equal("1", property!.Value);
}
[Fact]
public void AppendPropertyValue_NonDefaultDelimiter()
{
string projectXml =
@"<Project>
<PropertyGroup>
<MyProperty>1</MyProperty>
</PropertyGroup>
</Project>";
var project = ProjectRootElementFactory.Create(projectXml);
BuildUtilities.AppendPropertyValue(project, "1", "MyProperty", "2", '|');
var property = BuildUtilities.GetProperty(project, "MyProperty");
Assert.NotNull(property);
Assert.Equal("1|2", property!.Value);
}
[Fact]
public void RemovePropertyValue_DefaultDelimiter()
{
string projectXml =
@"<Project>
<PropertyGroup>
<MyProperty>1;2</MyProperty>
</PropertyGroup>
</Project>";
var project = ProjectRootElementFactory.Create(projectXml);
BuildUtilities.RemovePropertyValue(project, "1;2", "MyProperty", "2");
var property = BuildUtilities.GetProperty(project, "MyProperty");
Assert.NotNull(property);
Assert.Equal("1", property!.Value);
}
[Fact]
public void RemovePropertyValue_NonDefaultDelimiter()
{
string projectXml =
@"<Project>
<PropertyGroup>
<MyProperty>1|2|3</MyProperty>
</PropertyGroup>
</Project>";
var project = ProjectRootElementFactory.Create(projectXml);
BuildUtilities.RemovePropertyValue(project, "1|2|3", "MyProperty", "2", '|');
var property = BuildUtilities.GetProperty(project, "MyProperty");
Assert.NotNull(property);
Assert.Equal("1|3", property!.Value);
}
[Fact]
public void RemovePropertyValue_EmptyAfterRemove()
{
string projectXml =
@"<Project>
<PropertyGroup>
<MyProperty>1</MyProperty>
</PropertyGroup>
</Project>";
var project = ProjectRootElementFactory.Create(projectXml);
BuildUtilities.RemovePropertyValue(project, "1", "MyProperty", "1");
var property = BuildUtilities.GetProperty(project, "MyProperty");
Assert.NotNull(property);
Assert.Equal(string.Empty, property!.Value);
}
[Fact]
public void RemovePropertyValue_InheritedValue()
{
var project = ProjectRootElementFactory.Create();
BuildUtilities.RemovePropertyValue(project, "1;2", "MyProperty", "1");
var property = BuildUtilities.GetProperty(project, "MyProperty");
Assert.NotNull(property);
Assert.Equal("2", property!.Value);
}
[Fact]
public void RemovePropertyValue_MissingProperty()
{
var project = ProjectRootElementFactory.Create();
Assert.Throws<ArgumentException>("valueToRemove", () => BuildUtilities.RemovePropertyValue(project, "", "MyProperty", "1"));
var property = BuildUtilities.GetProperty(project, "MyProperty");
Assert.NotNull(property);
Assert.Equal(string.Empty, property!.Value);
}
[Fact]
public void RenamePropertyValue_DefaultDelimiter()
{
string projectXml =
@"<Project>
<PropertyGroup>
<MyProperty>1;2</MyProperty>
</PropertyGroup>
</Project>";
var project = ProjectRootElementFactory.Create(projectXml);
BuildUtilities.RenamePropertyValue(project, "1;2", "MyProperty", "2", "5");
var property = BuildUtilities.GetProperty(project, "MyProperty");
Assert.NotNull(property);
Assert.Equal("1;5", property!.Value);
}
[Fact]
public void RenamePropertyValue_NonDefaultDelimiter()
{
string projectXml =
@"<Project>
<PropertyGroup>
<MyProperty>1|2|3</MyProperty>
</PropertyGroup>
</Project>";
var project = ProjectRootElementFactory.Create(projectXml);
BuildUtilities.RenamePropertyValue(project, "1|2|3", "MyProperty", "2", "5", '|');
var property = BuildUtilities.GetProperty(project, "MyProperty");
Assert.NotNull(property);
Assert.Equal("1|5|3", property!.Value);
}
[Fact]
public void RenamePropertyValue_InheritedValue()
{
var project = ProjectRootElementFactory.Create();
BuildUtilities.RenamePropertyValue(project, "1;2", "MyProperty", "1", "3");
var property = BuildUtilities.GetProperty(project, "MyProperty");
Assert.NotNull(property);
Assert.Equal("3;2", property!.Value);
}
[Fact]
public void RenamePropertyValue_MissingProperty()
{
var project = ProjectRootElementFactory.Create();
Assert.Throws<ArgumentException>("oldValue", () => BuildUtilities.RenamePropertyValue(project, "", "MyProperty", "1", "2"));
var property = BuildUtilities.GetProperty(project, "MyProperty");
Assert.NotNull(property);
Assert.Equal(string.Empty, property!.Value);
}
}
}
| 35.217391 | 201 | 0.587901 | [
"MIT"
] | 77-A/.Net-Project | tests/Microsoft.VisualStudio.ProjectSystem.Managed.UnitTests/Build/BuildUtilitiesTests.cs | 11,808 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
namespace Xb
{
/// <summary>
/// String functions
/// 文字列関連関数群
/// </summary>
/// <remarks></remarks>
public class Str
{
/// <summary>
/// Double-Quote
/// </summary>
private const string Dq = "\"";
/// <summary>
/// Line-Feed charactor type
/// 改行コード指定種
/// </summary>
public enum LinefeedType
{
/// <summary>
/// LF - Unix
/// </summary>
/// <remarks></remarks>
Lf,
/// <summary>
/// CR + LF - Windows
/// </summary>
/// <remarks></remarks>
CrLf,
/// <summary>
/// CR - Mac
/// </summary>
/// <remarks></remarks>
Cr
}
/// <summary>
/// Get substring left side
/// 左から指定位置までの文字列を切り出す、もしくは指定位置までを削除する。
/// </summary>
/// <param name="target"></param>
/// <param name="length">
/// plus: slice left char
/// 値が正のとき 左 から切り出した文字列
///
/// minus: cut left char
/// 値が負のとき 左 から切り取った結果残った文字列
/// </param>
/// <returns></returns>
/// <remarks>
/// target = "ABCDEFG", position = 1 -> "A"
/// target = "ABCDEFG", position = 3 -> "ABC"
/// target = "ABCDEFG", position = -2 -> "CDEFG"
/// </remarks>
public static string Left(string target, int length)
{
if (string.IsNullOrEmpty(target))
return target;
if (length == 0)
return "";
if (target.Length <= System.Math.Abs(length))
{
return (length > 0)
? target
: "";
}
return (length > 0)
? target.Substring(0, length)
: target.Substring(System.Math.Abs(length));
}
/// <summary>
/// Get substring right side
/// 右から指定位置までの文字列を切り出す、もしくは指定位置までを削除する。
/// </summary>
/// <param name="target"></param>
/// <param name="length">
/// plus: slice right char
/// 値が正のとき 右 から切り出した文字列
///
/// minus: cut right char
/// 値が負のときは 右 から切り取った結果残った文字列
/// </param>
/// <returns></returns>
/// <remarks>
/// target = "ABCDEFG", position = 1 -> "G"
/// target = "ABCDEFG", position = 3 -> "EFG"
/// target = "ABCDEFG", position = -2 -> "ABCDE"
/// </remarks>
public static string Right(string target, int length)
{
if (string.IsNullOrEmpty(target))
return target;
if (length == 0)
return "";
if (target.Length <= System.Math.Abs(length))
{
return (length > 0)
? target
: "";
}
return (length > 0)
? target.Substring(target.Length - length)
: target.Substring(0, target.Length - System.Math.Abs(length));
}
/// <summary>
/// Get sliced substring
/// 文字列を、先頭/末尾から指定文字数数分切り出す。
/// </summary>
/// <param name="target"></param>
/// <param name="length">
/// plus: slice left char
/// 値が正のとき 左 から切り出した文字列
///
/// minus: slice right char
/// 値が正のとき 右 から切り出した文字列
/// </param>
/// <returns></returns>
/// <remarks>
/// target = "ABCDEFG", position = 1 -> "A"
/// target = "ABCDEFG", position = 3 -> "ABC"
/// target = "ABCDEFG", position = -2 -> "FG"
/// </remarks>
public static string Slice(string target, int length)
{
if (string.IsNullOrEmpty(target))
return target;
if (length == 0)
return "";
if (target.Length <= System.Math.Abs(length))
return target;
return (length > 0)
? target.Substring(0, length)
: target.Substring(target.Length - System.Math.Abs(length));
}
/// <summary>
/// Get cutted substring
/// 文字列を先頭/末尾から文字数単位で取り除き、余った文字列を返す。
/// </summary>
/// <param name="target"></param>
/// <param name="length">
/// plus: cut left char
/// 値が正のとき 左 から切り出した結果残った文字列
///
/// minus: cut right char
/// 値が負のとき 右 から切り出した結果残った文字列
/// </param>
/// <returns></returns>
/// <remarks>
/// target = "ABCDEFG", position = 1 -> "BCDEFG"
/// target = "ABCDEFG", position = 3 -> "DEFG"
/// target = "ABCDEFG", position = -2 -> "ABCDE"
/// </remarks>
public static string SliceReverse(string target, int length)
{
if (string.IsNullOrEmpty(target))
return target;
if (length == 0)
return target;
if (target.Length <= System.Math.Abs(length))
return "";
return (length > 0)
? target.Substring(length)
: target.Substring(0, target.Length - System.Math.Abs(length));
}
/// <summary>
/// Get sliced string block left side
/// 左から指定要素までの文字列を切り出す、もしくは指定位置までを削除する。
/// </summary>
/// <param name="target"></param>
/// <param name="length">
/// plus: slice left block
/// 値が正のとき 左 から切り出した要素文字列
///
/// minus: cut left block
/// 値が負のときは 左 から切り出した結果残った要素文字列
/// </param>
/// <param name="delimiter"></param>
/// <returns></returns>
/// <remarks>
/// target = "1/2/3/4", index = 2 -> "1/2"
/// target = "1/2/3/4/5", index = 3 -> "1/2/3"
/// target = "AAaa/bb Bb/cCcCcCc/DdDDdDd", index = -1 -> "bb Bb/cCcCcCc/DdDDdDd"
/// target = "AAaa/bb Bb/cCcCcCc/DdDDdDd", index = -3 -> "DdDDdDd"
/// </remarks>
public static string LeftSentence(string target, int length, string delimiter = "/")
{
if (string.IsNullOrEmpty(target))
return target;
if (length == 0)
return "";
if (delimiter == null)
return target;
var texts = new List<string>();
texts.AddRange(target.Split(new string[] {delimiter}, StringSplitOptions.None));
//分割した用素数より位置指定数値が大きいとき
if (texts.Count <= System.Math.Abs(length))
{
return (length > 0)
? target
: "";
}
return (length > 0)
? string.Join(delimiter, texts.GetRange(0, length).ToArray())
: string.Join(delimiter, texts.GetRange(System.Math.Abs(length),
texts.Count - System.Math.Abs(length)).ToArray());
}
/// <summary>
/// Get sliced string block right side
/// 右から指定要素までの文字列を切り出す、もしくは指定要素までを削除する。
/// </summary>
/// <param name="target"></param>
/// <param name="length">
/// plus: slice right block
/// 値が正のときは 右 から切り出した要素文字列
///
/// minus: cut right block
/// 値が負のときは 右 から切り出した結果残った要素文字列
/// </param>
/// <param name="delimiter"></param>
/// <returns></returns>
/// <remarks>
/// target = "1/2/3/4", index = 2 -> "3/4"
/// target = "1/2/3/4/5", index = 3 -> "3/4/5"
/// target = "AAaa/bb Bb/cCcCcCc/DdDDdDd", index = -1 -> "AAaa/bb Bb/cCcCcCc"
/// target = "AAaa/bb Bb/cCcCcCc/DdDDdDd", index = -3 -> "AAaa"
/// </remarks>
public static string RightSentence(string target, int length, string delimiter = "/")
{
if (string.IsNullOrEmpty(target))
return target;
if (length == 0)
return "";
if (delimiter == null)
return target;
var texts = new List<string>();
texts.AddRange(target.Split(new string[] {delimiter}, StringSplitOptions.None));
//分割した用素数より位置指定数値が大きいとき
if (texts.Count <= System.Math.Abs(length))
{
return (length > 0)
? target
: "";
}
return (length > 0)
? string.Join(delimiter, texts.GetRange(texts.Count - length, length).ToArray())
: string.Join(delimiter, texts.GetRange(0, texts.Count - System.Math.Abs(length)).ToArray());
}
/// <summary>
/// Get sliced string block
/// デリミタで区切られた要素文字列を、先頭/末尾から要素数単位で切り出す。
/// </summary>
/// <param name="target"></param>
/// <param name="length">
/// plus: slice left block
/// 値が正のとき 左 から切り出した要素文字列
///
/// plus: slice right block
/// 値が負のとき 右 から切り出した要素文字列
/// </param>
/// <param name="delimiter"></param>
/// <returns></returns>
/// <remarks>
/// target = "1/2/3/4", index = 2 -> "1/2"
/// target = "1/2/3/4/5", index = 3 -> "1/2/3"
/// target = "AAaa/bb Bb/cCcCcCc/DdDDdDd", index = -1 -> "DdDDdDd"
/// target = "AAaa/bb Bb/cCcCcCc/DdDDdDd", index = -3 -> "bb Bb/cCcCcCc/DdDDdDd"
/// </remarks>
public static string SliceSentence(string target, int length, string delimiter = "/")
{
if (string.IsNullOrEmpty(target))
return target;
if (length == 0)
return "";
if (delimiter == null)
return target;
var texts = new List<string>();
texts.AddRange(target.Split(new string[] {delimiter}, StringSplitOptions.None));
//分割した用素数より位置指定数値が大きいとき、全ての文字列を返す。
if (texts.Count <= System.Math.Abs(length))
return target;
return (length > 0)
? string.Join(delimiter, texts.GetRange(0, length).ToArray())
: string.Join(delimiter, texts.GetRange(texts.Count - System.Math.Abs(length), System.Math.Abs(length)).ToArray());
}
/// <summary>
/// Get cutted string block
/// 文字列を先頭/末尾から要素数単位で取り除き、余った要素の文字列を返す。
/// </summary>
/// <param name="target"></param>
/// <param name="length">
/// plus: cut left block
/// 値が正のときは 左 から切り出した結果残った要素文字列
///
/// minus: cut right block
/// 値が負のとき 右 から切り出した結果残った要素文字列
/// </param>
/// <param name="delimiter"></param>
/// <returns></returns>
/// <remarks>
/// target = "1/2/3/4", index = 2 -> "3/4"
/// target = "1/2/3/4/5", index = 3 -> "4/5"
/// target = "AAaa/bb Bb/cCcCcCc/DdDDdDd", index = -1 -> "AAaa/bb Bb/cCcCcCc"
/// target = "AAaa/bb Bb/cCcCcCc/DdDDdDd", index = -3 -> "AAaa"
/// </remarks>
public static string SliceReverseSentence(string target, int length, string delimiter = "/")
{
if (string.IsNullOrEmpty(target))
return target;
if (length == 0)
return target;
if (delimiter == null)
return "";
var texts = new List<string>();
texts.AddRange(target.Split(new string[] {delimiter}, StringSplitOptions.None));
//分割した用素数より位置指定数値が大きいとき、全ての文字列を返す。
if (texts.Count <= System.Math.Abs(length))
return "";
return (length > 0)
? string.Join(delimiter, texts.GetRange(length, texts.Count - length).ToArray())
: string.Join(delimiter, texts.GetRange(0, texts.Count + length).ToArray());
}
/// <summary>
/// Get Splitted String
/// 文字列を分割する。
/// </summary>
/// <param name="delimiter"></param>
/// <param name="target"></param>
/// <returns></returns>
/// <remarks></remarks>
public static string[] Split(string target, string delimiter = " ")
{
if (string.IsNullOrEmpty(target))
return new string[] {};
if (string.IsNullOrEmpty(delimiter))
return new string[] { target };
return target.Split(new string[] { delimiter }, StringSplitOptions.None);
}
/// <summary>
/// Validate string has only Single-Byte charactors
/// 文字列が全てASCIIコードか否か
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <remarks></remarks>
public static bool IsAscii(string value)
{
if (string.IsNullOrEmpty(value))
return true;
return (System.Text.Encoding.UTF8.GetByteCount(value) == value.Length);
}
/// <summary>
/// Validate string only Multi-Byte charactors
/// 文字列が全てマルチバイトか否か
/// </summary>
/// <param name="value"></param>
/// <param name="encode">null -> utf-8</param>
/// <returns>
/// 半角カナを1バイトにするときは、ShiftJISで判定すること
/// </returns>
public static bool IsMultiByte(string value, System.Text.Encoding encode = null)
{
if (string.IsNullOrEmpty(value))
return false;
if (encode == null)
encode = System.Text.Encoding.UTF8;
foreach (char c in value)
{
if (encode.GetByteCount(c.ToString()) <= 1)
return false;
}
return true;
}
/// <summary>
/// Get Linefeed charactor
/// 改行文字を取得する。
/// </summary>
/// <param name="linefeed"></param>
/// <returns></returns>
/// <remarks></remarks>
public static string GetLinefeed(Xb.Str.LinefeedType linefeed = Xb.Str.LinefeedType.CrLf)
{
switch (linefeed)
{
case Xb.Str.LinefeedType.Lf:
return "\n";
case Xb.Str.LinefeedType.CrLf:
return "\r\n";
case Xb.Str.LinefeedType.Cr:
return "\r";
default:
return "\r\n";
}
}
/// <summary>
/// Get Linefeed-Splitted multiline strings
/// 改行文字を判定して改行処理を通した文字列配列を取得する。
/// </summary>
/// <param name="multiLineText"></param>
/// <returns></returns>
/// <remarks></remarks>
public static string[] GetMultiLine(string multiLineText)
{
if (string.IsNullOrEmpty(multiLineText))
return new string[] {};
string[] result;
if (multiLineText.IndexOf("\r\n", StringComparison.Ordinal) != -1)
{
result = multiLineText.Split(new string[] {"\r\n"}, StringSplitOptions.None);
}
else if (multiLineText.IndexOf('\n') != -1)
{
result = multiLineText.Split(new string[] { "\n" }, StringSplitOptions.None);
}
else if (multiLineText.IndexOf('\r') != -1)
{
result = multiLineText.Split(new string[] { "\r" }, StringSplitOptions.None);
}
else
{
return new string[] { multiLineText };
}
if (result.Length > 1
&& string.IsNullOrEmpty(result[result.Length - 1]))
{
Array.Resize(ref result, result.Length - 1);
}
return result;
}
/// <summary>
/// Get Byte-Array from string
/// 文字列からバイト配列を取得する。
/// </summary>
/// <param name="target"></param>
/// <param name="encode">null to utf-8</param>
/// <returns></returns>
/// <remarks></remarks>
public static System.Byte[] GetBytes(string target, System.Text.Encoding encode = null)
{
if (target == null)
return new System.Byte[] {};
if (encode == null)
encode = System.Text.Encoding.UTF8;
return encode.GetBytes(target);
}
/// <summary>
/// Get Byte-Length from string
/// 文字列のバイト長を取得する。
/// </summary>
/// <param name="target"></param>
/// <param name="encode">ull to utf-8</param>
/// <returns></returns>
/// <remarks></remarks>
public static int GetByteLength(string target, System.Text.Encoding encode = null)
{
return GetBytes(target, encode).Length;
}
/// <summary>
/// Escape Html-Special-Charactors
/// HTML用特殊文字をエスケープする。
/// </summary>
/// <param name="html"></param>
/// <returns></returns>
/// <remarks>
/// Like: PHP - htmlspecialchars(html, ENT_COMPAT)
/// </remarks>
public static string EscapeHtml(string html)
{
if (html == null)
html = "";
return html.Replace("&", "&")
.Replace(Xb.Str.Dq, """)
.Replace("<", "<")
.Replace(">", ">");
}
/// <summary>
/// Unescape Html-Special-Charactors
/// エスケープされたHTML特殊文字を戻す。
/// </summary>
/// <param name="html"></param>
/// <returns></returns>
/// <remarks></remarks>
public static string UnescapeHtml(string html)
{
if (html == null)
html = "";
return html.Replace("&", "&")
.Replace(""", Xb.Str.Dq)
.Replace("<", "<")
.Replace(">", ">");
}
/// <summary>
/// Quote string value, and Escape for MySql
/// 文字列をシングルクォートで囲む。文字列中にシングルクォートがある場合、MySQL式のエスケープを行う。
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
/// <remarks></remarks>
public static string MySqlQuote(string text)
{
if (text == null)
text = "";
return "'" + text.Replace("\\", "\\\\").Replace("'", "\\'") + "'";
}
/// <summary>
/// Quote string value, and Escape for Microsoft Sql Server
/// 文字列をシングルクォートで囲む。文字列中にシングルクォートがある場合、SQL-Server/SQLite式のエスケープを行う。
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
/// <remarks></remarks>
public static string SqlQuote(string text)
{
if (text == null)
text = "";
return "'" + text.Replace("'", "''") + "'";
}
/// <summary>
/// Double-Quote string value, and Escape for JSON
/// 文字列をダブルクォートで囲む。文字列中にダブルクォートがある場合、JSON式エスケープを行う。
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
/// <remarks></remarks>
public static string Dquote(string text)
{
if (text == null)
text = "";
return Xb.Str.Dq + text.Replace(Xb.Str.Dq, "\\" + Xb.Str.Dq) + Xb.Str.Dq;
}
/// <summary>
/// Double-Quote string value, and Escape for CSV
/// 文字列をダブルクォートで囲む。文字列中にダブルクォートがある場合、CSV式エスケープを行う。
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
/// <remarks></remarks>
public static string CsvDquote(string text)
{
if (text == null)
text = "";
return Xb.Str.Dq
+ text.Replace(Xb.Str.Dq, Xb.Str.Dq + Xb.Str.Dq).Replace(",", "\\,")
+ Xb.Str.Dq;
}
/// <summary>
/// Get string from Byte-Array, auto detect Japanese-Encode
/// バイト配列を文字列に変換する。
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
/// <remarks>
/// エンコードが分かっているときは、Encoding.GetString()を使うこと。
/// </remarks>
public static string GetString(byte[] bytes)
{
if (bytes == null)
return "";
return Xb.Str.GetEncode(bytes).GetString(bytes, 0, bytes.Length);
}
/// <summary>
/// Get string from Stream, auto detect Japanese-Encode
/// バイト配列を文字列に変換する。
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
/// <remarks>
/// エンコードが分かっているときは、Encoding.GetString()を使うこと。
/// </remarks>
public static string GetString(System.IO.Stream stream)
{
if (stream == null)
return "";
var bytes = Xb.Byte.GetBytes(stream);
return Xb.Str.GetEncode(bytes).GetString(bytes, 0, bytes.Length);
}
/// <summary>
/// Detect Encode from Byte-Array(for Japanese)
/// 文字コードを判定する
/// </summary>
/// <param name="bytes"></param>
/// <param name="forceJapaneseDetection"></param>
/// <returns></returns>
/// <remarks>
/// not found, return ASCII.
///
/// thanks:
/// http://dobon.net/vb/dotnet/string/detectcode.html
///
/// Jcode.pmのgetcodeメソッドを移植したものです。
/// Jcode.pm(http://openlab.ring.gr.jp/Jcode/index-j.html)
/// Jcode.pmのCopyright: Copyright 1999-2005 Dan Kogai
/// </remarks>
public static System.Text.Encoding GetEncode(byte[] bytes, bool forceJapaneseDetection = false)
{
const byte bEscape = 0x1b;
const byte bAt = 0x40;
const byte bDollar = 0x24;
const byte bAnd = 0x26;
const byte bOpen = 0x28;
const byte bB = 0x42;
const byte bD = 0x44;
const byte bJ = 0x4a;
const byte bI = 0x49;
int len = bytes.Length;
byte b1 = 0;
byte b2 = 0;
byte b3 = 0;
byte b4 = 0;
//Encode::is_utf8 は無視
bool isBinary = false;
for (var i = 0; i <= len - 1; i++)
{
b1 = bytes[i];
if (b1 <= 0x6 || b1 == 0x7f || b1 == 0xff)
{
//'binary'
isBinary = true;
if (b1 == 0x0 && i < len - 1 && bytes[i + 1] <= 0x7f)
{
//smells like raw unicode
return System.Text.Encoding.Unicode;
}
}
}
if (isBinary && forceJapaneseDetection == false)
{
return System.Text.Encoding.GetEncoding("us-ascii");
}
//not Japanese
var notJapanese = true;
for (var i = 0; i <= len - 1; i++)
{
b1 = bytes[i];
if (b1 == bEscape || 0x80 <= b1)
{
notJapanese = false;
break;
}
}
if (notJapanese && forceJapaneseDetection == false)
{
return System.Text.Encoding.GetEncoding("us-ascii");
}
for (var i = 0; i <= len - 3; i++)
{
b1 = bytes[i];
b2 = bytes[i + 1];
b3 = bytes[i + 2];
if (b1 == bEscape)
{
if (b2 == bDollar
&& b3 == bAt)
{
//JIS_0208 1978
//JIS
return System.Text.Encoding.GetEncoding("iso-2022-jp");
}
else if (b2 == bDollar
&& b3 == bB)
{
//JIS_0208 1983
//JIS
return System.Text.Encoding.GetEncoding("iso-2022-jp");
}
else if (b2 == bOpen
&& (b3 == bB || b3 == bJ))
{
//JIS_ASC
//JIS
return System.Text.Encoding.GetEncoding("iso-2022-jp");
}
else if (b2 == bOpen
&& b3 == bI)
{
//JIS_KANA
//JIS
return System.Text.Encoding.GetEncoding("iso-2022-jp");
}
if (i < len - 3)
{
b4 = bytes[i + 3];
if (b2 == bDollar
&& b3 == bOpen
&& b4 == bD)
{
//JIS_0212
//JIS
return System.Text.Encoding.GetEncoding("iso-2022-jp");
}
if (i < len - 5
&& b2 == bAnd
&& b3 == bAt
&& b4 == bEscape
&& bytes[i + 4] == bDollar
&& bytes[i + 5] == bB)
{
//JIS_0208 1990
//JIS
return System.Text.Encoding.GetEncoding("iso-2022-jp");
}
}
}
}
//should be euc|sjis|utf8
//use of (?:) by Hiroki Ohzaki <ohzaki@iod.ricoh.co.jp>
int sjis = 0;
int euc = 0;
int utf8 = 0;
for (var i = 0; i <= len - 2; i++)
{
b1 = bytes[i];
b2 = bytes[i + 1];
if (
(
(0x81 <= b1 && b1 <= 0x9f)
|| (0xe0 <= b1 && b1 <= 0xfc)
)
&& ( (0x40 <= b2 && b2 <= 0x7e)
|| (0x80 <= b2 && b2 <= 0xfc))
)
{
//SJIS_C
sjis += 2;
i += 1;
}
}
for (var i = 0; i <= len - 2; i++)
{
b1 = bytes[i];
b2 = bytes[i + 1];
if (
(
(0xa1 <= b1 && b1 <= 0xfe)
&& (0xa1 <= b2 && b2 <= 0xfe)
)
|| (
b1 == 0x8e
&& (0xa1 <= b2 && b2 <= 0xdf)
)
)
{
//EUC_C
//EUC_KANA
euc += 2;
i += 1;
}
else if (i < len - 2)
{
b3 = bytes[i + 2];
if (b1 == 0x8f
&& (0xa1 <= b2 && b2 <= 0xfe)
&& (0xa1 <= b3 && b3 <= 0xfe))
{
//EUC_0212
euc += 3;
i += 2;
}
}
}
for (var i = 0; i <= len - 2; i++)
{
b1 = bytes[i];
b2 = bytes[i + 1];
if ((0xc0 <= b1 && b1 <= 0xdf)
&& (0x80 <= b2 && b2 <= 0xbf))
{
//UTF8
utf8 += 2;
i += 1;
}
else if (i < len - 2)
{
b3 = bytes[i + 2];
if ((0xe0 <= b1 && b1 <= 0xef)
&& (0x80 <= b2 && b2 <= 0xbf)
&& (0x80 <= b3 && b3 <= 0xbf))
{
//UTF8
utf8 += 3;
i += 2;
}
}
}
//M. Takahashi's suggestion
//utf8 += utf8 / 2;
if (euc > sjis && euc > utf8)
{
//EUC
return System.Text.Encoding.GetEncoding("euc-jp");
}
else if (sjis > euc && sjis > utf8)
{
//SJIS
return System.Text.Encoding.GetEncoding("shift_jis");
}
else if (utf8 > euc && utf8 > sjis)
{
//UTF8
return System.Text.Encoding.UTF8;
}
return System.Text.Encoding.GetEncoding("us-ascii");
}
/// <summary>
/// Detect Encode from Byte-Array(for Japanese)
/// 文字コードを判定する
/// </summary>
/// <param name="bytes"></param>
/// <param name="forceJapaneseDetection"></param>
/// <returns></returns>
/// <remarks>
/// not found, return ASCII.
///
/// thanks:
/// http://dobon.net/vb/dotnet/string/detectcode.html
///
/// Jcode.pmのgetcodeメソッドを移植したものです。
/// Jcode.pm(http://openlab.ring.gr.jp/Jcode/index-j.html)
/// Jcode.pmのCopyright: Copyright 1999-2005 Dan Kogai
/// </remarks>
public static System.Text.Encoding GetEncode(System.IO.Stream stream, bool forceJapaneseDetection = false)
{
return Xb.Str.GetEncode(Xb.Byte.GetBytes(stream), forceJapaneseDetection);
}
}
}
| 32.14164 | 139 | 0.422716 | [
"MIT"
] | ume05rw/Xb.Core | Xb.Core.PCL4.5/Xb/Str.cs | 32,543 | C# |
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.Configuration;
using PMCommonEntities.Models;
using PMUnifiedAPI.Models;
namespace PMFundManagerConsole
{
public class PseudoMarketsDbContext : DbContext
{
public DbSet<PseudoFunds> PseudoFunds { get; set; }
public DbSet<PseudoFundHistories> PseudoFundHistories { get; set; }
public DbSet<PseudoFundUnderlyingSecurities> PseudoFundUnderlyingSecurities { get; set; }
public DbSet<Orders> Orders { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// Grab the connection string from appsettings.json
var connectionString = Program.configuration.GetConnectionString("PMDB");
// Use the SQL Server Entity Framework Core connector
optionsBuilder.UseSqlServer(connectionString);
}
}
}
| 34.714286 | 97 | 0.726337 | [
"MIT"
] | pseudomarkets/PMFundManagerConsole | PMFundManagerConsole/PseudoMarketsDbContext.cs | 974 | C# |
using Expressive.Expressions;
using Expressive.Expressions.Binary.Logical;
namespace Expressive.Operators.Logical
{
internal class OrOperator : OperatorBase
{
#region OperatorBase Members
public override string[] Tags => new[] { "||", "or" };
public override IExpression BuildExpression(Token previousToken, IExpression[] expressions, ExpressiveOptions options)
{
return new OrExpression(expressions[0], expressions[1], options);
}
public override OperatorPrecedence GetPrecedence(Token previousToken)
{
return OperatorPrecedence.Or;
}
#endregion
}
}
| 26.6 | 126 | 0.666165 | [
"MIT"
] | denispakizh/expressive | Source/CSharp/Expressive/Expressive/Operators/Logical/OrOperator.cs | 667 | C# |
using OpenQA.Selenium;
using OpenQA.Selenium.Appium;
using System.Diagnostics;
using TestWare.Core.Libraries;
using TestWare.Engines.Appium.WinAppDriver.Configuration;
namespace TestWare.Engines.Appium.WinAppDriver.Factory
{
internal static class WindowsDriverFactory
{
private const int _waitForApplicationToOpen = 5;
private const int _retriesWaitForApplication = 16;
private static IWindowsDriver _rootDriver;
public static IWindowsDriver CreateRootWinAppDriverSession(Capabilities capabilities)
{
LaunchApplication(capabilities);
var appCapabilities = new AppiumOptions()
{
App = "Root",
DeviceName = "WindowsPC",
PlatformName = "Windows"
};
_rootDriver = new WindowsDriver(new Uri(capabilities.WinAppDriverUrl), appCapabilities, TimeSpan.FromSeconds(_waitForApplicationToOpen));
_rootDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(_waitForApplicationToOpen);
return AttachToApplication(capabilities);
}
private static void LaunchApplication(Capabilities capabilities)
{
/*
var allProcess = Process.GetProcesses();
//var a = allProcess.FirstOrDefault().Modules[0].FileName;
var processes3 = allProcess.Select(x => x.MainModule?.FileName == capabilities.ApplicationPath);
*/
Process[] processes = Process.GetProcessesByName(capabilities.ApplicationName);
foreach (Process process in processes)
{
process.Kill();
}
Process.Start(capabilities.ApplicationPath);
}
private static IWindowsDriver AttachToApplication(Capabilities capabilities)
{
WindowsDriver driver = null;
RetryPolicies.ExecuteActionWithRetries(
() =>
{
IWebElement window = null;
if (!string.IsNullOrEmpty(capabilities.ApplicationClassName))
{
window = _rootDriver.FindElement(MobileBy.ClassName(capabilities.ApplicationClassName));
}
else if (!string.IsNullOrEmpty(capabilities.ApplicationName))
{
window = _rootDriver.FindElement(MobileBy.Name(capabilities.ApplicationName));
}
var topLevelWindowHandle = window.GetAttribute("NativeWindowHandle");
topLevelWindowHandle = int.Parse(topLevelWindowHandle).ToString("x"); // Convert to Hex
var appCapabilities = new AppiumOptions();
appCapabilities.AddAdditionalAppiumOption("appTopLevelWindow", topLevelWindowHandle);
driver = new WindowsDriver(new Uri(capabilities.WinAppDriverUrl), appCapabilities, TimeSpan.FromMinutes(capabilities.CommandTimeOutInMinutes));
},
numberOfRetries: _retriesWaitForApplication);
if (driver == null)
{
throw new DriveNotFoundException();
}
return driver;
}
}
}
| 37.298851 | 160 | 0.614792 | [
"MIT"
] | ctrl-alt-d/net6-automation-testware | src/Engines/TestWare.Engines.WinAppDriver/Factory/WindowsDriverFactory.cs | 3,247 | C# |
using System;
using Microsoft.AspNetCore.Http;
namespace DatingApp.API.Dtos
{
public class PhotoForCreationDto
{
public string Url { get; set; }
public IFormFile File { get; set; }
public string Description { get; set; }
public DateTime DateAdded { get; set; }
public string PublicId { get; set; }
public PhotoForCreationDto()
{
DateAdded = DateTime.Now;
}
}
} | 23.736842 | 48 | 0.596452 | [
"MIT"
] | Fractal-Technology/dateNow | DateNow.API/DatingApp.API/Dtos/PhotoForCreationDto.cs | 451 | C# |
namespace Domains.Core.Subdomains.Battle.Code.Interfaces
{
public interface IChargingMeterView
{
float ChargeValue { get; set; }
}
} | 21.714286 | 56 | 0.690789 | [
"MIT"
] | migus88/Slapality | Assets/Domains/Core/Subdomains/Battle/Code/Interfaces/IChargingMeterView.cs | 152 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Linq.Expressions;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Core;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNetCore.Mvc
{
/// <summary>
/// A base class for an MVC controller without view support.
/// </summary>
[Controller]
public abstract class ControllerBase
{
private ControllerContext _controllerContext;
private IModelMetadataProvider _metadataProvider;
private IModelBinderFactory _modelBinderFactory;
private IObjectModelValidator _objectValidator;
private IUrlHelper _url;
private ProblemDetailsFactory _problemDetailsFactory;
/// <summary>
/// Gets the <see cref="Http.HttpContext"/> for the executing action.
/// </summary>
public HttpContext HttpContext => ControllerContext.HttpContext;
/// <summary>
/// Gets the <see cref="HttpRequest"/> for the executing action.
/// </summary>
public HttpRequest Request => HttpContext?.Request;
/// <summary>
/// Gets the <see cref="HttpResponse"/> for the executing action.
/// </summary>
public HttpResponse Response => HttpContext?.Response;
/// <summary>
/// Gets the <see cref="AspNetCore.Routing.RouteData"/> for the executing action.
/// </summary>
public RouteData RouteData => ControllerContext.RouteData;
/// <summary>
/// Gets the <see cref="ModelStateDictionary"/> that contains the state of the model and of model-binding validation.
/// </summary>
public ModelStateDictionary ModelState => ControllerContext.ModelState;
/// <summary>
/// Gets or sets the <see cref="Mvc.ControllerContext"/>.
/// </summary>
/// <remarks>
/// <see cref="Controllers.IControllerActivator"/> activates this property while activating controllers.
/// If user code directly instantiates a controller, the getter returns an empty
/// <see cref="Mvc.ControllerContext"/>.
/// </remarks>
[ControllerContext]
public ControllerContext ControllerContext
{
get
{
if (_controllerContext == null)
{
_controllerContext = new ControllerContext();
}
return _controllerContext;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_controllerContext = value;
}
}
/// <summary>
/// Gets or sets the <see cref="IModelMetadataProvider"/>.
/// </summary>
public IModelMetadataProvider MetadataProvider
{
get
{
if (_metadataProvider == null)
{
_metadataProvider = HttpContext?.RequestServices?.GetRequiredService<IModelMetadataProvider>();
}
return _metadataProvider;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_metadataProvider = value;
}
}
/// <summary>
/// Gets or sets the <see cref="IModelBinderFactory"/>.
/// </summary>
public IModelBinderFactory ModelBinderFactory
{
get
{
if (_modelBinderFactory == null)
{
_modelBinderFactory = HttpContext?.RequestServices?.GetRequiredService<IModelBinderFactory>();
}
return _modelBinderFactory;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_modelBinderFactory = value;
}
}
/// <summary>
/// Gets or sets the <see cref="IUrlHelper"/>.
/// </summary>
public IUrlHelper Url
{
get
{
if (_url == null)
{
var factory = HttpContext?.RequestServices?.GetRequiredService<IUrlHelperFactory>();
_url = factory?.GetUrlHelper(ControllerContext);
}
return _url;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_url = value;
}
}
/// <summary>
/// Gets or sets the <see cref="IObjectModelValidator"/>.
/// </summary>
public IObjectModelValidator ObjectValidator
{
get
{
if (_objectValidator == null)
{
_objectValidator = HttpContext?.RequestServices?.GetRequiredService<IObjectModelValidator>();
}
return _objectValidator;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_objectValidator = value;
}
}
/// <summary>
/// Gets or sets the <see cref="ProblemDetailsFactory"/>.
/// </summary>
public ProblemDetailsFactory ProblemDetailsFactory
{
get
{
if (_problemDetailsFactory == null)
{
_problemDetailsFactory = HttpContext?.RequestServices?.GetRequiredService<ProblemDetailsFactory>();
}
return _problemDetailsFactory;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_problemDetailsFactory = value;
}
}
/// <summary>
/// Gets the <see cref="ClaimsPrincipal"/> for user associated with the executing action.
/// </summary>
public ClaimsPrincipal User => HttpContext?.User;
/// <summary>
/// Creates a <see cref="StatusCodeResult"/> object by specifying a <paramref name="statusCode"/>.
/// </summary>
/// <param name="statusCode">The status code to set on the response.</param>
/// <returns>The created <see cref="StatusCodeResult"/> object for the response.</returns>
[NonAction]
public virtual StatusCodeResult StatusCode([ActionResultStatusCode] int statusCode)
=> new StatusCodeResult(statusCode);
/// <summary>
/// Creates a <see cref="ObjectResult"/> object by specifying a <paramref name="statusCode"/> and <paramref name="value"/>
/// </summary>
/// <param name="statusCode">The status code to set on the response.</param>
/// <param name="value">The value to set on the <see cref="ObjectResult"/>.</param>
/// <returns>The created <see cref="ObjectResult"/> object for the response.</returns>
[NonAction]
public virtual ObjectResult StatusCode([ActionResultStatusCode] int statusCode, [ActionResultObjectValue] object value)
{
return new ObjectResult(value)
{
StatusCode = statusCode
};
}
/// <summary>
/// Creates a <see cref="ContentResult"/> object by specifying a <paramref name="content"/> string.
/// </summary>
/// <param name="content">The content to write to the response.</param>
/// <returns>The created <see cref="ContentResult"/> object for the response.</returns>
[NonAction]
public virtual ContentResult Content(string content)
=> Content(content, (MediaTypeHeaderValue)null);
/// <summary>
/// Creates a <see cref="ContentResult"/> object by specifying a
/// <paramref name="content"/> string and a content type.
/// </summary>
/// <param name="content">The content to write to the response.</param>
/// <param name="contentType">The content type (MIME type).</param>
/// <returns>The created <see cref="ContentResult"/> object for the response.</returns>
[NonAction]
public virtual ContentResult Content(string content, string contentType)
=> Content(content, MediaTypeHeaderValue.Parse(contentType));
/// <summary>
/// Creates a <see cref="ContentResult"/> object by specifying a
/// <paramref name="content"/> string, a <paramref name="contentType"/>, and <paramref name="contentEncoding"/>.
/// </summary>
/// <param name="content">The content to write to the response.</param>
/// <param name="contentType">The content type (MIME type).</param>
/// <param name="contentEncoding">The content encoding.</param>
/// <returns>The created <see cref="ContentResult"/> object for the response.</returns>
/// <remarks>
/// If encoding is provided by both the 'charset' and the <paramref name="contentEncoding"/> parameters, then
/// the <paramref name="contentEncoding"/> parameter is chosen as the final encoding.
/// </remarks>
[NonAction]
public virtual ContentResult Content(string content, string contentType, Encoding contentEncoding)
{
var mediaTypeHeaderValue = MediaTypeHeaderValue.Parse(contentType);
mediaTypeHeaderValue.Encoding = contentEncoding ?? mediaTypeHeaderValue.Encoding;
return Content(content, mediaTypeHeaderValue);
}
/// <summary>
/// Creates a <see cref="ContentResult"/> object by specifying a
/// <paramref name="content"/> string and a <paramref name="contentType"/>.
/// </summary>
/// <param name="content">The content to write to the response.</param>
/// <param name="contentType">The content type (MIME type).</param>
/// <returns>The created <see cref="ContentResult"/> object for the response.</returns>
[NonAction]
public virtual ContentResult Content(string content, MediaTypeHeaderValue contentType)
{
return new ContentResult
{
Content = content,
ContentType = contentType?.ToString()
};
}
/// <summary>
/// Creates a <see cref="NoContentResult"/> object that produces an empty
/// <see cref="StatusCodes.Status204NoContent"/> response.
/// </summary>
/// <returns>The created <see cref="NoContentResult"/> object for the response.</returns>
[NonAction]
public virtual NoContentResult NoContent()
=> new NoContentResult();
/// <summary>
/// Creates a <see cref="OkResult"/> object that produces an empty <see cref="StatusCodes.Status200OK"/> response.
/// </summary>
/// <returns>The created <see cref="OkResult"/> for the response.</returns>
[NonAction]
public virtual OkResult Ok()
=> new OkResult();
/// <summary>
/// Creates an <see cref="OkObjectResult"/> object that produces an <see cref="StatusCodes.Status200OK"/> response.
/// </summary>
/// <param name="value">The content value to format in the entity body.</param>
/// <returns>The created <see cref="OkObjectResult"/> for the response.</returns>
[NonAction]
public virtual OkObjectResult Ok([ActionResultObjectValue] object value)
=> new OkObjectResult(value);
#region RedirectResult variants
/// <summary>
/// Creates a <see cref="RedirectResult"/> object that redirects (<see cref="StatusCodes.Status302Found"/>)
/// to the specified <paramref name="url"/>.
/// </summary>
/// <param name="url">The URL to redirect to.</param>
/// <returns>The created <see cref="RedirectResult"/> for the response.</returns>
[NonAction]
public virtual RedirectResult Redirect(string url)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(url));
}
return new RedirectResult(url);
}
/// <summary>
/// Creates a <see cref="RedirectResult"/> object with <see cref="RedirectResult.Permanent"/> set to true
/// (<see cref="StatusCodes.Status301MovedPermanently"/>) using the specified <paramref name="url"/>.
/// </summary>
/// <param name="url">The URL to redirect to.</param>
/// <returns>The created <see cref="RedirectResult"/> for the response.</returns>
[NonAction]
public virtual RedirectResult RedirectPermanent(string url)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(url));
}
return new RedirectResult(url, permanent: true);
}
/// <summary>
/// Creates a <see cref="RedirectResult"/> object with <see cref="RedirectResult.Permanent"/> set to false
/// and <see cref="RedirectResult.PreserveMethod"/> set to true (<see cref="StatusCodes.Status307TemporaryRedirect"/>)
/// using the specified <paramref name="url"/>.
/// </summary>
/// <param name="url">The URL to redirect to.</param>
/// <returns>The created <see cref="RedirectResult"/> for the response.</returns>
[NonAction]
public virtual RedirectResult RedirectPreserveMethod(string url)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(url));
}
return new RedirectResult(url: url, permanent: false, preserveMethod: true);
}
/// <summary>
/// Creates a <see cref="RedirectResult"/> object with <see cref="RedirectResult.Permanent"/> set to true
/// and <see cref="RedirectResult.PreserveMethod"/> set to true (<see cref="StatusCodes.Status308PermanentRedirect"/>)
/// using the specified <paramref name="url"/>.
/// </summary>
/// <param name="url">The URL to redirect to.</param>
/// <returns>The created <see cref="RedirectResult"/> for the response.</returns>
[NonAction]
public virtual RedirectResult RedirectPermanentPreserveMethod(string url)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(url));
}
return new RedirectResult(url: url, permanent: true, preserveMethod: true);
}
/// <summary>
/// Creates a <see cref="LocalRedirectResult"/> object that redirects
/// (<see cref="StatusCodes.Status302Found"/>) to the specified local <paramref name="localUrl"/>.
/// </summary>
/// <param name="localUrl">The local URL to redirect to.</param>
/// <returns>The created <see cref="LocalRedirectResult"/> for the response.</returns>
[NonAction]
public virtual LocalRedirectResult LocalRedirect(string localUrl)
{
if (string.IsNullOrEmpty(localUrl))
{
throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(localUrl));
}
return new LocalRedirectResult(localUrl);
}
/// <summary>
/// Creates a <see cref="LocalRedirectResult"/> object with <see cref="LocalRedirectResult.Permanent"/> set to
/// true (<see cref="StatusCodes.Status301MovedPermanently"/>) using the specified <paramref name="localUrl"/>.
/// </summary>
/// <param name="localUrl">The local URL to redirect to.</param>
/// <returns>The created <see cref="LocalRedirectResult"/> for the response.</returns>
[NonAction]
public virtual LocalRedirectResult LocalRedirectPermanent(string localUrl)
{
if (string.IsNullOrEmpty(localUrl))
{
throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(localUrl));
}
return new LocalRedirectResult(localUrl, permanent: true);
}
/// <summary>
/// Creates a <see cref="LocalRedirectResult"/> object with <see cref="LocalRedirectResult.Permanent"/> set to
/// false and <see cref="LocalRedirectResult.PreserveMethod"/> set to true
/// (<see cref="StatusCodes.Status307TemporaryRedirect"/>) using the specified <paramref name="localUrl"/>.
/// </summary>
/// <param name="localUrl">The local URL to redirect to.</param>
/// <returns>The created <see cref="LocalRedirectResult"/> for the response.</returns>
[NonAction]
public virtual LocalRedirectResult LocalRedirectPreserveMethod(string localUrl)
{
if (string.IsNullOrEmpty(localUrl))
{
throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(localUrl));
}
return new LocalRedirectResult(localUrl: localUrl, permanent: false, preserveMethod: true);
}
/// <summary>
/// Creates a <see cref="LocalRedirectResult"/> object with <see cref="LocalRedirectResult.Permanent"/> set to
/// true and <see cref="LocalRedirectResult.PreserveMethod"/> set to true
/// (<see cref="StatusCodes.Status308PermanentRedirect"/>) using the specified <paramref name="localUrl"/>.
/// </summary>
/// <param name="localUrl">The local URL to redirect to.</param>
/// <returns>The created <see cref="LocalRedirectResult"/> for the response.</returns>
[NonAction]
public virtual LocalRedirectResult LocalRedirectPermanentPreserveMethod(string localUrl)
{
if (string.IsNullOrEmpty(localUrl))
{
throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(localUrl));
}
return new LocalRedirectResult(localUrl: localUrl, permanent: true, preserveMethod: true);
}
/// <summary>
/// Redirects (<see cref="StatusCodes.Status302Found"/>) to an action with the same name as current one.
/// The 'controller' and 'action' names are retrieved from the ambient values of the current request.
/// </summary>
/// <returns>The created <see cref="RedirectToActionResult"/> for the response.</returns>
/// <example>
/// A POST request to an action named "Product" updates a product and redirects to an action, also named
/// "Product", showing details of the updated product.
/// <code>
/// [HttpGet]
/// public IActionResult Product(int id)
/// {
/// var product = RetrieveProduct(id);
/// return View(product);
/// }
///
/// [HttpPost]
/// public IActionResult Product(int id, Product product)
/// {
/// UpdateProduct(product);
/// return RedirectToAction();
/// }
/// </code>
/// </example>
[NonAction]
public virtual RedirectToActionResult RedirectToAction()
=> RedirectToAction(actionName: null);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status302Found"/>) to the specified action using the <paramref name="actionName"/>.
/// </summary>
/// <param name="actionName">The name of the action.</param>
/// <returns>The created <see cref="RedirectToActionResult"/> for the response.</returns>
[NonAction]
public virtual RedirectToActionResult RedirectToAction(string actionName)
=> RedirectToAction(actionName, routeValues: null);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status302Found"/>) to the specified action using the
/// <paramref name="actionName"/> and <paramref name="routeValues"/>.
/// </summary>
/// <param name="actionName">The name of the action.</param>
/// <param name="routeValues">The parameters for a route.</param>
/// <returns>The created <see cref="RedirectToActionResult"/> for the response.</returns>
[NonAction]
public virtual RedirectToActionResult RedirectToAction(string actionName, object routeValues)
=> RedirectToAction(actionName, controllerName: null, routeValues: routeValues);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status302Found"/>) to the specified action using the
/// <paramref name="actionName"/> and the <paramref name="controllerName"/>.
/// </summary>
/// <param name="actionName">The name of the action.</param>
/// <param name="controllerName">The name of the controller.</param>
/// <returns>The created <see cref="RedirectToActionResult"/> for the response.</returns>
[NonAction]
public virtual RedirectToActionResult RedirectToAction(string actionName, string controllerName)
=> RedirectToAction(actionName, controllerName, routeValues: null);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status302Found"/>) to the specified action using the specified
/// <paramref name="actionName"/>, <paramref name="controllerName"/>, and <paramref name="routeValues"/>.
/// </summary>
/// <param name="actionName">The name of the action.</param>
/// <param name="controllerName">The name of the controller.</param>
/// <param name="routeValues">The parameters for a route.</param>
/// <returns>The created <see cref="RedirectToActionResult"/> for the response.</returns>
[NonAction]
public virtual RedirectToActionResult RedirectToAction(
string actionName,
string controllerName,
object routeValues)
=> RedirectToAction(actionName, controllerName, routeValues, fragment: null);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status302Found"/>) to the specified action using the specified
/// <paramref name="actionName"/>, <paramref name="controllerName"/>, and <paramref name="fragment"/>.
/// </summary>
/// <param name="actionName">The name of the action.</param>
/// <param name="controllerName">The name of the controller.</param>
/// <param name="fragment">The fragment to add to the URL.</param>
/// <returns>The created <see cref="RedirectToActionResult"/> for the response.</returns>
[NonAction]
public virtual RedirectToActionResult RedirectToAction(
string actionName,
string controllerName,
string fragment)
=> RedirectToAction(actionName, controllerName, routeValues: null, fragment: fragment);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status302Found"/>) to the specified action using the specified <paramref name="actionName"/>,
/// <paramref name="controllerName"/>, <paramref name="routeValues"/>, and <paramref name="fragment"/>.
/// </summary>
/// <param name="actionName">The name of the action.</param>
/// <param name="controllerName">The name of the controller.</param>
/// <param name="routeValues">The parameters for a route.</param>
/// <param name="fragment">The fragment to add to the URL.</param>
/// <returns>The created <see cref="RedirectToActionResult"/> for the response.</returns>
[NonAction]
public virtual RedirectToActionResult RedirectToAction(
string actionName,
string controllerName,
object routeValues,
string fragment)
{
return new RedirectToActionResult(actionName, controllerName, routeValues, fragment)
{
UrlHelper = Url,
};
}
/// <summary>
/// Redirects (<see cref="StatusCodes.Status307TemporaryRedirect"/>) to the specified action with
/// <see cref="RedirectToActionResult.Permanent"/> set to false and <see cref="RedirectToActionResult.PreserveMethod"/>
/// set to true, using the specified <paramref name="actionName"/>, <paramref name="controllerName"/>,
/// <paramref name="routeValues"/>, and <paramref name="fragment"/>.
/// </summary>
/// <param name="actionName">The name of the action.</param>
/// <param name="controllerName">The name of the controller.</param>
/// <param name="routeValues">The route data to use for generating the URL.</param>
/// <param name="fragment">The fragment to add to the URL.</param>
/// <returns>The created <see cref="RedirectToActionResult"/> for the response.</returns>
[NonAction]
public virtual RedirectToActionResult RedirectToActionPreserveMethod(
string actionName = null,
string controllerName = null,
object routeValues = null,
string fragment = null)
{
return new RedirectToActionResult(
actionName: actionName,
controllerName: controllerName,
routeValues: routeValues,
permanent: false,
preserveMethod: true,
fragment: fragment)
{
UrlHelper = Url,
};
}
/// <summary>
/// Redirects (<see cref="StatusCodes.Status301MovedPermanently"/>) to the specified action with
/// <see cref="RedirectToActionResult.Permanent"/> set to true using the specified <paramref name="actionName"/>.
/// </summary>
/// <param name="actionName">The name of the action.</param>
/// <returns>The created <see cref="RedirectToActionResult"/> for the response.</returns>
[NonAction]
public virtual RedirectToActionResult RedirectToActionPermanent(string actionName)
=> RedirectToActionPermanent(actionName, routeValues: null);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status301MovedPermanently"/>) to the specified action with
/// <see cref="RedirectToActionResult.Permanent"/> set to true using the specified <paramref name="actionName"/>
/// and <paramref name="routeValues"/>.
/// </summary>
/// <param name="actionName">The name of the action.</param>
/// <param name="routeValues">The parameters for a route.</param>
/// <returns>The created <see cref="RedirectToActionResult"/> for the response.</returns>
[NonAction]
public virtual RedirectToActionResult RedirectToActionPermanent(string actionName, object routeValues)
=> RedirectToActionPermanent(actionName, controllerName: null, routeValues: routeValues);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status301MovedPermanently"/>) to the specified action with
/// <see cref="RedirectToActionResult.Permanent"/> set to true using the specified <paramref name="actionName"/>
/// and <paramref name="controllerName"/>.
/// </summary>
/// <param name="actionName">The name of the action.</param>
/// <param name="controllerName">The name of the controller.</param>
/// <returns>The created <see cref="RedirectToActionResult"/> for the response.</returns>
[NonAction]
public virtual RedirectToActionResult RedirectToActionPermanent(string actionName, string controllerName)
=> RedirectToActionPermanent(actionName, controllerName, routeValues: null);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status301MovedPermanently"/>) to the specified action with
/// <see cref="RedirectToActionResult.Permanent"/> set to true using the specified <paramref name="actionName"/>,
/// <paramref name="controllerName"/>, and <paramref name="fragment"/>.
/// </summary>
/// <param name="actionName">The name of the action.</param>
/// <param name="controllerName">The name of the controller.</param>
/// <param name="fragment">The fragment to add to the URL.</param>
/// <returns>The created <see cref="RedirectToActionResult"/> for the response.</returns>
[NonAction]
public virtual RedirectToActionResult RedirectToActionPermanent(
string actionName,
string controllerName,
string fragment)
=> RedirectToActionPermanent(actionName, controllerName, routeValues: null, fragment: fragment);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status301MovedPermanently"/>) to the specified action with
/// <see cref="RedirectToActionResult.Permanent"/> set to true using the specified <paramref name="actionName"/>,
/// <paramref name="controllerName"/>, and <paramref name="routeValues"/>.
/// </summary>
/// <param name="actionName">The name of the action.</param>
/// <param name="controllerName">The name of the controller.</param>
/// <param name="routeValues">The parameters for a route.</param>
/// <returns>The created <see cref="RedirectToActionResult"/> for the response.</returns>
[NonAction]
public virtual RedirectToActionResult RedirectToActionPermanent(
string actionName,
string controllerName,
object routeValues)
=> RedirectToActionPermanent(actionName, controllerName, routeValues, fragment: null);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status301MovedPermanently"/>) to the specified action with
/// <see cref="RedirectToActionResult.Permanent"/> set to true using the specified <paramref name="actionName"/>,
/// <paramref name="controllerName"/>, <paramref name="routeValues"/>, and <paramref name="fragment"/>.
/// </summary>
/// <param name="actionName">The name of the action.</param>
/// <param name="controllerName">The name of the controller.</param>
/// <param name="routeValues">The parameters for a route.</param>
/// <param name="fragment">The fragment to add to the URL.</param>
/// <returns>The created <see cref="RedirectToActionResult"/> for the response.</returns>
[NonAction]
public virtual RedirectToActionResult RedirectToActionPermanent(
string actionName,
string controllerName,
object routeValues,
string fragment)
{
return new RedirectToActionResult(
actionName,
controllerName,
routeValues,
permanent: true,
fragment: fragment)
{
UrlHelper = Url,
};
}
/// <summary>
/// Redirects (<see cref="StatusCodes.Status308PermanentRedirect"/>) to the specified action with
/// <see cref="RedirectToActionResult.Permanent"/> set to true and <see cref="RedirectToActionResult.PreserveMethod"/>
/// set to true, using the specified <paramref name="actionName"/>, <paramref name="controllerName"/>,
/// <paramref name="routeValues"/>, and <paramref name="fragment"/>.
/// </summary>
/// <param name="actionName">The name of the action.</param>
/// <param name="controllerName">The name of the controller.</param>
/// <param name="routeValues">The route data to use for generating the URL.</param>
/// <param name="fragment">The fragment to add to the URL.</param>
/// <returns>The created <see cref="RedirectToActionResult"/> for the response.</returns>
[NonAction]
public virtual RedirectToActionResult RedirectToActionPermanentPreserveMethod(
string actionName = null,
string controllerName = null,
object routeValues = null,
string fragment = null)
{
return new RedirectToActionResult(
actionName: actionName,
controllerName: controllerName,
routeValues: routeValues,
permanent: true,
preserveMethod: true,
fragment: fragment)
{
UrlHelper = Url,
};
}
/// <summary>
/// Redirects (<see cref="StatusCodes.Status302Found"/>) to the specified route using the specified <paramref name="routeName"/>.
/// </summary>
/// <param name="routeName">The name of the route.</param>
/// <returns>The created <see cref="RedirectToRouteResult"/> for the response.</returns>
[NonAction]
public virtual RedirectToRouteResult RedirectToRoute(string routeName)
=> RedirectToRoute(routeName, routeValues: null);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status302Found"/>) to the specified route using the specified <paramref name="routeValues"/>.
/// </summary>
/// <param name="routeValues">The parameters for a route.</param>
/// <returns>The created <see cref="RedirectToRouteResult"/> for the response.</returns>
[NonAction]
public virtual RedirectToRouteResult RedirectToRoute(object routeValues)
=> RedirectToRoute(routeName: null, routeValues: routeValues);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status302Found"/>) to the specified route using the specified
/// <paramref name="routeName"/> and <paramref name="routeValues"/>.
/// </summary>
/// <param name="routeName">The name of the route.</param>
/// <param name="routeValues">The parameters for a route.</param>
/// <returns>The created <see cref="RedirectToRouteResult"/> for the response.</returns>
[NonAction]
public virtual RedirectToRouteResult RedirectToRoute(string routeName, object routeValues)
=> RedirectToRoute(routeName, routeValues, fragment: null);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status302Found"/>) to the specified route using the specified
/// <paramref name="routeName"/> and <paramref name="fragment"/>.
/// </summary>
/// <param name="routeName">The name of the route.</param>
/// <param name="fragment">The fragment to add to the URL.</param>
/// <returns>The created <see cref="RedirectToRouteResult"/> for the response.</returns>
[NonAction]
public virtual RedirectToRouteResult RedirectToRoute(string routeName, string fragment)
=> RedirectToRoute(routeName, routeValues: null, fragment: fragment);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status302Found"/>) to the specified route using the specified
/// <paramref name="routeName"/>, <paramref name="routeValues"/>, and <paramref name="fragment"/>.
/// </summary>
/// <param name="routeName">The name of the route.</param>
/// <param name="routeValues">The parameters for a route.</param>
/// <param name="fragment">The fragment to add to the URL.</param>
/// <returns>The created <see cref="RedirectToRouteResult"/> for the response.</returns>
[NonAction]
public virtual RedirectToRouteResult RedirectToRoute(
string routeName,
object routeValues,
string fragment)
{
return new RedirectToRouteResult(routeName, routeValues, fragment)
{
UrlHelper = Url,
};
}
/// <summary>
/// Redirects (<see cref="StatusCodes.Status307TemporaryRedirect"/>) to the specified route with
/// <see cref="RedirectToRouteResult.Permanent"/> set to false and <see cref="RedirectToRouteResult.PreserveMethod"/>
/// set to true, using the specified <paramref name="routeName"/>, <paramref name="routeValues"/>, and <paramref name="fragment"/>.
/// </summary>
/// <param name="routeName">The name of the route.</param>
/// <param name="routeValues">The route data to use for generating the URL.</param>
/// <param name="fragment">The fragment to add to the URL.</param>
/// <returns>The created <see cref="RedirectToRouteResult"/> for the response.</returns>
[NonAction]
public virtual RedirectToRouteResult RedirectToRoutePreserveMethod(
string routeName = null,
object routeValues = null,
string fragment = null)
{
return new RedirectToRouteResult(
routeName: routeName,
routeValues: routeValues,
permanent: false,
preserveMethod: true,
fragment: fragment)
{
UrlHelper = Url,
};
}
/// <summary>
/// Redirects (<see cref="StatusCodes.Status301MovedPermanently"/>) to the specified route with
/// <see cref="RedirectToRouteResult.Permanent"/> set to true using the specified <paramref name="routeName"/>.
/// </summary>
/// <param name="routeName">The name of the route.</param>
/// <returns>The created <see cref="RedirectToRouteResult"/> for the response.</returns>
[NonAction]
public virtual RedirectToRouteResult RedirectToRoutePermanent(string routeName)
=> RedirectToRoutePermanent(routeName, routeValues: null);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status301MovedPermanently"/>) to the specified route with
/// <see cref="RedirectToRouteResult.Permanent"/> set to true using the specified <paramref name="routeValues"/>.
/// </summary>
/// <param name="routeValues">The parameters for a route.</param>
/// <returns>The created <see cref="RedirectToRouteResult"/> for the response.</returns>
[NonAction]
public virtual RedirectToRouteResult RedirectToRoutePermanent(object routeValues)
=> RedirectToRoutePermanent(routeName: null, routeValues: routeValues);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status301MovedPermanently"/>) to the specified route with
/// <see cref="RedirectToRouteResult.Permanent"/> set to true using the specified <paramref name="routeName"/>
/// and <paramref name="routeValues"/>.
/// </summary>
/// <param name="routeName">The name of the route.</param>
/// <param name="routeValues">The parameters for a route.</param>
/// <returns>The created <see cref="RedirectToRouteResult"/> for the response.</returns>
[NonAction]
public virtual RedirectToRouteResult RedirectToRoutePermanent(string routeName, object routeValues)
=> RedirectToRoutePermanent(routeName, routeValues, fragment: null);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status301MovedPermanently"/>) to the specified route with
/// <see cref="RedirectToRouteResult.Permanent"/> set to true using the specified <paramref name="routeName"/>
/// and <paramref name="fragment"/>.
/// </summary>
/// <param name="routeName">The name of the route.</param>
/// <param name="fragment">The fragment to add to the URL.</param>
/// <returns>The created <see cref="RedirectToRouteResult"/> for the response.</returns>
[NonAction]
public virtual RedirectToRouteResult RedirectToRoutePermanent(string routeName, string fragment)
=> RedirectToRoutePermanent(routeName, routeValues: null, fragment: fragment);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status301MovedPermanently"/>) to the specified route with
/// <see cref="RedirectToRouteResult.Permanent"/> set to true using the specified <paramref name="routeName"/>,
/// <paramref name="routeValues"/>, and <paramref name="fragment"/>.
/// </summary>
/// <param name="routeName">The name of the route.</param>
/// <param name="routeValues">The parameters for a route.</param>
/// <param name="fragment">The fragment to add to the URL.</param>
/// <returns>The created <see cref="RedirectToRouteResult"/> for the response.</returns>
[NonAction]
public virtual RedirectToRouteResult RedirectToRoutePermanent(
string routeName,
object routeValues,
string fragment)
{
return new RedirectToRouteResult(routeName, routeValues, permanent: true, fragment: fragment)
{
UrlHelper = Url,
};
}
/// <summary>
/// Redirects (<see cref="StatusCodes.Status308PermanentRedirect"/>) to the specified route with
/// <see cref="RedirectToRouteResult.Permanent"/> set to true and <see cref="RedirectToRouteResult.PreserveMethod"/>
/// set to true, using the specified <paramref name="routeName"/>, <paramref name="routeValues"/>, and <paramref name="fragment"/>.
/// </summary>
/// <param name="routeName">The name of the route.</param>
/// <param name="routeValues">The route data to use for generating the URL.</param>
/// <param name="fragment">The fragment to add to the URL.</param>
/// <returns>The created <see cref="RedirectToRouteResult"/> for the response.</returns>
[NonAction]
public virtual RedirectToRouteResult RedirectToRoutePermanentPreserveMethod(
string routeName = null,
object routeValues = null,
string fragment = null)
{
return new RedirectToRouteResult(
routeName: routeName,
routeValues: routeValues,
permanent: true,
preserveMethod: true,
fragment: fragment)
{
UrlHelper = Url,
};
}
/// <summary>
/// Redirects (<see cref="StatusCodes.Status302Found"/>) to the specified <paramref name="pageName"/>.
/// </summary>
/// <param name="pageName">The name of the page.</param>
/// <returns>The <see cref="RedirectToPageResult"/>.</returns>
[NonAction]
public virtual RedirectToPageResult RedirectToPage(string pageName)
=> RedirectToPage(pageName, routeValues: null);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status302Found"/>) to the specified <paramref name="pageName"/>
/// using the specified <paramref name="routeValues"/>.
/// </summary>
/// <param name="pageName">The name of the page.</param>
/// <param name="routeValues">The parameters for a route.</param>
/// <returns>The <see cref="RedirectToPageResult"/>.</returns>
[NonAction]
public virtual RedirectToPageResult RedirectToPage(string pageName, object routeValues)
=> RedirectToPage(pageName, pageHandler: null, routeValues: routeValues, fragment: null);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status302Found"/>) to the specified <paramref name="pageName"/>
/// using the specified <paramref name="pageHandler"/>.
/// </summary>
/// <param name="pageName">The name of the page.</param>
/// <param name="pageHandler">The page handler to redirect to.</param>
/// <returns>The <see cref="RedirectToPageResult"/>.</returns>
[NonAction]
public virtual RedirectToPageResult RedirectToPage(string pageName, string pageHandler)
=> RedirectToPage(pageName, pageHandler, routeValues: null);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status302Found"/>) to the specified <paramref name="pageName"/>.
/// </summary>
/// <param name="pageName">The name of the page.</param>
/// <param name="pageHandler">The page handler to redirect to.</param>
/// <param name="routeValues">The parameters for a route.</param>
/// <returns>The <see cref="RedirectToPageResult"/>.</returns>
[NonAction]
public virtual RedirectToPageResult RedirectToPage(string pageName, string pageHandler, object routeValues)
=> RedirectToPage(pageName, pageHandler, routeValues, fragment: null);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status302Found"/>) to the specified <paramref name="pageName"/>
/// using the specified <paramref name="fragment"/>.
/// </summary>
/// <param name="pageName">The name of the page.</param>
/// <param name="pageHandler">The page handler to redirect to.</param>
/// <param name="fragment">The fragment to add to the URL.</param>
/// <returns>The <see cref="RedirectToPageResult"/>.</returns>
[NonAction]
public virtual RedirectToPageResult RedirectToPage(string pageName, string pageHandler, string fragment)
=> RedirectToPage(pageName, pageHandler, routeValues: null, fragment: fragment);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status302Found"/>) to the specified <paramref name="pageName"/>
/// using the specified <paramref name="routeValues"/> and <paramref name="fragment"/>.
/// </summary>
/// <param name="pageName">The name of the page.</param>
/// <param name="pageHandler">The page handler to redirect to.</param>
/// <param name="routeValues">The parameters for a route.</param>
/// <param name="fragment">The fragment to add to the URL.</param>
/// <returns>The <see cref="RedirectToPageResult"/>.</returns>
[NonAction]
public virtual RedirectToPageResult RedirectToPage(string pageName, string pageHandler, object routeValues, string fragment)
=> new RedirectToPageResult(pageName, pageHandler, routeValues, fragment);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status301MovedPermanently"/>) to the specified <paramref name="pageName"/>.
/// </summary>
/// <param name="pageName">The name of the page.</param>
/// <returns>The <see cref="RedirectToPageResult"/> with <see cref="RedirectToPageResult.Permanent"/> set.</returns>
[NonAction]
public virtual RedirectToPageResult RedirectToPagePermanent(string pageName)
=> RedirectToPagePermanent(pageName, routeValues: null);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status301MovedPermanently"/>) to the specified <paramref name="pageName"/>
/// using the specified <paramref name="routeValues"/>.
/// </summary>
/// <param name="pageName">The name of the page.</param>
/// <param name="routeValues">The parameters for a route.</param>
/// <returns>The <see cref="RedirectToPageResult"/> with <see cref="RedirectToPageResult.Permanent"/> set.</returns>
[NonAction]
public virtual RedirectToPageResult RedirectToPagePermanent(string pageName, object routeValues)
=> RedirectToPagePermanent(pageName, pageHandler: null, routeValues: routeValues, fragment: null);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status301MovedPermanently"/>) to the specified <paramref name="pageName"/>
/// using the specified <paramref name="pageHandler"/>.
/// </summary>
/// <param name="pageName">The name of the page.</param>
/// <param name="pageHandler">The page handler to redirect to.</param>
/// <returns>The <see cref="RedirectToPageResult"/> with <see cref="RedirectToPageResult.Permanent"/> set.</returns>
[NonAction]
public virtual RedirectToPageResult RedirectToPagePermanent(string pageName, string pageHandler)
=> RedirectToPagePermanent(pageName, pageHandler, routeValues: null, fragment: null);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status301MovedPermanently"/>) to the specified <paramref name="pageName"/>
/// using the specified <paramref name="fragment"/>.
/// </summary>
/// <param name="pageName">The name of the page.</param>
/// <param name="pageHandler">The page handler to redirect to.</param>
/// <param name="fragment">The fragment to add to the URL.</param>
/// <returns>The <see cref="RedirectToPageResult"/> with <see cref="RedirectToPageResult.Permanent"/> set.</returns>
[NonAction]
public virtual RedirectToPageResult RedirectToPagePermanent(string pageName, string pageHandler, string fragment)
=> RedirectToPagePermanent(pageName, pageHandler, routeValues: null, fragment: fragment);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status301MovedPermanently"/>) to the specified <paramref name="pageName"/>
/// using the specified <paramref name="routeValues"/> and <paramref name="fragment"/>.
/// </summary>
/// <param name="pageName">The name of the page.</param>
/// <param name="pageHandler">The page handler to redirect to.</param>
/// <param name="routeValues">The parameters for a route.</param>
/// <param name="fragment">The fragment to add to the URL.</param>
/// <returns>The <see cref="RedirectToPageResult"/> with <see cref="RedirectToPageResult.Permanent"/> set.</returns>
[NonAction]
public virtual RedirectToPageResult RedirectToPagePermanent(
string pageName,
string pageHandler,
object routeValues,
string fragment)
=> new RedirectToPageResult(pageName, pageHandler, routeValues, permanent: true, fragment: fragment);
/// <summary>
/// Redirects (<see cref="StatusCodes.Status307TemporaryRedirect"/>) to the specified page with
/// <see cref="RedirectToRouteResult.Permanent"/> set to false and <see cref="RedirectToRouteResult.PreserveMethod"/>
/// set to true, using the specified <paramref name="pageName"/>, <paramref name="routeValues"/>, and <paramref name="fragment"/>.
/// </summary>
/// <param name="pageName">The name of the page.</param>
/// <param name="pageHandler">The page handler to redirect to.</param>
/// <param name="routeValues">The route data to use for generating the URL.</param>
/// <param name="fragment">The fragment to add to the URL.</param>
/// <returns>The created <see cref="RedirectToRouteResult"/> for the response.</returns>
[NonAction]
public virtual RedirectToPageResult RedirectToPagePreserveMethod(
string pageName,
string pageHandler = null,
object routeValues = null,
string fragment = null)
{
if (pageName == null)
{
throw new ArgumentNullException(nameof(pageName));
}
return new RedirectToPageResult(
pageName: pageName,
pageHandler: pageHandler,
routeValues: routeValues,
permanent: false,
preserveMethod: true,
fragment: fragment);
}
/// <summary>
/// Redirects (<see cref="StatusCodes.Status308PermanentRedirect"/>) to the specified route with
/// <see cref="RedirectToRouteResult.Permanent"/> set to true and <see cref="RedirectToRouteResult.PreserveMethod"/>
/// set to true, using the specified <paramref name="pageName"/>, <paramref name="routeValues"/>, and <paramref name="fragment"/>.
/// </summary>
/// <param name="pageName">The name of the page.</param>
/// <param name="pageHandler">The page handler to redirect to.</param>
/// <param name="routeValues">The route data to use for generating the URL.</param>
/// <param name="fragment">The fragment to add to the URL.</param>
/// <returns>The created <see cref="RedirectToRouteResult"/> for the response.</returns>
[NonAction]
public virtual RedirectToPageResult RedirectToPagePermanentPreserveMethod(
string pageName,
string pageHandler = null,
object routeValues = null,
string fragment = null)
{
if (pageName == null)
{
throw new ArgumentNullException(nameof(pageName));
}
return new RedirectToPageResult(
pageName: pageName,
pageHandler: pageHandler,
routeValues: routeValues,
permanent: true,
preserveMethod: true,
fragment: fragment);
}
#endregion
#region FileResult variants
/// <summary>
/// Returns a file with the specified <paramref name="fileContents" /> as content (<see cref="StatusCodes.Status200OK"/>),
/// and the specified <paramref name="contentType" /> as the Content-Type.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="fileContents">The file contents.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <returns>The created <see cref="FileContentResult"/> for the response.</returns>
[NonAction]
public virtual FileContentResult File(byte[] fileContents, string contentType)
=> File(fileContents, contentType, fileDownloadName: null);
/// <summary>
/// Returns a file with the specified <paramref name="fileContents" /> as content (<see cref="StatusCodes.Status200OK"/>),
/// and the specified <paramref name="contentType" /> as the Content-Type.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="fileContents">The file contents.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <param name="enableRangeProcessing">Set to <c>true</c> to enable range requests processing.</param>
/// <returns>The created <see cref="FileContentResult"/> for the response.</returns>
[NonAction]
public virtual FileContentResult File(byte[] fileContents, string contentType, bool enableRangeProcessing)
=> File(fileContents, contentType, fileDownloadName: null, enableRangeProcessing: enableRangeProcessing);
/// <summary>
/// Returns a file with the specified <paramref name="fileContents" /> as content (<see cref="StatusCodes.Status200OK"/>), the
/// specified <paramref name="contentType" /> as the Content-Type and the specified <paramref name="fileDownloadName" /> as the suggested file name.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="fileContents">The file contents.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <param name="fileDownloadName">The suggested file name.</param>
/// <returns>The created <see cref="FileContentResult"/> for the response.</returns>
[NonAction]
public virtual FileContentResult File(byte[] fileContents, string contentType, string fileDownloadName)
=> new FileContentResult(fileContents, contentType) { FileDownloadName = fileDownloadName };
/// <summary>
/// Returns a file with the specified <paramref name="fileContents" /> as content (<see cref="StatusCodes.Status200OK"/>), the
/// specified <paramref name="contentType" /> as the Content-Type and the specified <paramref name="fileDownloadName" /> as the suggested file name.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="fileContents">The file contents.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <param name="fileDownloadName">The suggested file name.</param>
/// <param name="enableRangeProcessing">Set to <c>true</c> to enable range requests processing.</param>
/// <returns>The created <see cref="FileContentResult"/> for the response.</returns>
[NonAction]
public virtual FileContentResult File(byte[] fileContents, string contentType, string fileDownloadName, bool enableRangeProcessing)
=> new FileContentResult(fileContents, contentType)
{
FileDownloadName = fileDownloadName,
EnableRangeProcessing = enableRangeProcessing,
};
/// <summary>
/// Returns a file with the specified <paramref name="fileContents" /> as content (<see cref="StatusCodes.Status200OK"/>),
/// and the specified <paramref name="contentType" /> as the Content-Type.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="fileContents">The file contents.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <param name="lastModified">The <see cref="DateTimeOffset"/> of when the file was last modified.</param>
/// <param name="entityTag">The <see cref="EntityTagHeaderValue"/> associated with the file.</param>
/// <returns>The created <see cref="FileContentResult"/> for the response.</returns>
[NonAction]
public virtual FileContentResult File(byte[] fileContents, string contentType, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag)
{
return new FileContentResult(fileContents, contentType)
{
LastModified = lastModified,
EntityTag = entityTag,
};
}
/// <summary>
/// Returns a file with the specified <paramref name="fileContents" /> as content (<see cref="StatusCodes.Status200OK"/>),
/// and the specified <paramref name="contentType" /> as the Content-Type.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="fileContents">The file contents.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <param name="lastModified">The <see cref="DateTimeOffset"/> of when the file was last modified.</param>
/// <param name="entityTag">The <see cref="EntityTagHeaderValue"/> associated with the file.</param>
/// <param name="enableRangeProcessing">Set to <c>true</c> to enable range requests processing.</param>
/// <returns>The created <see cref="FileContentResult"/> for the response.</returns>
[NonAction]
public virtual FileContentResult File(byte[] fileContents, string contentType, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag, bool enableRangeProcessing)
{
return new FileContentResult(fileContents, contentType)
{
LastModified = lastModified,
EntityTag = entityTag,
EnableRangeProcessing = enableRangeProcessing,
};
}
/// <summary>
/// Returns a file with the specified <paramref name="fileContents" /> as content (<see cref="StatusCodes.Status200OK"/>), the
/// specified <paramref name="contentType" /> as the Content-Type, and the specified <paramref name="fileDownloadName" /> as the suggested file name.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="fileContents">The file contents.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <param name="fileDownloadName">The suggested file name.</param>
/// <param name="lastModified">The <see cref="DateTimeOffset"/> of when the file was last modified.</param>
/// <param name="entityTag">The <see cref="EntityTagHeaderValue"/> associated with the file.</param>
/// <returns>The created <see cref="FileContentResult"/> for the response.</returns>
[NonAction]
public virtual FileContentResult File(byte[] fileContents, string contentType, string fileDownloadName, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag)
{
return new FileContentResult(fileContents, contentType)
{
LastModified = lastModified,
EntityTag = entityTag,
FileDownloadName = fileDownloadName,
};
}
/// <summary>
/// Returns a file with the specified <paramref name="fileContents" /> as content (<see cref="StatusCodes.Status200OK"/>), the
/// specified <paramref name="contentType" /> as the Content-Type, and the specified <paramref name="fileDownloadName" /> as the suggested file name.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="fileContents">The file contents.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <param name="fileDownloadName">The suggested file name.</param>
/// <param name="lastModified">The <see cref="DateTimeOffset"/> of when the file was last modified.</param>
/// <param name="entityTag">The <see cref="EntityTagHeaderValue"/> associated with the file.</param>
/// <param name="enableRangeProcessing">Set to <c>true</c> to enable range requests processing.</param>
/// <returns>The created <see cref="FileContentResult"/> for the response.</returns>
[NonAction]
public virtual FileContentResult File(byte[] fileContents, string contentType, string fileDownloadName, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag, bool enableRangeProcessing)
{
return new FileContentResult(fileContents, contentType)
{
LastModified = lastModified,
EntityTag = entityTag,
FileDownloadName = fileDownloadName,
EnableRangeProcessing = enableRangeProcessing,
};
}
/// <summary>
/// Returns a file in the specified <paramref name="fileStream" /> (<see cref="StatusCodes.Status200OK"/>), with the
/// specified <paramref name="contentType" /> as the Content-Type.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="fileStream">The <see cref="Stream"/> with the contents of the file.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <returns>The created <see cref="FileStreamResult"/> for the response.</returns>
/// <remarks>
/// The <paramref name="fileStream" /> parameter is disposed after the response is sent.
/// </remarks>
[NonAction]
public virtual FileStreamResult File(Stream fileStream, string contentType)
=> File(fileStream, contentType, fileDownloadName: null);
/// <summary>
/// Returns a file in the specified <paramref name="fileStream" /> (<see cref="StatusCodes.Status200OK"/>), with the
/// specified <paramref name="contentType" /> as the Content-Type.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="fileStream">The <see cref="Stream"/> with the contents of the file.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <param name="enableRangeProcessing">Set to <c>true</c> to enable range requests processing.</param>
/// <returns>The created <see cref="FileStreamResult"/> for the response.</returns>
/// <remarks>
/// The <paramref name="fileStream" /> parameter is disposed after the response is sent.
/// </remarks>
[NonAction]
public virtual FileStreamResult File(Stream fileStream, string contentType, bool enableRangeProcessing)
=> File(fileStream, contentType, fileDownloadName: null, enableRangeProcessing: enableRangeProcessing);
/// <summary>
/// Returns a file in the specified <paramref name="fileStream" /> (<see cref="StatusCodes.Status200OK"/>) with the
/// specified <paramref name="contentType" /> as the Content-Type and the
/// specified <paramref name="fileDownloadName" /> as the suggested file name.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="fileStream">The <see cref="Stream"/> with the contents of the file.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <param name="fileDownloadName">The suggested file name.</param>
/// <returns>The created <see cref="FileStreamResult"/> for the response.</returns>
/// <remarks>
/// The <paramref name="fileStream" /> parameter is disposed after the response is sent.
/// </remarks>
[NonAction]
public virtual FileStreamResult File(Stream fileStream, string contentType, string fileDownloadName)
=> new FileStreamResult(fileStream, contentType) { FileDownloadName = fileDownloadName };
/// <summary>
/// Returns a file in the specified <paramref name="fileStream" /> (<see cref="StatusCodes.Status200OK"/>) with the
/// specified <paramref name="contentType" /> as the Content-Type and the
/// specified <paramref name="fileDownloadName" /> as the suggested file name.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="fileStream">The <see cref="Stream"/> with the contents of the file.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <param name="fileDownloadName">The suggested file name.</param>
/// <param name="enableRangeProcessing">Set to <c>true</c> to enable range requests processing.</param>
/// <returns>The created <see cref="FileStreamResult"/> for the response.</returns>
/// <remarks>
/// The <paramref name="fileStream" /> parameter is disposed after the response is sent.
/// </remarks>
[NonAction]
public virtual FileStreamResult File(Stream fileStream, string contentType, string fileDownloadName, bool enableRangeProcessing)
=> new FileStreamResult(fileStream, contentType)
{
FileDownloadName = fileDownloadName,
EnableRangeProcessing = enableRangeProcessing,
};
/// <summary>
/// Returns a file in the specified <paramref name="fileStream" /> (<see cref="StatusCodes.Status200OK"/>),
/// and the specified <paramref name="contentType" /> as the Content-Type.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="fileStream">The <see cref="Stream"/> with the contents of the file.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <param name="lastModified">The <see cref="DateTimeOffset"/> of when the file was last modified.</param>
/// <param name="entityTag">The <see cref="EntityTagHeaderValue"/> associated with the file.</param>
/// <returns>The created <see cref="FileStreamResult"/> for the response.</returns>
/// <remarks>
/// The <paramref name="fileStream" /> parameter is disposed after the response is sent.
/// </remarks>
[NonAction]
public virtual FileStreamResult File(Stream fileStream, string contentType, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag)
{
return new FileStreamResult(fileStream, contentType)
{
LastModified = lastModified,
EntityTag = entityTag,
};
}
/// <summary>
/// Returns a file in the specified <paramref name="fileStream" /> (<see cref="StatusCodes.Status200OK"/>),
/// and the specified <paramref name="contentType" /> as the Content-Type.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="fileStream">The <see cref="Stream"/> with the contents of the file.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <param name="lastModified">The <see cref="DateTimeOffset"/> of when the file was last modified.</param>
/// <param name="entityTag">The <see cref="EntityTagHeaderValue"/> associated with the file.</param>
/// <param name="enableRangeProcessing">Set to <c>true</c> to enable range requests processing.</param>
/// <returns>The created <see cref="FileStreamResult"/> for the response.</returns>
/// <remarks>
/// The <paramref name="fileStream" /> parameter is disposed after the response is sent.
/// </remarks>
[NonAction]
public virtual FileStreamResult File(Stream fileStream, string contentType, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag, bool enableRangeProcessing)
{
return new FileStreamResult(fileStream, contentType)
{
LastModified = lastModified,
EntityTag = entityTag,
EnableRangeProcessing = enableRangeProcessing,
};
}
/// <summary>
/// Returns a file in the specified <paramref name="fileStream" /> (<see cref="StatusCodes.Status200OK"/>), the
/// specified <paramref name="contentType" /> as the Content-Type, and the specified <paramref name="fileDownloadName" /> as the suggested file name.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="fileStream">The <see cref="Stream"/> with the contents of the file.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <param name="fileDownloadName">The suggested file name.</param>
/// <param name="lastModified">The <see cref="DateTimeOffset"/> of when the file was last modified.</param>
/// <param name="entityTag">The <see cref="EntityTagHeaderValue"/> associated with the file.</param>
/// <returns>The created <see cref="FileStreamResult"/> for the response.</returns>
/// <remarks>
/// The <paramref name="fileStream" /> parameter is disposed after the response is sent.
/// </remarks>
[NonAction]
public virtual FileStreamResult File(Stream fileStream, string contentType, string fileDownloadName, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag)
{
return new FileStreamResult(fileStream, contentType)
{
LastModified = lastModified,
EntityTag = entityTag,
FileDownloadName = fileDownloadName,
};
}
/// <summary>
/// Returns a file in the specified <paramref name="fileStream" /> (<see cref="StatusCodes.Status200OK"/>), the
/// specified <paramref name="contentType" /> as the Content-Type, and the specified <paramref name="fileDownloadName" /> as the suggested file name.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="fileStream">The <see cref="Stream"/> with the contents of the file.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <param name="fileDownloadName">The suggested file name.</param>
/// <param name="lastModified">The <see cref="DateTimeOffset"/> of when the file was last modified.</param>
/// <param name="entityTag">The <see cref="EntityTagHeaderValue"/> associated with the file.</param>
/// <param name="enableRangeProcessing">Set to <c>true</c> to enable range requests processing.</param>
/// <returns>The created <see cref="FileStreamResult"/> for the response.</returns>
/// <remarks>
/// The <paramref name="fileStream" /> parameter is disposed after the response is sent.
/// </remarks>
[NonAction]
public virtual FileStreamResult File(Stream fileStream, string contentType, string fileDownloadName, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag, bool enableRangeProcessing)
{
return new FileStreamResult(fileStream, contentType)
{
LastModified = lastModified,
EntityTag = entityTag,
FileDownloadName = fileDownloadName,
EnableRangeProcessing = enableRangeProcessing,
};
}
/// <summary>
/// Returns the file specified by <paramref name="virtualPath" /> (<see cref="StatusCodes.Status200OK"/>) with the
/// specified <paramref name="contentType" /> as the Content-Type.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="virtualPath">The virtual path of the file to be returned.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <returns>The created <see cref="VirtualFileResult"/> for the response.</returns>
[NonAction]
public virtual VirtualFileResult File(string virtualPath, string contentType)
=> File(virtualPath, contentType, fileDownloadName: null);
/// <summary>
/// Returns the file specified by <paramref name="virtualPath" /> (<see cref="StatusCodes.Status200OK"/>) with the
/// specified <paramref name="contentType" /> as the Content-Type.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="virtualPath">The virtual path of the file to be returned.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <param name="enableRangeProcessing">Set to <c>true</c> to enable range requests processing.</param>
/// <returns>The created <see cref="VirtualFileResult"/> for the response.</returns>
[NonAction]
public virtual VirtualFileResult File(string virtualPath, string contentType, bool enableRangeProcessing)
=> File(virtualPath, contentType, fileDownloadName: null, enableRangeProcessing: enableRangeProcessing);
/// <summary>
/// Returns the file specified by <paramref name="virtualPath" /> (<see cref="StatusCodes.Status200OK"/>) with the
/// specified <paramref name="contentType" /> as the Content-Type and the
/// specified <paramref name="fileDownloadName" /> as the suggested file name.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="virtualPath">The virtual path of the file to be returned.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <param name="fileDownloadName">The suggested file name.</param>
/// <returns>The created <see cref="VirtualFileResult"/> for the response.</returns>
[NonAction]
public virtual VirtualFileResult File(string virtualPath, string contentType, string fileDownloadName)
=> new VirtualFileResult(virtualPath, contentType) { FileDownloadName = fileDownloadName };
/// <summary>
/// Returns the file specified by <paramref name="virtualPath" /> (<see cref="StatusCodes.Status200OK"/>) with the
/// specified <paramref name="contentType" /> as the Content-Type and the
/// specified <paramref name="fileDownloadName" /> as the suggested file name.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="virtualPath">The virtual path of the file to be returned.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <param name="fileDownloadName">The suggested file name.</param>
/// <param name="enableRangeProcessing">Set to <c>true</c> to enable range requests processing.</param>
/// <returns>The created <see cref="VirtualFileResult"/> for the response.</returns>
[NonAction]
public virtual VirtualFileResult File(string virtualPath, string contentType, string fileDownloadName, bool enableRangeProcessing)
=> new VirtualFileResult(virtualPath, contentType)
{
FileDownloadName = fileDownloadName,
EnableRangeProcessing = enableRangeProcessing,
};
/// <summary>
/// Returns the file specified by <paramref name="virtualPath" /> (<see cref="StatusCodes.Status200OK"/>), and the
/// specified <paramref name="contentType" /> as the Content-Type.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="virtualPath">The virtual path of the file to be returned.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <param name="lastModified">The <see cref="DateTimeOffset"/> of when the file was last modified.</param>
/// <param name="entityTag">The <see cref="EntityTagHeaderValue"/> associated with the file.</param>
/// <returns>The created <see cref="VirtualFileResult"/> for the response.</returns>
[NonAction]
public virtual VirtualFileResult File(string virtualPath, string contentType, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag)
{
return new VirtualFileResult(virtualPath, contentType)
{
LastModified = lastModified,
EntityTag = entityTag,
};
}
/// <summary>
/// Returns the file specified by <paramref name="virtualPath" /> (<see cref="StatusCodes.Status200OK"/>), and the
/// specified <paramref name="contentType" /> as the Content-Type.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="virtualPath">The virtual path of the file to be returned.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <param name="lastModified">The <see cref="DateTimeOffset"/> of when the file was last modified.</param>
/// <param name="entityTag">The <see cref="EntityTagHeaderValue"/> associated with the file.</param>
/// <param name="enableRangeProcessing">Set to <c>true</c> to enable range requests processing.</param>
/// <returns>The created <see cref="VirtualFileResult"/> for the response.</returns>
[NonAction]
public virtual VirtualFileResult File(string virtualPath, string contentType, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag, bool enableRangeProcessing)
{
return new VirtualFileResult(virtualPath, contentType)
{
LastModified = lastModified,
EntityTag = entityTag,
EnableRangeProcessing = enableRangeProcessing,
};
}
/// <summary>
/// Returns the file specified by <paramref name="virtualPath" /> (<see cref="StatusCodes.Status200OK"/>), the
/// specified <paramref name="contentType" /> as the Content-Type, and the specified <paramref name="fileDownloadName" /> as the suggested file name.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="virtualPath">The virtual path of the file to be returned.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <param name="fileDownloadName">The suggested file name.</param>
/// <param name="lastModified">The <see cref="DateTimeOffset"/> of when the file was last modified.</param>
/// <param name="entityTag">The <see cref="EntityTagHeaderValue"/> associated with the file.</param>
/// <returns>The created <see cref="VirtualFileResult"/> for the response.</returns>
[NonAction]
public virtual VirtualFileResult File(string virtualPath, string contentType, string fileDownloadName, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag)
{
return new VirtualFileResult(virtualPath, contentType)
{
LastModified = lastModified,
EntityTag = entityTag,
FileDownloadName = fileDownloadName,
};
}
/// <summary>
/// Returns the file specified by <paramref name="virtualPath" /> (<see cref="StatusCodes.Status200OK"/>), the
/// specified <paramref name="contentType" /> as the Content-Type, and the specified <paramref name="fileDownloadName" /> as the suggested file name.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="virtualPath">The virtual path of the file to be returned.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <param name="fileDownloadName">The suggested file name.</param>
/// <param name="lastModified">The <see cref="DateTimeOffset"/> of when the file was last modified.</param>
/// <param name="entityTag">The <see cref="EntityTagHeaderValue"/> associated with the file.</param>
/// <param name="enableRangeProcessing">Set to <c>true</c> to enable range requests processing.</param>
/// <returns>The created <see cref="VirtualFileResult"/> for the response.</returns>
[NonAction]
public virtual VirtualFileResult File(string virtualPath, string contentType, string fileDownloadName, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag, bool enableRangeProcessing)
{
return new VirtualFileResult(virtualPath, contentType)
{
LastModified = lastModified,
EntityTag = entityTag,
FileDownloadName = fileDownloadName,
EnableRangeProcessing = enableRangeProcessing,
};
}
/// <summary>
/// Returns the file specified by <paramref name="physicalPath" /> (<see cref="StatusCodes.Status200OK"/>) with the
/// specified <paramref name="contentType" /> as the Content-Type.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="physicalPath">The path to the file. The path must be an absolute path.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <returns>The created <see cref="PhysicalFileResult"/> for the response.</returns>
[NonAction]
public virtual PhysicalFileResult PhysicalFile(string physicalPath, string contentType)
=> PhysicalFile(physicalPath, contentType, fileDownloadName: null);
/// <summary>
/// Returns the file specified by <paramref name="physicalPath" /> (<see cref="StatusCodes.Status200OK"/>) with the
/// specified <paramref name="contentType" /> as the Content-Type.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="physicalPath">The path to the file. The path must be an absolute path.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <param name="enableRangeProcessing">Set to <c>true</c> to enable range requests processing.</param>
/// <returns>The created <see cref="PhysicalFileResult"/> for the response.</returns>
[NonAction]
public virtual PhysicalFileResult PhysicalFile(string physicalPath, string contentType, bool enableRangeProcessing)
=> PhysicalFile(physicalPath, contentType, fileDownloadName: null, enableRangeProcessing: enableRangeProcessing);
/// <summary>
/// Returns the file specified by <paramref name="physicalPath" /> (<see cref="StatusCodes.Status200OK"/>) with the
/// specified <paramref name="contentType" /> as the Content-Type and the
/// specified <paramref name="fileDownloadName" /> as the suggested file name.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="physicalPath">The path to the file. The path must be an absolute path.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <param name="fileDownloadName">The suggested file name.</param>
/// <returns>The created <see cref="PhysicalFileResult"/> for the response.</returns>
[NonAction]
public virtual PhysicalFileResult PhysicalFile(
string physicalPath,
string contentType,
string fileDownloadName)
=> new PhysicalFileResult(physicalPath, contentType) { FileDownloadName = fileDownloadName };
/// <summary>
/// Returns the file specified by <paramref name="physicalPath" /> (<see cref="StatusCodes.Status200OK"/>) with the
/// specified <paramref name="contentType" /> as the Content-Type and the
/// specified <paramref name="fileDownloadName" /> as the suggested file name.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="physicalPath">The path to the file. The path must be an absolute path.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <param name="fileDownloadName">The suggested file name.</param>
/// <param name="enableRangeProcessing">Set to <c>true</c> to enable range requests processing.</param>
/// <returns>The created <see cref="PhysicalFileResult"/> for the response.</returns>
[NonAction]
public virtual PhysicalFileResult PhysicalFile(
string physicalPath,
string contentType,
string fileDownloadName,
bool enableRangeProcessing)
=> new PhysicalFileResult(physicalPath, contentType)
{
FileDownloadName = fileDownloadName,
EnableRangeProcessing = enableRangeProcessing,
};
/// <summary>
/// Returns the file specified by <paramref name="physicalPath" /> (<see cref="StatusCodes.Status200OK"/>), and
/// the specified <paramref name="contentType" /> as the Content-Type.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="physicalPath">The path to the file. The path must be an absolute path.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <param name="lastModified">The <see cref="DateTimeOffset"/> of when the file was last modified.</param>
/// <param name="entityTag">The <see cref="EntityTagHeaderValue"/> associated with the file.</param>
/// <returns>The created <see cref="PhysicalFileResult"/> for the response.</returns>
[NonAction]
public virtual PhysicalFileResult PhysicalFile(string physicalPath, string contentType, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag)
{
return new PhysicalFileResult(physicalPath, contentType)
{
LastModified = lastModified,
EntityTag = entityTag,
};
}
/// <summary>
/// Returns the file specified by <paramref name="physicalPath" /> (<see cref="StatusCodes.Status200OK"/>), and
/// the specified <paramref name="contentType" /> as the Content-Type.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="physicalPath">The path to the file. The path must be an absolute path.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <param name="lastModified">The <see cref="DateTimeOffset"/> of when the file was last modified.</param>
/// <param name="entityTag">The <see cref="EntityTagHeaderValue"/> associated with the file.</param>
/// <param name="enableRangeProcessing">Set to <c>true</c> to enable range requests processing.</param>
/// <returns>The created <see cref="PhysicalFileResult"/> for the response.</returns>
[NonAction]
public virtual PhysicalFileResult PhysicalFile(string physicalPath, string contentType, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag, bool enableRangeProcessing)
{
return new PhysicalFileResult(physicalPath, contentType)
{
LastModified = lastModified,
EntityTag = entityTag,
EnableRangeProcessing = enableRangeProcessing,
};
}
/// <summary>
/// Returns the file specified by <paramref name="physicalPath" /> (<see cref="StatusCodes.Status200OK"/>), the
/// specified <paramref name="contentType" /> as the Content-Type, and the specified <paramref name="fileDownloadName" /> as the suggested file name.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="physicalPath">The path to the file. The path must be an absolute path.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <param name="fileDownloadName">The suggested file name.</param>
/// <param name="lastModified">The <see cref="DateTimeOffset"/> of when the file was last modified.</param>
/// <param name="entityTag">The <see cref="EntityTagHeaderValue"/> associated with the file.</param>
/// <returns>The created <see cref="PhysicalFileResult"/> for the response.</returns>
[NonAction]
public virtual PhysicalFileResult PhysicalFile(string physicalPath, string contentType, string fileDownloadName, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag)
{
return new PhysicalFileResult(physicalPath, contentType)
{
LastModified = lastModified,
EntityTag = entityTag,
FileDownloadName = fileDownloadName,
};
}
/// <summary>
/// Returns the file specified by <paramref name="physicalPath" /> (<see cref="StatusCodes.Status200OK"/>), the
/// specified <paramref name="contentType" /> as the Content-Type, and the specified <paramref name="fileDownloadName" /> as the suggested file name.
/// This supports range requests (<see cref="StatusCodes.Status206PartialContent"/> or
/// <see cref="StatusCodes.Status416RangeNotSatisfiable"/> if the range is not satisfiable).
/// </summary>
/// <param name="physicalPath">The path to the file. The path must be an absolute path.</param>
/// <param name="contentType">The Content-Type of the file.</param>
/// <param name="fileDownloadName">The suggested file name.</param>
/// <param name="lastModified">The <see cref="DateTimeOffset"/> of when the file was last modified.</param>
/// <param name="entityTag">The <see cref="EntityTagHeaderValue"/> associated with the file.</param>
/// <param name="enableRangeProcessing">Set to <c>true</c> to enable range requests processing.</param>
/// <returns>The created <see cref="PhysicalFileResult"/> for the response.</returns>
[NonAction]
public virtual PhysicalFileResult PhysicalFile(string physicalPath, string contentType, string fileDownloadName, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag, bool enableRangeProcessing)
{
return new PhysicalFileResult(physicalPath, contentType)
{
LastModified = lastModified,
EntityTag = entityTag,
FileDownloadName = fileDownloadName,
EnableRangeProcessing = enableRangeProcessing,
};
}
#endregion
/// <summary>
/// Creates an <see cref="UnauthorizedResult"/> that produces an <see cref="StatusCodes.Status401Unauthorized"/> response.
/// </summary>
/// <returns>The created <see cref="UnauthorizedResult"/> for the response.</returns>
[NonAction]
public virtual UnauthorizedResult Unauthorized()
=> new UnauthorizedResult();
/// <summary>
/// Creates an <see cref="UnauthorizedObjectResult"/> that produces a <see cref="StatusCodes.Status401Unauthorized"/> response.
/// </summary>
/// <returns>The created <see cref="UnauthorizedObjectResult"/> for the response.</returns>
[NonAction]
public virtual UnauthorizedObjectResult Unauthorized([ActionResultObjectValue] object value)
=> new UnauthorizedObjectResult(value);
/// <summary>
/// Creates an <see cref="NotFoundResult"/> that produces a <see cref="StatusCodes.Status404NotFound"/> response.
/// </summary>
/// <returns>The created <see cref="NotFoundResult"/> for the response.</returns>
[NonAction]
public virtual NotFoundResult NotFound()
=> new NotFoundResult();
/// <summary>
/// Creates an <see cref="NotFoundObjectResult"/> that produces a <see cref="StatusCodes.Status404NotFound"/> response.
/// </summary>
/// <returns>The created <see cref="NotFoundObjectResult"/> for the response.</returns>
[NonAction]
public virtual NotFoundObjectResult NotFound([ActionResultObjectValue] object value)
=> new NotFoundObjectResult(value);
/// <summary>
/// Creates an <see cref="BadRequestResult"/> that produces a <see cref="StatusCodes.Status400BadRequest"/> response.
/// </summary>
/// <returns>The created <see cref="BadRequestResult"/> for the response.</returns>
[NonAction]
public virtual BadRequestResult BadRequest()
=> new BadRequestResult();
/// <summary>
/// Creates an <see cref="BadRequestObjectResult"/> that produces a <see cref="StatusCodes.Status400BadRequest"/> response.
/// </summary>
/// <param name="error">An error object to be returned to the client.</param>
/// <returns>The created <see cref="BadRequestObjectResult"/> for the response.</returns>
[NonAction]
public virtual BadRequestObjectResult BadRequest([ActionResultObjectValue] object error)
=> new BadRequestObjectResult(error);
/// <summary>
/// Creates an <see cref="BadRequestObjectResult"/> that produces a <see cref="StatusCodes.Status400BadRequest"/> response.
/// </summary>
/// <param name="modelState">The <see cref="ModelStateDictionary" /> containing errors to be returned to the client.</param>
/// <returns>The created <see cref="BadRequestObjectResult"/> for the response.</returns>
[NonAction]
public virtual BadRequestObjectResult BadRequest([ActionResultObjectValue] ModelStateDictionary modelState)
{
if (modelState == null)
{
throw new ArgumentNullException(nameof(modelState));
}
return new BadRequestObjectResult(modelState);
}
/// <summary>
/// Creates an <see cref="UnprocessableEntityResult"/> that produces a <see cref="StatusCodes.Status422UnprocessableEntity"/> response.
/// </summary>
/// <returns>The created <see cref="UnprocessableEntityResult"/> for the response.</returns>
[NonAction]
public virtual UnprocessableEntityResult UnprocessableEntity()
=> new UnprocessableEntityResult();
/// <summary>
/// Creates an <see cref="UnprocessableEntityObjectResult"/> that produces a <see cref="StatusCodes.Status422UnprocessableEntity"/> response.
/// </summary>
/// <param name="error">An error object to be returned to the client.</param>
/// <returns>The created <see cref="UnprocessableEntityObjectResult"/> for the response.</returns>
[NonAction]
public virtual UnprocessableEntityObjectResult UnprocessableEntity([ActionResultObjectValue] object error)
=> new UnprocessableEntityObjectResult(error);
/// <summary>
/// Creates an <see cref="UnprocessableEntityObjectResult"/> that produces a <see cref="StatusCodes.Status422UnprocessableEntity"/> response.
/// </summary>
/// <param name="modelState">The <see cref="ModelStateDictionary" /> containing errors to be returned to the client.</param>
/// <returns>The created <see cref="UnprocessableEntityObjectResult"/> for the response.</returns>
[NonAction]
public virtual UnprocessableEntityObjectResult UnprocessableEntity([ActionResultObjectValue] ModelStateDictionary modelState)
{
if (modelState == null)
{
throw new ArgumentNullException(nameof(modelState));
}
return new UnprocessableEntityObjectResult(modelState);
}
/// <summary>
/// Creates an <see cref="ConflictResult"/> that produces a <see cref="StatusCodes.Status409Conflict"/> response.
/// </summary>
/// <returns>The created <see cref="ConflictResult"/> for the response.</returns>
[NonAction]
public virtual ConflictResult Conflict()
=> new ConflictResult();
/// <summary>
/// Creates an <see cref="ConflictObjectResult"/> that produces a <see cref="StatusCodes.Status409Conflict"/> response.
/// </summary>
/// <param name="error">Contains errors to be returned to the client.</param>
/// <returns>The created <see cref="ConflictObjectResult"/> for the response.</returns>
[NonAction]
public virtual ConflictObjectResult Conflict([ActionResultObjectValue] object error)
=> new ConflictObjectResult(error);
/// <summary>
/// Creates an <see cref="ConflictObjectResult"/> that produces a <see cref="StatusCodes.Status409Conflict"/> response.
/// </summary>
/// <param name="modelState">The <see cref="ModelStateDictionary" /> containing errors to be returned to the client.</param>
/// <returns>The created <see cref="ConflictObjectResult"/> for the response.</returns>
[NonAction]
public virtual ConflictObjectResult Conflict([ActionResultObjectValue] ModelStateDictionary modelState)
=> new ConflictObjectResult(modelState);
/// <summary>
/// Creates an <see cref="ObjectResult"/> that produces a <see cref="ProblemDetails"/> response.
/// </summary>
/// <param name="statusCode">The value for <see cref="ProblemDetails.Status" />.</param>
/// <param name="detail">The value for <see cref="ProblemDetails.Detail" />.</param>
/// <param name="instance">The value for <see cref="ProblemDetails.Instance" />.</param>
/// <param name="title">The value for <see cref="ProblemDetails.Title" />.</param>
/// <param name="type">The value for <see cref="ProblemDetails.Type" />.</param>
/// <returns>The created <see cref="ObjectResult"/> for the response.</returns>
[NonAction]
public virtual ObjectResult Problem(
string detail = null,
string instance = null,
int? statusCode = null,
string title = null,
string type = null)
{
ProblemDetails problemDetails;
if (ProblemDetailsFactory == null)
{
// ProblemDetailsFactory may be null in unit testing scenarios. Improvise to make this more testable.
problemDetails = new ProblemDetails
{
Detail = detail,
Instance = instance,
Status = statusCode ?? 500,
Title = title,
Type = type,
};
}
else
{
problemDetails = ProblemDetailsFactory.CreateProblemDetails(
HttpContext,
statusCode: statusCode ?? 500,
title: title,
type: type,
detail: detail,
instance: instance);
}
return new ObjectResult(problemDetails)
{
StatusCode = problemDetails.Status
};
}
/// <summary>
/// Creates an <see cref="BadRequestObjectResult"/> that produces a <see cref="StatusCodes.Status400BadRequest"/> response.
/// </summary>
/// <returns>The created <see cref="BadRequestObjectResult"/> for the response.</returns>
[NonAction]
public virtual ActionResult ValidationProblem([ActionResultObjectValue] ValidationProblemDetails descriptor)
{
if (descriptor == null)
{
throw new ArgumentNullException(nameof(descriptor));
}
return new BadRequestObjectResult(descriptor);
}
/// <summary>
/// Creates an <see cref="ActionResult"/> that produces a <see cref="StatusCodes.Status400BadRequest"/> response
/// with validation errors from <paramref name="modelStateDictionary"/>.
/// </summary>
/// <param name="modelStateDictionary">The <see cref="ModelStateDictionary"/>.</param>
/// <returns>The created <see cref="BadRequestObjectResult"/> for the response.</returns>
[NonAction]
public virtual ActionResult ValidationProblem([ActionResultObjectValue] ModelStateDictionary modelStateDictionary)
=> ValidationProblem(detail: null, modelStateDictionary: modelStateDictionary);
/// <summary>
/// Creates an <see cref="ActionResult"/> that produces a <see cref="StatusCodes.Status400BadRequest"/> response
/// with validation errors from <see cref="ModelState"/>.
/// </summary>
/// <returns>The created <see cref="ActionResult"/> for the response.</returns>
[NonAction]
public virtual ActionResult ValidationProblem()
=> ValidationProblem(ModelState);
/// <summary>
/// Creates an <see cref="ActionResult"/> that produces a <see cref="StatusCodes.Status400BadRequest"/> response
/// with a <see cref="ValidationProblemDetails"/> value.
/// </summary>
/// <param name="detail">The value for <see cref="ProblemDetails.Detail" />.</param>
/// <param name="instance">The value for <see cref="ProblemDetails.Instance" />.</param>
/// <param name="statusCode">The status code.</param>
/// <param name="title">The value for <see cref="ProblemDetails.Title" />.</param>
/// <param name="type">The value for <see cref="ProblemDetails.Type" />.</param>
/// <param name="modelStateDictionary">The <see cref="ModelStateDictionary"/>.
/// When <see langword="null"/> uses <see cref="ModelState"/>.</param>
/// <returns>The created <see cref="ActionResult"/> for the response.</returns>
[NonAction]
public virtual ActionResult ValidationProblem(
string detail = null,
string instance = null,
int? statusCode = null,
string title = null,
string type = null,
[ActionResultObjectValue] ModelStateDictionary modelStateDictionary = null)
{
modelStateDictionary ??= ModelState;
ValidationProblemDetails validationProblem;
if (ProblemDetailsFactory == null)
{
// ProblemDetailsFactory may be null in unit testing scenarios. Improvise to make this more testable.
validationProblem = new ValidationProblemDetails(modelStateDictionary)
{
Detail = detail,
Instance = instance,
Status = statusCode,
Title = title,
Type = type,
};
}
else
{
validationProblem = ProblemDetailsFactory?.CreateValidationProblemDetails(
HttpContext,
modelStateDictionary,
statusCode: statusCode,
title: title,
type: type,
detail: detail,
instance: instance);
}
if (validationProblem.Status == 400)
{
// For compatibility with 2.x, continue producing BadRequestObjectResult instances if the status code is 400.
return new BadRequestObjectResult(validationProblem);
}
return new ObjectResult(validationProblem)
{
StatusCode = validationProblem.Status
};
}
/// <summary>
/// Creates a <see cref="CreatedResult"/> object that produces a <see cref="StatusCodes.Status201Created"/> response.
/// </summary>
/// <param name="uri">The URI at which the content has been created.</param>
/// <param name="value">The content value to format in the entity body.</param>
/// <returns>The created <see cref="CreatedResult"/> for the response.</returns>
[NonAction]
public virtual CreatedResult Created(string uri, [ActionResultObjectValue] object value)
{
if (uri == null)
{
throw new ArgumentNullException(nameof(uri));
}
return new CreatedResult(uri, value);
}
/// <summary>
/// Creates a <see cref="CreatedResult"/> object that produces a <see cref="StatusCodes.Status201Created"/> response.
/// </summary>
/// <param name="uri">The URI at which the content has been created.</param>
/// <param name="value">The content value to format in the entity body.</param>
/// <returns>The created <see cref="CreatedResult"/> for the response.</returns>
[NonAction]
public virtual CreatedResult Created(Uri uri, [ActionResultObjectValue] object value)
{
if (uri == null)
{
throw new ArgumentNullException(nameof(uri));
}
return new CreatedResult(uri, value);
}
/// <summary>
/// Creates a <see cref="CreatedAtActionResult"/> object that produces a <see cref="StatusCodes.Status201Created"/> response.
/// </summary>
/// <param name="actionName">The name of the action to use for generating the URL.</param>
/// <param name="value">The content value to format in the entity body.</param>
/// <returns>The created <see cref="CreatedAtActionResult"/> for the response.</returns>
[NonAction]
public virtual CreatedAtActionResult CreatedAtAction(string actionName, [ActionResultObjectValue] object value)
=> CreatedAtAction(actionName, routeValues: null, value: value);
/// <summary>
/// Creates a <see cref="CreatedAtActionResult"/> object that produces a <see cref="StatusCodes.Status201Created"/> response.
/// </summary>
/// <param name="actionName">The name of the action to use for generating the URL.</param>
/// <param name="routeValues">The route data to use for generating the URL.</param>
/// <param name="value">The content value to format in the entity body.</param>
/// <returns>The created <see cref="CreatedAtActionResult"/> for the response.</returns>
[NonAction]
public virtual CreatedAtActionResult CreatedAtAction(string actionName, object routeValues, [ActionResultObjectValue] object value)
=> CreatedAtAction(actionName, controllerName: null, routeValues: routeValues, value: value);
/// <summary>
/// Creates a <see cref="CreatedAtActionResult"/> object that produces a <see cref="StatusCodes.Status201Created"/> response.
/// </summary>
/// <param name="actionName">The name of the action to use for generating the URL.</param>
/// <param name="controllerName">The name of the controller to use for generating the URL.</param>
/// <param name="routeValues">The route data to use for generating the URL.</param>
/// <param name="value">The content value to format in the entity body.</param>
/// <returns>The created <see cref="CreatedAtActionResult"/> for the response.</returns>
[NonAction]
public virtual CreatedAtActionResult CreatedAtAction(
string actionName,
string controllerName,
object routeValues,
[ActionResultObjectValue] object value)
=> new CreatedAtActionResult(actionName, controllerName, routeValues, value);
/// <summary>
/// Creates a <see cref="CreatedAtRouteResult"/> object that produces a <see cref="StatusCodes.Status201Created"/> response.
/// </summary>
/// <param name="routeName">The name of the route to use for generating the URL.</param>
/// <param name="value">The content value to format in the entity body.</param>
/// <returns>The created <see cref="CreatedAtRouteResult"/> for the response.</returns>
[NonAction]
public virtual CreatedAtRouteResult CreatedAtRoute(string routeName, [ActionResultObjectValue] object value)
=> CreatedAtRoute(routeName, routeValues: null, value: value);
/// <summary>
/// Creates a <see cref="CreatedAtRouteResult"/> object that produces a <see cref="StatusCodes.Status201Created"/> response.
/// </summary>
/// <param name="routeValues">The route data to use for generating the URL.</param>
/// <param name="value">The content value to format in the entity body.</param>
/// <returns>The created <see cref="CreatedAtRouteResult"/> for the response.</returns>
[NonAction]
public virtual CreatedAtRouteResult CreatedAtRoute(object routeValues, [ActionResultObjectValue] object value)
=> CreatedAtRoute(routeName: null, routeValues: routeValues, value: value);
/// <summary>
/// Creates a <see cref="CreatedAtRouteResult"/> object that produces a <see cref="StatusCodes.Status201Created"/> response.
/// </summary>
/// <param name="routeName">The name of the route to use for generating the URL.</param>
/// <param name="routeValues">The route data to use for generating the URL.</param>
/// <param name="value">The content value to format in the entity body.</param>
/// <returns>The created <see cref="CreatedAtRouteResult"/> for the response.</returns>
[NonAction]
public virtual CreatedAtRouteResult CreatedAtRoute(string routeName, object routeValues, [ActionResultObjectValue] object value)
=> new CreatedAtRouteResult(routeName, routeValues, value);
/// <summary>
/// Creates a <see cref="AcceptedResult"/> object that produces an <see cref="StatusCodes.Status202Accepted"/> response.
/// </summary>
/// <returns>The created <see cref="AcceptedResult"/> for the response.</returns>
[NonAction]
public virtual AcceptedResult Accepted()
=> new AcceptedResult();
/// <summary>
/// Creates a <see cref="AcceptedResult"/> object that produces an <see cref="StatusCodes.Status202Accepted"/> response.
/// </summary>
/// <param name="value">The optional content value to format in the entity body; may be null.</param>
/// <returns>The created <see cref="AcceptedResult"/> for the response.</returns>
[NonAction]
public virtual AcceptedResult Accepted([ActionResultObjectValue] object value)
=> new AcceptedResult(location: null, value: value);
/// <summary>
/// Creates a <see cref="AcceptedResult"/> object that produces an <see cref="StatusCodes.Status202Accepted"/> response.
/// </summary>
/// <param name="uri">The optional URI with the location at which the status of requested content can be monitored.
/// May be null.</param>
/// <returns>The created <see cref="AcceptedResult"/> for the response.</returns>
[NonAction]
public virtual AcceptedResult Accepted(Uri uri)
{
if (uri == null)
{
throw new ArgumentNullException(nameof(uri));
}
return new AcceptedResult(locationUri: uri, value: null);
}
/// <summary>
/// Creates a <see cref="AcceptedResult"/> object that produces an <see cref="StatusCodes.Status202Accepted"/> response.
/// </summary>
/// <param name="uri">The optional URI with the location at which the status of requested content can be monitored.
/// May be null.</param>
/// <returns>The created <see cref="AcceptedResult"/> for the response.</returns>
[NonAction]
public virtual AcceptedResult Accepted(string uri)
=> new AcceptedResult(location: uri, value: null);
/// <summary>
/// Creates a <see cref="AcceptedResult"/> object that produces an <see cref="StatusCodes.Status202Accepted"/> response.
/// </summary>
/// <param name="uri">The URI with the location at which the status of requested content can be monitored.</param>
/// <param name="value">The optional content value to format in the entity body; may be null.</param>
/// <returns>The created <see cref="AcceptedResult"/> for the response.</returns>
[NonAction]
public virtual AcceptedResult Accepted(string uri, [ActionResultObjectValue] object value)
=> new AcceptedResult(uri, value);
/// <summary>
/// Creates a <see cref="AcceptedResult"/> object that produces an <see cref="StatusCodes.Status202Accepted"/> response.
/// </summary>
/// <param name="uri">The URI with the location at which the status of requested content can be monitored.</param>
/// <param name="value">The optional content value to format in the entity body; may be null.</param>
/// <returns>The created <see cref="AcceptedResult"/> for the response.</returns>
[NonAction]
public virtual AcceptedResult Accepted(Uri uri, [ActionResultObjectValue] object value)
{
if (uri == null)
{
throw new ArgumentNullException(nameof(uri));
}
return new AcceptedResult(locationUri: uri, value: value);
}
/// <summary>
/// Creates a <see cref="AcceptedAtActionResult"/> object that produces an <see cref="StatusCodes.Status202Accepted"/> response.
/// </summary>
/// <param name="actionName">The name of the action to use for generating the URL.</param>
/// <returns>The created <see cref="AcceptedAtActionResult"/> for the response.</returns>
[NonAction]
public virtual AcceptedAtActionResult AcceptedAtAction(string actionName)
=> AcceptedAtAction(actionName, routeValues: null, value: null);
/// <summary>
/// Creates a <see cref="AcceptedAtActionResult"/> object that produces an <see cref="StatusCodes.Status202Accepted"/> response.
/// </summary>
/// <param name="actionName">The name of the action to use for generating the URL.</param>
/// <param name="controllerName">The name of the controller to use for generating the URL.</param>
/// <returns>The created <see cref="AcceptedAtActionResult"/> for the response.</returns>
[NonAction]
public virtual AcceptedAtActionResult AcceptedAtAction(string actionName, string controllerName)
=> AcceptedAtAction(actionName, controllerName, routeValues: null, value: null);
/// <summary>
/// Creates a <see cref="AcceptedAtActionResult"/> object that produces an <see cref="StatusCodes.Status202Accepted"/> response.
/// </summary>
/// <param name="actionName">The name of the action to use for generating the URL.</param>
/// <param name="value">The optional content value to format in the entity body; may be null.</param>
/// <returns>The created <see cref="AcceptedAtActionResult"/> for the response.</returns>
[NonAction]
public virtual AcceptedAtActionResult AcceptedAtAction(string actionName, [ActionResultObjectValue] object value)
=> AcceptedAtAction(actionName, routeValues: null, value: value);
/// <summary>
/// Creates a <see cref="AcceptedAtActionResult"/> object that produces an <see cref="StatusCodes.Status202Accepted"/> response.
/// </summary>
/// <param name="actionName">The name of the action to use for generating the URL.</param>
/// <param name="controllerName">The name of the controller to use for generating the URL.</param>
/// <param name="routeValues">The route data to use for generating the URL.</param>
/// <returns>The created <see cref="AcceptedAtActionResult"/> for the response.</returns>
[NonAction]
public virtual AcceptedAtActionResult AcceptedAtAction(string actionName, string controllerName, [ActionResultObjectValue] object routeValues)
=> AcceptedAtAction(actionName, controllerName, routeValues, value: null);
/// <summary>
/// Creates a <see cref="AcceptedAtActionResult"/> object that produces an <see cref="StatusCodes.Status202Accepted"/> response.
/// </summary>
/// <param name="actionName">The name of the action to use for generating the URL.</param>
/// <param name="routeValues">The route data to use for generating the URL.</param>
/// <param name="value">The optional content value to format in the entity body; may be null.</param>
/// <returns>The created <see cref="AcceptedAtActionResult"/> for the response.</returns>
[NonAction]
public virtual AcceptedAtActionResult AcceptedAtAction(string actionName, object routeValues, [ActionResultObjectValue] object value)
=> AcceptedAtAction(actionName, controllerName: null, routeValues: routeValues, value: value);
/// <summary>
/// Creates a <see cref="AcceptedAtActionResult"/> object that produces an <see cref="StatusCodes.Status202Accepted"/> response.
/// </summary>
/// <param name="actionName">The name of the action to use for generating the URL.</param>
/// <param name="controllerName">The name of the controller to use for generating the URL.</param>
/// <param name="routeValues">The route data to use for generating the URL.</param>
/// <param name="value">The optional content value to format in the entity body; may be null.</param>
/// <returns>The created <see cref="AcceptedAtActionResult"/> for the response.</returns>
[NonAction]
public virtual AcceptedAtActionResult AcceptedAtAction(
string actionName,
string controllerName,
object routeValues,
[ActionResultObjectValue] object value)
=> new AcceptedAtActionResult(actionName, controllerName, routeValues, value);
/// <summary>
/// Creates a <see cref="AcceptedAtRouteResult"/> object that produces an <see cref="StatusCodes.Status202Accepted"/> response.
/// </summary>
/// <param name="routeValues">The route data to use for generating the URL.</param>
/// <returns>The created <see cref="AcceptedAtRouteResult"/> for the response.</returns>
[NonAction]
public virtual AcceptedAtRouteResult AcceptedAtRoute([ActionResultObjectValue] object routeValues)
=> AcceptedAtRoute(routeName: null, routeValues: routeValues, value: null);
/// <summary>
/// Creates a <see cref="AcceptedAtRouteResult"/> object that produces an <see cref="StatusCodes.Status202Accepted"/> response.
/// </summary>
/// <param name="routeName">The name of the route to use for generating the URL.</param>
/// <returns>The created <see cref="AcceptedAtRouteResult"/> for the response.</returns>
[NonAction]
public virtual AcceptedAtRouteResult AcceptedAtRoute(string routeName)
=> AcceptedAtRoute(routeName, routeValues: null, value: null);
/// <summary>
/// Creates a <see cref="AcceptedAtRouteResult"/> object that produces an <see cref="StatusCodes.Status202Accepted"/> response.
/// </summary>
/// <param name="routeName">The name of the route to use for generating the URL.</param>
///<param name="routeValues">The route data to use for generating the URL.</param>
/// <returns>The created <see cref="AcceptedAtRouteResult"/> for the response.</returns>
[NonAction]
public virtual AcceptedAtRouteResult AcceptedAtRoute(string routeName, object routeValues)
=> AcceptedAtRoute(routeName, routeValues, value: null);
/// <summary>
/// Creates a <see cref="AcceptedAtRouteResult"/> object that produces an <see cref="StatusCodes.Status202Accepted"/> response.
/// </summary>
/// <param name="routeValues">The route data to use for generating the URL.</param>
/// <param name="value">The optional content value to format in the entity body; may be null.</param>
/// <returns>The created <see cref="AcceptedAtRouteResult"/> for the response.</returns>
[NonAction]
public virtual AcceptedAtRouteResult AcceptedAtRoute(object routeValues, [ActionResultObjectValue] object value)
=> AcceptedAtRoute(routeName: null, routeValues: routeValues, value: value);
/// <summary>
/// Creates a <see cref="AcceptedAtRouteResult"/> object that produces an <see cref="StatusCodes.Status202Accepted"/> response.
/// </summary>
/// <param name="routeName">The name of the route to use for generating the URL.</param>
/// <param name="routeValues">The route data to use for generating the URL.</param>
/// <param name="value">The optional content value to format in the entity body; may be null.</param>
/// <returns>The created <see cref="AcceptedAtRouteResult"/> for the response.</returns>
[NonAction]
public virtual AcceptedAtRouteResult AcceptedAtRoute(string routeName, object routeValues, [ActionResultObjectValue] object value)
=> new AcceptedAtRouteResult(routeName, routeValues, value);
/// <summary>
/// Creates a <see cref="ChallengeResult"/>.
/// </summary>
/// <returns>The created <see cref="ChallengeResult"/> for the response.</returns>
/// <remarks>
/// The behavior of this method depends on the <see cref="IAuthenticationService"/> in use.
/// <see cref="StatusCodes.Status401Unauthorized"/> and <see cref="StatusCodes.Status403Forbidden"/>
/// are among likely status results.
/// </remarks>
[NonAction]
public virtual ChallengeResult Challenge()
=> new ChallengeResult();
/// <summary>
/// Creates a <see cref="ChallengeResult"/> with the specified authentication schemes.
/// </summary>
/// <param name="authenticationSchemes">The authentication schemes to challenge.</param>
/// <returns>The created <see cref="ChallengeResult"/> for the response.</returns>
/// <remarks>
/// The behavior of this method depends on the <see cref="IAuthenticationService"/> in use.
/// <see cref="StatusCodes.Status401Unauthorized"/> and <see cref="StatusCodes.Status403Forbidden"/>
/// are among likely status results.
/// </remarks>
[NonAction]
public virtual ChallengeResult Challenge(params string[] authenticationSchemes)
=> new ChallengeResult(authenticationSchemes);
/// <summary>
/// Creates a <see cref="ChallengeResult"/> with the specified <paramref name="properties" />.
/// </summary>
/// <param name="properties"><see cref="AuthenticationProperties"/> used to perform the authentication
/// challenge.</param>
/// <returns>The created <see cref="ChallengeResult"/> for the response.</returns>
/// <remarks>
/// The behavior of this method depends on the <see cref="IAuthenticationService"/> in use.
/// <see cref="StatusCodes.Status401Unauthorized"/> and <see cref="StatusCodes.Status403Forbidden"/>
/// are among likely status results.
/// </remarks>
[NonAction]
public virtual ChallengeResult Challenge(AuthenticationProperties properties)
=> new ChallengeResult(properties);
/// <summary>
/// Creates a <see cref="ChallengeResult"/> with the specified authentication schemes and
/// <paramref name="properties" />.
/// </summary>
/// <param name="properties"><see cref="AuthenticationProperties"/> used to perform the authentication
/// challenge.</param>
/// <param name="authenticationSchemes">The authentication schemes to challenge.</param>
/// <returns>The created <see cref="ChallengeResult"/> for the response.</returns>
/// <remarks>
/// The behavior of this method depends on the <see cref="IAuthenticationService"/> in use.
/// <see cref="StatusCodes.Status401Unauthorized"/> and <see cref="StatusCodes.Status403Forbidden"/>
/// are among likely status results.
/// </remarks>
[NonAction]
public virtual ChallengeResult Challenge(
AuthenticationProperties properties,
params string[] authenticationSchemes)
=> new ChallengeResult(authenticationSchemes, properties);
/// <summary>
/// Creates a <see cref="ForbidResult"/> (<see cref="StatusCodes.Status403Forbidden"/> by default).
/// </summary>
/// <returns>The created <see cref="ForbidResult"/> for the response.</returns>
/// <remarks>
/// Some authentication schemes, such as cookies, will convert <see cref="StatusCodes.Status403Forbidden"/> to
/// a redirect to show a login page.
/// </remarks>
[NonAction]
public virtual ForbidResult Forbid()
=> new ForbidResult();
/// <summary>
/// Creates a <see cref="ForbidResult"/> (<see cref="StatusCodes.Status403Forbidden"/> by default) with the
/// specified authentication schemes.
/// </summary>
/// <param name="authenticationSchemes">The authentication schemes to challenge.</param>
/// <returns>The created <see cref="ForbidResult"/> for the response.</returns>
/// <remarks>
/// Some authentication schemes, such as cookies, will convert <see cref="StatusCodes.Status403Forbidden"/> to
/// a redirect to show a login page.
/// </remarks>
[NonAction]
public virtual ForbidResult Forbid(params string[] authenticationSchemes)
=> new ForbidResult(authenticationSchemes);
/// <summary>
/// Creates a <see cref="ForbidResult"/> (<see cref="StatusCodes.Status403Forbidden"/> by default) with the
/// specified <paramref name="properties" />.
/// </summary>
/// <param name="properties"><see cref="AuthenticationProperties"/> used to perform the authentication
/// challenge.</param>
/// <returns>The created <see cref="ForbidResult"/> for the response.</returns>
/// <remarks>
/// Some authentication schemes, such as cookies, will convert <see cref="StatusCodes.Status403Forbidden"/> to
/// a redirect to show a login page.
/// </remarks>
[NonAction]
public virtual ForbidResult Forbid(AuthenticationProperties properties)
=> new ForbidResult(properties);
/// <summary>
/// Creates a <see cref="ForbidResult"/> (<see cref="StatusCodes.Status403Forbidden"/> by default) with the
/// specified authentication schemes and <paramref name="properties" />.
/// </summary>
/// <param name="properties"><see cref="AuthenticationProperties"/> used to perform the authentication
/// challenge.</param>
/// <param name="authenticationSchemes">The authentication schemes to challenge.</param>
/// <returns>The created <see cref="ForbidResult"/> for the response.</returns>
/// <remarks>
/// Some authentication schemes, such as cookies, will convert <see cref="StatusCodes.Status403Forbidden"/> to
/// a redirect to show a login page.
/// </remarks>
[NonAction]
public virtual ForbidResult Forbid(AuthenticationProperties properties, params string[] authenticationSchemes)
=> new ForbidResult(authenticationSchemes, properties);
/// <summary>
/// Creates a <see cref="SignInResult"/>.
/// </summary>
/// <param name="principal">The <see cref="ClaimsPrincipal"/> containing the user claims.</param>
/// <returns>The created <see cref="SignInResult"/> for the response.</returns>
[NonAction]
public virtual SignInResult SignIn(ClaimsPrincipal principal)
=> new SignInResult(principal);
/// <summary>
/// Creates a <see cref="SignInResult"/> with the specified authentication scheme.
/// </summary>
/// <param name="principal">The <see cref="ClaimsPrincipal"/> containing the user claims.</param>
/// <param name="authenticationScheme">The authentication scheme to use for the sign-in operation.</param>
/// <returns>The created <see cref="SignInResult"/> for the response.</returns>
[NonAction]
public virtual SignInResult SignIn(ClaimsPrincipal principal, string authenticationScheme)
=> new SignInResult(authenticationScheme, principal);
/// <summary>
/// Creates a <see cref="SignInResult"/> with <paramref name="properties"/>.
/// </summary>
/// <param name="principal">The <see cref="ClaimsPrincipal"/> containing the user claims.</param>
/// <param name="properties"><see cref="AuthenticationProperties"/> used to perform the sign-in operation.</param>
/// <returns>The created <see cref="SignInResult"/> for the response.</returns>
[NonAction]
public virtual SignInResult SignIn(
ClaimsPrincipal principal,
AuthenticationProperties properties)
=> new SignInResult(principal, properties);
/// <summary>
/// Creates a <see cref="SignInResult"/> with the specified authentication scheme and
/// <paramref name="properties" />.
/// </summary>
/// <param name="principal">The <see cref="ClaimsPrincipal"/> containing the user claims.</param>
/// <param name="properties"><see cref="AuthenticationProperties"/> used to perform the sign-in operation.</param>
/// <param name="authenticationScheme">The authentication scheme to use for the sign-in operation.</param>
/// <returns>The created <see cref="SignInResult"/> for the response.</returns>
[NonAction]
public virtual SignInResult SignIn(
ClaimsPrincipal principal,
AuthenticationProperties properties,
string authenticationScheme)
=> new SignInResult(authenticationScheme, principal, properties);
/// <summary>
/// Creates a <see cref="SignOutResult"/>.
/// </summary>
/// <returns>The created <see cref="SignOutResult"/> for the response.</returns>
[NonAction]
public virtual SignOutResult SignOut()
=> new SignOutResult();
/// <summary>
/// Creates a <see cref="SignOutResult"/> with <paramref name="properties"/>.
/// </summary>
/// <param name="properties"><see cref="AuthenticationProperties"/> used to perform the sign-out operation.</param>
/// <returns>The created <see cref="SignOutResult"/> for the response.</returns>
[NonAction]
public virtual SignOutResult SignOut(AuthenticationProperties properties)
=> new SignOutResult(properties);
/// <summary>
/// Creates a <see cref="SignOutResult"/> with the specified authentication schemes.
/// </summary>
/// <param name="authenticationSchemes">The authentication schemes to use for the sign-out operation.</param>
/// <returns>The created <see cref="SignOutResult"/> for the response.</returns>
[NonAction]
public virtual SignOutResult SignOut(params string[] authenticationSchemes)
=> new SignOutResult(authenticationSchemes);
/// <summary>
/// Creates a <see cref="SignOutResult"/> with the specified authentication schemes and
/// <paramref name="properties" />.
/// </summary>
/// <param name="properties"><see cref="AuthenticationProperties"/> used to perform the sign-out operation.</param>
/// <param name="authenticationSchemes">The authentication scheme to use for the sign-out operation.</param>
/// <returns>The created <see cref="SignOutResult"/> for the response.</returns>
[NonAction]
public virtual SignOutResult SignOut(AuthenticationProperties properties, params string[] authenticationSchemes)
=> new SignOutResult(authenticationSchemes, properties);
/// <summary>
/// Updates the specified <paramref name="model"/> instance using values from the controller's current
/// <see cref="IValueProvider"/>.
/// </summary>
/// <typeparam name="TModel">The type of the model object.</typeparam>
/// <param name="model">The model instance to update.</param>
/// <returns>A <see cref="Task"/> that on completion returns <c>true</c> if the update is successful.</returns>
[NonAction]
public virtual Task<bool> TryUpdateModelAsync<TModel>(
TModel model)
where TModel : class
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
return TryUpdateModelAsync(model, prefix: string.Empty);
}
/// <summary>
/// Updates the specified <paramref name="model"/> instance using values from the controller's current
/// <see cref="IValueProvider"/> and a <paramref name="prefix"/>.
/// </summary>
/// <typeparam name="TModel">The type of the model object.</typeparam>
/// <param name="model">The model instance to update.</param>
/// <param name="prefix">The prefix to use when looking up values in the current <see cref="IValueProvider"/>.
/// </param>
/// <returns>A <see cref="Task"/> that on completion returns <c>true</c> if the update is successful.</returns>
[NonAction]
public virtual async Task<bool> TryUpdateModelAsync<TModel>(
TModel model,
string prefix)
where TModel : class
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (prefix == null)
{
throw new ArgumentNullException(nameof(prefix));
}
var (success, valueProvider) = await CompositeValueProvider.TryCreateAsync(ControllerContext, ControllerContext.ValueProviderFactories);
if (!success)
{
return false;
}
return await TryUpdateModelAsync(model, prefix, valueProvider);
}
/// <summary>
/// Updates the specified <paramref name="model"/> instance using the <paramref name="valueProvider"/> and a
/// <paramref name="prefix"/>.
/// </summary>
/// <typeparam name="TModel">The type of the model object.</typeparam>
/// <param name="model">The model instance to update.</param>
/// <param name="prefix">The prefix to use when looking up values in the <paramref name="valueProvider"/>.
/// </param>
/// <param name="valueProvider">The <see cref="IValueProvider"/> used for looking up values.</param>
/// <returns>A <see cref="Task"/> that on completion returns <c>true</c> if the update is successful.</returns>
[NonAction]
public virtual Task<bool> TryUpdateModelAsync<TModel>(
TModel model,
string prefix,
IValueProvider valueProvider)
where TModel : class
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (prefix == null)
{
throw new ArgumentNullException(nameof(prefix));
}
if (valueProvider == null)
{
throw new ArgumentNullException(nameof(valueProvider));
}
return ModelBindingHelper.TryUpdateModelAsync(
model,
prefix,
ControllerContext,
MetadataProvider,
ModelBinderFactory,
valueProvider,
ObjectValidator);
}
/// <summary>
/// Updates the specified <paramref name="model"/> instance using values from the controller's current
/// <see cref="IValueProvider"/> and a <paramref name="prefix"/>.
/// </summary>
/// <typeparam name="TModel">The type of the model object.</typeparam>
/// <param name="model">The model instance to update.</param>
/// <param name="prefix">The prefix to use when looking up values in the current <see cref="IValueProvider"/>.
/// </param>
/// <param name="includeExpressions"> <see cref="Expression"/>(s) which represent top-level properties
/// which need to be included for the current model.</param>
/// <returns>A <see cref="Task"/> that on completion returns <c>true</c> if the update is successful.</returns>
[NonAction]
public async Task<bool> TryUpdateModelAsync<TModel>(
TModel model,
string prefix,
params Expression<Func<TModel, object>>[] includeExpressions)
where TModel : class
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (includeExpressions == null)
{
throw new ArgumentNullException(nameof(includeExpressions));
}
var (success, valueProvider) = await CompositeValueProvider.TryCreateAsync(ControllerContext, ControllerContext.ValueProviderFactories);
if (!success)
{
return false;
}
return await ModelBindingHelper.TryUpdateModelAsync(
model,
prefix,
ControllerContext,
MetadataProvider,
ModelBinderFactory,
valueProvider,
ObjectValidator,
includeExpressions);
}
/// <summary>
/// Updates the specified <paramref name="model"/> instance using values from the controller's current
/// <see cref="IValueProvider"/> and a <paramref name="prefix"/>.
/// </summary>
/// <typeparam name="TModel">The type of the model object.</typeparam>
/// <param name="model">The model instance to update.</param>
/// <param name="prefix">The prefix to use when looking up values in the current <see cref="IValueProvider"/>.
/// </param>
/// <param name="propertyFilter">A predicate which can be used to filter properties at runtime.</param>
/// <returns>A <see cref="Task"/> that on completion returns <c>true</c> if the update is successful.</returns>
[NonAction]
public async Task<bool> TryUpdateModelAsync<TModel>(
TModel model,
string prefix,
Func<ModelMetadata, bool> propertyFilter)
where TModel : class
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (propertyFilter == null)
{
throw new ArgumentNullException(nameof(propertyFilter));
}
var (success, valueProvider) = await CompositeValueProvider.TryCreateAsync(ControllerContext, ControllerContext.ValueProviderFactories);
if (!success)
{
return false;
}
return await ModelBindingHelper.TryUpdateModelAsync(
model,
prefix,
ControllerContext,
MetadataProvider,
ModelBinderFactory,
valueProvider,
ObjectValidator,
propertyFilter);
}
/// <summary>
/// Updates the specified <paramref name="model"/> instance using the <paramref name="valueProvider"/> and a
/// <paramref name="prefix"/>.
/// </summary>
/// <typeparam name="TModel">The type of the model object.</typeparam>
/// <param name="model">The model instance to update.</param>
/// <param name="prefix">The prefix to use when looking up values in the <paramref name="valueProvider"/>.
/// </param>
/// <param name="valueProvider">The <see cref="IValueProvider"/> used for looking up values.</param>
/// <param name="includeExpressions"> <see cref="Expression"/>(s) which represent top-level properties
/// which need to be included for the current model.</param>
/// <returns>A <see cref="Task"/> that on completion returns <c>true</c> if the update is successful.</returns>
[NonAction]
public Task<bool> TryUpdateModelAsync<TModel>(
TModel model,
string prefix,
IValueProvider valueProvider,
params Expression<Func<TModel, object>>[] includeExpressions)
where TModel : class
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (valueProvider == null)
{
throw new ArgumentNullException(nameof(valueProvider));
}
if (includeExpressions == null)
{
throw new ArgumentNullException(nameof(includeExpressions));
}
return ModelBindingHelper.TryUpdateModelAsync(
model,
prefix,
ControllerContext,
MetadataProvider,
ModelBinderFactory,
valueProvider,
ObjectValidator,
includeExpressions);
}
/// <summary>
/// Updates the specified <paramref name="model"/> instance using the <paramref name="valueProvider"/> and a
/// <paramref name="prefix"/>.
/// </summary>
/// <typeparam name="TModel">The type of the model object.</typeparam>
/// <param name="model">The model instance to update.</param>
/// <param name="prefix">The prefix to use when looking up values in the <paramref name="valueProvider"/>.
/// </param>
/// <param name="valueProvider">The <see cref="IValueProvider"/> used for looking up values.</param>
/// <param name="propertyFilter">A predicate which can be used to filter properties at runtime.</param>
/// <returns>A <see cref="Task"/> that on completion returns <c>true</c> if the update is successful.</returns>
[NonAction]
public Task<bool> TryUpdateModelAsync<TModel>(
TModel model,
string prefix,
IValueProvider valueProvider,
Func<ModelMetadata, bool> propertyFilter)
where TModel : class
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (valueProvider == null)
{
throw new ArgumentNullException(nameof(valueProvider));
}
if (propertyFilter == null)
{
throw new ArgumentNullException(nameof(propertyFilter));
}
return ModelBindingHelper.TryUpdateModelAsync(
model,
prefix,
ControllerContext,
MetadataProvider,
ModelBinderFactory,
valueProvider,
ObjectValidator,
propertyFilter);
}
/// <summary>
/// Updates the specified <paramref name="model"/> instance using values from the controller's current
/// <see cref="IValueProvider"/> and a <paramref name="prefix"/>.
/// </summary>
/// <param name="model">The model instance to update.</param>
/// <param name="modelType">The type of model instance to update.</param>
/// <param name="prefix">The prefix to use when looking up values in the current <see cref="IValueProvider"/>.
/// </param>
/// <returns>A <see cref="Task"/> that on completion returns <c>true</c> if the update is successful.</returns>
[NonAction]
public virtual async Task<bool> TryUpdateModelAsync(
object model,
Type modelType,
string prefix)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (modelType == null)
{
throw new ArgumentNullException(nameof(modelType));
}
var (success, valueProvider) = await CompositeValueProvider.TryCreateAsync(ControllerContext, ControllerContext.ValueProviderFactories);
if (!success)
{
return false;
}
return await ModelBindingHelper.TryUpdateModelAsync(
model,
modelType,
prefix,
ControllerContext,
MetadataProvider,
ModelBinderFactory,
valueProvider,
ObjectValidator);
}
/// <summary>
/// Updates the specified <paramref name="model"/> instance using the <paramref name="valueProvider"/> and a
/// <paramref name="prefix"/>.
/// </summary>
/// <param name="model">The model instance to update.</param>
/// <param name="modelType">The type of model instance to update.</param>
/// <param name="prefix">The prefix to use when looking up values in the <paramref name="valueProvider"/>.
/// </param>
/// <param name="valueProvider">The <see cref="IValueProvider"/> used for looking up values.</param>
/// <param name="propertyFilter">A predicate which can be used to filter properties at runtime.</param>
/// <returns>A <see cref="Task"/> that on completion returns <c>true</c> if the update is successful.</returns>
[NonAction]
public Task<bool> TryUpdateModelAsync(
object model,
Type modelType,
string prefix,
IValueProvider valueProvider,
Func<ModelMetadata, bool> propertyFilter)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (modelType == null)
{
throw new ArgumentNullException(nameof(modelType));
}
if (valueProvider == null)
{
throw new ArgumentNullException(nameof(valueProvider));
}
if (propertyFilter == null)
{
throw new ArgumentNullException(nameof(propertyFilter));
}
return ModelBindingHelper.TryUpdateModelAsync(
model,
modelType,
prefix,
ControllerContext,
MetadataProvider,
ModelBinderFactory,
valueProvider,
ObjectValidator,
propertyFilter);
}
/// <summary>
/// Validates the specified <paramref name="model"/> instance.
/// </summary>
/// <param name="model">The model to validate.</param>
/// <returns><c>true</c> if the <see cref="ModelState"/> is valid; <c>false</c> otherwise.</returns>
[NonAction]
public virtual bool TryValidateModel(
object model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
return TryValidateModel(model, prefix: null);
}
/// <summary>
/// Validates the specified <paramref name="model"/> instance.
/// </summary>
/// <param name="model">The model to validate.</param>
/// <param name="prefix">The key to use when looking up information in <see cref="ModelState"/>.
/// </param>
/// <returns><c>true</c> if the <see cref="ModelState"/> is valid;<c>false</c> otherwise.</returns>
[NonAction]
public virtual bool TryValidateModel(
object model,
string prefix)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
ObjectValidator.Validate(
ControllerContext,
validationState: null,
prefix: prefix ?? string.Empty,
model: model);
return ModelState.IsValid;
}
}
}
| 53.213087 | 210 | 0.623708 | [
"Apache-2.0"
] | 1kevgriff/aspnetcore | src/Mvc/Mvc.Core/src/ControllerBase.cs | 155,329 | C# |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using Windows.Devices.Geolocation;
using Windows.Foundation;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace SDKTemplate
{
public sealed partial class Scenario1_TrackPosition : Page
{
// Proides access to location data
private Geolocator _geolocator = null;
// A pointer to the main page
private MainPage _rootPage = MainPage.Current;
public Scenario1_TrackPosition()
{
this.InitializeComponent();
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
if (_geolocator != null)
{
_geolocator.PositionChanged -= OnPositionChanged;
_geolocator.StatusChanged -= OnStatusChanged;
}
}
/// <summary>
/// This is the click handler for the 'StartTracking' button.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void StartTracking(object sender, RoutedEventArgs e)
{
// Request permission to access location
var accessStatus = await Geolocator.RequestAccessAsync();
switch (accessStatus)
{
case GeolocationAccessStatus.Allowed:
// You should set MovementThreshold for distance-based tracking
// or ReportInterval for periodic-based tracking before adding event
// handlers. If none is set, a ReportInterval of 1 second is used
// as a default and a position will be returned every 1 second.
//
// Value of 2000 milliseconds (2 seconds)
// isn't a requirement, it is just an example.
_geolocator = new Geolocator { ReportInterval = 2000 };
// Subscribe to PositionChanged event to get updated tracking positions
_geolocator.PositionChanged += OnPositionChanged;
// Subscribe to StatusChanged event to get updates of location status changes
_geolocator.StatusChanged += OnStatusChanged;
_rootPage.NotifyUser("Waiting for update...", NotifyType.StatusMessage);
LocationDisabledMessage.Visibility = Visibility.Collapsed;
StartTrackingButton.IsEnabled = false;
StopTrackingButton.IsEnabled = true;
break;
case GeolocationAccessStatus.Denied:
_rootPage.NotifyUser("Access to location is denied.", NotifyType.ErrorMessage);
LocationDisabledMessage.Visibility = Visibility.Visible;
break;
case GeolocationAccessStatus.Unspecified:
_rootPage.NotifyUser("Unspecificed error!", NotifyType.ErrorMessage);
LocationDisabledMessage.Visibility = Visibility.Collapsed;
break;
}
}
/// <summary>
/// This is the click handler for the 'StopTracking' button.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void StopTracking(object sender, RoutedEventArgs e)
{
_geolocator.PositionChanged -= OnPositionChanged;
_geolocator.StatusChanged -= OnStatusChanged;
_geolocator = null;
StartTrackingButton.IsEnabled = true;
StopTrackingButton.IsEnabled = false;
// Clear status
_rootPage.NotifyUser("", NotifyType.StatusMessage);
}
/// <summary>
/// Event handler for PositionChanged events. It is raised when
/// a location is available for the tracking session specified.
/// </summary>
/// <param name="sender">Geolocator instance</param>
/// <param name="e">Position data</param>
async private void OnPositionChanged(Geolocator sender, PositionChangedEventArgs e)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
_rootPage.NotifyUser("Location updated.", NotifyType.StatusMessage);
UpdateLocationData(e.Position);
});
}
/// <summary>
/// Event handler for StatusChanged events. It is raised when the
/// location status in the system changes.
/// </summary>
/// <param name="sender">Geolocator instance</param>
/// <param name="e">Statu data</param>
async private void OnStatusChanged(Geolocator sender, StatusChangedEventArgs e)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
// Show the location setting message only if status is disabled.
LocationDisabledMessage.Visibility = Visibility.Collapsed;
switch (e.Status)
{
case PositionStatus.Ready:
// Location platform is providing valid data.
ScenarioOutput_Status.Text = "Ready";
_rootPage.NotifyUser("Location platform is ready.", NotifyType.StatusMessage);
break;
case PositionStatus.Initializing:
// Location platform is attempting to acquire a fix.
ScenarioOutput_Status.Text = "Initializing";
_rootPage.NotifyUser("Location platform is attempting to obtain a position.", NotifyType.StatusMessage);
break;
case PositionStatus.NoData:
// Location platform could not obtain location data.
ScenarioOutput_Status.Text = "No data";
_rootPage.NotifyUser("Not able to determine the location.", NotifyType.ErrorMessage);
break;
case PositionStatus.Disabled:
// The permission to access location data is denied by the user or other policies.
ScenarioOutput_Status.Text = "Disabled";
_rootPage.NotifyUser("Access to location is denied.", NotifyType.ErrorMessage);
// Show message to the user to go to location settings
LocationDisabledMessage.Visibility = Visibility.Visible;
// Clear cached location data if any
UpdateLocationData(null);
break;
case PositionStatus.NotInitialized:
// The location platform is not initialized. This indicates that the application
// has not made a request for location data.
ScenarioOutput_Status.Text = "Not initialized";
_rootPage.NotifyUser("No request for location is made yet.", NotifyType.StatusMessage);
break;
case PositionStatus.NotAvailable:
// The location platform is not available on this version of the OS.
ScenarioOutput_Status.Text = "Not available";
_rootPage.NotifyUser("Location is not available on this version of the OS.", NotifyType.ErrorMessage);
break;
default:
ScenarioOutput_Status.Text = "Unknown";
_rootPage.NotifyUser(string.Empty, NotifyType.StatusMessage);
break;
}
});
}
/// <summary>
/// Updates the user interface with the Geoposition data provided
/// </summary>
/// <param name="position">Geoposition to display its details</param>
private void UpdateLocationData(Geoposition position)
{
if (position == null)
{
ScenarioOutput_Latitude.Text = "No data";
ScenarioOutput_Longitude.Text = "No data";
ScenarioOutput_Accuracy.Text = "No data";
ScenarioOutput_IsRemoteSource.Text = "No data";
}
else
{
ScenarioOutput_Latitude.Text = position.Coordinate.Point.Position.Latitude.ToString();
ScenarioOutput_Longitude.Text = position.Coordinate.Point.Position.Longitude.ToString();
ScenarioOutput_Accuracy.Text = position.Coordinate.Accuracy.ToString();
ScenarioOutput_IsRemoteSource.Text = position.Coordinate.IsRemoteSource.ToString();
}
}
}
}
| 44.603774 | 129 | 0.554357 | [
"MIT"
] | ayhrgr/Windows-universal-samples | Samples/Geolocation/cs/Scenario1_TrackPosition.xaml.cs | 9,247 | C# |
using MonkeyConfAr.ViewModels;
using Xamarin.Forms;
namespace MonkeyConfAr.Views
{
public partial class PlaneTrackingPage : ContentPage
{
public PlaneTrackingPageViewModel ViewModel
{
get => BindingContext as PlaneTrackingPageViewModel;
}
public PlaneTrackingPage()
{
InitializeComponent();
}
protected override async void OnAppearing()
{
base.OnAppearing();
await ViewModel.InitializeArAsync(_arSurface);
}
}
} | 21.92 | 64 | 0.614964 | [
"MIT"
] | r2d2rigo/MonkeyConfAR | src/MonkeyConfAr/MonkeyConfAr/Views/PlaneTrackingPage.xaml.cs | 550 | C# |
/* _BEGIN_TEMPLATE_
{
"id": "CFM_654",
"name": [
"热心的酒保",
"Friendly Bartender"
],
"text": [
"在你的回合结束时,为你的英雄恢复#1点生命值。",
"At the end of your turn, restore #1 Health to your hero."
],
"cardClass": "NEUTRAL",
"type": "MINION",
"cost": 2,
"rarity": "COMMON",
"set": "GANGS",
"collectible": true,
"dbfId": 40914
}
_END_TEMPLATE_ */
namespace HREngine.Bots
{
class Sim_CFM_654 : SimTemplate //* Friendly Bartender
{
// At the end of your turn, restore 1 Health to your Hero.
public override void onTurnEndsTrigger(Playfield p, Minion triggerEffectMinion, bool turnEndOfOwner)
{
if (triggerEffectMinion.own == turnEndOfOwner)
{
if (triggerEffectMinion.own)
{
var heal = p.getMinionHeal(1);
p.minionGetDamageOrHeal(p.ownHero, -heal, true);
}
else
{
var heal = p.getEnemyMinionHeal(1);
p.minionGetDamageOrHeal(p.enemyHero, -heal, true);
}
}
}
}
} | 24.170213 | 108 | 0.523768 | [
"MIT"
] | chi-rei-den/Silverfish | cards/GANGS/CFM/Sim_CFM_654.cs | 1,189 | C# |
using TableauCri.Models.Configuration;
namespace TableauCri.Models.Configuration
{
public class TableauApiSettingsSource : TableauApiSettings { }
}
| 21.857143 | 66 | 0.816993 | [
"Apache-2.0"
] | sgchoe/TableauCri | TableauCri/Models/Configuration/TableauApiSettingsSource.cs | 153 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
namespace PSDocs.Models
{
public sealed class Text : DocumentNode
{
public override DocumentNodeType Type => DocumentNodeType.Text;
public string Content { get; set; }
}
}
| 21.384615 | 71 | 0.679856 | [
"MIT"
] | BernieWhite/PSDocs | src/PSDocs/Models/Text.cs | 280 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using ServiceStack.Formats;
using ServiceStack.Html;
using ServiceStack.Markdown;
using ServiceStack.Support.Markdown;
using ServiceStack.Testing;
using ServiceStack.VirtualPath;
namespace ServiceStack.ServiceHost.Tests.Formats
{
public class ExternalProductHelper
{
//Any helpers returning MvcHtmlString won't be escaped
public MvcHtmlString ProductTable(List<Product> products)
{
var sb = new StringBuilder();
sb.AppendFormat("<table><thead><tr><th>Id</th><th>Name</th><th>Price</th></tr></thead><tbody>\n");
products.ForEach(x =>
sb.AppendFormat("<tr><th>{0}</th><th>{1}</th><th>{2}</th></tr>\n",
x.ProductID, x.Name, x.Price)
);
sb.AppendFormat("</tbody></table>\n");
return MvcHtmlString.Create(sb.ToString());
}
}
public class CustomBaseClass<T> : MarkdownViewBase<T>
{
public MvcHtmlString Field(string fieldName, string fieldValue)
{
var sb = new StringBuilder();
sb.AppendFormat("<label for='{0}'>{0}</label>\n", fieldName);
sb.AppendFormat("<input name='{0}' value='{1}'/>\n", fieldName, fieldValue);
return MvcHtmlString.Create(sb.ToString());
}
}
[TestFixture]
public class IntroductionLayoutTests : MarkdownTestBase
{
private InMemoryVirtualPathProvider pathProvider;
private MarkdownFormat markdownFormat;
private ServiceStackHost appHost;
[TestFixtureSetUp]
public void TestFixtureSetUp()
{
appHost = new BasicAppHost().Init();
}
[TestFixtureTearDown]
public void TestFixtureTearDown()
{
appHost.Dispose();
}
[SetUp]
public void SetUp()
{
ServiceStackHost.Instance.VirtualFileSources = pathProvider = new InMemoryVirtualPathProvider(new BasicAppHost());
markdownFormat = new MarkdownFormat
{
VirtualPathProvider = pathProvider,
};
}
[Test]
public void Simple_Layout_Example()
{
var websiteTemplate =
@"<!DOCTYPE html>
<html>
<head>
<title>Simple Site</title>
</head>
<body>
<div id=""header"">
<a href=""/"">Home</a>
<a href=""/About"">About</a>
</div>
<div id=""body"">
<!--@Body-->
</div>
</body>
</html>".NormalizeNewLines();
var pageTemplate =
@"@Layout websiteTemplate
# About this Site
This is some content that will make up the ""about""
page of our web-site. We'll use this in conjunction
with a layout template. The content you are seeing here
comes from ^^^websiteTemplate.
And obviously I can have code in here too. Here is the
current date/year: @DateTime.Now.Year
".NormalizeNewLines();
var expectedHtml = @"<!DOCTYPE html>
<html>
<head>
<title>Simple Site</title>
</head>
<body>
<div id=""header"">
<a href=""/"">Home</a>
<a href=""/About"">About</a>
</div>
<div id=""body"">
<h1>About this Site</h1>
<p>This is some content that will make up the "about"
page of our web-site. We'll use this in conjunction
with a layout template. The content you are seeing here
comes from ^^^websiteTemplate.</p>
<p>And obviously I can have code in here too. Here is the
current date/year: 2016</p>
</div>
</body>
</html>".NormalizeNewLines();
markdownFormat.AddFileAndPage(
new MarkdownPage(markdownFormat, @"C:\path\to\page-tpl", PageName, pageTemplate));
markdownFormat.AddFileAndTemplate(@"websiteTemplate", websiteTemplate);
var html = markdownFormat.RenderDynamicPageHtml(PageName);
Console.WriteLine(html);
Assert.That(html, Is.EqualTo(expectedHtml));
}
[Test]
public void Layout_MasterPage_Scenarios_Adding_Sections()
{
var websiteTemplate =
@"<!DOCTYPE html>
<html>
<head>
<title>Simple Site</title>
</head>
<body>
<div id=""header"">
<a href=""/"">Home</a>
<a href=""/About"">About</a>
</div>
<div id=""left-menu"">
<!--@Menu-->
</div>
<div id=""body"">
<!--@Body-->
</div>
<div id=""footer"">
<!--@Footer-->
</div>
</body>
</html>".NormalizeNewLines();
var pageTemplate =
@"@Layout websiteTemplate
# About this Site
This is some content that will make up the ""about""
page of our web-site. We'll use this in conjunction
with a layout template. The content you are seeing here
comes from ^^^websiteTemplate.
And obviously I can have code in here too. Here is the
current date/year: @DateTime.Now.Year
@section Menu {
- About Item 1
- About Item 2
}
@section Footer {
This is my custom footer for Home
}
".NormalizeNewLines();
var expectedHtml = @"<!DOCTYPE html>
<html>
<head>
<title>Simple Site</title>
</head>
<body>
<div id=""header"">
<a href=""/"">Home</a>
<a href=""/About"">About</a>
</div>
<div id=""left-menu"">
<ul>
<li>About Item 1</li>
<li>About Item 2</li>
</ul>
</div>
<div id=""body"">
<h1>About this Site</h1>
<p>This is some content that will make up the "about"
page of our web-site. We'll use this in conjunction
with a layout template. The content you are seeing here
comes from ^^^websiteTemplate.</p>
<p>And obviously I can have code in here too. Here is the
current date/year: 2016</p>
</div>
<div id=""footer"">
<p>This is my custom footer for Home</p>
</div>
</body>
</html>".NormalizeNewLines();
markdownFormat.AddPage(
new MarkdownPage(markdownFormat, @"C:\path\to\page-tpl", PageName, pageTemplate));
markdownFormat.AddFileAndTemplate(@"websiteTemplate", websiteTemplate);
var html = markdownFormat.RenderDynamicPageHtml(PageName);
Console.WriteLine(html);
Assert.That(html, Is.EqualTo(expectedHtml));
}
[Test]
public void Encapsulation_and_reuse_with_HTML_helpers()
{
var pageTemplate =
@"@model ServiceStack.ServiceHost.Tests.Formats.Product
<fieldset>
<legend>Edit Product</legend>
<div>
@Html.LabelFor(m => m.ProductID)
</div>
<div>
@Html.TextBoxFor(m => m.ProductID)
</div>
</fieldset>".NormalizeNewLines();
var expectedHtml =
@"<fieldset>
<legend>Edit Product</legend>
<div>
<label for=""ProductID"">ProductID</label> </div>
<div>
<input id=""ProductID"" name=""ProductID"" type=""text"" value=""10"" /> </div>
</fieldset>".NormalizeNewLines();
var product = new Product { ProductID = 10 };
var html = RenderToHtml(pageTemplate, product);
Console.WriteLine(html);
Assert.That(html, Is.EqualTo(expectedHtml));
}
[Test]
public void Using_External_HTML_Helpers()
{
var pageTemplate =
@"@model System.Collections.Generic.List<ServiceStack.ServiceHost.Tests.Formats.Product>
@helper Prod: ServiceStack.ServiceHost.Tests.Formats.ExternalProductHelper
<fieldset>
<legend>All Products</legend>
@Prod.ProductTable(Model)
</fieldset>".NormalizeNewLines();
var expectedHtml =
@"<fieldset>
<legend>All Products</legend>
<table><thead><tr><th>Id</th><th>Name</th><th>Price</th></tr></thead><tbody>
<tr><th>0</th><th>Pen</th><th>1.99</th></tr>
<tr><th>0</th><th>Glass</th><th>9.99</th></tr>
<tr><th>0</th><th>Book</th><th>14.99</th></tr>
<tr><th>0</th><th>DVD</th><th>11.99</th></tr>
</tbody></table>
</fieldset>".NormalizeNewLines();
var products = new List<Product> {
new Product("Pen", 1.99m),
new Product("Glass", 9.99m),
new Product("Book", 14.99m),
new Product("DVD", 11.99m),
};
var html = RenderToHtml(pageTemplate, products);
Console.WriteLine(html);
Assert.That(html, Is.EqualTo(expectedHtml));
}
[Test]
public void Using_Custom_base_class()
{
var pageTemplate =
@"@inherits ServiceStack.ServiceHost.Tests.Formats.CustomBaseClass<ServiceStack.ServiceHost.Tests.Formats.Product>
<fieldset>
<legend>All Products</legend>
@Field(""Name"", Model.Name)
</fieldset>".NormalizeNewLines();
var expectedHtml =
@"<fieldset>
<legend>All Products</legend>
<label for='Name'>Name</label>
<input name='Name' value='Pen'/>
</fieldset>".NormalizeNewLines();
var html = RenderToHtml(pageTemplate, new Product("Pen", 1.99m));
Console.WriteLine(html);
Assert.That(html, Is.EqualTo(expectedHtml));
}
}
} | 27.942029 | 127 | 0.5611 | [
"Apache-2.0"
] | MinistryOfMagic/ServiceStack | tests/ServiceStack.ServiceHost.Tests/Formats/IntroductionLayoutTests.cs | 9,298 | C# |
namespace MBran.Components.Models
{
public class RenderOptionsDefinition
{
public string Name { get; set; }
public string Value { get; set; }
public string Description { get; set; }
}
}
| 23.2 | 48 | 0.594828 | [
"MIT"
] | markglibres/mbran-umbraco-components | src/MBran.Components/Models/RenderOptionsDefinition.cs | 234 | C# |
using System;
using System.Drawing;
using DotNet.Highcharts.Enums;
using DotNet.Highcharts.Attributes;
using DotNet.Highcharts.Helpers;
namespace DotNet.Highcharts.Options
{
/// <summary>
/// A wrapper object for all the series options in specific states.
/// </summary>
public class PlotOptionsScatterStates
{
/// <summary>
/// Options for the hovered series
/// </summary>
public PlotOptionsScatterStatesHover Hover { get; set; }
}
} | 21.52381 | 68 | 0.736726 | [
"MIT"
] | juniorgasparotto/SpentBook | samples/dotnethighcharts-28017/DotNet.Highcharts/DotNet.Highcharts/Options/PlotOptionsScatterStates.cs | 452 | C# |
using EasyPagination.Core.Extensions;
using Shouldly;
using Xunit;
namespace EasyPagination.Async.Tests;
public class AsyncPageTests
{
private readonly ICollection<Entity> _items;
public AsyncPageTests()
{
_items = EntityGenerator.Create(2500);
}
[Fact]
public async Task Should_provide_next_page_when_it_is_available()
{
var pageOptions = new PageOptions
{
PageSize = 100
};
var firstPage = await _items.ToAsyncEnumerable().GetPageAsync(pageOptions);
var secondPage = await firstPage.NextPageAsync();
secondPage.Items.Count.ShouldBe(100);
secondPage.Items.ShouldAllBe(i => 101 <= i.Id && i.Id <= 200);
secondPage.Settings.CurrentPage.ShouldBe(2);
secondPage.Settings.PageSize.ShouldBe(firstPage.Settings.PageSize);
secondPage.Settings.PageSize.ShouldBe(100);
}
[Fact]
public async Task Should_provide_null_for_next_page_when_current_page_is_last()
{
var pageOptions = new PageOptions
{
Page = 3
};
var page = await _items.ToAsyncEnumerable().GetPageAsync(pageOptions);
var nextPage = await page.NextPageAsync();
nextPage.ShouldBeNull();
}
[Fact]
public async Task Should_map_page()
{
var page = await _items.ToAsyncEnumerable().GetPageAsync(new PageOptions());
var mappedPage = page.Map(o => o.Id);
mappedPage.Items.First().ShouldBe(1);
}
[Fact]
public async Task Should_provide_next_page_when_current_page_is_mapped()
{
var page = await _items.ToAsyncEnumerable().GetPageAsync(new PageOptions());
var mappedPage = page.Map(o => o.Id);
var nextPage = await mappedPage.NextPageAsync();
nextPage.Items.First().ShouldBe(1001);
}
[Fact]
public async Task Should_map_page_when_current_page_is_mapped()
{
var page = await _items.ToAsyncEnumerable().GetPageAsync(new PageOptions());
var mappedPage = page.Map(o => o.Id);
var newMappedPage = mappedPage.Map(o => -o);
newMappedPage.Items.First().ShouldBe(-1);
}
[Fact]
public async Task Should_map_wrong_page_without_errors()
{
var page = await _items.ToAsyncEnumerable().GetPageAsync(new PageOptions
{
Page = 6
});
var mappedPage = page.Map(o => o.Id);
mappedPage.Items.Count.ShouldBe(0);
mappedPage.Settings.CurrentPage.ShouldBeNull();
}
} | 26.666667 | 84 | 0.637891 | [
"MIT"
] | morozyan/EasyPagination | src/EasyPagination.Async.Tests/AsyncPageTests.cs | 2,562 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using NBitcoin;
using Xels.Bitcoin.AsyncWork;
using Xels.Bitcoin.Base;
using Xels.Bitcoin.Utilities;
namespace Xels.Bitcoin.Features.BlockStore.Pruning
{
/// <inheritdoc/>
public sealed class PruneBlockStoreService : IPruneBlockStoreService
{
private IAsyncLoop asyncLoop;
private readonly IAsyncProvider asyncProvider;
private readonly IBlockRepository blockRepository;
private readonly IChainState chainState;
private readonly ILogger logger;
private readonly INodeLifetime nodeLifetime;
private readonly IPrunedBlockRepository prunedBlockRepository;
private readonly StoreSettings storeSettings;
/// <inheritdoc/>
public ChainedHeader PrunedUpToHeaderTip { get; private set; }
public PruneBlockStoreService(
IAsyncProvider asyncProvider,
IBlockRepository blockRepository,
IPrunedBlockRepository prunedBlockRepository,
IChainState chainState,
ILoggerFactory loggerFactory,
INodeLifetime nodeLifetime,
StoreSettings storeSettings)
{
this.asyncProvider = asyncProvider;
this.blockRepository = blockRepository;
this.prunedBlockRepository = prunedBlockRepository;
this.chainState = chainState;
this.logger = loggerFactory.CreateLogger(this.GetType().FullName);
this.nodeLifetime = nodeLifetime;
this.storeSettings = storeSettings;
}
/// <inheritdoc/>
public void Initialize()
{
this.PrunedUpToHeaderTip = this.chainState.BlockStoreTip.GetAncestor(this.prunedBlockRepository.PrunedTip.Height);
this.asyncLoop = this.asyncProvider.CreateAndRunAsyncLoop($"{this.GetType().Name}.{nameof(this.PruneBlocks)}", token =>
{
this.PruneBlocks();
return Task.CompletedTask;
},
this.nodeLifetime.ApplicationStopping,
repeatEvery: TimeSpans.TenSeconds);
}
/// <inheritdoc/>
public void PruneBlocks()
{
if (this.PrunedUpToHeaderTip == null)
throw new BlockStoreException($"{nameof(this.PrunedUpToHeaderTip)} has not been set, please call initialize first.");
if (this.blockRepository.TipHashAndHeight.Height < this.storeSettings.AmountOfBlocksToKeep)
{
this.logger.LogTrace("(-)[PRUNE_ABORTED_BLOCKSTORE_TIP_BELOW_AMOUNTOFBLOCKSTOKEEP]");
return;
}
if (this.blockRepository.TipHashAndHeight.Height == this.PrunedUpToHeaderTip.Height)
{
this.logger.LogTrace("(-)[PRUNE_ABORTED_BLOCKSTORE_TIP_EQUALS_PRUNEDTIP]");
return;
}
if (this.blockRepository.TipHashAndHeight.Height <= (this.PrunedUpToHeaderTip.Height + this.storeSettings.AmountOfBlocksToKeep))
{
this.logger.LogTrace("(-)[PRUNE_ABORTED_BLOCKSTORE_TIP_BELOW_OR_EQUAL_THRESHOLD]");
return;
}
int heightToPruneFrom = this.blockRepository.TipHashAndHeight.Height - this.storeSettings.AmountOfBlocksToKeep;
ChainedHeader startFrom = this.chainState.BlockStoreTip.GetAncestor(heightToPruneFrom);
if (startFrom == null)
{
this.logger.LogInformation("(-)[PRUNE_ABORTED_START_BLOCK_NOT_FOUND]{0}:{1}", nameof(heightToPruneFrom), heightToPruneFrom);
return;
}
this.logger.LogInformation("Pruning triggered, delete from {0} to {1}.", heightToPruneFrom, this.PrunedUpToHeaderTip.Height);
var chainedHeadersToDelete = new List<ChainedHeader>();
while (startFrom.Previous != null && this.PrunedUpToHeaderTip != startFrom)
{
chainedHeadersToDelete.Add(startFrom);
startFrom = startFrom.Previous;
}
this.logger.LogDebug("{0} blocks will be pruned.", chainedHeadersToDelete.Count);
ChainedHeader prunedTip = chainedHeadersToDelete.First();
this.blockRepository.DeleteBlocks(chainedHeadersToDelete.Select(c => c.HashBlock).ToList());
this.prunedBlockRepository.UpdatePrunedTip(prunedTip);
this.PrunedUpToHeaderTip = prunedTip;
this.logger.LogInformation($"Store has been pruned up to {this.PrunedUpToHeaderTip.Height}.");
}
/// <inheritdoc/>
public void Dispose()
{
this.asyncLoop?.Dispose();
}
}
}
| 39.857143 | 140 | 0.64727 | [
"MIT"
] | xels-io/SideChain-SmartContract | src/Xels.Bitcoin.Features.BlockStore/Pruning/PruneBlockStoreService.cs | 4,745 | C# |
using EventStore.Core.Exceptions;
using EventStore.Core.TransactionLog.Chunks.TFChunk;
using NUnit.Framework;
namespace EventStore.Core.Tests.TransactionLog
{
[TestFixture]
public class when_opening_tfchunk_from_non_existing_file: SpecificationWithFile
{
[Test]
public void it_should_throw_a_file_not_found_exception()
{
Assert.Throws<CorruptDatabaseException>(() => TFChunk.FromCompletedFile(Filename, verifyHash: true, unbufferedRead: false));
}
}
} | 32 | 136 | 0.740234 | [
"Apache-2.0"
] | shaan1337/EventStore | src/EventStore.Core.Tests/TransactionLog/when_opening_tfchunk_from_non_existing_file.cs | 512 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Prism.Navigation;
using ReactiveUI;
using Samples.Infrastructure;
using Shiny.Notifications;
namespace Samples.Notifications
{
public class ChannelListViewModel : ViewModel
{
public ChannelListViewModel(INavigationService navigator,
INotificationManager notifications,
IDialogs dialogs)
{
this.Create = navigator.NavigateCommand("ChannelCreate");
this.LoadChannels = ReactiveCommand.CreateFromTask(async () =>
{
var channels = await notifications.GetChannels();
this.Channels = channels
.Select(x => new CommandItem
{
Text = x.Identifier,
SecondaryCommand = ReactiveCommand.CreateFromTask(async () =>
{
var confirm = await dialogs.Confirm("Are you sure you wish to delete this channel?");
if (confirm)
{
await notifications.DeleteChannel(x.Identifier);
this.LoadChannels.Execute(null);
}
})
})
.ToList();
this.RaisePropertyChanged(nameof(this.Channels));
});
}
public ICommand Create { get; }
public ICommand LoadChannels { get; }
public IList<CommandItem> Channels { get; private set; }
public override void OnAppearing()
{
base.OnAppearing();
this.LoadChannels.Execute(null);
}
}
}
| 31.964912 | 113 | 0.511526 | [
"MIT"
] | moljac/shinysamples | Samples/Notifications/ChannelListViewModel.cs | 1,824 | C# |
using HotChocolate.Types;
using Snapshooter.Xunit;
using Xunit;
namespace HotChocolate.Data.Filters
{
public class EnumOperationInputTests
{
[Fact]
public void Create_OperationType()
{
// arrange
// act
ISchema schema = SchemaBuilder.New()
.AddQueryType(
t => t
.Name("Query")
.Field("foo")
.Type<StringType>()
.Resolver("foo")
.Argument("test", a => a.Type<EnumOperationInput<FooBar>>()))
.AddFiltering()
.Create();
// assert
schema.ToString().MatchSnapshot();
}
[Fact]
public void Create_Implicit_Operation()
{
// arrange
// act
ISchema schema = SchemaBuilder.New()
.AddQueryType(
t => t
.Name("Query")
.Field("foo")
.Type<StringType>()
.Resolver("foo")
.Argument("test", a => a.Type<FilterInputType<Foo>>()))
.AddFiltering()
.Create();
// assert
schema.ToString().MatchSnapshot();
}
[Fact]
public void Create_Explicit_Operation()
{
// arrange
// act
ISchema schema = SchemaBuilder.New()
.AddQueryType(
t => t
.Name("Query")
.Field("foo")
.Type<StringType>()
.Resolver("foo")
.Argument("test", a => a.Type<FooFilterType>()))
.TryAddConvention<IFilterConvention>(
(sp) => new FilterConvention(x => x.UseMock()))
.AddFiltering()
.Create();
// assert
schema.ToString().MatchSnapshot();
}
public class FooFilterType : FilterInputType
{
protected override void Configure(IFilterInputTypeDescriptor descriptor)
{
descriptor.Field("comparable").Type<EnumOperationInput<FooBar>>();
}
}
public class Foo
{
public FooBar FooBar { get; set; }
public FooBar? FooBarNullable { get; set; }
}
public enum FooBar
{
Foo,
Bar
}
}
} | 28.097826 | 85 | 0.42205 | [
"MIT"
] | damikun/hotchocolate | src/HotChocolate/Data/test/Data.Filters.Tests/Types/EnumOperationInputTypeTests.cs | 2,585 | C# |
////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Daniel Kollmann
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this list of conditions
// and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// - Neither the name of Daniel Kollmann nor the names of its contributors may be used to endorse
// or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
// WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
using Brainiac.Design.Properties;
namespace Brainiac.Design.Attributes
{
[AttributeUsage(AttributeTargets.Property)]
public class DesignerEnum : DesignerProperty
{
public enum ExportMode { Namespace_Type_Value, Type_Value, Value }
protected static ExportMode __exportMode= ExportMode.Namespace_Type_Value;
/// <summary>
/// Defines is enumerations are exported as Namespace.Enum.Value or simply as Value.
/// </summary>
public static ExportMode ExportTextMode
{
get { return __exportMode; }
set { __exportMode= value; }
}
protected static string __exportPrefix= string.Empty;
/// <summary>
/// This prefix is placed in front of the enum's value when exporting;
/// </summary>
public static string ExportPrefix
{
get { return __exportPrefix; }
set { __exportPrefix= value; }
}
protected object[] _excludedElements;
/// <summary>
/// The values of the enum which will not be shown in the designer.
/// </summary>
public object[] ExcludedElements
{
get { return _excludedElements; }
}
/// <summary>
/// Creates a new designer attribute for handling an enumeration value.
/// </summary>
/// <param name="displayName">The name shown on the node and in the property editor for the property.</param>
/// <param name="description">The description shown in the property editor for the property.</param>
/// <param name="category">The category shown in the property editor for the property.</param>
/// <param name="displayMode">Defines how the property is visualised in the editor.</param>
/// <param name="displayOrder">Defines the order the properties will be sorted in when shown in the property grid. Lower come first.</param>
/// <param name="flags">Defines the designer flags stored for the property.</param>
/// <param name="exclude">The enum values which will be excluded from the values shown in the designer.</param>
public DesignerEnum(string displayName, string description, string category, DisplayMode displayMode, int displayOrder, DesignerFlags flags, object[] exclude) : base(displayName, description, category, displayMode, displayOrder, flags, new EditorType[] { new EditorType("EditorValue", typeof(DesignerEnumEditor)) })
{
_excludedElements= exclude;
}
public override string GetDisplayValue(object obj)
{
Type type= obj.GetType();
if(!type.IsEnum)
throw new Exception( string.Format(Resources.ExceptionDesignerAttributeExpectedEnum, obj) );
int enumval= (int)obj;
string enumName= Enum.GetName(type, enumval);
if(enumName ==string.Empty)
throw new Exception( string.Format(Resources.ExceptionDesignerAttributeEnumValueIllegal, enumval) );
return enumName;
}
public override string GetExportValue(object obj)
{
Type type= obj.GetType();
switch(__exportMode)
{
case(ExportMode.Namespace_Type_Value): return string.Format("{0}{1}.{2}", __exportPrefix, type.FullName.Replace('+', '.'), Enum.GetName(type, (int)obj));
case(ExportMode.Type_Value): return string.Format("{0}{1}.{2}", __exportPrefix, type.Name, Enum.GetName(type, (int)obj));
case(ExportMode.Value): return string.Format("{0}{1}", __exportPrefix, Enum.GetName(type, (int)obj));
}
Debug.Check(false);
return null;
}
public override string GetStringValue(object obj)
{
string enumName= GetDisplayValue(obj);
int enumval= (int)obj;
return string.Format("{0}:{1}", enumName, enumval);
}
public override object FromStringValue(Type type, string str)
{
if(!type.IsEnum)
throw new Exception( string.Format(Resources.ExceptionDesignerAttributeExpectedEnum, type) );
string[] parts= str.Split(':');
if(parts.Length !=2)
{
// keep compatibility with version 1
//throw new Exception( string.Format(Resources.ExceptionDesignerAttributeEnumCouldNotReadValue, str) );
parts= new string[] { str, "-1" };
}
string enumname= parts[0];
int enumval;
try
{
// try to get the enum value by name
enumval= (int)Enum.Parse(type, enumname, true);
}
catch
{
// try to read the stored enum value index
if(!int.TryParse(parts[1], NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out enumval))
throw new Exception( string.Format(Resources.ExceptionDesignerAttributeEnumCouldNotParseValue, str) );
// try to get the enum value by index
if(Enum.ToObject(type, enumval) ==null)
throw new Exception( string.Format(Resources.ExceptionDesignerAttributeEnumIllegalEnumIndex, enumval) );
}
return enumval;
}
}
}
| 40.300613 | 318 | 0.6928 | [
"BSD-3-Clause"
] | SVemulapalli/Brainiac-Designer | Brainiac Designer Base/Attributes/DesignerEnum.cs | 6,569 | C# |
namespace FMData.Rest.Responses
{
/// <summary>
/// Authentication Response
/// </summary>
public class AuthResponse : BaseResponse
{
/// <summary>
/// Wrapper for the Response object from FileMaker API.
/// </summary>
public AuthResponseResult Response { get; set; }
}
} | 25.230769 | 63 | 0.591463 | [
"MIT"
] | Chevreuil41/fmdata | src/FMData.Rest/Responses/AuthResponse.cs | 330 | C# |
using System;
using AVFoundation;
using Accelerate;
using AudioToolbox;
using AudioUnit;
using CoreAnimation;
using CoreAudioKit;
using CoreGraphics;
using Foundation;
using GLKit;
using ObjCRuntime;
using UIKit;
namespace EZAudioKit
{
// @interface EZAudioDevice : NSObject
[BaseType(typeof(NSObject))]
interface EZAudioDevice
{
// +(EZAudioDevice *)currentInputDevice;
[Static]
[Export("currentInputDevice")]
EZAudioDevice CurrentInputDevice();
// +(EZAudioDevice *)currentOutputDevice;
[Static]
[Export("currentOutputDevice")]
EZAudioDevice CurrentOutputDevice();
// +(NSArray *)inputDevices;
[Static]
[Export("inputDevices")]
EZAudioDevice[] InputDevices();
// +(NSArray *)outputDevices;
[Static]
[Export("outputDevices")]
EZAudioDevice[] OutputDevices();
// +(void)enumerateInputDevicesUsingBlock:(void (^)(EZAudioDevice *, BOOL *))block;
[Static]
[Export("enumerateInputDevicesUsingBlock:")]
//todo write wrapper: had bool*
void EnumerateInputDevicesUsingBlock(Action<EZAudioDevice, IntPtr> block);
// +(void)enumerateOutputDevicesUsingBlock:(void (^)(EZAudioDevice *, BOOL *))block;
[Static]
[Export("enumerateOutputDevicesUsingBlock:")]
//todo write wrapper: had bool*
void EnumerateOutputDevicesUsingBlock(Action<EZAudioDevice, IntPtr> block);
// @property (readonly, copy, nonatomic) NSString * name;
[Export("name")]
string Name { get; }
// @property (readonly, nonatomic, strong) AVAudioSessionPortDescription * port;
[Export("port", ArgumentSemantic.Strong)]
AVAudioSessionPortDescription Port { get; }
// @property (readonly, nonatomic, strong) AVAudioSessionDataSourceDescription * dataSource;
[Export("dataSource", ArgumentSemantic.Strong)]
AVAudioSessionDataSourceDescription DataSource { get; }
}
// @interface EZAudioFloatData : NSObject
[BaseType(typeof(NSObject))]
interface EZAudioFloatData
{
// +(instancetype)dataWithNumberOfChannels:(int)numberOfChannels buffers:(float **)buffers bufferSize:(UInt32)bufferSize;
[Static]
[Export("dataWithNumberOfChannels:buffers:bufferSize:")]
EZAudioFloatData DataWithNumberOfChannels(int numberOfChannels, IntPtr buffers, uint bufferSize);
// @property (readonly, assign, nonatomic) int numberOfChannels;
[Export("numberOfChannels")]
int NumberOfChannels { get; }
// @property (readonly, assign, nonatomic) float ** buffers;
[Export("buffers", ArgumentSemantic.Assign)]
IntPtr Buffers { get; }
// @property (readonly, assign, nonatomic) UInt32 bufferSize;
[Export("bufferSize")]
uint BufferSize { get; }
//todo write wrapper: had float*
// -(float *)bufferForChannel:(int)channel;
[Export("bufferForChannel:")]
IntPtr BufferForChannel(int channel);
}
//todo write wrapper: had float**
// typedef void (^EZAudioWaveformDataCompletionBlock)(float **, int);
delegate void EZAudioWaveformDataCompletionBlock(ref IntPtr waveformData, int length);
// @protocol EZAudioFileDelegate <NSObject>
[Protocol, Model]
[BaseType(typeof(NSObject))]
interface EZAudioFileDelegate
{
//todo write wrapper: had float**
// @optional -(void)audioFile:(EZAudioFile *)audioFile readAudio:(float **)buffer withBufferSize:(UInt32)bufferSize withNumberOfChannels:(UInt32)numberOfChannels;
[Export("audioFile:readAudio:withBufferSize:withNumberOfChannels:")]
void AudioFile(EZAudioFile audioFile, ref IntPtr buffer, uint bufferSize, uint numberOfChannels);
// @optional -(void)audioFileUpdatedPosition:(EZAudioFile *)audioFile;
[Export("audioFileUpdatedPosition:")]
void AudioFileUpdatedPosition(EZAudioFile audioFile);
// @optional -(void)audioFile:(EZAudioFile *)audioFile updatedPosition:(SInt64)framePosition __attribute__((deprecated("")));
[Export("audioFile:updatedPosition:")]
void AudioFile(EZAudioFile audioFile, long framePosition);
}
// @interface EZAudioFile : NSObject <NSCopying>
[BaseType(typeof(NSObject))]
interface EZAudioFile : INSCopying
{
[Wrap("WeakDelegate")]
EZAudioFileDelegate Delegate { get; set; }
// @property (nonatomic, weak) id<EZAudioFileDelegate> delegate;
[NullAllowed, Export("delegate", ArgumentSemantic.Weak)]
NSObject WeakDelegate { get; set; }
// -(instancetype)initWithURL:(NSURL *)url;
[Export("initWithURL:")]
IntPtr Constructor(NSUrl url);
// -(instancetype)initWithURL:(NSURL *)url delegate:(id<EZAudioFileDelegate>)delegate;
[Export("initWithURL:delegate:")]
IntPtr Constructor(NSUrl url, EZAudioFileDelegate @delegate);
// -(instancetype)initWithURL:(NSURL *)url delegate:(id<EZAudioFileDelegate>)delegate clientFormat:(AudioStreamBasicDescription)clientFormat;
[Export("initWithURL:delegate:clientFormat:")]
IntPtr Constructor(NSUrl url, EZAudioFileDelegate @delegate, AudioStreamBasicDescription clientFormat);
// +(instancetype)audioFileWithURL:(NSURL *)url;
[Static]
[Export("audioFileWithURL:")]
EZAudioFile AudioFileWithURL(NSUrl url);
// +(instancetype)audioFileWithURL:(NSURL *)url delegate:(id<EZAudioFileDelegate>)delegate;
[Static]
[Export("audioFileWithURL:delegate:")]
EZAudioFile AudioFileWithURL(NSUrl url, EZAudioFileDelegate @delegate);
// +(instancetype)audioFileWithURL:(NSURL *)url delegate:(id<EZAudioFileDelegate>)delegate clientFormat:(AudioStreamBasicDescription)clientFormat;
[Static]
[Export("audioFileWithURL:delegate:clientFormat:")]
EZAudioFile AudioFileWithURL(NSUrl url, EZAudioFileDelegate @delegate, AudioStreamBasicDescription clientFormat);
// +(AudioStreamBasicDescription)defaultClientFormat;
[Static]
[Export("defaultClientFormat")]
AudioStreamBasicDescription DefaultClientFormat();
// +(Float64)defaultClientFormatSampleRate;
[Static]
[Export("defaultClientFormatSampleRate")]
double DefaultClientFormatSampleRate();
// +(NSArray *)supportedAudioFileTypes;
[Static]
[Export("supportedAudioFileTypes")]
NSString[] SupportedAudioFileTypes();
// -(void)readFrames:(UInt32)frames audioBufferList:(AudioBufferList *)audioBufferList bufferSize:(UInt32 *)bufferSize eof:(BOOL *)eof;
[Export("readFrames:audioBufferList:bufferSize:eof:")]
void ReadFrames(uint frames, AudioBuffers audioBufferList, IntPtr bufferSize, IntPtr eof);
// -(void)seekToFrame:(SInt64)frame;
[Export("seekToFrame:")]
void SeekToFrame(long frame);
// @property (readwrite) AudioStreamBasicDescription clientFormat;
[Export("clientFormat", ArgumentSemantic.Assign)]
AudioStreamBasicDescription ClientFormat { get; set; }
// @property (readwrite, nonatomic) NSTimeInterval currentTime;
[Export("currentTime")]
double CurrentTime { get; set; }
// @property (readonly) NSTimeInterval duration;
[Export("duration")]
double Duration { get; }
// @property (readonly) AudioStreamBasicDescription fileFormat;
[Export("fileFormat")]
AudioStreamBasicDescription FileFormat { get; }
// @property (readonly) NSString * formattedCurrentTime;
[Export("formattedCurrentTime")]
string FormattedCurrentTime { get; }
// @property (readonly) NSString * formattedDuration;
[Export("formattedDuration")]
string FormattedDuration { get; }
// @property (readonly) SInt64 frameIndex;
[Export("frameIndex")]
long FrameIndex { get; }
// @property (readonly) NSDictionary * metadata;
[Export("metadata")]
NSDictionary Metadata { get; }
// @property (readonly) NSTimeInterval totalDuration __attribute__((deprecated("")));
[Export("totalDuration")]
double TotalDuration { get; }
// @property (readonly) SInt64 totalClientFrames;
[Export("totalClientFrames")]
long TotalClientFrames { get; }
// @property (readonly) SInt64 totalFrames;
[Export("totalFrames")]
long TotalFrames { get; }
// @property (readonly, copy, nonatomic) NSURL * url;
[Export("url", ArgumentSemantic.Copy)]
NSUrl Url { get; }
// -(EZAudioFloatData *)getWaveformData;
[Export("getWaveformData")]
EZAudioFloatData GetWaveformData();
// -(EZAudioFloatData *)getWaveformDataWithNumberOfPoints:(UInt32)numberOfPoints;
[Export("getWaveformDataWithNumberOfPoints:")]
EZAudioFloatData GetWaveformDataWithNumberOfPoints(uint numberOfPoints);
// -(void)getWaveformDataWithCompletionBlock:(EZAudioWaveformDataCompletionBlock)completion;
[Export("getWaveformDataWithCompletionBlock:")]
void GetWaveformDataWithCompletionBlock(EZAudioWaveformDataCompletionBlock completion);
// -(void)getWaveformDataWithNumberOfPoints:(UInt32)numberOfPoints completion:(EZAudioWaveformDataCompletionBlock)completion;
[Export("getWaveformDataWithNumberOfPoints:completion:")]
void GetWaveformDataWithNumberOfPoints(uint numberOfPoints, EZAudioWaveformDataCompletionBlock completion);
}
// @protocol EZOutputDataSource <NSObject>
[Protocol, Model]
[BaseType(typeof(NSObject))]
interface EZOutputDataSource
{
// @required -(OSStatus)output:(EZOutput *)output shouldFillAudioBufferList:(AudioBufferList *)audioBufferList withNumberOfFrames:(UInt32)frames timestamp:(const AudioTimeStamp *)timestamp;
[Abstract]
[Export("output:shouldFillAudioBufferList:withNumberOfFrames:timestamp:")]
int ShouldFillAudioBufferList(EZOutput output, AudioBuffers audioBufferList, uint frames, IntPtr timestamp);
}
// @protocol EZOutputDelegate <NSObject>
[Protocol, Model]
[BaseType(typeof(NSObject))]
interface EZOutputDelegate
{
// @optional -(void)output:(EZOutput *)output changedPlayingState:(BOOL)isPlaying;
[Export("output:changedPlayingState:")]
void ChangedPlayingState(EZOutput output, bool isPlaying);
// @optional -(void)output:(EZOutput *)output changedDevice:(EZAudioDevice *)device;
[Export("output:changedDevice:")]
void ChangedDevice(EZOutput output, EZAudioDevice device);
// @optional -(void)output:(EZOutput *)output playedAudio:(float **)buffer withBufferSize:(UInt32)bufferSize withNumberOfChannels:(UInt32)numberOfChannels;
[Export("output:playedAudio:withBufferSize:withNumberOfChannels:")]
void PlayedAudio(EZOutput output, IntPtr buffer, uint bufferSize, uint numberOfChannels);
}
// @interface EZOutput : NSObject
[BaseType(typeof(NSObject))]
interface EZOutput
{
// -(instancetype)initWithDataSource:(id<EZOutputDataSource>)dataSource;
[Export("initWithDataSource:")]
IntPtr Constructor(EZOutputDataSource dataSource);
// -(instancetype)initWithDataSource:(id<EZOutputDataSource>)dataSource inputFormat:(AudioStreamBasicDescription)inputFormat;
[Export("initWithDataSource:inputFormat:")]
IntPtr Constructor(EZOutputDataSource dataSource, AudioStreamBasicDescription inputFormat);
// +(instancetype)output;
[Static]
[Export("output")]
EZOutput Output();
// +(instancetype)outputWithDataSource:(id<EZOutputDataSource>)dataSource;
[Static]
[Export("outputWithDataSource:")]
EZOutput OutputWithDataSource(EZOutputDataSource dataSource);
// +(instancetype)outputWithDataSource:(id<EZOutputDataSource>)dataSource inputFormat:(AudioStreamBasicDescription)inputFormat;
[Static]
[Export("outputWithDataSource:inputFormat:")]
EZOutput OutputWithDataSource(EZOutputDataSource dataSource, AudioStreamBasicDescription inputFormat);
// +(instancetype)sharedOutput;
[Static]
[Export("sharedOutput")]
EZOutput SharedOutput();
// @property (readwrite, nonatomic) AudioStreamBasicDescription inputFormat;
[Export("inputFormat", ArgumentSemantic.Assign)]
AudioStreamBasicDescription InputFormat { get; set; }
// @property (readwrite, nonatomic) AudioStreamBasicDescription clientFormat;
[Export("clientFormat", ArgumentSemantic.Assign)]
AudioStreamBasicDescription ClientFormat { get; set; }
// @property (nonatomic, weak) id<EZOutputDataSource> dataSource;
[Export("dataSource", ArgumentSemantic.Weak)]
EZOutputDataSource DataSource { get; set; }
[Wrap("WeakDelegate")]
EZOutputDelegate Delegate { get; set; }
// @property (nonatomic, weak) id<EZOutputDelegate> delegate;
[NullAllowed, Export("delegate", ArgumentSemantic.Weak)]
NSObject WeakDelegate { get; set; }
// @property (readonly) BOOL isPlaying;
[Export("isPlaying")]
bool IsPlaying { get; }
// @property (assign, nonatomic) float pan;
[Export("pan")]
float Pan { get; set; }
// @property (assign, nonatomic) float volume;
[Export("volume")]
float Volume { get; set; }
//todo look here later
// @property (readonly) AUGraph graph;
//[Export("graph")]
//AUGraph Graph { get; }
//fixme AudioUnit.AudioUnit doesn't work (3 below methods)
// @property (readonly) AudioUnit converterAudioUnit;
[Export("converterAudioUnit")]
IntPtr ConverterAudioUnit { get; }
// @property (readonly) AudioUnit mixerAudioUnit;
[Export("mixerAudioUnit")]
IntPtr MixerAudioUnit { get; }
// @property (readonly) AudioUnit outputAudioUnit;
[Export("outputAudioUnit")]
IntPtr OutputAudioUnit { get; }
// @property (readwrite, nonatomic, strong) EZAudioDevice * device;
[Export("device", ArgumentSemantic.Strong)]
EZAudioDevice Device { get; set; }
// -(void)startPlayback;
[Export("startPlayback")]
void StartPlayback();
// -(void)stopPlayback;
[Export("stopPlayback")]
void StopPlayback();
//todo look here augraph
// -(OSStatus)connectOutputOfSourceNode:(AUNode)sourceNode sourceNodeOutputBus:(UInt32)sourceNodeOutputBus toDestinationNode:(AUNode)destinationNode destinationNodeInputBus:(UInt32)destinationNodeInputBus inGraph:(AUGraph)graph;
//[Export("connectOutputOfSourceNode:sourceNodeOutputBus:toDestinationNode:destinationNodeInputBus:inGraph:")]
//int ConnectOutputOfSourceNode(int sourceNode, uint sourceNodeOutputBus, int destinationNode, uint destinationNodeInputBus, AUGraph graph);
// -(AudioStreamBasicDescription)defaultClientFormat;
[Export("defaultClientFormat")]
AudioStreamBasicDescription DefaultClientFormat();
// -(AudioStreamBasicDescription)defaultInputFormat;
[Export("defaultInputFormat")]
AudioStreamBasicDescription DefaultInputFormat();
// -(OSType)outputAudioUnitSubType;
[Export("outputAudioUnitSubType")]
uint OutputAudioUnitSubType();
}
// @protocol EZMicrophoneDelegate <NSObject>
[Protocol, Model]
[BaseType(typeof(NSObject))]
interface EZMicrophoneDelegate
{
// @optional -(void)microphone:(EZMicrophone *)microphone changedPlayingState:(BOOL)isPlaying;
[Export("microphone:changedPlayingState:")]
void ChangedPlayingState(EZMicrophone microphone, bool isPlaying);
// @optional -(void)microphone:(EZMicrophone *)microphone changedDevice:(EZAudioDevice *)device;
[Export("microphone:changedDevice:")]
void ChangedDevice(EZMicrophone microphone, EZAudioDevice device);
// @optional -(void)microphone:(EZMicrophone *)microphone hasAudioStreamBasicDescription:(AudioStreamBasicDescription)audioStreamBasicDescription;
[Export("microphone:hasAudioStreamBasicDescription:")]
void HasAudioStreamBasicDescription(EZMicrophone microphone, AudioStreamBasicDescription audioStreamBasicDescription);
// @optional -(void)microphone:(EZMicrophone *)microphone hasAudioReceived:(float **)buffer withBufferSize:(UInt32)bufferSize withNumberOfChannels:(UInt32)numberOfChannels;
[Export("microphone:hasAudioReceived:withBufferSize:withNumberOfChannels:")]
void HasAudioReceived(EZMicrophone microphone, IntPtr buffer, uint bufferSize, uint numberOfChannels);
// @optional -(void)microphone:(EZMicrophone *)microphone hasBufferList:(AudioBufferList *)bufferList withBufferSize:(UInt32)bufferSize withNumberOfChannels:(UInt32)numberOfChannels;
[Export("microphone:hasBufferList:withBufferSize:withNumberOfChannels:")]
void HasBufferList(EZMicrophone microphone, AudioBuffers bufferList, uint bufferSize, uint numberOfChannels);
}
// @interface EZMicrophone : NSObject <EZOutputDataSource>
[BaseType(typeof(NSObject))]
interface EZMicrophone : EZOutputDataSource
{
[Wrap("WeakDelegate")]
EZMicrophoneDelegate Delegate { get; set; }
// @property (nonatomic, weak) id<EZMicrophoneDelegate> delegate;
[NullAllowed, Export("delegate", ArgumentSemantic.Weak)]
NSObject WeakDelegate { get; set; }
// @property (nonatomic, strong) EZAudioDevice * device;
[Export("device", ArgumentSemantic.Strong)]
EZAudioDevice Device { get; set; }
// @property (assign, nonatomic) BOOL microphoneOn;
[Export("microphoneOn")]
bool MicrophoneOn { get; set; }
// @property (nonatomic, strong) EZOutput * output;
[Export("output", ArgumentSemantic.Strong)]
EZOutput Output { get; set; }
// -(EZMicrophone *)initWithMicrophoneDelegate:(id<EZMicrophoneDelegate>)delegate;
[Export("initWithMicrophoneDelegate:")]
IntPtr Constructor(EZMicrophoneDelegate @delegate);
// -(EZMicrophone *)initWithMicrophoneDelegate:(id<EZMicrophoneDelegate>)delegate withAudioStreamBasicDescription:(AudioStreamBasicDescription)audioStreamBasicDescription;
[Export("initWithMicrophoneDelegate:withAudioStreamBasicDescription:")]
IntPtr Constructor(EZMicrophoneDelegate @delegate, AudioStreamBasicDescription audioStreamBasicDescription);
// -(EZMicrophone *)initWithMicrophoneDelegate:(id<EZMicrophoneDelegate>)delegate startsImmediately:(BOOL)startsImmediately;
[Export("initWithMicrophoneDelegate:startsImmediately:")]
IntPtr Constructor(EZMicrophoneDelegate @delegate, bool startsImmediately);
// -(EZMicrophone *)initWithMicrophoneDelegate:(id<EZMicrophoneDelegate>)delegate withAudioStreamBasicDescription:(AudioStreamBasicDescription)audioStreamBasicDescription startsImmediately:(BOOL)startsImmediately;
[Export("initWithMicrophoneDelegate:withAudioStreamBasicDescription:startsImmediately:")]
IntPtr Constructor(EZMicrophoneDelegate @delegate, AudioStreamBasicDescription audioStreamBasicDescription, bool startsImmediately);
// +(EZMicrophone *)microphoneWithDelegate:(id<EZMicrophoneDelegate>)delegate;
[Static]
[Export("microphoneWithDelegate:")]
EZMicrophone MicrophoneWithDelegate(EZMicrophoneDelegate @delegate);
// +(EZMicrophone *)microphoneWithDelegate:(id<EZMicrophoneDelegate>)delegate withAudioStreamBasicDescription:(AudioStreamBasicDescription)audioStreamBasicDescription;
[Static]
[Export("microphoneWithDelegate:withAudioStreamBasicDescription:")]
EZMicrophone MicrophoneWithDelegate(EZMicrophoneDelegate @delegate, AudioStreamBasicDescription audioStreamBasicDescription);
// +(EZMicrophone *)microphoneWithDelegate:(id<EZMicrophoneDelegate>)delegate startsImmediately:(BOOL)startsImmediately;
[Static]
[Export("microphoneWithDelegate:startsImmediately:")]
EZMicrophone MicrophoneWithDelegate(EZMicrophoneDelegate @delegate, bool startsImmediately);
// +(EZMicrophone *)microphoneWithDelegate:(id<EZMicrophoneDelegate>)delegate withAudioStreamBasicDescription:(AudioStreamBasicDescription)audioStreamBasicDescription startsImmediately:(BOOL)startsImmediately;
[Static]
[Export("microphoneWithDelegate:withAudioStreamBasicDescription:startsImmediately:")]
EZMicrophone MicrophoneWithDelegate(EZMicrophoneDelegate @delegate, AudioStreamBasicDescription audioStreamBasicDescription, bool startsImmediately);
// +(EZMicrophone *)sharedMicrophone;
[Static]
[Export("sharedMicrophone")]
EZMicrophone SharedMicrophone();
// -(void)startFetchingAudio;
[Export("startFetchingAudio")]
void StartFetchingAudio();
// -(void)stopFetchingAudio;
[Export("stopFetchingAudio")]
void StopFetchingAudio();
// -(AudioStreamBasicDescription)audioStreamBasicDescription;
// -(void)setAudioStreamBasicDescription:(AudioStreamBasicDescription)asbd;
[Export("audioStreamBasicDescription")]
//[Verify(MethodToProperty)]
//todo check if this is right
AudioStreamBasicDescription AudioStreamBasicDescription { get; set; }
// -(AudioUnit *)audioUnit;
[Export("audioUnit")]
//todo write wrapper: had AudioUnit**
IntPtr AudioUnit();
// -(AudioStreamBasicDescription)defaultStreamFormat;
[Export("defaultStreamFormat")]
AudioStreamBasicDescription DefaultStreamFormat();
// -(UInt32)numberOfChannels;
[Export("numberOfChannels")]
uint NumberOfChannels();
}
// @protocol EZRecorderDelegate <NSObject>
[Protocol, Model]
[BaseType(typeof(NSObject))]
interface EZRecorderDelegate
{
// @optional -(void)recorderDidClose:(EZRecorder *)recorder;
[Export("recorderDidClose:")]
void RecorderDidClose(EZRecorder recorder);
// @optional -(void)recorderUpdatedCurrentTime:(EZRecorder *)recorder;
[Export("recorderUpdatedCurrentTime:")]
void RecorderUpdatedCurrentTime(EZRecorder recorder);
}
// @interface EZRecorder : NSObject
[BaseType(typeof(NSObject))]
interface EZRecorder
{
[Wrap("WeakDelegate")]
EZRecorderDelegate Delegate { get; set; }
// @property (nonatomic, weak) id<EZRecorderDelegate> delegate;
[NullAllowed, Export("delegate", ArgumentSemantic.Weak)]
NSObject WeakDelegate { get; set; }
// -(instancetype)initWithURL:(NSURL *)url clientFormat:(AudioStreamBasicDescription)clientFormat fileType:(EZRecorderFileType)fileType;
[Export("initWithURL:clientFormat:fileType:")]
IntPtr Constructor(NSUrl url, AudioStreamBasicDescription clientFormat, EZRecorderFileType fileType);
// -(instancetype)initWithURL:(NSURL *)url clientFormat:(AudioStreamBasicDescription)clientFormat fileType:(EZRecorderFileType)fileType delegate:(id<EZRecorderDelegate>)delegate;
[Export("initWithURL:clientFormat:fileType:delegate:")]
IntPtr Constructor(NSUrl url, AudioStreamBasicDescription clientFormat, EZRecorderFileType fileType, EZRecorderDelegate @delegate);
// -(instancetype)initWithURL:(NSURL *)url clientFormat:(AudioStreamBasicDescription)clientFormat fileFormat:(AudioStreamBasicDescription)fileFormat audioFileTypeID:(AudioFileTypeID)audioFileTypeID;
[Export("initWithURL:clientFormat:fileFormat:audioFileTypeID:")]
IntPtr Constructor(NSUrl url, AudioStreamBasicDescription clientFormat, AudioStreamBasicDescription fileFormat, uint audioFileTypeID);
// -(instancetype)initWithURL:(NSURL *)url clientFormat:(AudioStreamBasicDescription)clientFormat fileFormat:(AudioStreamBasicDescription)fileFormat audioFileTypeID:(AudioFileTypeID)audioFileTypeID delegate:(id<EZRecorderDelegate>)delegate;
[Export("initWithURL:clientFormat:fileFormat:audioFileTypeID:delegate:")]
IntPtr Constructor(NSUrl url, AudioStreamBasicDescription clientFormat, AudioStreamBasicDescription fileFormat, uint audioFileTypeID, EZRecorderDelegate @delegate);
//Removed Constructor with same parameters
// -(instancetype)initWithDestinationURL:(NSURL *)url sourceFormat:(AudioStreamBasicDescription)sourceFormat destinationFileType:(EZRecorderFileType)destinationFileType __attribute__((deprecated("")));
//[Export("initWithDestinationURL:sourceFormat:destinationFileType:")]
//IntPtr Constructor(NSUrl url, AudioStreamBasicDescription sourceFormat, EZRecorderFileType destinationFileType);
// +(instancetype)recorderWithURL:(NSURL *)url clientFormat:(AudioStreamBasicDescription)clientFormat fileType:(EZRecorderFileType)fileType;
[Static]
[Export("recorderWithURL:clientFormat:fileType:")]
EZRecorder RecorderWithURL(NSUrl url, AudioStreamBasicDescription clientFormat, EZRecorderFileType fileType);
// +(instancetype)recorderWithURL:(NSURL *)url clientFormat:(AudioStreamBasicDescription)clientFormat fileType:(EZRecorderFileType)fileType delegate:(id<EZRecorderDelegate>)delegate;
[Static]
[Export("recorderWithURL:clientFormat:fileType:delegate:")]
EZRecorder RecorderWithURL(NSUrl url, AudioStreamBasicDescription clientFormat, EZRecorderFileType fileType, EZRecorderDelegate @delegate);
// +(instancetype)recorderWithURL:(NSURL *)url clientFormat:(AudioStreamBasicDescription)clientFormat fileFormat:(AudioStreamBasicDescription)fileFormat audioFileTypeID:(AudioFileTypeID)audioFileTypeID;
[Static]
[Export("recorderWithURL:clientFormat:fileFormat:audioFileTypeID:")]
EZRecorder RecorderWithURL(NSUrl url, AudioStreamBasicDescription clientFormat, AudioStreamBasicDescription fileFormat, uint audioFileTypeID);
// +(instancetype)recorderWithURL:(NSURL *)url clientFormat:(AudioStreamBasicDescription)clientFormat fileFormat:(AudioStreamBasicDescription)fileFormat audioFileTypeID:(AudioFileTypeID)audioFileTypeID delegate:(id<EZRecorderDelegate>)delegate;
[Static]
[Export("recorderWithURL:clientFormat:fileFormat:audioFileTypeID:delegate:")]
EZRecorder RecorderWithURL(NSUrl url, AudioStreamBasicDescription clientFormat, AudioStreamBasicDescription fileFormat, uint audioFileTypeID, EZRecorderDelegate @delegate);
// +(instancetype)recorderWithDestinationURL:(NSURL *)url sourceFormat:(AudioStreamBasicDescription)sourceFormat destinationFileType:(EZRecorderFileType)destinationFileType __attribute__((deprecated("")));
[Static]
[Export("recorderWithDestinationURL:sourceFormat:destinationFileType:")]
EZRecorder RecorderWithDestinationURL(NSUrl url, AudioStreamBasicDescription sourceFormat, EZRecorderFileType destinationFileType);
// @property (readwrite) AudioStreamBasicDescription clientFormat;
[Export("clientFormat", ArgumentSemantic.Assign)]
AudioStreamBasicDescription ClientFormat { get; set; }
// @property (readonly) NSTimeInterval currentTime;
[Export("currentTime")]
double CurrentTime { get; }
// @property (readonly) NSTimeInterval duration;
[Export("duration")]
double Duration { get; }
// @property (readonly) AudioStreamBasicDescription fileFormat;
[Export("fileFormat")]
AudioStreamBasicDescription FileFormat { get; }
// @property (readonly) NSString * formattedCurrentTime;
[Export("formattedCurrentTime")]
string FormattedCurrentTime { get; }
// @property (readonly) NSString * formattedDuration;
[Export("formattedDuration")]
string FormattedDuration { get; }
// @property (readonly) SInt64 frameIndex;
[Export("frameIndex")]
long FrameIndex { get; }
// @property (readonly) SInt64 totalFrames;
[Export("totalFrames")]
long TotalFrames { get; }
// -(NSURL *)url;
[Export("url")]
NSUrl Url();
// -(void)appendDataFromBufferList:(AudioBufferList *)bufferList withBufferSize:(UInt32)bufferSize;
[Export("appendDataFromBufferList:withBufferSize:")]
void AppendDataFromBufferList(AudioBuffers bufferList, uint bufferSize);
// -(void)closeAudioFile;
[Export("closeAudioFile")]
void CloseAudioFile();
}
// @protocol EZAudioPlayerDelegate <NSObject>
[Protocol, Model]
[BaseType(typeof(NSObject))]
interface EZAudioPlayerDelegate
{
//todo write wrapper: had float**
// @optional -(void)audioPlayer:(EZAudioPlayer *)audioPlayer playedAudio:(float **)buffer withBufferSize:(UInt32)bufferSize withNumberOfChannels:(UInt32)numberOfChannels inAudioFile:(EZAudioFile *)audioFile;
[Export("audioPlayer:playedAudio:withBufferSize:withNumberOfChannels:inAudioFile:")]
void PlayedAudio(EZAudioPlayer audioPlayer, ref IntPtr buffer, uint bufferSize, uint numberOfChannels, EZAudioFile audioFile);
// @optional -(void)audioPlayer:(EZAudioPlayer *)audioPlayer updatedPosition:(SInt64)framePosition inAudioFile:(EZAudioFile *)audioFile;
[Export("audioPlayer:updatedPosition:inAudioFile:")]
void UpdatedPosition(EZAudioPlayer audioPlayer, long framePosition, EZAudioFile audioFile);
// @optional -(void)audioPlayer:(EZAudioPlayer *)audioPlayer reachedEndOfAudioFile:(EZAudioFile *)audioFile;
[Export("audioPlayer:reachedEndOfAudioFile:")]
void ReachedEndOfAudioFile(EZAudioPlayer audioPlayer, EZAudioFile audioFile);
}
// @interface EZAudioPlayer : NSObject <EZAudioFileDelegate, EZOutputDataSource, EZOutputDelegate>
[BaseType(typeof(NSObject))]
interface EZAudioPlayer : EZAudioFileDelegate, EZOutputDataSource, EZOutputDelegate
{
[Wrap("WeakDelegate")]
EZAudioPlayerDelegate Delegate { get; set; }
// @property (nonatomic, weak) id<EZAudioPlayerDelegate> delegate;
[NullAllowed, Export("delegate", ArgumentSemantic.Weak)]
NSObject WeakDelegate { get; set; }
// @property (assign, nonatomic) BOOL shouldLoop;
[Export("shouldLoop")]
bool ShouldLoop { get; set; }
// @property (readonly, assign, nonatomic) EZAudioPlayerState state;
[Export("state", ArgumentSemantic.Assign)]
EZAudioPlayerState State { get; }
// -(instancetype)initWithAudioFile:(EZAudioFile *)audioFile;
[Export("initWithAudioFile:")]
IntPtr Constructor(EZAudioFile audioFile);
// -(instancetype)initWithAudioFile:(EZAudioFile *)audioFile delegate:(id<EZAudioPlayerDelegate>)delegate;
[Export("initWithAudioFile:delegate:")]
IntPtr Constructor(EZAudioFile audioFile, EZAudioPlayerDelegate @delegate);
// -(instancetype)initWithDelegate:(id<EZAudioPlayerDelegate>)delegate;
[Export("initWithDelegate:")]
IntPtr Constructor(EZAudioPlayerDelegate @delegate);
// -(instancetype)initWithURL:(NSURL *)url;
[Export("initWithURL:")]
IntPtr Constructor(NSUrl url);
// -(instancetype)initWithURL:(NSURL *)url delegate:(id<EZAudioPlayerDelegate>)delegate;
[Export("initWithURL:delegate:")]
IntPtr Constructor(NSUrl url, EZAudioPlayerDelegate @delegate);
// +(instancetype)audioPlayer;
[Static]
[Export("audioPlayer")]
EZAudioPlayer AudioPlayer();
// +(instancetype)audioPlayerWithAudioFile:(EZAudioFile *)audioFile;
[Static]
[Export("audioPlayerWithAudioFile:")]
EZAudioPlayer AudioPlayerWithAudioFile(EZAudioFile audioFile);
// +(instancetype)audioPlayerWithAudioFile:(EZAudioFile *)audioFile delegate:(id<EZAudioPlayerDelegate>)delegate;
[Static]
[Export("audioPlayerWithAudioFile:delegate:")]
EZAudioPlayer AudioPlayerWithAudioFile(EZAudioFile audioFile, EZAudioPlayerDelegate @delegate);
// +(instancetype)audioPlayerWithDelegate:(id<EZAudioPlayerDelegate>)delegate;
[Static]
[Export("audioPlayerWithDelegate:")]
EZAudioPlayer AudioPlayerWithDelegate(EZAudioPlayerDelegate @delegate);
// +(instancetype)audioPlayerWithURL:(NSURL *)url;
[Static]
[Export("audioPlayerWithURL:")]
EZAudioPlayer AudioPlayerWithURL(NSUrl url);
// +(instancetype)audioPlayerWithURL:(NSURL *)url delegate:(id<EZAudioPlayerDelegate>)delegate;
[Static]
[Export("audioPlayerWithURL:delegate:")]
EZAudioPlayer AudioPlayerWithURL(NSUrl url, EZAudioPlayerDelegate @delegate);
// +(instancetype)sharedAudioPlayer;
[Static]
[Export("sharedAudioPlayer")]
EZAudioPlayer SharedAudioPlayer();
//fixme why are there 2 audioFiles in this class?
// @property (readwrite, copy, nonatomic) EZAudioFile * audioFile;
[Export("audioFile", ArgumentSemantic.Copy)]
EZAudioFile AudioFileProperty { get; set; }
// @property (readwrite, nonatomic) NSTimeInterval currentTime;
[Export("currentTime")]
double CurrentTime { get; set; }
// @property (readwrite) EZAudioDevice * device;
[Export("device", ArgumentSemantic.Assign)]
EZAudioDevice Device { get; set; }
// @property (readonly) NSTimeInterval duration;
[Export("duration")]
double Duration { get; }
// @property (readonly) NSString * formattedCurrentTime;
[Export("formattedCurrentTime")]
string FormattedCurrentTime { get; }
// @property (readonly) NSString * formattedDuration;
[Export("formattedDuration")]
string FormattedDuration { get; }
// @property (readwrite, nonatomic, strong) EZOutput * output;
[Export("output", ArgumentSemantic.Strong)]
EZOutput Output { get; set; }
// @property (readonly) SInt64 frameIndex;
[Export("frameIndex")]
long FrameIndex { get; }
// @property (readonly) BOOL isPlaying;
[Export("isPlaying")]
bool IsPlaying { get; }
// @property (assign, nonatomic) float pan;
[Export("pan")]
float Pan { get; set; }
// @property (readonly) SInt64 totalFrames;
[Export("totalFrames")]
long TotalFrames { get; }
// @property (readonly, copy, nonatomic) NSURL * url;
[Export("url", ArgumentSemantic.Copy)]
NSUrl Url { get; }
// @property (assign, nonatomic) float volume;
[Export("volume")]
float Volume { get; set; }
// -(void)play;
[Export("play")]
void Play();
// -(void)playAudioFile:(EZAudioFile *)audioFile;
[Export("playAudioFile:")]
void PlayAudioFile(EZAudioFile audioFile);
// -(void)pause;
[Export("pause")]
void Pause();
// -(void)seekToFrame:(SInt64)frame;
[Export("seekToFrame:")]
void SeekToFrame(long frame);
}
// @interface EZAudioUtilities : NSObject
[BaseType(typeof(NSObject))]
interface EZAudioUtilities
{
// +(BOOL)shouldExitOnCheckResultFail;
// +(void)setShouldExitOnCheckResultFail:(BOOL)shouldExitOnCheckResultFail;
[Static]
[Export("shouldExitOnCheckResultFail")]
//[Verify(MethodToProperty)]
//todo check if this is right
bool ShouldExitOnCheckResultFail { get; set; }
// +(AudioBufferList *)audioBufferListWithNumberOfFrames:(UInt32)frames numberOfChannels:(UInt32)channels interleaved:(BOOL)interleaved;
[Static]
[Export("audioBufferListWithNumberOfFrames:numberOfChannels:interleaved:")]
AudioBuffers AudioBufferListWithNumberOfFrames(uint frames, uint channels, bool interleaved);
// +(float **)floatBuffersWithNumberOfFrames:(UInt32)frames numberOfChannels:(UInt32)channels;
[Static]
[Export("floatBuffersWithNumberOfFrames:numberOfChannels:")]
IntPtr FloatBuffersWithNumberOfFrames(uint frames, uint channels);
// +(void)freeBufferList:(AudioBufferList *)bufferList;
[Static]
[Export("freeBufferList:")]
void FreeBufferList(AudioBuffers bufferList);
// +(void)freeFloatBuffers:(float **)buffers numberOfChannels:(UInt32)channels;
[Static]
[Export("freeFloatBuffers:numberOfChannels:")]
void FreeFloatBuffers(IntPtr buffers, uint channels);
// +(AudioStreamBasicDescription)AIFFFormatWithNumberOfChannels:(UInt32)channels sampleRate:(float)sampleRate;
[Static]
[Export("AIFFFormatWithNumberOfChannels:sampleRate:")]
AudioStreamBasicDescription AIFFFormatWithNumberOfChannels(uint channels, float sampleRate);
// +(AudioStreamBasicDescription)iLBCFormatWithSampleRate:(float)sampleRate;
[Static]
[Export("iLBCFormatWithSampleRate:")]
AudioStreamBasicDescription ILBCFormatWithSampleRate(float sampleRate);
// +(AudioStreamBasicDescription)floatFormatWithNumberOfChannels:(UInt32)channels sampleRate:(float)sampleRate;
[Static]
[Export("floatFormatWithNumberOfChannels:sampleRate:")]
AudioStreamBasicDescription FloatFormatWithNumberOfChannels(uint channels, float sampleRate);
// +(AudioStreamBasicDescription)M4AFormatWithNumberOfChannels:(UInt32)channels sampleRate:(float)sampleRate;
[Static]
[Export("M4AFormatWithNumberOfChannels:sampleRate:")]
AudioStreamBasicDescription M4AFormatWithNumberOfChannels(uint channels, float sampleRate);
// +(AudioStreamBasicDescription)monoFloatFormatWithSampleRate:(float)sampleRate;
[Static]
[Export("monoFloatFormatWithSampleRate:")]
AudioStreamBasicDescription MonoFloatFormatWithSampleRate(float sampleRate);
// +(AudioStreamBasicDescription)monoCanonicalFormatWithSampleRate:(float)sampleRate;
[Static]
[Export("monoCanonicalFormatWithSampleRate:")]
AudioStreamBasicDescription MonoCanonicalFormatWithSampleRate(float sampleRate);
// +(AudioStreamBasicDescription)stereoCanonicalNonInterleavedFormatWithSampleRate:(float)sampleRate;
[Static]
[Export("stereoCanonicalNonInterleavedFormatWithSampleRate:")]
AudioStreamBasicDescription StereoCanonicalNonInterleavedFormatWithSampleRate(float sampleRate);
// +(AudioStreamBasicDescription)stereoFloatInterleavedFormatWithSampleRate:(float)sampleRate;
[Static]
[Export("stereoFloatInterleavedFormatWithSampleRate:")]
AudioStreamBasicDescription StereoFloatInterleavedFormatWithSampleRate(float sampleRate);
// +(AudioStreamBasicDescription)stereoFloatNonInterleavedFormatWithSampleRate:(float)sampleRate;
[Static]
[Export("stereoFloatNonInterleavedFormatWithSampleRate:")]
AudioStreamBasicDescription StereoFloatNonInterleavedFormatWithSampleRate(float sampleRate);
// +(BOOL)isFloatFormat:(AudioStreamBasicDescription)asbd;
[Static]
[Export("isFloatFormat:")]
bool IsFloatFormat(AudioStreamBasicDescription asbd);
// +(BOOL)isInterleaved:(AudioStreamBasicDescription)asbd;
[Static]
[Export("isInterleaved:")]
bool IsInterleaved(AudioStreamBasicDescription asbd);
// +(BOOL)isLinearPCM:(AudioStreamBasicDescription)asbd;
[Static]
[Export("isLinearPCM:")]
bool IsLinearPCM(AudioStreamBasicDescription asbd);
// +(void)printASBD:(AudioStreamBasicDescription)asbd;
[Static]
[Export("printASBD:")]
void PrintASBD(AudioStreamBasicDescription asbd);
// +(NSString *)displayTimeStringFromSeconds:(NSTimeInterval)seconds;
[Static]
[Export("displayTimeStringFromSeconds:")]
string DisplayTimeStringFromSeconds(double seconds);
// +(NSString *)stringForAudioStreamBasicDescription:(AudioStreamBasicDescription)asbd;
[Static]
[Export("stringForAudioStreamBasicDescription:")]
string StringForAudioStreamBasicDescription(AudioStreamBasicDescription asbd);
//todo Was AudioStreamBasicDescription *
// +(void)setCanonicalAudioStreamBasicDescription:(AudioStreamBasicDescription *)asbd numberOfChannels:(UInt32)nChannels interleaved:(BOOL)interleaved;
[Static]
[Export("setCanonicalAudioStreamBasicDescription:numberOfChannels:interleaved:")]
void SetCanonicalAudioStreamBasicDescription(IntPtr asbd, uint nChannels, bool interleaved);
//todo was float*
// +(void)appendBufferAndShift:(float *)buffer withBufferSize:(int)bufferLength toScrollHistory:(float *)scrollHistory withScrollHistorySize:(int)scrollHistoryLength;
[Static]
[Export("appendBufferAndShift:withBufferSize:toScrollHistory:withScrollHistorySize:")]
void AppendBufferAndShift(IntPtr buffer, int bufferLength, IntPtr scrollHistory, int scrollHistoryLength);
// +(void)appendValue:(float)value toScrollHistory:(float *)scrollHistory withScrollHistorySize:(int)scrollHistoryLength;
[Static]
[Export("appendValue:toScrollHistory:withScrollHistorySize:")]
void AppendValue(float value, IntPtr scrollHistory, int scrollHistoryLength);
// +(float)MAP:(float)value leftMin:(float)leftMin leftMax:(float)leftMax rightMin:(float)rightMin rightMax:(float)rightMax;
[Static]
[Export("MAP:leftMin:leftMax:rightMin:rightMax:")]
float MAP(float value, float leftMin, float leftMax, float rightMin, float rightMax);
//todo write wrapper: had float*
// +(float)RMS:(float *)buffer length:(int)bufferSize;
[Static]
[Export("RMS:length:")]
float RMS(IntPtr buffer, int bufferSize);
// +(float)SGN:(float)value;
[Static]
[Export("SGN:")]
float SGN(float value);
// +(NSString *)noteNameStringForFrequency:(float)frequency includeOctave:(BOOL)includeOctave;
[Static]
[Export("noteNameStringForFrequency:includeOctave:")]
string NoteNameStringForFrequency(float frequency, bool includeOctave);
// +(void)checkResult:(OSStatus)result operation:(const char *)operation;
[Static]
[Export("checkResult:operation:")]
void CheckResult(int result, IntPtr operation);
// +(NSString *)stringFromUInt32Code:(UInt32)code;
[Static]
[Export("stringFromUInt32Code:")]
string StringFromUInt32Code(uint code);
//todo write wrapper: had CGColorRef*, nfloat* (multiple)
// +(void)getColorComponentsFromCGColor:(CGColorRef)color red:(CGFloat *)red green:(CGFloat *)green blue:(CGFloat *)blue alpha:(CGFloat *)alpha;
[Static]
[Export("getColorComponentsFromCGColor:red:green:blue:alpha:")]
void GetColorComponentsFromCGColor(IntPtr color, IntPtr red, IntPtr green, IntPtr blue, IntPtr alpha);
//todo write wrapper: had float** int* float* bool*
// +(void)updateScrollHistory:(float **)scrollHistory withLength:(int)scrollHistoryLength atIndex:(int *)index withBuffer:(float *)buffer withBufferSize:(int)bufferSize isResolutionChanging:(BOOL *)isChanging;
[Static]
[Export("updateScrollHistory:withLength:atIndex:withBuffer:withBufferSize:isResolutionChanging:")]
void UpdateScrollHistory(ref IntPtr scrollHistory, int scrollHistoryLength, IntPtr index, IntPtr buffer, int bufferSize, IntPtr isChanging);
//todo write wrapper: had TPCircularBuffer*
// +(void)appendDataToCircularBuffer:(TPCircularBuffer *)circularBuffer fromAudioBufferList:(AudioBufferList *)audioBufferList;
[Static]
[Export("appendDataToCircularBuffer:fromAudioBufferList:")]
void AppendDataToCircularBuffer(IntPtr circularBuffer, AudioBuffers audioBufferList);
//todo write wrapper: had TPCircularBuffer*
// +(void)circularBuffer:(TPCircularBuffer *)circularBuffer withSize:(int)size;
[Static]
[Export("circularBuffer:withSize:")]
void CircularBuffer(IntPtr circularBuffer, int size);
//todo write wrapper: had TPCircularBuffer*
// +(void)freeCircularBuffer:(TPCircularBuffer *)circularBuffer;
[Static]
[Export("freeCircularBuffer:")]
void FreeCircularBuffer(IntPtr circularBuffer);
//todo write wrapper: had float*, EZPlotHistoryInfo*
// +(void)appendBufferRMS:(float *)buffer withBufferSize:(UInt32)bufferSize toHistoryInfo:(EZPlotHistoryInfo *)historyInfo;
[Static]
[Export("appendBufferRMS:withBufferSize:toHistoryInfo:")]
void AppendBufferRMS(IntPtr buffer, uint bufferSize, IntPtr historyInfo);
//todo write wrapper: had float*, EZPlotHistoryInfo*
// +(void)appendBuffer:(float *)buffer withBufferSize:(UInt32)bufferSize toHistoryInfo:(EZPlotHistoryInfo *)historyInfo;
[Static]
[Export("appendBuffer:withBufferSize:toHistoryInfo:")]
void AppendBuffer(IntPtr buffer, uint bufferSize, IntPtr historyInfo);
//todo write wrapper: had EZPlotHistoryInfo*
// +(void)clearHistoryInfo:(EZPlotHistoryInfo *)historyInfo;
[Static]
[Export("clearHistoryInfo:")]
void ClearHistoryInfo(IntPtr historyInfo);
//todo write wrapper: had EZPlotHistoryInfo*
// +(void)freeHistoryInfo:(EZPlotHistoryInfo *)historyInfo;
[Static]
[Export("freeHistoryInfo:")]
void FreeHistoryInfo(IntPtr historyInfo);
//todo write wrapper: had EZPlotHistoryInfo*
// +(EZPlotHistoryInfo *)historyInfoWithDefaultLength:(int)defaultLength maximumLength:(int)maximumLength;
[Static]
[Export("historyInfoWithDefaultLength:maximumLength:")]
IntPtr HistoryInfoWithDefaultLength(int defaultLength, int maximumLength);
}
// @interface EZPlot : UIView
[BaseType(typeof(UIView))]
interface EZPlot
{
// @property (nonatomic, strong) UIColor * backgroundColor;
[Export("backgroundColor", ArgumentSemantic.Strong)]
UIColor BackgroundColor { get; set; }
// @property (nonatomic, strong) UIColor * color;
[Export("color", ArgumentSemantic.Strong)]
UIColor Color { get; set; }
// @property (assign, nonatomic) float gain;
[Export("gain")]
float Gain { get; set; }
// @property (assign, nonatomic) EZPlotType plotType;
[Export("plotType", ArgumentSemantic.Assign)]
EZPlotType PlotType { get; set; }
// @property (assign, nonatomic) BOOL shouldFill;
[Export("shouldFill")]
bool ShouldFill { get; set; }
// @property (assign, nonatomic) BOOL shouldMirror;
[Export("shouldMirror")]
bool ShouldMirror { get; set; }
// -(void)clear;
[Export("clear")]
void Clear();
//todo write wrapper: had float*
// -(void)updateBuffer:(float *)buffer withBufferSize:(UInt32)bufferSize;
[Export("updateBuffer:withBufferSize:")]
void UpdateBuffer(IntPtr buffer, uint bufferSize);
}
// @protocol EZAudioDisplayLinkDelegate <NSObject>
[Protocol, Model]
[BaseType(typeof(NSObject))]
interface EZAudioDisplayLinkDelegate
{
// @required -(void)displayLinkNeedsDisplay:(EZAudioDisplayLink *)displayLink;
[Abstract]
[Export("displayLinkNeedsDisplay:")]
void DisplayLinkNeedsDisplay(EZAudioDisplayLink displayLink);
}
// @interface EZAudioDisplayLink : NSObject
[BaseType(typeof(NSObject))]
interface EZAudioDisplayLink
{
// +(instancetype)displayLinkWithDelegate:(id<EZAudioDisplayLinkDelegate>)delegate;
[Static]
[Export("displayLinkWithDelegate:")]
EZAudioDisplayLink DisplayLinkWithDelegate(EZAudioDisplayLinkDelegate @delegate);
[Wrap("WeakDelegate")]
EZAudioDisplayLinkDelegate Delegate { get; set; }
// @property (nonatomic, weak) id<EZAudioDisplayLinkDelegate> delegate;
[NullAllowed, Export("delegate", ArgumentSemantic.Weak)]
NSObject WeakDelegate { get; set; }
// -(void)start;
[Export("start")]
void Start();
// -(void)stop;
[Export("stop")]
void Stop();
}
// @interface EZAudioPlotWaveformLayer : CAShapeLayer
[BaseType(typeof(CAShapeLayer))]
interface EZAudioPlotWaveformLayer
{
}
// @interface EZAudioPlot : EZPlot
[BaseType(typeof(EZPlot))]
interface EZAudioPlot : EZAudioDisplayLinkDelegate
{
// @property (assign, nonatomic) BOOL shouldOptimizeForRealtimePlot;
[Export("shouldOptimizeForRealtimePlot")]
bool ShouldOptimizeForRealtimePlot { get; set; }
// @property (assign, nonatomic) BOOL shouldCenterYAxis;
[Export("shouldCenterYAxis")]
bool ShouldCenterYAxis { get; set; }
// @property (nonatomic, strong) EZAudioPlotWaveformLayer * waveformLayer;
[Export("waveformLayer", ArgumentSemantic.Strong)]
EZAudioPlotWaveformLayer WaveformLayer { get; set; }
// -(int)setRollingHistoryLength:(int)historyLength;
[Export("setRollingHistoryLength:")]
int SetRollingHistoryLength(int historyLength);
// -(int)rollingHistoryLength;
[Export("rollingHistoryLength")]
int RollingHistoryLength();
//todo write wrapper: had CGPathRef*, EZRect (EZRect is a CGRect on phone)
// -(CGPathRef)createPathWithPoints:(CGPoint *)points pointCount:(UInt32)pointCount inRect:(EZRect)rect;
[Export("createPathWithPoints:pointCount:inRect:")]
IntPtr CreatePathWithPoints(IntPtr points, uint pointCount, CGRect rect);
// -(int)defaultRollingHistoryLength;
[Export("defaultRollingHistoryLength")]
int DefaultRollingHistoryLength();
// -(void)setupPlot;
[Export("setupPlot")]
void SetupPlot();
// -(int)initialPointCount;
[Export("initialPointCount")]
int InitialPointCount();
// -(int)maximumRollingHistoryLength;
[Export("maximumRollingHistoryLength")]
int MaximumRollingHistoryLength();
// -(void)redraw;
[Export("redraw")]
void Redraw();
// -(void)setSampleData:(float *)data length:(int)length;
[Export("setSampleData:length:")]
void SetSampleData(IntPtr data, int length);
// @property (nonatomic, strong) EZAudioDisplayLink * displayLink;
[Export("displayLink", ArgumentSemantic.Strong)]
EZAudioDisplayLink DisplayLink { get; set; }
//todo write wrapper: had EZPlotHistoryInfo*
// @property (assign, nonatomic) EZPlotHistoryInfo * historyInfo;
[Export("historyInfo", ArgumentSemantic.Assign)]
IntPtr HistoryInfo { get; set; }
//todo write wrapper: had CGPoint*
// @property (assign, nonatomic) CGPoint * points;
[Export("points", ArgumentSemantic.Assign)]
IntPtr Points { get; set; }
// @property (assign, nonatomic) UInt32 pointCount;
[Export("pointCount")]
uint PointCount { get; set; }
}
#region Extension
/*
// @interface (EZAudioPlot) <EZAudioDisplayLinkDelegate>
[Category]
[BaseType(typeof(EZAudioPlot))]
interface EZAudioPlot_ : EZAudioDisplayLinkDelegate
{
// @property (nonatomic, strong) EZAudioDisplayLink * displayLink;
[Export("displayLink", ArgumentSemantic.Strong)]
EZAudioDisplayLink DisplayLink { get; set; }
//todo write wrapper: had EZPlotHistoryInfo*
// @property (assign, nonatomic) EZPlotHistoryInfo * historyInfo;
[Export("historyInfo", ArgumentSemantic.Assign)]
IntPtr HistoryInfo { get; set; }
//todo write wrapper: had CGPoint*
// @property (assign, nonatomic) CGPoint * points;
[Export("points", ArgumentSemantic.Assign)]
IntPtr Points { get; set; }
// @property (assign, nonatomic) UInt32 pointCount;
[Export("pointCount")]
uint PointCount { get; set; }
}*/
#endregion
// @interface EZAudioPlotGL : GLKView
[BaseType(typeof(GLKView))]
interface EZAudioPlotGL
{
// @property (nonatomic, strong) UIColor * backgroundColor;
[Export("backgroundColor", ArgumentSemantic.Strong)]
UIColor BackgroundColor { get; set; }
// @property (nonatomic, strong) UIColor * color;
[Export("color", ArgumentSemantic.Strong)]
UIColor Color { get; set; }
// @property (assign, nonatomic) float gain;
[Export("gain")]
float Gain { get; set; }
// @property (assign, nonatomic) EZPlotType plotType;
[Export("plotType", ArgumentSemantic.Assign)]
EZPlotType PlotType { get; set; }
// @property (assign, nonatomic) BOOL shouldFill;
[Export("shouldFill")]
bool ShouldFill { get; set; }
// @property (assign, nonatomic) BOOL shouldMirror;
[Export("shouldMirror")]
bool ShouldMirror { get; set; }
//todo write wrapper: had float* [DONE]
// -(void)updateBuffer:(float *)buffer withBufferSize:(UInt32)bufferSize;
[Export("updateBuffer:withBufferSize:")]//[Internal]
void UpdateBuffer(IntPtr buffer, uint bufferSize);
// -(int)setRollingHistoryLength:(int)historyLength;
[Export("setRollingHistoryLength:")]
int SetRollingHistoryLength(int historyLength);
// -(int)rollingHistoryLength;
[Export("rollingHistoryLength")]
int RollingHistoryLength();
// -(void)clear;
[Export("clear")]
void Clear();
// -(void)pauseDrawing;
[Export("pauseDrawing")]
void PauseDrawing();
// -(void)resumeDrawing;
[Export("resumeDrawing")]
void ResumeDrawing();
//todo write wrapper: had EZAudioPlotGLPoint*
// -(void)redrawWithPoints:(EZAudioPlotGLPoint *)points pointCount:(UInt32)pointCount baseEffect:(GLKBaseEffect *)baseEffect vertexBufferObject:(GLuint)vbo vertexArrayBuffer:(GLuint)vab interpolated:(BOOL)interpolated mirrored:(BOOL)mirrored gain:(float)gain;
[Export("redrawWithPoints:pointCount:baseEffect:vertexBufferObject:vertexArrayBuffer:interpolated:mirrored:gain:")]
void RedrawWithPoints(IntPtr points, uint pointCount, GLKBaseEffect baseEffect, uint vbo, uint vab, bool interpolated, bool mirrored, float gain);
// -(void)redraw;
[Export("redraw")]
void Redraw();
// -(void)setup;
[Export("setup")]
void Setup();
//todo write wrapper: had float*
// -(void)setSampleData:(float *)data length:(int)length;
[Export("setSampleData:length:")]
void SetSampleData(IntPtr data, int length);
// -(int)defaultRollingHistoryLength;
[Export("defaultRollingHistoryLength")]
int DefaultRollingHistoryLength();
// -(int)maximumRollingHistoryLength;
[Export("maximumRollingHistoryLength")]
int MaximumRollingHistoryLength();
}
/* Accelerate framework not fully supported
//// @protocol EZAudioFFTDelegate <NSObject>
//[Protocol, Model]
//[BaseType(typeof(NSObject))]
//interface EZAudioFFTDelegate
//{
// //todo write wrapper: had float*
// // @optional -(void)fft:(EZAudioFFT *)fft updatedWithFFTData:(float *)fftData bufferSize:(vDSP_Length)bufferSize;
// [Export("fft:updatedWithFFTData:bufferSize:")]ee
// void UpdatedWithFFTData(EZAudioFFT fft, IntPtr fftData, nuint bufferSize);
//}
//// @interface EZAudioFFT : NSObject
//[BaseType(typeof(NSObject))]
//interface EZAudioFFT
//{
// // -(instancetype)initWithMaximumBufferSize:(vDSP_Length)maximumBufferSize sampleRate:(float)sampleRate;
// [Export("initWithMaximumBufferSize:sampleRate:")]
// IntPtr Constructor(nuint maximumBufferSize, float sampleRate);
// // -(instancetype)initWithMaximumBufferSize:(vDSP_Length)maximumBufferSize sampleRate:(float)sampleRate delegate:(id<EZAudioFFTDelegate>)delegate;
// [Export("initWithMaximumBufferSize:sampleRate:delegate:")]
// IntPtr Constructor(nuint maximumBufferSize, float sampleRate, EZAudioFFTDelegate @delegate);
// // +(instancetype)fftWithMaximumBufferSize:(vDSP_Length)maximumBufferSize sampleRate:(float)sampleRate;
// [Static]
// [Export("fftWithMaximumBufferSize:sampleRate:")]
// EZAudioFFT FftWithMaximumBufferSize(nuint maximumBufferSize, float sampleRate);
// // +(instancetype)fftWithMaximumBufferSize:(vDSP_Length)maximumBufferSize sampleRate:(float)sampleRate delegate:(id<EZAudioFFTDelegate>)delegate;
// [Static]
// [Export("fftWithMaximumBufferSize:sampleRate:delegate:")]
// EZAudioFFT FftWithMaximumBufferSize(nuint maximumBufferSize, float sampleRate, EZAudioFFTDelegate @delegate);
// [Wrap("WeakDelegate")]
// EZAudioFFTDelegate Delegate { get; set; }
// // @property (nonatomic, weak) id<EZAudioFFTDelegate> delegate;
// [NullAllowed, Export("delegate", ArgumentSemantic.Weak)]
// NSObject WeakDelegate { get; set; }
// // @property (readonly, nonatomic) COMPLEX_SPLIT complexSplit;
// [Export("complexSplit")]
// COMPLEX_SPLIT ComplexSplit { get; }
// //todo write wrapper: had float*
// // @property (readonly, nonatomic) float * fftData;
// [Export("fftData")]
// IntPtr FftData { get; }
// // @property (readonly, nonatomic) FFTSetup fftSetup;
// [Export("fftSetup")]
// unsafe FFTSetup* FftSetup { get; }
// //todo write wrapper: had float*
// // @property (readonly, nonatomic) float * inversedFFTData;
// [Export("inversedFFTData")]
// IntPtr InversedFFTData { get; }
// // @property (readonly, nonatomic) float maxFrequency;
// [Export("maxFrequency")]
// float MaxFrequency { get; }
// // @property (readonly, nonatomic) vDSP_Length maxFrequencyIndex;
// [Export("maxFrequencyIndex")]
// nuint MaxFrequencyIndex { get; }
// // @property (readonly, nonatomic) float maxFrequencyMagnitude;
// [Export("maxFrequencyMagnitude")]
// float MaxFrequencyMagnitude { get; }
// // @property (readonly, nonatomic) vDSP_Length maximumBufferSize;
// [Export("maximumBufferSize")]
// nuint MaximumBufferSize { get; }
// // @property (readwrite, nonatomic) float sampleRate;
// [Export("sampleRate")]
// float SampleRate { get; set; }
// //todo write wrapper: 2 float*
// // -(float *)computeFFTWithBuffer:(float *)buffer withBufferSize:(UInt32)bufferSize;
// [Export("computeFFTWithBuffer:withBufferSize:")]
// IntPtr ComputeFFTWithBuffer(IntPtr buffer, uint bufferSize);
// // -(float)frequencyAtIndex:(vDSP_Length)index;
// [Export("frequencyAtIndex:")]
// float FrequencyAtIndex(nuint index);
// // -(float)frequencyMagnitudeAtIndex:(vDSP_Length)index;
// [Export("frequencyMagnitudeAtIndex:")]
// float FrequencyMagnitudeAtIndex(nuint index);
//}
//
//// @interface EZAudioFFTRolling : EZAudioFFT
//[BaseType(typeof(EZAudioFFT))]
//interface EZAudioFFTRolling
//{
// // -(instancetype)initWithWindowSize:(vDSP_Length)windowSize sampleRate:(float)sampleRate;
// [Export("initWithWindowSize:sampleRate:")]
// IntPtr Constructor(nuint windowSize, float sampleRate);
// // -(instancetype)initWithWindowSize:(vDSP_Length)windowSize sampleRate:(float)sampleRate delegate:(id<EZAudioFFTDelegate>)delegate;
// [Export("initWithWindowSize:sampleRate:delegate:")]
// IntPtr Constructor(nuint windowSize, float sampleRate, EZAudioFFTDelegate @delegate);
// // -(instancetype)initWithWindowSize:(vDSP_Length)windowSize historyBufferSize:(vDSP_Length)historyBufferSize sampleRate:(float)sampleRate;
// [Export("initWithWindowSize:historyBufferSize:sampleRate:")]
// IntPtr Constructor(nuint windowSize, nuint historyBufferSize, float sampleRate);
// // -(instancetype)initWithWindowSize:(vDSP_Length)windowSize historyBufferSize:(vDSP_Length)historyBufferSize sampleRate:(float)sampleRate delegate:(id<EZAudioFFTDelegate>)delegate;
// [Export("initWithWindowSize:historyBufferSize:sampleRate:delegate:")]
// IntPtr Constructor(nuint windowSize, nuint historyBufferSize, float sampleRate, EZAudioFFTDelegate @delegate);
// // +(instancetype)fftWithWindowSize:(vDSP_Length)windowSize sampleRate:(float)sampleRate;
// [Static]
// [Export("fftWithWindowSize:sampleRate:")]
// EZAudioFFTRolling FftWithWindowSize(nuint windowSize, float sampleRate);
// // +(instancetype)fftWithWindowSize:(vDSP_Length)windowSize sampleRate:(float)sampleRate delegate:(id<EZAudioFFTDelegate>)delegate;
// [Static]
// [Export("fftWithWindowSize:sampleRate:delegate:")]
// EZAudioFFTRolling FftWithWindowSize(nuint windowSize, float sampleRate, EZAudioFFTDelegate @delegate);
// // +(instancetype)fftWithWindowSize:(vDSP_Length)windowSize historyBufferSize:(vDSP_Length)historyBufferSize sampleRate:(float)sampleRate;
// [Static]
// [Export("fftWithWindowSize:historyBufferSize:sampleRate:")]
// EZAudioFFTRolling FftWithWindowSize(nuint windowSize, nuint historyBufferSize, float sampleRate);
// // +(instancetype)fftWithWindowSize:(vDSP_Length)windowSize historyBufferSize:(vDSP_Length)historyBufferSize sampleRate:(float)sampleRate delegate:(id<EZAudioFFTDelegate>)delegate;
// [Static]
// [Export("fftWithWindowSize:historyBufferSize:sampleRate:delegate:")]
// EZAudioFFTRolling FftWithWindowSize(nuint windowSize, nuint historyBufferSize, float sampleRate, EZAudioFFTDelegate @delegate);
// // @property (readonly, nonatomic) vDSP_Length windowSize;
// [Export("windowSize")]
// nuint WindowSize { get; }
// // @property (readonly, nonatomic) float * timeDomainData;
// [Export("timeDomainData")]
// IntPtr TimeDomainData { get; }
// // @property (readonly, nonatomic) UInt32 timeDomainBufferSize;
// [Export("timeDomainBufferSize")]
// uint TimeDomainBufferSize { get; }
//}
*/
// @interface EZAudioFloatConverter : NSObject
[BaseType(typeof(NSObject))]
interface EZAudioFloatConverter
{
// +(instancetype)converterWithInputFormat:(AudioStreamBasicDescription)inputFormat;
[Static]
[Export("converterWithInputFormat:")]
EZAudioFloatConverter ConverterWithInputFormat(AudioStreamBasicDescription inputFormat);
// @property (readonly, assign, nonatomic) AudioStreamBasicDescription inputFormat;
[Export("inputFormat", ArgumentSemantic.Assign)]
AudioStreamBasicDescription InputFormat { get; }
// @property (readonly, assign, nonatomic) AudioStreamBasicDescription floatFormat;
[Export("floatFormat", ArgumentSemantic.Assign)]
AudioStreamBasicDescription FloatFormat { get; }
// -(instancetype)initWithInputFormat:(AudioStreamBasicDescription)inputFormat;
[Export("initWithInputFormat:")]
IntPtr Constructor(AudioStreamBasicDescription inputFormat);
// -(void)convertDataFromAudioBufferList:(AudioBufferList *)audioBufferList withNumberOfFrames:(UInt32)frames toFloatBuffers:(float **)buffers;
[Export("convertDataFromAudioBufferList:withNumberOfFrames:toFloatBuffers:")]
void ConvertDataFromAudioBufferList(AudioBuffers audioBufferList, uint frames, IntPtr buffers);
// -(void)convertDataFromAudioBufferList:(AudioBufferList *)audioBufferList withNumberOfFrames:(UInt32)frames toFloatBuffers:(float **)buffers packetDescriptions:(AudioStreamPacketDescription *)packetDescriptions;
[Export("convertDataFromAudioBufferList:withNumberOfFrames:toFloatBuffers:packetDescriptions:")]
void ConvertDataFromAudioBufferList(AudioBuffers audioBufferList, uint frames, IntPtr buffers, IntPtr packetDescriptions);
}
//todo look at all the methods and properties with TPCircularBuffer *
// @interface EZAudio : NSObject
[BaseType(typeof(NSObject))]
interface EZAudio
{
// +(BOOL)shouldExitOnCheckResultFail __attribute__((deprecated("")));
// +(void)setShouldExitOnCheckResultFail:(BOOL)shouldExitOnCheckResultFail __attribute__((deprecated("")));
[Static]
[Export("shouldExitOnCheckResultFail")]
//[Verify(MethodToProperty)]
//todo check if this is right
bool ShouldExitOnCheckResultFail { get; set; }
// +(AudioBufferList *)audioBufferListWithNumberOfFrames:(UInt32)frames numberOfChannels:(UInt32)channels interleaved:(BOOL)interleaved __attribute__((deprecated("")));
[Static]
[Export("audioBufferListWithNumberOfFrames:numberOfChannels:interleaved:")]
AudioBuffers AudioBufferListWithNumberOfFrames(uint frames, uint channels, bool interleaved);
// +(float **)floatBuffersWithNumberOfFrames:(UInt32)frames numberOfChannels:(UInt32)channels __attribute__((deprecated("")));
[Static]
[Export("floatBuffersWithNumberOfFrames:numberOfChannels:")]
IntPtr FloatBuffersWithNumberOfFrames(uint frames, uint channels);
// +(void)freeBufferList:(AudioBufferList *)bufferList __attribute__((deprecated("")));
[Static]
[Export("freeBufferList:")]
void FreeBufferList(AudioBuffers bufferList);
// +(void)freeFloatBuffers:(float **)buffers numberOfChannels:(UInt32)channels __attribute__((deprecated("")));
[Static]
[Export("freeFloatBuffers:numberOfChannels:")]
void FreeFloatBuffers(IntPtr buffers, uint channels);
// +(AudioStreamBasicDescription)AIFFFormatWithNumberOfChannels:(UInt32)channels sampleRate:(float)sampleRate __attribute__((deprecated("")));
[Static]
[Export("AIFFFormatWithNumberOfChannels:sampleRate:")]
AudioStreamBasicDescription AIFFFormatWithNumberOfChannels(uint channels, float sampleRate);
// +(AudioStreamBasicDescription)iLBCFormatWithSampleRate:(float)sampleRate __attribute__((deprecated("")));
[Static]
[Export("iLBCFormatWithSampleRate:")]
AudioStreamBasicDescription ILBCFormatWithSampleRate(float sampleRate);
// +(AudioStreamBasicDescription)floatFormatWithNumberOfChannels:(UInt32)channels sampleRate:(float)sampleRate __attribute__((deprecated("")));
[Static]
[Export("floatFormatWithNumberOfChannels:sampleRate:")]
AudioStreamBasicDescription FloatFormatWithNumberOfChannels(uint channels, float sampleRate);
// +(AudioStreamBasicDescription)M4AFormatWithNumberOfChannels:(UInt32)channels sampleRate:(float)sampleRate __attribute__((deprecated("")));
[Static]
[Export("M4AFormatWithNumberOfChannels:sampleRate:")]
AudioStreamBasicDescription M4AFormatWithNumberOfChannels(uint channels, float sampleRate);
// +(AudioStreamBasicDescription)monoFloatFormatWithSampleRate:(float)sampleRate __attribute__((deprecated("")));
[Static]
[Export("monoFloatFormatWithSampleRate:")]
AudioStreamBasicDescription MonoFloatFormatWithSampleRate(float sampleRate);
// +(AudioStreamBasicDescription)monoCanonicalFormatWithSampleRate:(float)sampleRate __attribute__((deprecated("")));
[Static]
[Export("monoCanonicalFormatWithSampleRate:")]
AudioStreamBasicDescription MonoCanonicalFormatWithSampleRate(float sampleRate);
// +(AudioStreamBasicDescription)stereoCanonicalNonInterleavedFormatWithSampleRate:(float)sampleRate __attribute__((deprecated("")));
[Static]
[Export("stereoCanonicalNonInterleavedFormatWithSampleRate:")]
AudioStreamBasicDescription StereoCanonicalNonInterleavedFormatWithSampleRate(float sampleRate);
// +(AudioStreamBasicDescription)stereoFloatInterleavedFormatWithSampleRate:(float)sampleRate __attribute__((deprecated("")));
[Static]
[Export("stereoFloatInterleavedFormatWithSampleRate:")]
AudioStreamBasicDescription StereoFloatInterleavedFormatWithSampleRate(float sampleRate);
// +(AudioStreamBasicDescription)stereoFloatNonInterleavedFormatWithSampleRate:(float)sampleRate __attribute__((deprecated("")));
[Static]
[Export("stereoFloatNonInterleavedFormatWithSampleRate:")]
AudioStreamBasicDescription StereoFloatNonInterleavedFormatWithSampleRate(float sampleRate);
// +(BOOL)isFloatFormat:(AudioStreamBasicDescription)asbd __attribute__((deprecated("")));
[Static]
[Export("isFloatFormat:")]
bool IsFloatFormat(AudioStreamBasicDescription asbd);
// +(BOOL)isInterleaved:(AudioStreamBasicDescription)asbd __attribute__((deprecated("")));
[Static]
[Export("isInterleaved:")]
bool IsInterleaved(AudioStreamBasicDescription asbd);
// +(BOOL)isLinearPCM:(AudioStreamBasicDescription)asbd __attribute__((deprecated("")));
[Static]
[Export("isLinearPCM:")]
bool IsLinearPCM(AudioStreamBasicDescription asbd);
// +(void)printASBD:(AudioStreamBasicDescription)asbd __attribute__((deprecated("")));
[Static]
[Export("printASBD:")]
void PrintASBD(AudioStreamBasicDescription asbd);
// +(NSString *)displayTimeStringFromSeconds:(NSTimeInterval)seconds __attribute__((deprecated("")));
[Static]
[Export("displayTimeStringFromSeconds:")]
string DisplayTimeStringFromSeconds(double seconds);
// +(NSString *)stringForAudioStreamBasicDescription:(AudioStreamBasicDescription)asbd __attribute__((deprecated("")));
[Static]
[Export("stringForAudioStreamBasicDescription:")]
string StringForAudioStreamBasicDescription(AudioStreamBasicDescription asbd);
//todo write wrapper: had AudioStreamBasicDescription*
// +(void)setCanonicalAudioStreamBasicDescription:(AudioStreamBasicDescription *)asbd numberOfChannels:(UInt32)nChannels interleaved:(BOOL)interleaved __attribute__((deprecated("")));
[Static]
[Export("setCanonicalAudioStreamBasicDescription:numberOfChannels:interleaved:")]
void SetCanonicalAudioStreamBasicDescription(IntPtr asbd, uint nChannels, bool interleaved);
//todo write wrapper: 2 float*
// +(void)appendBufferAndShift:(float *)buffer withBufferSize:(int)bufferLength toScrollHistory:(float *)scrollHistory withScrollHistorySize:(int)scrollHistoryLength __attribute__((deprecated("")));
[Static]
[Export("appendBufferAndShift:withBufferSize:toScrollHistory:withScrollHistorySize:")]
void AppendBufferAndShift(IntPtr buffer, int bufferLength, IntPtr scrollHistory, int scrollHistoryLength);
//todo write wrapper: had float*
// +(void)appendValue:(float)value toScrollHistory:(float *)scrollHistory withScrollHistorySize:(int)scrollHistoryLength __attribute__((deprecated("")));
[Static]
[Export("appendValue:toScrollHistory:withScrollHistorySize:")]
void AppendValue(float value, IntPtr scrollHistory, int scrollHistoryLength);
// +(float)MAP:(float)value leftMin:(float)leftMin leftMax:(float)leftMax rightMin:(float)rightMin rightMax:(float)rightMax __attribute__((deprecated("")));
[Static]
[Export("MAP:leftMin:leftMax:rightMin:rightMax:")]
float MAP(float value, float leftMin, float leftMax, float rightMin, float rightMax);
//todo write wrapper: had float*
// +(float)RMS:(float *)buffer length:(int)bufferSize __attribute__((deprecated("")));
[Static]
[Export("RMS:length:")]
float RMS(IntPtr buffer, int bufferSize);
// +(float)SGN:(float)value __attribute__((deprecated("")));
[Static]
[Export("SGN:")]
float SGN(float value);
//todo write wrapper: had sbyte*
// +(void)checkResult:(OSStatus)result operation:(const char *)operation __attribute__((deprecated("")));
[Static]
[Export("checkResult:operation:")]
void CheckResult(int result, IntPtr operation);
// +(NSString *)stringFromUInt32Code:(UInt32)code __attribute__((deprecated("")));
[Static]
[Export("stringFromUInt32Code:")]
string StringFromUInt32Code(uint code);
//todo write wrapper: float** int*, float*, bool*
// +(void)updateScrollHistory:(float **)scrollHistory withLength:(int)scrollHistoryLength atIndex:(int *)index withBuffer:(float *)buffer withBufferSize:(int)bufferSize isResolutionChanging:(BOOL *)isChanging __attribute__((deprecated("")));
[Static]
[Export("updateScrollHistory:withLength:atIndex:withBuffer:withBufferSize:isResolutionChanging:")]
void UpdateScrollHistory(ref IntPtr scrollHistory, int scrollHistoryLength, IntPtr index, IntPtr buffer, int bufferSize, IntPtr isChanging);
//todo write wrapper: had TPCircularBuffer*
// +(void)appendDataToCircularBuffer:(TPCircularBuffer *)circularBuffer fromAudioBufferList:(AudioBufferList *)audioBufferList __attribute__((deprecated("")));
[Static]
[Export("appendDataToCircularBuffer:fromAudioBufferList:")]
void AppendDataToCircularBuffer(IntPtr circularBuffer, AudioBuffers audioBufferList);
//todo write wrapper: had TPCircularBuffer*
// +(void)circularBuffer:(TPCircularBuffer *)circularBuffer withSize:(int)size __attribute__((deprecated("")));
[Static]
[Export("circularBuffer:withSize:")]
void CircularBuffer(IntPtr circularBuffer, int size);
//todo write wrapper: had TPCircularBuffer*
// +(void)freeCircularBuffer:(TPCircularBuffer *)circularBuffer __attribute__((deprecated("")));
[Static]
[Export("freeCircularBuffer:")]
void FreeCircularBuffer(IntPtr circularBuffer);
}
} | 42.646986 | 261 | 0.761087 | [
"MIT"
] | NashZhou/EZAudioXamarinBinding | EZAudio/EZAudioBinding/EZAudioBinding/ApiDefinition.cs | 68,621 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.