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 SpiceSharp
{
/// <summary>
/// Exception for identifying a bad parameter.
/// </summary>
public class BadParameterException : CircuitException
{
/// <summary>
/// Initializes a new instance of the <see cref="BadParameterException"/> class.
/// </summary>
public BadParameterException() { }
/// <summary>
/// Initializes a new instance of the <see cref="BadParameterException"/> class.
/// </summary>
/// <param name="parameterName">Name of the parameter.</param>
public BadParameterException(string parameterName)
: base("Invalid parameter value for '{0}'".FormatString(parameterName))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BadParameterException"/> class.
/// </summary>
/// <param name="parameterName">Name of the parameter.</param>
/// <param name="innerException">The inner exception.</param>
public BadParameterException(string parameterName, Exception innerException)
: base("Invalid parameter value for '{0}'".FormatString(parameterName), innerException)
{
}
}
}
| 35.028571 | 99 | 0.613377 | [
"MIT"
] | AIFramework/SpiceSharp | SpiceSharpNetFr/Diagnostics/BadParameterException.cs | 1,228 | C# |
using System.Threading.Tasks;
using Pokemon.Domain.Services;
using Microsoft.Extensions.Logging;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using Pokemon.Services.Translations.Models;
namespace Pokemon.Services
{
public class TextTranslationProcessor : ITextTranslationProcessor
{
private readonly ILogger<TextTranslationProcessor> _logger;
private readonly IHttpClientFactory _httpClientFactory;
public TextTranslationProcessor(ILogger<TextTranslationProcessor> logger, IHttpClientFactory httpClientFactory)
{
_logger = logger;
_httpClientFactory = httpClientFactory;
}
public async Task<string> Process(string stringToTranslate, string translateTo)
{
_logger.LogInformation($"Translating {stringToTranslate} into {translateTo}");
var request = BuildRequestMessage(stringToTranslate,translateTo);
var client = _httpClientFactory.CreateClient("TranslationApi");
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
Translation translationResponse = null;
using var jsonStream = await response.Content.ReadAsStreamAsync();
translationResponse = await JsonSerializer.DeserializeAsync<Translation>(jsonStream);
if(translationResponse.TranslationSuccess.Total > 0)
{
return translationResponse.Contents.Translated;
}
}
return stringToTranslate;
}
// this could possibly be extracted into a message builder class
private HttpRequestMessage BuildRequestMessage(string stringToTranslate, string translateTo)
{
var json = JsonSerializer.Serialize(new { text = stringToTranslate });
var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
var request = new HttpRequestMessage(HttpMethod.Post, $"{translateTo}")
{
Content = stringContent
};
return request;
}
}
}
| 35.852459 | 119 | 0.656607 | [
"MIT"
] | thedarkjester/PokemonApi | code/src/Pokemon.Services/Translations/TextTranslationProcessor.cs | 2,189 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace FlowersCatsSurprise.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings) (global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.677419 | 151 | 0.584186 | [
"Apache-2.0"
] | AutomateThePlanet/AutomateThePlanet-Learning-Series | dotnet/GiftsForGeeks/FlowersCatsSurprise/Properties/Settings.Designer.cs | 1,077 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;
namespace Azure.Management.Network.Models
{
public partial class VpnSite : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
if (Etag != null)
{
writer.WritePropertyName("etag");
writer.WriteStringValue(Etag);
}
if (Id != null)
{
writer.WritePropertyName("id");
writer.WriteStringValue(Id);
}
if (Name != null)
{
writer.WritePropertyName("name");
writer.WriteStringValue(Name);
}
if (Type != null)
{
writer.WritePropertyName("type");
writer.WriteStringValue(Type);
}
if (Location != null)
{
writer.WritePropertyName("location");
writer.WriteStringValue(Location);
}
if (Tags != null)
{
writer.WritePropertyName("tags");
writer.WriteStartObject();
foreach (var item in Tags)
{
writer.WritePropertyName(item.Key);
writer.WriteStringValue(item.Value);
}
writer.WriteEndObject();
}
writer.WritePropertyName("properties");
writer.WriteStartObject();
if (VirtualWan != null)
{
writer.WritePropertyName("virtualWan");
writer.WriteObjectValue(VirtualWan);
}
if (DeviceProperties != null)
{
writer.WritePropertyName("deviceProperties");
writer.WriteObjectValue(DeviceProperties);
}
if (IpAddress != null)
{
writer.WritePropertyName("ipAddress");
writer.WriteStringValue(IpAddress);
}
if (SiteKey != null)
{
writer.WritePropertyName("siteKey");
writer.WriteStringValue(SiteKey);
}
if (AddressSpace != null)
{
writer.WritePropertyName("addressSpace");
writer.WriteObjectValue(AddressSpace);
}
if (BgpProperties != null)
{
writer.WritePropertyName("bgpProperties");
writer.WriteObjectValue(BgpProperties);
}
if (ProvisioningState != null)
{
writer.WritePropertyName("provisioningState");
writer.WriteStringValue(ProvisioningState.Value.ToString());
}
if (IsSecuritySite != null)
{
writer.WritePropertyName("isSecuritySite");
writer.WriteBooleanValue(IsSecuritySite.Value);
}
if (VpnSiteLinks != null)
{
writer.WritePropertyName("vpnSiteLinks");
writer.WriteStartArray();
foreach (var item in VpnSiteLinks)
{
writer.WriteObjectValue(item);
}
writer.WriteEndArray();
}
writer.WriteEndObject();
writer.WriteEndObject();
}
internal static VpnSite DeserializeVpnSite(JsonElement element)
{
string etag = default;
string id = default;
string name = default;
string type = default;
string location = default;
IDictionary<string, string> tags = default;
SubResource virtualWan = default;
DeviceProperties deviceProperties = default;
string ipAddress = default;
string siteKey = default;
AddressSpace addressSpace = default;
BgpSettings bgpProperties = default;
ProvisioningState? provisioningState = default;
bool? isSecuritySite = default;
IList<VpnSiteLink> vpnSiteLinks = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("etag"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
etag = property.Value.GetString();
continue;
}
if (property.NameEquals("id"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
id = property.Value.GetString();
continue;
}
if (property.NameEquals("name"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
name = property.Value.GetString();
continue;
}
if (property.NameEquals("type"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
type = property.Value.GetString();
continue;
}
if (property.NameEquals("location"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
location = property.Value.GetString();
continue;
}
if (property.NameEquals("tags"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
Dictionary<string, string> dictionary = new Dictionary<string, string>();
foreach (var property0 in property.Value.EnumerateObject())
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
dictionary.Add(property0.Name, null);
}
else
{
dictionary.Add(property0.Name, property0.Value.GetString());
}
}
tags = dictionary;
continue;
}
if (property.NameEquals("properties"))
{
foreach (var property0 in property.Value.EnumerateObject())
{
if (property0.NameEquals("virtualWan"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
virtualWan = SubResource.DeserializeSubResource(property0.Value);
continue;
}
if (property0.NameEquals("deviceProperties"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
deviceProperties = DeviceProperties.DeserializeDeviceProperties(property0.Value);
continue;
}
if (property0.NameEquals("ipAddress"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
ipAddress = property0.Value.GetString();
continue;
}
if (property0.NameEquals("siteKey"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
siteKey = property0.Value.GetString();
continue;
}
if (property0.NameEquals("addressSpace"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
addressSpace = AddressSpace.DeserializeAddressSpace(property0.Value);
continue;
}
if (property0.NameEquals("bgpProperties"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
bgpProperties = BgpSettings.DeserializeBgpSettings(property0.Value);
continue;
}
if (property0.NameEquals("provisioningState"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
provisioningState = new ProvisioningState(property0.Value.GetString());
continue;
}
if (property0.NameEquals("isSecuritySite"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
isSecuritySite = property0.Value.GetBoolean();
continue;
}
if (property0.NameEquals("vpnSiteLinks"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
List<VpnSiteLink> array = new List<VpnSiteLink>();
foreach (var item in property0.Value.EnumerateArray())
{
if (item.ValueKind == JsonValueKind.Null)
{
array.Add(null);
}
else
{
array.Add(VpnSiteLink.DeserializeVpnSiteLink(item));
}
}
vpnSiteLinks = array;
continue;
}
}
continue;
}
}
return new VpnSite(id, name, type, location, tags, etag, virtualWan, deviceProperties, ipAddress, siteKey, addressSpace, bgpProperties, provisioningState, isSecuritySite, vpnSiteLinks);
}
}
}
| 39.212625 | 197 | 0.405151 | [
"MIT"
] | AzureDataBox/azure-sdk-for-net | sdk/testcommon/Azure.Management.Network.2020_04/src/Generated/Models/VpnSite.Serialization.cs | 11,803 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Sarif;
using Microsoft.CodeAnalysis.Sarif.Baseline;
using Microsoft.CodeAnalysis.Sarif.Baseline.ResultMatching;
namespace SarifBaseline.Extensions
{
/// <summary>
/// DirectResultMatchingComparer is an adapter for ResultMatchingComparer for bare Results.
/// This sorts Results as needed for the Result Matching algorithm.
/// This adapter is used to keep persisted baselines ideally sorted.
/// </summary>
public class DirectResultMatchingComparer : IComparer<Result>
{
public static DirectResultMatchingComparer Instance = new DirectResultMatchingComparer();
public int Compare(Result left, Result right)
{
return ResultMatchingComparer.Instance.Compare(new ExtractedResult(left, left.Run), new ExtractedResult(right, right.Run));
}
}
}
| 36.333333 | 135 | 0.743119 | [
"MIT"
] | Eduardo-Silla/sarif-sdk | src/Test.EndToEnd.Baselining/Extensions/DirectResultMatchingComparer.cs | 981 | C# |
using System;
using System.Collections.Generic;
using Shouldly;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
List<string> steList = new List<string> { "A2", "A1", "A1" };
try
{
steList.ShouldAllBeEqual();
} catch(Exception EX)
{
Console.WriteLine(EX.Message);
Console.ReadLine();
}
}
}
}
| 19.833333 | 73 | 0.476891 | [
"BSD-3-Clause"
] | Haneen96/shouldly | src/ConsoleApp1/Program.cs | 478 | C# |
/* ====================================================================
Licensed To the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file To You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed To in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
/* ================================================================
* About NPOI
* Author: Tony Qu
* Author's email: tonyqus (at) gmail.com
* Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn)
* HomePage: http://www.codeplex.com/npoi
* Contributors:
*
* ==============================================================*/
namespace Zephyr.Utils.NPOI.HPSF
{
using System;
using Zephyr.Utils.NPOI.Util;
/// <summary>
/// Class To manipulate data in the Clipboard Variant (Variant#VT_CF VT_CF) format.
/// @author Drew Varner (Drew.Varner inOrAround sc.edu)
/// @since 2002-04-29
/// </summary>
public class Thumbnail
{
/// <summary>
/// OffSet in bytes where the Clipboard Format Tag starts in the <c>byte[]</c> returned by SummaryInformation#GetThumbnail()
/// </summary>
public const int OFFSet_CFTAG = 4;
/// <summary>
/// OffSet in bytes where the Clipboard Format starts in the <c>byte[]</c> returned by SummaryInformation#GetThumbnail()
/// </summary>
/// <remarks>This is only valid if the Clipboard Format Tag is CFTAG_WINDOWS</remarks>
public const int OFFSet_CF = 8;
/// <summary>
/// OffSet in bytes where the Windows Metafile (WMF) image data starts in the <c>byte[]</c> returned by SummaryInformation#GetThumbnail()
/// There is only WMF data at this point in the
/// <c>byte[]</c> if the Clipboard Format Tag is
/// CFTAG_WINDOWS and the Clipboard Format is
/// CF_METAFILEPICT.
/// </summary>
/// <remarks>Note: The <c>byte[]</c> that starts at
/// <c>OFFSet_WMFDATA</c> and ends at
/// <c>GetThumbnail().Length - 1</c> forms a complete WMF
/// image. It can be saved To disk with a <c>.wmf</c> file
/// type and Read using a WMF-capable image viewer.</remarks>
public const int OFFSet_WMFDATA = 20;
/// <summary>
/// Clipboard Format Tag - Windows clipboard format
/// </summary>
/// <remarks>A <c>DWORD</c> indicating a built-in Windows clipboard format value</remarks>
public const int CFTAG_WINDOWS = -1;
/// <summary>
/// Clipboard Format Tag - Macintosh clipboard format
/// </summary>
/// <remarks>A <c>DWORD</c> indicating a Macintosh clipboard format value</remarks>
public const int CFTAG_MACINTOSH = -2;
/// <summary>
/// Clipboard Format Tag - Format ID
/// </summary>
/// <remarks>A GUID containing a format identifier (FMTID). This is rarely used.</remarks>
public const int CFTAG_FMTID = -3;
/// <summary>
/// Clipboard Format Tag - No Data
/// </summary>
/// <remarks>A <c>DWORD</c> indicating No data. This is rarely used.</remarks>
public const int CFTAG_NODATA = 0;
/// <summary>
/// Clipboard Format - Windows metafile format. This is the recommended way To store thumbnails in Property Streams.
/// </summary>
/// <remarks>Note:This is not the same format used in
/// regular WMF images. The clipboard version of this format has an
/// extra clipboard-specific header.</remarks>
public const int CF_METAFILEPICT = 3;
/// <summary>
/// Clipboard Format - Device Independent Bitmap
/// </summary>
public const int CF_DIB = 8;
/// <summary>
/// Clipboard Format - Enhanced Windows metafile format
/// </summary>
public const int CF_ENHMETAFILE = 14;
/// <summary>
/// Clipboard Format - Bitmap
/// </summary>
/// <remarks>see msdn.microsoft.com/library/en-us/dnw98bk/html/clipboardoperations.asp</remarks>
[Obsolete]
public const int CF_BITMAP = 2;
/**
* A <c>byte[]</c> To hold a thumbnail image in (
* Variant#VT_CF VT_CF) format.
*/
private byte[] thumbnailData = null;
/// <summary>
/// Default Constructor. If you use it then one you'll have To Add
/// the thumbnail <c>byte[]</c> from {@link
/// SummaryInformation#GetThumbnail()} To do any useful
/// manipulations, otherwise you'll Get a
/// <c>NullPointerException</c>.
/// </summary>
public Thumbnail()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Thumbnail"/> class.
/// </summary>
/// <param name="thumbnailData">The thumbnail data.</param>
public Thumbnail(byte[] thumbnailData)
{
this.thumbnailData = thumbnailData;
}
/// <summary>
/// Gets or sets the thumbnail as a <c>byte[]</c> in {@link
/// Variant#VT_CF VT_CF} format.
/// </summary>
/// <value>The thumbnail value</value>
public byte[] ThumbnailData
{
get
{
return thumbnailData;
}
set { this.thumbnailData = value; }
}
/// <summary>
/// Returns an <c>int</c> representing the Clipboard
/// Format Tag
/// Possible return values are:
/// <ul>
/// <li>{@link #CFTAG_WINDOWS CFTAG_WINDOWS}</li>
/// <li>{@link #CFTAG_MACINTOSH CFTAG_MACINTOSH}</li>
/// <li>{@link #CFTAG_FMTID CFTAG_FMTID}</li>
/// <li>{@link #CFTAG_NODATA CFTAG_NODATA}</li>
/// </ul>
/// </summary>
/// <returns>A flag indicating the Clipboard Format Tag</returns>
public long ClipboardFormatTag
{
get
{
long clipboardFormatTag = LittleEndian.GetUInt(this.ThumbnailData,
OFFSet_CFTAG);
return clipboardFormatTag;
}
}
/// <summary>
/// Returns an <c>int</c> representing the Clipboard
/// Format
/// Will throw an exception if the Thumbnail's Clipboard Format
/// Tag is not {@link Thumbnail#CFTAG_WINDOWS CFTAG_WINDOWS}.
/// Possible return values are:
/// <ul>
/// <li>{@link #CF_METAFILEPICT CF_METAFILEPICT}</li>
/// <li>{@link #CF_DIB CF_DIB}</li>
/// <li>{@link #CF_ENHMETAFILE CF_ENHMETAFILE}</li>
/// <li>{@link #CF_BITMAP CF_BITMAP}</li>
/// </ul>
/// </summary>
/// <returns>a flag indicating the Clipboard Format</returns>
public long GetClipboardFormat()
{
if (!(ClipboardFormatTag == CFTAG_WINDOWS))
throw new HPSFException("Clipboard Format Tag of Thumbnail must " +
"be CFTAG_WINDOWS.");
return LittleEndian.GetUInt(this.ThumbnailData, OFFSet_CF);
}
/// <summary>
/// Returns the Thumbnail as a <c>byte[]</c> of WMF data
/// if the Thumbnail's Clipboard Format Tag is {@link
/// #CFTAG_WINDOWS CFTAG_WINDOWS} and its Clipboard Format is
/// {@link #CF_METAFILEPICT CF_METAFILEPICT}
/// This
/// <c>byte[]</c> is in the traditional WMF file, not the
/// clipboard-specific version with special headers.
/// See <a href="http://www.wvware.com/caolan/ora-wmf.html" tarGet="_blank">http://www.wvware.com/caolan/ora-wmf.html</a>
/// for more information on the WMF image format.
/// @return A WMF image of the Thumbnail
/// @throws HPSFException if the Thumbnail isn't CFTAG_WINDOWS and
/// CF_METAFILEPICT
/// </summary>
/// <returns></returns>
public byte[] GetThumbnailAsWMF()
{
if (!(ClipboardFormatTag == CFTAG_WINDOWS))
throw new HPSFException("Clipboard Format Tag of Thumbnail must " +
"be CFTAG_WINDOWS.");
if (!(GetClipboardFormat() == CF_METAFILEPICT))
throw new HPSFException("Clipboard Format of Thumbnail must " +
"be CF_METAFILEPICT.");
else
{
byte[] thumbnail = this.ThumbnailData;
int wmfImageLength = thumbnail.Length - OFFSet_WMFDATA;
byte[] wmfImage = new byte[wmfImageLength];
Array.Copy(thumbnail,
OFFSet_WMFDATA,
wmfImage,
0,
wmfImageLength);
return wmfImage;
}
}
}
} | 38.408 | 145 | 0.552177 | [
"MIT"
] | zhupangithub/WEBERP | Code/Zephyr.Net/Zephyr.Utils/Document/Excel/NPOI/HPSF/Thumbnail.cs | 9,602 | C# |
class MyClass {
public static void Main() {
double d = 3.2;
/* inserted */
int _5 = 7;
int i1 = d;
}
}
class DerivedClass: MyClass {}
| 15.5 | 30 | 0.548387 | [
"Apache-2.0"
] | thufv/DeepFix-C- | data/Mutation/CS0266_2_mutation_04/[E]CS0266.cs | 157 | C# |
// Copyright (c) Philipp Wagner. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
namespace ApacheJenaSample.Csv.Aotp.Model
{
public class Flight
{
/// <summary>
/// Year
/// </summary>
public int Year { get; set; }
/// <summary>
/// Month
/// </summary>
public int Month { get; set; }
/// <summary>
/// Day of Month.
/// </summary>
public int DayOfMonth { get; set; }
/// <summary>
/// Day of Week.
/// </summary>
public int DayOfWeek { get; set; }
/// <summary>
/// Flight Date (yyyy-MM-dd)
/// </summary>
public DateTime FlightDate { get; set; }
/// <summary>
/// Unique Carrier Code. When the same code has been used by multiple carriers, a numeric suffix is
/// used for earlier users, for example, PA, PA(1), PA(2). Use this field for analysis across a range
/// of years.
/// </summary>
public string UniqueCarrier { get; set; }
/// <summary>
/// Tail Number.
/// </summary>
public string TailNumber { get; set; }
/// <summary>
/// Flight Number.
/// </summary>
public string FlightNumber { get; set; }
/// <summary>
/// Origin Airport, Airport ID. An identification number assigned by US DOT to identify a unique airport. Use
/// this field for airport analysis across a range of years because an airport can change its airport code
/// and airport codes can be reused.
/// </summary>
public string OriginAirport { get; set; }
/// <summary>
/// Origin Airport.
/// </summary>
public string Origin { get; set; }
/// <summary>
/// Origin Airport, State Code.
/// </summary>
public string OriginState { get; set; }
/// <summary>
/// Destination Airport, Airport ID. An identification number assigned by US DOT to identify a unique airport. Use
/// this field for airport analysis across a range of years because an airport can change its airport code
/// and airport codes can be reused.
/// </summary>
public string DestinationAirport { get; set; }
/// <summary>
/// Destination Airport.
/// </summary>
public string Destination { get; set; }
/// <summary>
/// Destination Airport, State Code.
/// </summary>
public string DestinationState { get; set; }
/// <summary>
/// CRS Departure Time (local time: hhmm).
/// </summary>
public TimeSpan? ScheduledDepartureTime { get; set; }
/// <summary>
/// Actual Departure Time (local time: hhmm).
/// </summary>
public TimeSpan? ActualDepartureTime { get; set; }
/// <summary>
/// Difference in minutes between scheduled and actual departure time. Early departures show negative numbers.
/// </summary>
public int? DepartureDelay { get; set; }
/// <summary>
/// Difference in minutes between scheduled and actual departure time. Early departures set to 0.
/// </summary>
public int? DepartureDelayNew { get; set; }
/// <summary>
/// Departure Delay Indicator, 15 Minutes or More (1=Yes).
/// </summary>
public bool? DepartureDelayIndicator { get; set; }
/// <summary>
/// Departure Delay intervals, every (15 minutes from -15 to 180).
/// </summary>
public string DepartureDelayGroup { get; set; }
/// <summary>
/// Taxi Out Time, in Minutes.
/// </summary>
public int? TaxiOut { get; set; }
/// <summary>
/// Wheels Off Time (local time: hhmm).
/// </summary>
public TimeSpan? WheelsOff { get; set; }
/// <summary>
/// Wheels On Time (local time: hhmm).
/// </summary>
public TimeSpan? WheelsOn { get; set; }
/// <summary>
/// Taxi In Time, in Minutes.
/// </summary>
public int? TaxiIn { get; set; }
/// <summary>
/// CRS Arrival Time (local time: hhmm).
/// </summary>
public TimeSpan? ScheduledArrivalTime { get; set; }
/// <summary>
/// Actual Arrival Time (local time: hhmm).
/// </summary>
public TimeSpan? ActualArrivalTime { get; set; }
/// <summary>
/// Difference in minutes between scheduled and actual arrival time. Early arrivals show negative numbers.
/// </summary>
public int? ArrivalDelay { get; set; }
/// <summary>
/// Difference in minutes between scheduled and actual arrival time. Early arrivals set to 0.
/// </summary>
public int? ArrivalDelayNew { get; set; }
/// <summary>
/// Arrival Delay Indicator, 15 Minutes or More (1=Yes).
/// </summary>
public bool? ArrivalDelayIndicator { get; set; }
/// <summary>
/// Arrival Delay intervals, every (15-minutes from -15 to 180).
/// </summary>
public string ArrivalDelayGroup { get; set; }
/// <summary>
/// Cancelled Flight Indicator (1=Yes).
/// </summary>
public bool? CancelledFlight { get; set; }
/// <summary>
/// Specifies The Reason For Cancellation.
/// </summary>
public string CancellationCode { get; set; }
/// <summary>
/// Diverted Flight Indicator (1=Yes).
/// </summary>
public bool? DivertedFlight { get; set; }
/// <summary>
/// CRS Elapsed Time of Flight, in Minutes.
/// </summary>
public int? ScheduledElapsedTimeOfFlight { get; set; }
/// <summary>
/// Actual Elapsed Time of Flight, in Minutes.
/// </summary>
public int? ActualElapsedTimeOfFlight { get; set; }
/// <summary>
/// Flight Time, in Minutes.
/// </summary>
public int? AirTime { get; set; }
/// <summary>
/// Number of Flights.
/// </summary>
public int? NumberOfFlights { get; set; }
/// <summary>
/// Distance between airports (miles).
/// </summary>
public float? Distance { get; set; }
/// <summary>
/// Distance Intervals, every 250 Miles, for Flight Segment.
/// </summary>
public int? DistanceGroup { get; set; }
/// <summary>
/// Carrier Delay, in Minutes.
/// </summary>
public int? CarrierDelay { get; set; }
/// <summary>
/// Weather Delay, in Minutes.
/// </summary>
public int? WeatherDelay { get; set; }
/// <summary>
/// National Air System Delay, in Minutes.
/// </summary>
public int? NasDelay { get; set; }
/// <summary>
/// Security Delay, in Minutes.
/// </summary>
public int? SecurityDelay { get; set; }
/// <summary>
/// Late Aircraft Delay, in Minutes.
/// </summary>
public int? LateAircraftDelay { get; set; }
}
} | 31.152542 | 123 | 0.535229 | [
"MIT"
] | bytefish/ApacheJenaSample | ApacheJenaSample/ApacheJenaSample.Csv.Aotp/Model/Flight.cs | 7,352 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System.Runtime.Serialization;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// This class stores several source parsing related options and offers access to their values.
/// </summary>
[Serializable]
public sealed class CSharpParseOptions : ParseOptions, IEquatable<CSharpParseOptions>, ISerializable
{
/// <summary>
/// The default parse options.
/// </summary>
public static readonly CSharpParseOptions Default = new CSharpParseOptions();
/// <summary>
/// Gets the language version.
/// </summary>
public readonly LanguageVersion LanguageVersion;
internal readonly ImmutableArray<string> PreprocessorSymbols;
/// <summary>
/// Gets the names of defined preprocessor symbols.
/// </summary>
public override IEnumerable<string> PreprocessorSymbolNames
{
get { return PreprocessorSymbols; }
}
// NOTE: warnaserror[+|-], warnaserror[+|-]:<warn list>, unsafe[+|-], warn:<n>, nowarn:<warn list>
public CSharpParseOptions(
LanguageVersion languageVersion = LanguageVersion.CSharp6,
DocumentationMode documentationMode = DocumentationMode.Parse,
SourceCodeKind kind = SourceCodeKind.Regular,
params string[] preprocessorSymbols)
: this(languageVersion, documentationMode, kind, preprocessorSymbols.AsImmutableOrEmpty())
{
}
public CSharpParseOptions(
LanguageVersion languageVersion = LanguageVersion.CSharp6,
DocumentationMode documentationMode = DocumentationMode.Parse,
SourceCodeKind kind = SourceCodeKind.Regular,
ImmutableArray<string> preprocessorSymbols = default(ImmutableArray<string>))
: this(languageVersion, documentationMode, kind, preprocessorSymbols.NullToEmpty(), privateCtor: true)
{
if (!languageVersion.IsValid())
{
throw new ArgumentOutOfRangeException("languageVersion");
}
if (!kind.IsValid())
{
throw new ArgumentOutOfRangeException("kind");
}
if (!preprocessorSymbols.IsDefaultOrEmpty)
{
foreach (var preprocessorSymbol in preprocessorSymbols)
{
if (!SyntaxFacts.IsValidIdentifier(preprocessorSymbol))
{
throw new ArgumentException("preprocessorSymbols");
}
}
}
}
// No validation
internal CSharpParseOptions(
LanguageVersion languageVersion,
DocumentationMode documentationMode,
SourceCodeKind kind,
ImmutableArray<string> preprocessorSymbols,
bool privateCtor) //dummy param to distinguish from public ctor
: base(kind, documentationMode)
{
Debug.Assert(!preprocessorSymbols.IsDefault);
this.LanguageVersion = languageVersion;
this.PreprocessorSymbols = preprocessorSymbols;
}
public new CSharpParseOptions WithKind(SourceCodeKind kind)
{
if (kind == this.Kind)
{
return this;
}
if (!kind.IsValid())
{
throw new ArgumentOutOfRangeException("kind");
}
return new CSharpParseOptions(
this.LanguageVersion,
this.DocumentationMode,
kind,
this.PreprocessorSymbols,
privateCtor: true
);
}
protected override ParseOptions CommonWithKind(SourceCodeKind kind)
{
return WithKind(kind);
}
protected override ParseOptions CommonWithDocumentationMode(DocumentationMode documentationMode)
{
return WithDocumentationMode(documentationMode);
}
public CSharpParseOptions WithLanguageVersion(LanguageVersion version)
{
if (version == this.LanguageVersion)
{
return this;
}
if (!version.IsValid())
{
throw new ArgumentOutOfRangeException("version");
}
return new CSharpParseOptions(
version,
this.DocumentationMode,
this.Kind,
this.PreprocessorSymbols,
privateCtor: true
);
}
public CSharpParseOptions WithPreprocessorSymbols(IEnumerable<string> preprocessorSymbols)
{
return WithPreprocessorSymbols(preprocessorSymbols.AsImmutableOrNull());
}
public CSharpParseOptions WithPreprocessorSymbols(params string[] preprocessorSymbols)
{
return WithPreprocessorSymbols(ImmutableArray.Create<string>(preprocessorSymbols));
}
public CSharpParseOptions WithPreprocessorSymbols(ImmutableArray<string> symbols)
{
if (symbols.IsDefault)
{
symbols = ImmutableArray<string>.Empty;
}
if (symbols.Equals(this.PreprocessorSymbols))
{
return this;
}
return new CSharpParseOptions(
this.LanguageVersion,
this.DocumentationMode,
this.Kind,
symbols,
privateCtor: true
);
}
public new CSharpParseOptions WithDocumentationMode(DocumentationMode documentationMode)
{
if (documentationMode == this.DocumentationMode)
{
return this;
}
if (!documentationMode.IsValid())
{
throw new ArgumentOutOfRangeException("documentationMode");
}
return new CSharpParseOptions(
this.LanguageVersion,
documentationMode,
this.Kind,
this.PreprocessorSymbols,
privateCtor: true
);
}
public override bool Equals(object obj)
{
return this.Equals(obj as CSharpParseOptions);
}
public bool Equals(CSharpParseOptions other)
{
if (object.ReferenceEquals(this, other))
{
return true;
}
if (!base.EqualsHelper(other))
{
return false;
}
return this.LanguageVersion == other.LanguageVersion;
}
public override int GetHashCode()
{
return
Hash.Combine(base.GetHashCodeHelper(),
Hash.Combine((int)this.LanguageVersion, 0));
}
#region "serialization"
private CSharpParseOptions(SerializationInfo info, StreamingContext context)
: base(info, context)
{
//public readonly LanguageVersion LanguageVersion;
this.LanguageVersion = (LanguageVersion)info.GetValue("LanguageVersion", typeof(LanguageVersion));
//internal readonly ImmutableArray<string> PreprocessorSymbols;
this.PreprocessorSymbols = info.GetArray<string>("PreprocessorSymbols");
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
//public readonly LanguageVersion LanguageVersion;
info.AddValue("LanguageVersion", this.LanguageVersion, typeof(LanguageVersion));
//internal readonly ImmutableArray<string> PreprocessorSymbols;
info.AddArray("PreprocessorSymbols", this.PreprocessorSymbols);
}
#endregion
}
} | 33.071429 | 184 | 0.590113 | [
"Apache-2.0"
] | codemonkey85/roslyn | Src/Compilers/CSharp/Source/CSharpParseOptions.cs | 8,336 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System.IO;
using Newtonsoft.Json;
namespace AndroidApp
{
class AppConfiguration
{
private static AppConfiguration _singleton = null;
// User Unchangeable Settings
public string redirect_uri = "msauth://com.companyname.androidapp/DWxBsg%2FQ8zSqNAzwnqv6YIZbJr4%3D";
// Loadable / User Changable Settings
public string apiUrl { get; set; }
public string tenant { get; set; }
public string clientId { get; set; }
public string[] scopes { get; set; }
public static AppConfiguration Config(Stream configFileStream)
{
if (_singleton == null)
{
using (StreamReader streamReader = new StreamReader(configFileStream))
{
// Initialize
var settingsFileContent = streamReader.ReadToEnd();
_singleton = JsonConvert.DeserializeObject<AppConfiguration>(settingsFileContent);
}
}
return _singleton;
}
private AppConfiguration()
{
}
}
} | 25.903846 | 108 | 0.608018 | [
"MIT"
] | h2floh/KITEDemo | AndroidApp/AppConfiguration.cs | 1,349 | C# |
//
// Copyright 2015 Blu Age Corporation - Plano, Texas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Summer.Batch.Extra.Utils;
using System;
using System.Globalization;
namespace Summer.Batch.CoreTests.Util
{
[TestClass]
public sealed class BigDecimalUtilsTests
{
#region Test Abs.
[TestMethod]
public void BigDecimalUtils_Abs1Test()
{
decimal? decimal1 = 1.0m;
decimal? result = BigDecimalUtils.Abs(decimal1);
Assert.IsNotNull(result);
Assert.AreEqual(1, (int)result);
Assert.AreEqual(1L, (long)result);
Assert.AreEqual(1.0f, (float)result);
Assert.AreEqual(1.0d, (double)result);
string s = BigDecimalUtils.ToString(result);
Assert.AreEqual("1.0", BigDecimalUtils.ToString(result));
Assert.AreEqual((byte) 1, (byte)result);
Assert.AreEqual((short) 1, (short)result);
}
[TestMethod]
public void BigDecimalUtils_Abs2Test()
{
decimal? decimal1 = null;
decimal? result = BigDecimalUtils.Abs(decimal1);
Assert.AreEqual(null, result);
}
#endregion
#region Test Add.
[TestMethod]
public void BigDecimalUtils_Add1Test()
{
decimal? decimal1 = 1.0m;
decimal? decimal2 = 1.0m;
decimal? result = BigDecimalUtils.Add(decimal1, decimal2);
Assert.IsNotNull(result);
Assert.AreEqual(2, (int)result);
Assert.AreEqual(2L, (long)result);
Assert.AreEqual(2.0f, (float)result, 1.0f);
Assert.AreEqual(2.0, (double)result, 1.0);
Assert.AreEqual("2.0", BigDecimalUtils.ToString(result));
Assert.AreEqual((byte) 2, (byte)result);
Assert.AreEqual((short) 2, (short)result);
}
[TestMethod]
public void BigDecimalUtils_Add2Test()
{
decimal? decimal1 = 1.0m;
decimal? decimal2 = null;
decimal? result = BigDecimalUtils.Add(decimal1, decimal2);
Assert.IsNotNull(result);
Assert.AreEqual(1, (int)result);
Assert.AreEqual(1L, (long)result);
Assert.AreEqual(1.0f, (float)result, 1.0f);
Assert.AreEqual(1.0d, (double)result, 1.0d);
Assert.AreEqual("1.0", BigDecimalUtils.ToString(result));
Assert.AreEqual((byte) 1, (byte)result);
Assert.AreEqual((short) 1, (short)result);
}
[TestMethod]
public void BigDecimalUtils_Add3Test()
{
decimal? decimal1 = null;
decimal? decimal2 = 1.0m;
decimal? result = BigDecimalUtils.Add(decimal1, decimal2);
Assert.IsNotNull(result);
Assert.AreEqual(1, (int)result);
Assert.AreEqual(1L, (long)result);
Assert.AreEqual(1.0f, (float)result, 1.0f);
Assert.AreEqual(1.0d, (double)result, 1.0d);
Assert.AreEqual("1.0", BigDecimalUtils.ToString(result));
Assert.AreEqual((byte) 1, (byte)result);
Assert.AreEqual((short) 1, (short)result);
}
#endregion
#region Test CompareTo.
[TestMethod]
public void BigDecimalUtils_CompareTo1Test()
{
decimal? decimal1 = 1.0m;
decimal? decimal2 = 1.0m;
int? result = BigDecimalUtils.CompareTo(decimal1, decimal2);
Assert.IsNotNull(result);
Assert.AreEqual((byte) 0, (byte)result);
Assert.AreEqual((short) 0, (short)result);
Assert.AreEqual(0, (int)result);
Assert.AreEqual(0L, (long)result);
Assert.AreEqual(0.0f, (float)result);
Assert.AreEqual(0.0d, (double)result);
Assert.AreEqual("0", result.ToString());
}
[TestMethod]
public void BigDecimalUtils_CompareTo2Test()
{
decimal? decimal1 = null;
decimal? decimal2 = 1.0m;
int? result = BigDecimalUtils.CompareTo(decimal1, decimal2);
Assert.AreEqual(null, result);
}
[TestMethod]
public void BigDecimalUtils_CompareTo3Test()
{
decimal? decimal1 = 1.0m;
decimal? decimal2 = null;
int? result = BigDecimalUtils.CompareTo(decimal1, decimal2);
Assert.AreEqual(null, result);
}
#endregion
#region Test Divide.
[TestMethod]
public void BigDecimalUtils_Divide1Test() {
decimal? decimal1 = 1.0m;
decimal? decimal2 = 1.0m;
int scale = 1;
decimal? result = BigDecimalUtils.Divide(decimal1,decimal2,scale);
Assert.IsNotNull(result);
Assert.AreEqual(1, (int)result);
Assert.AreEqual(1L, (long)result);
Assert.AreEqual(1.0f, (float)result);
Assert.AreEqual(1.0d, (double)result);
Assert.AreEqual("1", BigDecimalUtils.ToString(result));
Assert.AreEqual((byte) 1, (byte)result);
Assert.AreEqual((short) 1, (short)result);
}
[TestMethod]
public void BigDecimalUtils_Divide2Test()
{
decimal? decimal1 = 1.0m;
decimal? decimal2 = 3.0m;
int scale = 2;
decimal? result = BigDecimalUtils.Divide(decimal1, decimal2, scale);
Assert.IsNotNull(result);
Assert.AreEqual(0, (int)result);
Assert.AreEqual(0L, (long)result);
Assert.AreEqual(0.33f, (float)result);
Assert.AreEqual(0.33d, (double)result);
Assert.AreEqual("0.33", BigDecimalUtils.ToString(result));
Assert.AreEqual((byte)0, (byte)result);
Assert.AreEqual((short)0, (short)result);
}
[TestMethod]
public void BigDecimalUtils_Divide3Test()
{
decimal? decimal1 = 2.0m;
decimal? decimal2 = 3.0m;
int scale = 26;
decimal? result = BigDecimalUtils.Divide(decimal1, decimal2, scale);
Assert.IsNotNull(result);
Assert.AreEqual(0, (int)result);
Assert.AreEqual(0L, (long)result);
Assert.AreEqual(0.66666666666666666666666667f, (float)result);
Assert.AreEqual(0.66666666666666666666666667d, (double)result);
Assert.AreEqual("0.66666666666666666666666667", BigDecimalUtils.ToString(result));
Assert.AreEqual((byte)0, (byte)result);
Assert.AreEqual((short)0, (short)result);
}
[TestMethod]
public void BigDecimalUtils_Divide4Test() {
decimal? decimal1 = null;
decimal? decimal2 = 1.0m;
int scale = 1;
decimal? result = BigDecimalUtils.Divide(decimal1, decimal2, scale);
Assert.AreEqual(null, result);
}
[TestMethod]
public void BigDecimalUtils_Divide5Test() {
decimal? decimal1 = 1.0m;
decimal? decimal2 = null;
int scale = 1;
decimal? result = BigDecimalUtils.Divide(decimal1, decimal2, scale);
Assert.AreEqual(null, result);
}
#endregion
#region Test IsGreaterThan1, IsLowerThan, IsNullOrZeroValue.
[TestMethod]
public void BigDecimalUtils_IsGreaterThan1Test()
{
decimal? decimal1 = 1.0m;
decimal? decimal2 = 1.0m;
bool? result = BigDecimalUtils.IsGreaterThan(decimal1, decimal2);
Assert.IsNotNull(result);
Assert.AreEqual(false, result);
Assert.AreEqual("False", result.ToString());
}
[TestMethod]
public void BigDecimalUtils_IsGreaterThan2Test()
{
decimal? decimal1 = 1.0m;
decimal? decimal2 = 1.0m;
bool? result = BigDecimalUtils.IsGreaterThan(decimal1, decimal2);
Assert.IsNotNull(result);
Assert.AreEqual(false, result);
Assert.AreEqual("False", result.ToString());
}
[TestMethod]
public void BigDecimalUtils_IsGreaterThan3Test()
{
decimal? decimal1 = null;
decimal? decimal2 = 1.0m;
bool? result = BigDecimalUtils.IsGreaterThan(decimal1, decimal2);
Assert.AreEqual(null, result);
}
[TestMethod]
public void BigDecimalUtils_IsGreaterThan4Test()
{
decimal? decimal1 = 1.0m;
decimal? decimal2 = null;
bool? result = BigDecimalUtils.IsGreaterThan(decimal1, decimal2);
Assert.AreEqual(null, result);
}
[TestMethod]
public void BigDecimalUtils_IsLowerThan1Test()
{
decimal? decimal1 = 1.0m;
decimal? decimal2 = 1.0m;
bool? result = BigDecimalUtils.IsLowerThan(decimal1, decimal2);
Assert.IsNotNull(result);
Assert.AreEqual(false, result);
Assert.AreEqual("False", result.ToString());
}
[TestMethod]
public void BigDecimalUtils_IsLowerThan2Test()
{
decimal? decimal1 = 1.0m;
decimal? decimal2 = 1.0m;
bool? result = BigDecimalUtils.IsLowerThan(decimal1, decimal2);
Assert.IsNotNull(result);
Assert.AreEqual(false, result);
Assert.AreEqual("False", result.ToString());
}
[TestMethod]
public void BigDecimalUtils_IsLowerThan3Test()
{
decimal? decimal1 = null;
decimal? decimal2 = 1.0m;
bool? result = BigDecimalUtils.IsLowerThan(decimal1, decimal2);
Assert.AreEqual(null, result);
}
[TestMethod]
public void BigDecimalUtils_IsLowerThan4Test()
{
decimal? decimal1 = 1.0m;
decimal? decimal2 = null;
bool? result = BigDecimalUtils.IsLowerThan(decimal1, decimal2);
Assert.AreEqual(null, result);
}
[TestMethod]
public void BigDecimalUtils_IsNullOrZeroValue1Test()
{
decimal? decimal1 = null;
bool? result = BigDecimalUtils.IsNullOrZeroValue(decimal1);
Assert.IsNotNull(result);
Assert.AreEqual(true, result);
Assert.AreEqual("True", result.ToString());
}
[TestMethod]
public void BigDecimalUtils_IsNullOrZeroValue2Test()
{
decimal? decimal1 = 1.0m;
bool? result = BigDecimalUtils.IsNullOrZeroValue(decimal1);
Assert.IsNotNull(result);
Assert.AreEqual(false, result);
Assert.AreEqual("False", result.ToString());
}
[TestMethod]
public void BigDecimalUtils_IsNullOrZeroValue3Test()
{
decimal? decimal1 = 1.0m;
bool? result = BigDecimalUtils.IsNullOrZeroValue(decimal1);
Assert.IsNotNull(result);
Assert.AreEqual(false, result);
Assert.AreEqual("False", result.ToString());
}
#endregion
#region Test Multiply.
[TestMethod]
public void BigDecimalUtils_Multiply1Test()
{
decimal? decimal1 = 1.0m;
decimal? decimal2 = 1.0m;
decimal? result = BigDecimalUtils.Multiply(decimal1, decimal2);
Assert.IsNotNull(result);
Assert.AreEqual(1, (int)result);
Assert.AreEqual(1L, (long)result);
Assert.AreEqual(1.0f, (float)result);
Assert.AreEqual(1.0d, (double)result);
Assert.AreEqual("1.00", BigDecimalUtils.ToString(result));
Assert.AreEqual((byte) 1, (byte)result);
Assert.AreEqual((short) 1, (short)result);
}
[TestMethod]
public void BigDecimalUtils_Multiply2Test()
{
decimal? decimal1 = null;
decimal? decimal2 = 1.0m;
decimal? result = BigDecimalUtils.Multiply(decimal1, decimal2);
Assert.AreEqual(null, result);
}
[TestMethod]
public void BigDecimalUtils_Multiply3Test()
{
decimal? decimal1 = 1.0m;
decimal? decimal2 = null;
decimal? result = BigDecimalUtils.Multiply(decimal1, decimal2);
Assert.AreEqual(null, result);
}
#endregion
#region Test Substract.
[TestMethod]
public void BigDecimalUtils_Subtract1Test()
{
decimal? decimal1 = 1.0m;
decimal? decimal2 = 1.0m;
decimal? result = BigDecimalUtils.Subtract(decimal1, decimal2);
Assert.IsNotNull(result);
Assert.AreEqual(0, (int)result);
Assert.AreEqual(0L, (long)result);
Assert.AreEqual(0.0f, (float)result);
Assert.AreEqual(0.0d, (double)result);
Assert.AreEqual("0.0", BigDecimalUtils.ToString(result));
Assert.AreEqual((byte) 0, (byte)result);
Assert.AreEqual((short) 0, (short)result);
}
[TestMethod]
public void BigDecimalUtils_Subtract2Test()
{
decimal? decimal1 = null;
decimal? decimal2 = 1.0m;
decimal? result = BigDecimalUtils.Subtract(decimal1, decimal2);
Assert.AreEqual(null, result);
}
[TestMethod]
public void BigDecimalUtils_Subtract3Test()
{
decimal? decimal1 = 1.0m;
decimal? decimal2 = null;
decimal? result = BigDecimalUtils.Subtract(decimal1, decimal2);
Assert.AreEqual(null, result);
}
#endregion
#region Test ToString.
[TestMethod]
public void BigDecimalUtils_ToString1Test()
{
decimal? decimal1 = 1.0m;
String result = BigDecimalUtils.ToString(decimal1);
Assert.AreEqual("1.0", result);
}
[TestMethod]
public void BigDecimalUtils_ToString2Test()
{
decimal? decimal1 = null;
String result = BigDecimalUtils.ToString(decimal1);
Assert.AreEqual("", result);
}
[TestMethod]
public void BigDecimalUtils_ToString3Test()
{
decimal? decimal1 = 10.03513m;
String result = BigDecimalUtils.ToString(decimal1);
Assert.AreEqual("10.03513", result);
}
#endregion
}
}
| 36.066826 | 94 | 0.573716 | [
"Apache-2.0"
] | SummerBatch/SummerBatchCore | Summer.Batch.CoreTests/Util/BigDecimalUtilsTests.cs | 15,114 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace SausageChat
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
| 17.333333 | 40 | 0.733974 | [
"MIT"
] | ArchyInUse/SausageChat | SausageChat/App.xaml.cs | 312 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System.Threading.Tasks;
using Elastic.Elasticsearch.Xunit.XunitPlumbing;
using Nest;
using Tests.Framework.EndpointTests;
using static Tests.Framework.EndpointTests.UrlTester;
namespace Tests.XPack.Eql.Status
{
public class EqlSearchStatusUrlTests : UrlTestsBase
{
[U] public override async Task Urls() => await GET("/_eql/search/status/search_id")
.Fluent(c => c.Eql.SearchStatus("search_id", f => f))
.Request(c => c.Eql.SearchStatus(new EqlSearchStatusRequest("search_id")))
.FluentAsync(c => c.Eql.SearchStatusAsync("search_id", f => f))
.RequestAsync(c => c.Eql.SearchStatusAsync(new EqlSearchStatusRequest("search_id")));
}
}
| 39.181818 | 88 | 0.758701 | [
"Apache-2.0"
] | Jiasyuan/elasticsearch-net | tests/Tests/XPack/Eql/Status/EqlSearchStatusUrlTests.cs | 862 | 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 System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.HotReload;
using Microsoft.AspNetCore.Components.Rendering;
using Microsoft.AspNetCore.Components.RenderTree;
using Microsoft.AspNetCore.Components.Test.Helpers;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Logging.Abstractions;
using Xunit;
namespace Microsoft.AspNetCore.Components.Test
{
public class RendererTest
{
// Nothing should exceed the timeout in a successful run of the the tests, this is just here to catch
// failures.
private static readonly TimeSpan Timeout = Debugger.IsAttached ? System.Threading.Timeout.InfiniteTimeSpan : TimeSpan.FromSeconds(10);
private const string EventActionsName = nameof(NestedAsyncComponent.EventActions);
private const string WhatToRenderName = nameof(NestedAsyncComponent.WhatToRender);
private const string LogName = nameof(NestedAsyncComponent.Log);
[Fact]
public void CanRenderTopLevelComponents()
{
// Arrange
var renderer = new TestRenderer();
var component = new TestComponent(builder =>
{
builder.OpenElement(0, "my element");
builder.AddContent(1, "some text");
builder.CloseElement();
});
// Act
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
// Assert
var batch = renderer.Batches.Single();
var diff = batch.DiffsByComponentId[componentId].Single();
Assert.Collection(diff.Edits,
edit =>
{
Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type);
Assert.Equal(0, edit.ReferenceFrameIndex);
});
AssertFrame.Element(batch.ReferenceFrames[0], "my element", 2);
AssertFrame.Text(batch.ReferenceFrames[1], "some text");
}
[Fact]
public void CanRenderNestedComponents()
{
// Arrange
var renderer = new TestRenderer();
var component = new TestComponent(builder =>
{
builder.AddContent(0, "Hello");
builder.OpenComponent<MessageComponent>(1);
builder.AddAttribute(2, nameof(MessageComponent.Message), "Nested component output");
builder.CloseComponent();
});
// Act/Assert
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
var batch = renderer.Batches.Single();
var componentFrame = batch.ReferenceFrames
.Single(frame => frame.FrameType == RenderTreeFrameType.Component);
var nestedComponentId = componentFrame.ComponentId;
var nestedComponentDiff = batch.DiffsByComponentId[nestedComponentId].Single();
// We rendered both components
Assert.Equal(2, batch.DiffsByComponentId.Count);
// The nested component exists
Assert.IsType<MessageComponent>(componentFrame.Component);
// The nested component was rendered as part of the batch
Assert.Collection(nestedComponentDiff.Edits,
edit =>
{
Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type);
AssertFrame.Text(
batch.ReferenceFrames[edit.ReferenceFrameIndex],
"Nested component output");
});
}
[Fact]
public void CanReRenderTopLevelComponents()
{
// Arrange
var renderer = new TestRenderer();
var component = new MessageComponent { Message = "Initial message" };
var componentId = renderer.AssignRootComponentId(component);
// Act/Assert: first render
component.TriggerRender();
var batch = renderer.Batches.Single();
var firstDiff = batch.DiffsByComponentId[componentId].Single();
Assert.Collection(firstDiff.Edits,
edit =>
{
Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type);
Assert.Equal(0, edit.ReferenceFrameIndex);
AssertFrame.Text(batch.ReferenceFrames[0], "Initial message");
});
// Act/Assert: second render
component.Message = "Modified message";
component.TriggerRender();
var secondBatch = renderer.Batches.Skip(1).Single();
var secondDiff = secondBatch.DiffsByComponentId[componentId].Single();
Assert.Collection(secondDiff.Edits,
edit =>
{
Assert.Equal(RenderTreeEditType.UpdateText, edit.Type);
Assert.Equal(0, edit.ReferenceFrameIndex);
AssertFrame.Text(secondBatch.ReferenceFrames[0], "Modified message");
});
}
[Fact]
public void CanReRenderNestedComponents()
{
// Arrange: parent component already rendered
var renderer = new TestRenderer();
var parentComponent = new TestComponent(builder =>
{
builder.OpenComponent<MessageComponent>(0);
builder.CloseComponent();
});
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
parentComponent.TriggerRender();
var nestedComponentFrame = renderer.Batches.Single()
.ReferenceFrames
.Single(frame => frame.FrameType == RenderTreeFrameType.Component);
var nestedComponent = (MessageComponent)nestedComponentFrame.Component;
var nestedComponentId = nestedComponentFrame.ComponentId;
// Assert: initial render
nestedComponent.Message = "Render 1";
nestedComponent.TriggerRender();
var batch = renderer.Batches[1];
var firstDiff = batch.DiffsByComponentId[nestedComponentId].Single();
Assert.Collection(firstDiff.Edits,
edit =>
{
Assert.Equal(RenderTreeEditType.UpdateText, edit.Type);
Assert.Equal(0, edit.ReferenceFrameIndex);
AssertFrame.Text(batch.ReferenceFrames[0], "Render 1");
});
// Act/Assert: re-render
nestedComponent.Message = "Render 2";
nestedComponent.TriggerRender();
var secondBatch = renderer.Batches[2];
var secondDiff = secondBatch.DiffsByComponentId[nestedComponentId].Single();
Assert.Collection(secondDiff.Edits,
edit =>
{
Assert.Equal(RenderTreeEditType.UpdateText, edit.Type);
Assert.Equal(0, edit.ReferenceFrameIndex);
AssertFrame.Text(secondBatch.ReferenceFrames[0], "Render 2");
});
}
[Fact]
public async Task CanRenderAsyncTopLevelComponents()
{
// Arrange
var renderer = new TestRenderer();
var tcs = new TaskCompletionSource<int>();
var component = new AsyncComponent(tcs.Task, 5); // Triggers n renders, the first one creating <p>n</p> and the n-1 renders asynchronously update the value.
// Act
var componentId = renderer.AssignRootComponentId(component);
var renderTask = renderer.Dispatcher.InvokeAsync(() => renderer.RenderRootComponentAsync(componentId));
// Assert
Assert.False(renderTask.IsCompleted);
tcs.SetResult(0);
await renderTask;
Assert.Equal(5, renderer.Batches.Count);
// First render
var create = renderer.Batches[0];
var diff = create.DiffsByComponentId[componentId].Single();
Assert.Collection(diff.Edits,
edit =>
{
Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type);
Assert.Equal(0, edit.ReferenceFrameIndex);
});
AssertFrame.Element(create.ReferenceFrames[0], "p", 2);
AssertFrame.Text(create.ReferenceFrames[1], "5");
// Second render
for (var i = 1; i < 5; i++)
{
var update = renderer.Batches[i];
var updateDiff = update.DiffsByComponentId[componentId].Single();
Assert.Collection(updateDiff.Edits,
edit =>
{
Assert.Equal(RenderTreeEditType.StepIn, edit.Type);
},
edit =>
{
Assert.Equal(RenderTreeEditType.UpdateText, edit.Type);
},
edit =>
{
Assert.Equal(RenderTreeEditType.StepOut, edit.Type);
});
AssertFrame.Text(update.ReferenceFrames[0], (5 - i).ToString(CultureInfo.InvariantCulture));
}
}
[Fact]
public async Task CanRenderAsyncNestedComponents()
{
// Arrange
var renderer = new TestRenderer();
var component = new NestedAsyncComponent();
// Act/Assert
var componentId = renderer.AssignRootComponentId(component);
var log = new ConcurrentQueue<(int id, NestedAsyncComponent.EventType @event)>();
await renderer.Dispatcher.InvokeAsync(() => renderer.RenderRootComponentAsync(componentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
[EventActionsName] = new Dictionary<int, IList<NestedAsyncComponent.ExecutionAction>>
{
[0] = new List<NestedAsyncComponent.ExecutionAction>
{
NestedAsyncComponent.ExecutionAction.On(0, NestedAsyncComponent.EventType.OnInit),
NestedAsyncComponent.ExecutionAction.On(0, NestedAsyncComponent.EventType.OnInitAsyncAsync, async:true),
NestedAsyncComponent.ExecutionAction.On(0, NestedAsyncComponent.EventType.OnParametersSet),
NestedAsyncComponent.ExecutionAction.On(0, NestedAsyncComponent.EventType.OnParametersSetAsyncAsync, async: true),
},
[1] = new List<NestedAsyncComponent.ExecutionAction>
{
NestedAsyncComponent.ExecutionAction.On(1, NestedAsyncComponent.EventType.OnInit),
NestedAsyncComponent.ExecutionAction.On(1, NestedAsyncComponent.EventType.OnInitAsyncAsync, async:true),
NestedAsyncComponent.ExecutionAction.On(1, NestedAsyncComponent.EventType.OnParametersSet),
NestedAsyncComponent.ExecutionAction.On(1, NestedAsyncComponent.EventType.OnParametersSetAsyncAsync, async: true),
}
},
[WhatToRenderName] = new Dictionary<int, Func<NestedAsyncComponent, RenderFragment>>
{
[0] = CreateRenderFactory(new[] { 1 }),
[1] = CreateRenderFactory(Array.Empty<int>())
},
[LogName] = log
})));
var logForParent = log.Where(l => l.id == 0).ToArray();
var logForChild = log.Where(l => l.id == 1).ToArray();
AssertStream(0, logForParent);
AssertStream(1, logForChild);
}
[Fact]
public void CanReRenderRootComponentsWithNewParameters()
{
// This differs from the other "CanReRender..." tests above in that the root component is being supplied
// with new parameters from outside, as opposed to making its own decision to re-render.
// Arrange
var renderer = new TestRenderer();
var component = new MessageComponent();
var componentId = renderer.AssignRootComponentId(component);
renderer.RenderRootComponentAsync(componentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
[nameof(MessageComponent.Message)] = "Hello"
}));
// Assert 1: First render
var batch = renderer.Batches.Single();
var diff = batch.DiffsByComponentId[componentId].Single();
Assert.Collection(diff.Edits, edit =>
{
Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type);
Assert.Equal(0, edit.ReferenceFrameIndex);
});
AssertFrame.Text(batch.ReferenceFrames[0], "Hello");
// Act 2: Update params
renderer.RenderRootComponentAsync(componentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
[nameof(MessageComponent.Message)] = "Goodbye"
}));
// Assert 2: Second render
var batch2 = renderer.Batches.Skip(1).Single();
var diff2 = batch2.DiffsByComponentId[componentId].Single();
Assert.Collection(diff2.Edits, edit =>
{
Assert.Equal(RenderTreeEditType.UpdateText, edit.Type);
Assert.Equal(0, edit.ReferenceFrameIndex);
});
AssertFrame.Text(batch2.ReferenceFrames[0], "Goodbye");
}
[Fact]
public async Task CanAddAndRenderNewRootComponentsWhileNotQuiescent()
{
// Arrange 1: An async root component
var renderer = new TestRenderer();
var tcs1 = new TaskCompletionSource();
var component1 = new AsyncComponent(tcs1.Task, 1);
var component1Id = renderer.AssignRootComponentId(component1);
// Act/Assert 1: Its SetParametersAsync task remains incomplete
var renderTask1 = renderer.Dispatcher.InvokeAsync(() => renderer.RenderRootComponentAsync(component1Id));
Assert.False(renderTask1.IsCompleted);
// Arrange/Act 2: Can add a second root component while not quiescent
var tcs2 = new TaskCompletionSource();
var component2 = new AsyncComponent(tcs2.Task, 1);
var component2Id = renderer.AssignRootComponentId(component2);
var renderTask2 = renderer.Dispatcher.InvokeAsync(() => renderer.RenderRootComponentAsync(component2Id));
// Assert 2
Assert.False(renderTask1.IsCompleted);
Assert.False(renderTask2.IsCompleted);
// Completing the first task isn't enough to consider the system quiescent, because there's now a second task
tcs1.SetResult();
// renderTask1 should not complete until we finish tcs2.
// We can't really prove that absolutely, but at least show it doesn't happen during a certain time period.
await Assert.ThrowsAsync<TimeoutException>(() => renderTask1.WaitAsync(TimeSpan.FromMilliseconds(250)));
Assert.False(renderTask1.IsCompleted);
Assert.False(renderTask2.IsCompleted);
// Completing the second task does finally complete both render tasks
tcs2.SetResult();
await Task.WhenAll(renderTask1, renderTask2);
}
[Fact]
public async Task AsyncComponentTriggeringRootReRenderDoesNotDeadlock()
{
// Arrange
var renderer = new TestRenderer();
var tcs = new TaskCompletionSource();
int? componentId = null;
var hasRendered = false;
var component = new CallbackDuringSetParametersAsyncComponent
{
Callback = async () =>
{
await tcs.Task;
if (!hasRendered)
{
hasRendered = true;
// If we were to await here, then it would deadlock, because the component would be saying it's not
// finished rendering until the rendering system has already finished. The point of this test is to
// show that, as long as we don't await quiescence here, nothing within the system will be doing so
// and hence the whole process can complete.
_ = renderer.RenderRootComponentAsync(componentId.Value, ParameterView.Empty);
}
}
};
componentId = renderer.AssignRootComponentId(component);
// Act
var renderTask = renderer.Dispatcher.InvokeAsync(() => renderer.RenderRootComponentAsync(componentId.Value));
// Assert
Assert.False(renderTask.IsCompleted);
tcs.SetResult();
await renderTask;
}
[Fact]
public async Task CanRenderAsyncComponentsWithSyncChildComponents()
{
// Arrange
var renderer = new TestRenderer();
var component = new NestedAsyncComponent();
// Act/Assert
var componentId = renderer.AssignRootComponentId(component);
var log = new ConcurrentQueue<(int id, NestedAsyncComponent.EventType @event)>();
await renderer.Dispatcher.InvokeAsync(() => renderer.RenderRootComponentAsync(componentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
[EventActionsName] = new Dictionary<int, IList<NestedAsyncComponent.ExecutionAction>>
{
[0] = new List<NestedAsyncComponent.ExecutionAction>
{
NestedAsyncComponent.ExecutionAction.On(0, NestedAsyncComponent.EventType.OnInit),
NestedAsyncComponent.ExecutionAction.On(0, NestedAsyncComponent.EventType.OnInitAsyncAsync, async:true),
NestedAsyncComponent.ExecutionAction.On(0, NestedAsyncComponent.EventType.OnParametersSet),
NestedAsyncComponent.ExecutionAction.On(0, NestedAsyncComponent.EventType.OnParametersSetAsyncAsync, async: true),
},
[1] = new List<NestedAsyncComponent.ExecutionAction>
{
NestedAsyncComponent.ExecutionAction.On(1, NestedAsyncComponent.EventType.OnInit),
NestedAsyncComponent.ExecutionAction.On(1, NestedAsyncComponent.EventType.OnInitAsyncAsync),
NestedAsyncComponent.ExecutionAction.On(1, NestedAsyncComponent.EventType.OnParametersSet),
NestedAsyncComponent.ExecutionAction.On(1, NestedAsyncComponent.EventType.OnParametersSetAsyncAsync),
}
},
[WhatToRenderName] = new Dictionary<int, Func<NestedAsyncComponent, RenderFragment>>
{
[0] = CreateRenderFactory(new[] { 1 }),
[1] = CreateRenderFactory(Array.Empty<int>())
},
[LogName] = log
})));
var logForParent = log.Where(l => l.id == 0).ToArray();
var logForChild = log.Where(l => l.id == 1).ToArray();
AssertStream(0, logForParent);
AssertStream(1, logForChild);
}
[Fact]
public async Task CanRenderAsyncComponentsWithAsyncChildInit()
{
// Arrange
var renderer = new TestRenderer();
var component = new NestedAsyncComponent();
// Act/Assert
var componentId = renderer.AssignRootComponentId(component);
var log = new ConcurrentQueue<(int id, NestedAsyncComponent.EventType @event)>();
await renderer.Dispatcher.InvokeAsync(() => renderer.RenderRootComponentAsync(componentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
[EventActionsName] = new Dictionary<int, IList<NestedAsyncComponent.ExecutionAction>>
{
[0] = new List<NestedAsyncComponent.ExecutionAction>
{
NestedAsyncComponent.ExecutionAction.On(0, NestedAsyncComponent.EventType.OnInit),
NestedAsyncComponent.ExecutionAction.On(0, NestedAsyncComponent.EventType.OnInitAsyncAsync, async:true),
NestedAsyncComponent.ExecutionAction.On(0, NestedAsyncComponent.EventType.OnParametersSet),
NestedAsyncComponent.ExecutionAction.On(0, NestedAsyncComponent.EventType.OnParametersSetAsyncAsync, async: true),
},
[1] = new List<NestedAsyncComponent.ExecutionAction>
{
NestedAsyncComponent.ExecutionAction.On(1, NestedAsyncComponent.EventType.OnInit),
NestedAsyncComponent.ExecutionAction.On(1, NestedAsyncComponent.EventType.OnInitAsyncAsync, async:true),
NestedAsyncComponent.ExecutionAction.On(1, NestedAsyncComponent.EventType.OnParametersSet),
NestedAsyncComponent.ExecutionAction.On(1, NestedAsyncComponent.EventType.OnParametersSetAsyncAsync),
}
},
[WhatToRenderName] = new Dictionary<int, Func<NestedAsyncComponent, RenderFragment>>
{
[0] = CreateRenderFactory(new[] { 1 }),
[1] = CreateRenderFactory(Array.Empty<int>())
},
[LogName] = log
})));
var logForParent = log.Where(l => l.id == 0).ToArray();
var logForChild = log.Where(l => l.id == 1).ToArray();
AssertStream(0, logForParent);
AssertStream(1, logForChild);
}
[Fact]
public async Task CanRenderAsyncComponentsWithMultipleAsyncChildren()
{
// Arrange
var renderer = new TestRenderer();
var component = new NestedAsyncComponent();
// Act/Assert
var componentId = renderer.AssignRootComponentId(component);
var log = new ConcurrentQueue<(int id, NestedAsyncComponent.EventType @event)>();
await renderer.Dispatcher.InvokeAsync(() => renderer.RenderRootComponentAsync(componentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
[EventActionsName] = new Dictionary<int, IList<NestedAsyncComponent.ExecutionAction>>
{
[0] = new List<NestedAsyncComponent.ExecutionAction>
{
NestedAsyncComponent.ExecutionAction.On(0, NestedAsyncComponent.EventType.OnInit),
NestedAsyncComponent.ExecutionAction.On(0, NestedAsyncComponent.EventType.OnInitAsyncAsync, async:true),
NestedAsyncComponent.ExecutionAction.On(0, NestedAsyncComponent.EventType.OnParametersSet),
NestedAsyncComponent.ExecutionAction.On(0, NestedAsyncComponent.EventType.OnParametersSetAsyncAsync, async: true),
},
[1] = new List<NestedAsyncComponent.ExecutionAction>
{
NestedAsyncComponent.ExecutionAction.On(1, NestedAsyncComponent.EventType.OnInit),
NestedAsyncComponent.ExecutionAction.On(1, NestedAsyncComponent.EventType.OnInitAsyncAsync, async:true),
NestedAsyncComponent.ExecutionAction.On(1, NestedAsyncComponent.EventType.OnParametersSet),
NestedAsyncComponent.ExecutionAction.On(1, NestedAsyncComponent.EventType.OnParametersSetAsyncAsync, async:true),
},
[2] = new List<NestedAsyncComponent.ExecutionAction>
{
NestedAsyncComponent.ExecutionAction.On(2, NestedAsyncComponent.EventType.OnInit),
NestedAsyncComponent.ExecutionAction.On(2, NestedAsyncComponent.EventType.OnInitAsyncAsync, async:true),
NestedAsyncComponent.ExecutionAction.On(2, NestedAsyncComponent.EventType.OnParametersSet),
NestedAsyncComponent.ExecutionAction.On(2, NestedAsyncComponent.EventType.OnParametersSetAsyncAsync, async:true),
},
[3] = new List<NestedAsyncComponent.ExecutionAction>
{
NestedAsyncComponent.ExecutionAction.On(3, NestedAsyncComponent.EventType.OnInit),
NestedAsyncComponent.ExecutionAction.On(3, NestedAsyncComponent.EventType.OnInitAsyncAsync, async:true),
NestedAsyncComponent.ExecutionAction.On(3, NestedAsyncComponent.EventType.OnParametersSet),
NestedAsyncComponent.ExecutionAction.On(3, NestedAsyncComponent.EventType.OnParametersSetAsyncAsync, async:true),
}
},
[WhatToRenderName] = new Dictionary<int, Func<NestedAsyncComponent, RenderFragment>>
{
[0] = CreateRenderFactory(new[] { 1, 2 }),
[1] = CreateRenderFactory(new[] { 3 }),
[2] = CreateRenderFactory(Array.Empty<int>()),
[3] = CreateRenderFactory(Array.Empty<int>())
},
[LogName] = log
})));
var logForParent = log.Where(l => l.id == 0).ToArray();
var logForFirstChild = log.Where(l => l.id == 1).ToArray();
var logForSecondChild = log.Where(l => l.id == 2).ToArray();
var logForThirdChild = log.Where(l => l.id == 3).ToArray();
AssertStream(0, logForParent);
AssertStream(1, logForFirstChild);
AssertStream(2, logForSecondChild);
AssertStream(3, logForThirdChild);
}
[Fact]
public void DispatchingEventsWithoutAsyncWorkShouldCompleteSynchronously()
{
// Arrange: Render a component with an event handler
var renderer = new TestRenderer();
EventArgs receivedArgs = null;
var component = new EventComponent
{
OnTest = args => { receivedArgs = args; }
};
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
var eventHandlerId = renderer.Batches.Single()
.ReferenceFrames
.First(frame => frame.AttributeValue != null)
.AttributeEventHandlerId;
// Assert: Event not yet fired
Assert.Null(receivedArgs);
// Act/Assert: Event can be fired
var eventArgs = new EventArgs();
var task = renderer.DispatchEventAsync(eventHandlerId, eventArgs);
// This should always be run synchronously
Assert.True(task.IsCompletedSuccessfully);
}
[Fact]
public void CanDispatchEventsToTopLevelComponents()
{
// Arrange: Render a component with an event handler
var renderer = new TestRenderer();
EventArgs receivedArgs = null;
var component = new EventComponent
{
OnTest = args => { receivedArgs = args; }
};
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
var eventHandlerId = renderer.Batches.Single()
.ReferenceFrames
.First(frame => frame.AttributeValue != null)
.AttributeEventHandlerId;
// Assert: Event not yet fired
Assert.Null(receivedArgs);
// Act/Assert: Event can be fired
var eventArgs = new EventArgs();
var renderTask = renderer.DispatchEventAsync(eventHandlerId, eventArgs);
Assert.True(renderTask.IsCompletedSuccessfully);
Assert.Same(eventArgs, receivedArgs);
}
[Fact]
public void CanGetEventArgsTypeForHandler()
{
// Arrange: Render a component with an event handler
var renderer = new TestRenderer();
var component = new EventComponent
{
OnArbitraryDelegateEvent = (Func<DerivedEventArgs, Task>)(args => Task.CompletedTask),
};
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
var eventHandlerId = renderer.Batches.Single()
.ReferenceFrames
.First(frame => frame.AttributeValue != null)
.AttributeEventHandlerId;
// Assert: Can determine event args type
var eventArgsType = renderer.GetEventArgsType(eventHandlerId);
Assert.Same(typeof(DerivedEventArgs), eventArgsType);
}
[Fact]
public void CanGetEventArgsTypeForParameterlessHandler()
{
// Arrange: Render a component with an event handler
var renderer = new TestRenderer();
var component = new EventComponent
{
OnArbitraryDelegateEvent = (Func<Task>)(() => Task.CompletedTask),
};
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
var eventHandlerId = renderer.Batches.Single()
.ReferenceFrames
.First(frame => frame.AttributeValue != null)
.AttributeEventHandlerId;
// Assert: Can determine event args type
var eventArgsType = renderer.GetEventArgsType(eventHandlerId);
Assert.Same(typeof(EventArgs), eventArgsType);
}
[Fact]
public void CannotGetEventArgsTypeForMultiParameterHandler()
{
// Arrange: Render a component with an event handler
var renderer = new TestRenderer();
var component = new EventComponent
{
OnArbitraryDelegateEvent = (Action<EventArgs, string>)((x, y) => { }),
};
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
var eventHandlerId = renderer.Batches.Single()
.ReferenceFrames
.First(frame => frame.AttributeValue != null)
.AttributeEventHandlerId;
// Assert: Cannot determine event args type
var ex = Assert.Throws<InvalidOperationException>(() => renderer.GetEventArgsType(eventHandlerId));
Assert.Contains("declares more than one parameter", ex.Message);
}
[Fact]
public void CannotGetEventArgsTypeForHandlerWithNonEventArgsParameter()
{
// Arrange: Render a component with an event handler
var renderer = new TestRenderer();
var component = new EventComponent
{
OnArbitraryDelegateEvent = (Action<DateTime>)(arg => { }),
};
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
var eventHandlerId = renderer.Batches.Single()
.ReferenceFrames
.First(frame => frame.AttributeValue != null)
.AttributeEventHandlerId;
// Assert: Cannot determine event args type
var ex = Assert.Throws<InvalidOperationException>(() => renderer.GetEventArgsType(eventHandlerId));
Assert.Contains($"must inherit from {typeof(EventArgs).FullName}", ex.Message);
}
[Fact]
public void DispatchEventHandlesSynchronousExceptionsFromEventHandlers()
{
// Arrange: Render a component with an event handler
var renderer = new TestRenderer
{
ShouldHandleExceptions = true
};
var component = new EventComponent
{
OnTest = args => throw new Exception("Error")
};
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
var eventHandlerId = renderer.Batches.Single()
.ReferenceFrames
.First(frame => frame.AttributeValue != null)
.AttributeEventHandlerId;
// Assert: Event not yet fired
Assert.Empty(renderer.HandledExceptions);
// Act/Assert: Event can be fired
var eventArgs = new EventArgs();
var renderTask = renderer.DispatchEventAsync(eventHandlerId, eventArgs);
Assert.True(renderTask.IsCompletedSuccessfully);
var exception = Assert.Single(renderer.HandledExceptions);
Assert.Equal("Error", exception.Message);
}
[Fact]
public void CanDispatchTypedEventsToTopLevelComponents()
{
// Arrange: Render a component with an event handler
var renderer = new TestRenderer();
DerivedEventArgs receivedArgs = null;
var component = new EventComponent
{
OnClick = args => { receivedArgs = args; }
};
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
var eventHandlerId = renderer.Batches.Single()
.ReferenceFrames
.First(frame => frame.AttributeValue != null)
.AttributeEventHandlerId;
// Assert: Event not yet fired
Assert.Null(receivedArgs);
// Act/Assert: Event can be fired
var eventArgs = new DerivedEventArgs();
var renderTask = renderer.DispatchEventAsync(eventHandlerId, eventArgs);
Assert.True(renderTask.IsCompletedSuccessfully);
Assert.Same(eventArgs, receivedArgs);
}
[Fact]
public void CanDispatchActionEventsToTopLevelComponents()
{
// Arrange: Render a component with an event handler
var renderer = new TestRenderer();
object receivedArgs = null;
var component = new EventComponent
{
OnClickAction = () => { receivedArgs = new object(); }
};
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
var eventHandlerId = renderer.Batches.Single()
.ReferenceFrames
.First(frame => frame.AttributeValue != null)
.AttributeEventHandlerId;
// Assert: Event not yet fired
Assert.Null(receivedArgs);
// Act/Assert: Event can be fired
var eventArgs = new DerivedEventArgs();
var renderTask = renderer.DispatchEventAsync(eventHandlerId, eventArgs);
Assert.True(renderTask.IsCompletedSuccessfully);
Assert.NotNull(receivedArgs);
}
[Fact]
public void CanDispatchEventsToNestedComponents()
{
EventArgs receivedArgs = null;
// Arrange: Render parent component
var renderer = new TestRenderer();
var parentComponent = new TestComponent(builder =>
{
builder.OpenComponent<EventComponent>(0);
builder.CloseComponent();
});
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
parentComponent.TriggerRender();
// Arrange: Render nested component
var nestedComponentFrame = renderer.Batches.Single()
.ReferenceFrames
.Single(frame => frame.FrameType == RenderTreeFrameType.Component);
var nestedComponent = (EventComponent)nestedComponentFrame.Component;
nestedComponent.OnTest = args => { receivedArgs = args; };
var nestedComponentId = nestedComponentFrame.ComponentId;
nestedComponent.TriggerRender();
// Find nested component's event handler ID
var eventHandlerId = renderer.Batches[1]
.ReferenceFrames
.First(frame => frame.AttributeValue != null)
.AttributeEventHandlerId;
// Assert: Event not yet fired
Assert.Null(receivedArgs);
// Act/Assert: Event can be fired
var eventArgs = new EventArgs();
var renderTask = renderer.DispatchEventAsync(eventHandlerId, eventArgs);
Assert.True(renderTask.IsCompletedSuccessfully);
Assert.Same(eventArgs, receivedArgs);
}
[Fact]
public async Task CanAsyncDispatchEventsToTopLevelComponents()
{
// Arrange: Render a component with an event handler
var renderer = new TestRenderer();
EventArgs receivedArgs = null;
var state = 0;
var tcs = new TaskCompletionSource<object>();
var component = new EventComponent
{
OnTestAsync = async (args) =>
{
receivedArgs = args;
state = 1;
await tcs.Task;
state = 2;
},
};
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
var eventHandlerId = renderer.Batches.Single()
.ReferenceFrames
.First(frame => frame.AttributeValue != null)
.AttributeEventHandlerId;
// Assert: Event not yet fired
Assert.Null(receivedArgs);
// Act/Assert: Event can be fired
var eventArgs = new EventArgs();
var task = renderer.DispatchEventAsync(eventHandlerId, eventArgs);
Assert.Equal(1, state);
Assert.Same(eventArgs, receivedArgs);
tcs.SetResult(null);
await task;
Assert.Equal(2, state);
}
[Fact]
public async Task CanAsyncDispatchTypedEventsToTopLevelComponents()
{
// Arrange: Render a component with an event handler
var renderer = new TestRenderer();
DerivedEventArgs receivedArgs = null;
var state = 0;
var tcs = new TaskCompletionSource<object>();
var component = new EventComponent
{
OnClickAsync = async (args) =>
{
receivedArgs = args;
state = 1;
await tcs.Task;
state = 2;
}
};
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
var eventHandlerId = renderer.Batches.Single()
.ReferenceFrames
.First(frame => frame.AttributeValue != null)
.AttributeEventHandlerId;
// Assert: Event not yet fired
Assert.Null(receivedArgs);
// Act/Assert: Event can be fired
var eventArgs = new DerivedEventArgs();
var task = renderer.DispatchEventAsync(eventHandlerId, eventArgs);
Assert.Equal(1, state);
Assert.Same(eventArgs, receivedArgs);
tcs.SetResult(null);
await task;
Assert.Equal(2, state);
}
[Fact]
public async Task CanAsyncDispatchActionEventsToTopLevelComponents()
{
// Arrange: Render a component with an event handler
var renderer = new TestRenderer();
object receivedArgs = null;
var state = 0;
var tcs = new TaskCompletionSource<object>();
var component = new EventComponent
{
OnClickAsyncAction = async () =>
{
receivedArgs = new object();
state = 1;
await tcs.Task;
state = 2;
}
};
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
var eventHandlerId = renderer.Batches.Single()
.ReferenceFrames
.First(frame => frame.AttributeValue != null)
.AttributeEventHandlerId;
// Assert: Event not yet fired
Assert.Null(receivedArgs);
// Act/Assert: Event can be fired
var eventArgs = new DerivedEventArgs();
var task = renderer.DispatchEventAsync(eventHandlerId, eventArgs);
Assert.Equal(1, state);
Assert.NotNull(receivedArgs);
tcs.SetResult(null);
await task;
Assert.Equal(2, state);
}
[Fact]
public async Task CanAsyncDispatchEventsToNestedComponents()
{
EventArgs receivedArgs = null;
var state = 0;
var tcs = new TaskCompletionSource<object>();
// Arrange: Render parent component
var renderer = new TestRenderer();
var parentComponent = new TestComponent(builder =>
{
builder.OpenComponent<EventComponent>(0);
builder.CloseComponent();
});
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
parentComponent.TriggerRender();
// Arrange: Render nested component
var nestedComponentFrame = renderer.Batches.Single()
.ReferenceFrames
.Single(frame => frame.FrameType == RenderTreeFrameType.Component);
var nestedComponent = (EventComponent)nestedComponentFrame.Component;
nestedComponent.OnTestAsync = async (args) =>
{
receivedArgs = args;
state = 1;
await tcs.Task;
state = 2;
};
var nestedComponentId = nestedComponentFrame.ComponentId;
nestedComponent.TriggerRender();
// Find nested component's event handler ID
var eventHandlerId = renderer.Batches[1]
.ReferenceFrames
.First(frame => frame.AttributeValue != null)
.AttributeEventHandlerId;
// Assert: Event not yet fired
Assert.Null(receivedArgs);
// Act/Assert: Event can be fired
var eventArgs = new EventArgs();
var task = renderer.DispatchEventAsync(eventHandlerId, eventArgs);
Assert.Equal(1, state);
Assert.Same(eventArgs, receivedArgs);
tcs.SetResult(null);
await task;
Assert.Equal(2, state);
}
// This tests the behaviour of dispatching an event when the event-handler
// delegate is a bound-delegate with a target that points to the parent component.
//
// This is a very common case when a component accepts a delegate parameter that
// will be hooked up to a DOM event handler. It's essential that this will dispatch
// to the parent component so that manual StateHasChanged calls are not necessary.
[Fact]
public async Task EventDispatching_DelegateParameter_MethodToDelegateConversion()
{
// Arrange
var outerStateChangeCount = 0;
var renderer = new TestRenderer();
var parentComponent = new OuterEventComponent();
parentComponent.RenderFragment = (builder) =>
{
builder.OpenComponent<EventComponent>(0);
builder.AddAttribute(1, nameof(EventComponent.OnClickAction), (Action)parentComponent.SomeMethod);
builder.CloseComponent();
};
parentComponent.OnEvent = () =>
{
outerStateChangeCount++;
};
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
await parentComponent.TriggerRenderAsync();
var eventHandlerId = renderer.Batches[0]
.ReferenceFrames
.First(frame => frame.AttributeName == "onclickaction")
.AttributeEventHandlerId;
// Act
var eventArgs = new DerivedEventArgs();
await renderer.DispatchEventAsync(eventHandlerId, eventArgs);
// Assert
Assert.Equal(1, parentComponent.SomeMethodCallCount);
Assert.Equal(1, outerStateChangeCount);
}
// This is the inverse case of EventDispatching_DelegateParameter_MethodToDelegateConversion
// where the event-handling delegate has a target that is not a component.
//
// This is a degenerate case that we don't expect to occur in applications often,
// but it's important to verify the semantics.
[Fact]
public async Task EventDispatching_DelegateParameter_NoTargetLambda()
{
// Arrange
var outerStateChangeCount = 0;
var renderer = new TestRenderer();
var parentComponent = new OuterEventComponent();
parentComponent.RenderFragment = (builder) =>
{
builder.OpenComponent<EventComponent>(0);
builder.AddAttribute(1, nameof(EventComponent.OnClickAction), (Action)(() =>
{
parentComponent.SomeMethod();
}));
builder.CloseComponent();
};
parentComponent.OnEvent = () =>
{
outerStateChangeCount++;
};
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
await parentComponent.TriggerRenderAsync();
var eventHandlerId = renderer.Batches[0]
.ReferenceFrames
.First(frame => frame.AttributeName == "onclickaction")
.AttributeEventHandlerId;
// Act
var eventArgs = new DerivedEventArgs();
await renderer.DispatchEventAsync(eventHandlerId, eventArgs);
// Assert
Assert.Equal(1, parentComponent.SomeMethodCallCount);
Assert.Equal(0, outerStateChangeCount);
}
// This is a similar case to EventDispatching_DelegateParameter_MethodToDelegateConversion
// but uses our event handling infrastructure to achieve the same effect. The call to CreateDelegate
// is not necessary for correctness in this case - it should just no op.
[Fact]
public async Task EventDispatching_EventCallback_MethodToDelegateConversion()
{
// Arrange
var outerStateChangeCount = 0;
var renderer = new TestRenderer();
var parentComponent = new OuterEventComponent();
parentComponent.RenderFragment = (builder) =>
{
builder.OpenComponent<EventComponent>(0);
builder.AddAttribute(1, nameof(EventComponent.OnClickEventCallback), EventCallback.Factory.Create(parentComponent, (Action)parentComponent.SomeMethod));
builder.CloseComponent();
};
parentComponent.OnEvent = () =>
{
outerStateChangeCount++;
};
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
await parentComponent.TriggerRenderAsync();
var eventHandlerId = renderer.Batches[0]
.ReferenceFrames
.First(frame => frame.AttributeName == "onclick")
.AttributeEventHandlerId;
// Act
var eventArgs = new DerivedEventArgs();
await renderer.DispatchEventAsync(eventHandlerId, eventArgs);
// Assert
Assert.Equal(1, parentComponent.SomeMethodCallCount);
Assert.Equal(1, outerStateChangeCount);
}
// This is a similar case to EventDispatching_DelegateParameter_NoTargetLambda but it uses
// our event-handling infrastructure to avoid the need for a manual StateHasChanged()
[Fact]
public async Task EventDispatching_EventCallback_NoTargetLambda()
{
// Arrange
var outerStateChangeCount = 0;
var renderer = new TestRenderer();
var parentComponent = new OuterEventComponent();
parentComponent.RenderFragment = (builder) =>
{
builder.OpenComponent<EventComponent>(0);
builder.AddAttribute(1, nameof(EventComponent.OnClickEventCallback), EventCallback.Factory.Create(parentComponent, (Action)(() =>
{
parentComponent.SomeMethod();
})));
builder.CloseComponent();
};
parentComponent.OnEvent = () =>
{
outerStateChangeCount++;
};
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
await parentComponent.TriggerRenderAsync();
var eventHandlerId = renderer.Batches[0]
.ReferenceFrames
.First(frame => frame.AttributeName == "onclick")
.AttributeEventHandlerId;
// Act
var eventArgs = new DerivedEventArgs();
await renderer.DispatchEventAsync(eventHandlerId, eventArgs);
// Assert
Assert.Equal(1, parentComponent.SomeMethodCallCount);
Assert.Equal(1, outerStateChangeCount);
}
// This is a similar case to EventDispatching_DelegateParameter_NoTargetLambda but it uses
// our event-handling infrastructure to avoid the need for a manual StateHasChanged()
[Fact]
public async Task EventDispatching_EventCallback_AsyncNoTargetLambda()
{
// Arrange
var outerStateChangeCount = 0;
var renderer = new TestRenderer();
var parentComponent = new OuterEventComponent();
parentComponent.RenderFragment = (builder) =>
{
builder.OpenComponent<EventComponent>(0);
builder.AddAttribute(1, nameof(EventComponent.OnClickEventCallback), EventCallback.Factory.Create(parentComponent, (Func<Task>)(() =>
{
parentComponent.SomeMethod();
return Task.CompletedTask;
})));
builder.CloseComponent();
};
parentComponent.OnEvent = () =>
{
outerStateChangeCount++;
};
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
await parentComponent.TriggerRenderAsync();
var eventHandlerId = renderer.Batches[0]
.ReferenceFrames
.First(frame => frame.AttributeName == "onclick")
.AttributeEventHandlerId;
// Act
var eventArgs = new DerivedEventArgs();
await renderer.DispatchEventAsync(eventHandlerId, eventArgs);
// Assert
Assert.Equal(1, parentComponent.SomeMethodCallCount);
Assert.Equal(1, outerStateChangeCount);
}
[Fact]
public async Task EventDispatching_EventCallbackOfT_MethodToDelegateConversion()
{
// Arrange
var outerStateChangeCount = 0;
var renderer = new TestRenderer();
var parentComponent = new OuterEventComponent();
parentComponent.RenderFragment = (builder) =>
{
builder.OpenComponent<EventComponent>(0);
builder.AddAttribute(1, nameof(EventComponent.OnClickEventCallbackOfT), EventCallback.Factory.Create<DerivedEventArgs>(parentComponent, (Action)parentComponent.SomeMethod));
builder.CloseComponent();
};
parentComponent.OnEvent = () =>
{
outerStateChangeCount++;
};
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
await parentComponent.TriggerRenderAsync();
var eventHandlerId = renderer.Batches[0]
.ReferenceFrames
.First(frame => frame.AttributeName == "onclick")
.AttributeEventHandlerId;
// Act
var eventArgs = new DerivedEventArgs();
await renderer.DispatchEventAsync(eventHandlerId, eventArgs);
// Assert
Assert.Equal(1, parentComponent.SomeMethodCallCount);
Assert.Equal(1, outerStateChangeCount);
}
// This is a similar case to EventDispatching_DelegateParameter_NoTargetLambda but it uses
// our event-handling infrastructure to avoid the need for a manual StateHasChanged()
[Fact]
public async Task EventDispatching_EventCallbackOfT_NoTargetLambda()
{
// Arrange
var outerStateChangeCount = 0;
var renderer = new TestRenderer();
var parentComponent = new OuterEventComponent();
parentComponent.RenderFragment = (builder) =>
{
builder.OpenComponent<EventComponent>(0);
builder.AddAttribute(1, nameof(EventComponent.OnClickEventCallbackOfT), EventCallback.Factory.Create<DerivedEventArgs>(parentComponent, (Action)(() =>
{
parentComponent.SomeMethod();
})));
builder.CloseComponent();
};
parentComponent.OnEvent = () =>
{
outerStateChangeCount++;
};
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
await parentComponent.TriggerRenderAsync();
var eventHandlerId = renderer.Batches[0]
.ReferenceFrames
.First(frame => frame.AttributeName == "onclick")
.AttributeEventHandlerId;
// Act
var eventArgs = new DerivedEventArgs();
await renderer.DispatchEventAsync(eventHandlerId, eventArgs);
// Assert
Assert.Equal(1, parentComponent.SomeMethodCallCount);
Assert.Equal(1, outerStateChangeCount);
}
// This is a similar case to EventDispatching_DelegateParameter_NoTargetLambda but it uses
// our event-handling infrastructure to avoid the need for a manual StateHasChanged()
[Fact]
public async Task EventDispatching_EventCallbackOfT_AsyncNoTargetLambda()
{
// Arrange
var outerStateChangeCount = 0;
var renderer = new TestRenderer();
var parentComponent = new OuterEventComponent();
parentComponent.RenderFragment = (builder) =>
{
builder.OpenComponent<EventComponent>(0);
builder.AddAttribute(1, nameof(EventComponent.OnClickEventCallbackOfT), EventCallback.Factory.Create<DerivedEventArgs>(parentComponent, (Func<Task>)(() =>
{
parentComponent.SomeMethod();
return Task.CompletedTask;
})));
builder.CloseComponent();
};
parentComponent.OnEvent = () =>
{
outerStateChangeCount++;
};
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
await parentComponent.TriggerRenderAsync();
var eventHandlerId = renderer.Batches[0]
.ReferenceFrames
.First(frame => frame.AttributeName == "onclick")
.AttributeEventHandlerId;
// Act
var eventArgs = new DerivedEventArgs();
await renderer.DispatchEventAsync(eventHandlerId, eventArgs);
// Assert
Assert.Equal(1, parentComponent.SomeMethodCallCount);
Assert.Equal(1, outerStateChangeCount);
}
[Fact]
public async Task DispatchEventAsync_Delegate_SynchronousCompletion()
{
// Arrange
var renderer = new TestRenderer();
var parentComponent = new OuterEventComponent();
parentComponent.RenderFragment = (builder) =>
{
builder.OpenComponent<EventComponent>(0);
builder.AddAttribute(1, nameof(EventComponent.OnClickAction), (Action)(() =>
{
// Do nothing.
}));
builder.CloseComponent();
};
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
await parentComponent.TriggerRenderAsync();
var eventHandlerId = renderer.Batches[0]
.ReferenceFrames
.First(frame => frame.AttributeName == "onclickaction")
.AttributeEventHandlerId;
// Act
var task = renderer.DispatchEventAsync(eventHandlerId, new DerivedEventArgs());
// Assert
Assert.Equal(TaskStatus.RanToCompletion, task.Status);
await task; // Does not throw
}
[Fact]
public async Task DispatchEventAsync_EventCallback_SynchronousCompletion()
{
// Arrange
var renderer = new TestRenderer();
var parentComponent = new OuterEventComponent();
parentComponent.RenderFragment = (builder) =>
{
builder.OpenComponent<EventComponent>(0);
builder.AddAttribute(1, nameof(EventComponent.OnClickEventCallback), EventCallback.Factory.Create(parentComponent, (Action)(() =>
{
// Do nothing.
})));
builder.CloseComponent();
};
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
await parentComponent.TriggerRenderAsync();
var eventHandlerId = renderer.Batches[0]
.ReferenceFrames
.First(frame => frame.AttributeName == "onclick")
.AttributeEventHandlerId;
// Act
var task = renderer.DispatchEventAsync(eventHandlerId, new DerivedEventArgs());
// Assert
Assert.Equal(TaskStatus.RanToCompletion, task.Status);
await task; // Does not throw
}
[Fact]
public async Task DispatchEventAsync_EventCallbackOfT_SynchronousCompletion()
{
// Arrange
DerivedEventArgs arg = null;
var renderer = new TestRenderer();
var parentComponent = new OuterEventComponent();
parentComponent.RenderFragment = (builder) =>
{
builder.OpenComponent<EventComponent>(0);
builder.AddAttribute(1, nameof(EventComponent.OnClickEventCallbackOfT), EventCallback.Factory.Create(parentComponent, (Action<DerivedEventArgs>)((e) =>
{
arg = e;
})));
builder.CloseComponent();
};
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
await parentComponent.TriggerRenderAsync();
var eventHandlerId = renderer.Batches[0]
.ReferenceFrames
.First(frame => frame.AttributeName == "onclick")
.AttributeEventHandlerId;
// Act
var task = renderer.DispatchEventAsync(eventHandlerId, new DerivedEventArgs());
// Assert
Assert.NotNull(arg);
Assert.Equal(TaskStatus.RanToCompletion, task.Status);
await task; // Does not throw
}
[Fact]
public async Task DispatchEventAsync_Delegate_SynchronousCancellation()
{
// Arrange
var renderer = new TestRenderer();
var parentComponent = new OuterEventComponent();
parentComponent.RenderFragment = (builder) =>
{
builder.OpenComponent<EventComponent>(0);
builder.AddAttribute(1, nameof(EventComponent.OnClickAction), (Action)(() =>
{
throw new OperationCanceledException();
}));
builder.CloseComponent();
};
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
await parentComponent.TriggerRenderAsync();
var eventHandlerId = renderer.Batches[0]
.ReferenceFrames
.First(frame => frame.AttributeName == "onclickaction")
.AttributeEventHandlerId;
// Act
var task = renderer.DispatchEventAsync(eventHandlerId, new DerivedEventArgs());
// Assert
Assert.Equal(TaskStatus.Canceled, task.Status);
await Assert.ThrowsAsync<TaskCanceledException>(() => task);
}
[Fact]
public async Task DispatchEventAsync_EventCallback_SynchronousCancellation()
{
// Arrange
var renderer = new TestRenderer();
var parentComponent = new OuterEventComponent();
parentComponent.RenderFragment = (builder) =>
{
builder.OpenComponent<EventComponent>(0);
builder.AddAttribute(1, nameof(EventComponent.OnClickEventCallback), EventCallback.Factory.Create(parentComponent, (Action)(() =>
{
throw new OperationCanceledException();
})));
builder.CloseComponent();
};
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
await parentComponent.TriggerRenderAsync();
var eventHandlerId = renderer.Batches[0]
.ReferenceFrames
.First(frame => frame.AttributeName == "onclick")
.AttributeEventHandlerId;
// Act
var task = renderer.DispatchEventAsync(eventHandlerId, new DerivedEventArgs());
// Assert
Assert.Equal(TaskStatus.Canceled, task.Status);
await Assert.ThrowsAsync<TaskCanceledException>(() => task);
}
[Fact]
public async Task DispatchEventAsync_EventCallbackOfT_SynchronousCancellation()
{
// Arrange
DerivedEventArgs arg = null;
var renderer = new TestRenderer();
var parentComponent = new OuterEventComponent();
parentComponent.RenderFragment = (builder) =>
{
builder.OpenComponent<EventComponent>(0);
builder.AddAttribute(1, nameof(EventComponent.OnClickEventCallbackOfT), EventCallback.Factory.Create(parentComponent, (Action<DerivedEventArgs>)((e) =>
{
arg = e;
throw new OperationCanceledException();
})));
builder.CloseComponent();
};
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
await parentComponent.TriggerRenderAsync();
var eventHandlerId = renderer.Batches[0]
.ReferenceFrames
.First(frame => frame.AttributeName == "onclick")
.AttributeEventHandlerId;
// Act
var task = renderer.DispatchEventAsync(eventHandlerId, new DerivedEventArgs());
// Assert
Assert.NotNull(arg);
Assert.Equal(TaskStatus.Canceled, task.Status);
await Assert.ThrowsAsync<TaskCanceledException>(() => task);
}
[Fact]
public async Task DispatchEventAsync_Delegate_SynchronousException()
{
// Arrange
var renderer = new TestRenderer();
var parentComponent = new OuterEventComponent();
parentComponent.RenderFragment = (builder) =>
{
builder.OpenComponent<EventComponent>(0);
builder.AddAttribute(1, nameof(EventComponent.OnClickAction), (Action)(() =>
{
throw new InvalidTimeZoneException();
}));
builder.CloseComponent();
};
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
await parentComponent.TriggerRenderAsync();
var eventHandlerId = renderer.Batches[0]
.ReferenceFrames
.First(frame => frame.AttributeName == "onclickaction")
.AttributeEventHandlerId;
// Act
var task = renderer.DispatchEventAsync(eventHandlerId, new DerivedEventArgs());
// Assert
Assert.Equal(TaskStatus.Faulted, task.Status);
await Assert.ThrowsAsync<InvalidTimeZoneException>(() => task);
}
[Fact]
public async Task DispatchEventAsync_EventCallback_SynchronousException()
{
// Arrange
var renderer = new TestRenderer();
var parentComponent = new OuterEventComponent();
parentComponent.RenderFragment = (builder) =>
{
builder.OpenComponent<EventComponent>(0);
builder.AddAttribute(1, nameof(EventComponent.OnClickEventCallback), EventCallback.Factory.Create(parentComponent, (Action)(() =>
{
throw new InvalidTimeZoneException();
})));
builder.CloseComponent();
};
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
await parentComponent.TriggerRenderAsync();
var eventHandlerId = renderer.Batches[0]
.ReferenceFrames
.First(frame => frame.AttributeName == "onclick")
.AttributeEventHandlerId;
// Act
var task = renderer.DispatchEventAsync(eventHandlerId, new DerivedEventArgs());
// Assert
Assert.Equal(TaskStatus.Faulted, task.Status);
await Assert.ThrowsAsync<InvalidTimeZoneException>(() => task);
}
[Fact]
public async Task DispatchEventAsync_EventCallbackOfT_SynchronousException()
{
// Arrange
DerivedEventArgs arg = null;
var renderer = new TestRenderer();
var parentComponent = new OuterEventComponent();
parentComponent.RenderFragment = (builder) =>
{
builder.OpenComponent<EventComponent>(0);
builder.AddAttribute(1, nameof(EventComponent.OnClickEventCallbackOfT), EventCallback.Factory.Create<DerivedEventArgs>(parentComponent, (Action<DerivedEventArgs>)((e) =>
{
arg = e;
throw new InvalidTimeZoneException();
})));
builder.CloseComponent();
};
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
await parentComponent.TriggerRenderAsync();
var eventHandlerId = renderer.Batches[0]
.ReferenceFrames
.First(frame => frame.AttributeName == "onclick")
.AttributeEventHandlerId;
// Act
var task = renderer.DispatchEventAsync(eventHandlerId, new DerivedEventArgs());
// Assert
Assert.NotNull(arg);
Assert.Equal(TaskStatus.Faulted, task.Status);
await Assert.ThrowsAsync<InvalidTimeZoneException>(() => task);
}
[Fact]
public async Task DispatchEventAsync_Delegate_AsynchronousCompletion()
{
// Arrange
var tcs = new TaskCompletionSource<object>();
var renderer = new TestRenderer();
var parentComponent = new OuterEventComponent();
parentComponent.RenderFragment = (builder) =>
{
builder.OpenComponent<EventComponent>(0);
builder.AddAttribute(1, nameof(EventComponent.OnClickAsyncAction), (Func<Task>)(async () =>
{
await tcs.Task;
}));
builder.CloseComponent();
};
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
await parentComponent.TriggerRenderAsync();
var eventHandlerId = renderer.Batches[0]
.ReferenceFrames
.First(frame => frame.AttributeName == "onclickaction")
.AttributeEventHandlerId;
// Act
var task = renderer.DispatchEventAsync(eventHandlerId, new DerivedEventArgs());
// Assert
Assert.Equal(TaskStatus.WaitingForActivation, task.Status);
tcs.SetResult(null);
await task; // Does not throw
}
[Fact]
public async Task DispatchEventAsync_EventCallback_AsynchronousCompletion()
{
// Arrange
var tcs = new TaskCompletionSource<object>();
var renderer = new TestRenderer();
var parentComponent = new OuterEventComponent();
parentComponent.RenderFragment = (builder) =>
{
builder.OpenComponent<EventComponent>(0);
builder.AddAttribute(1, nameof(EventComponent.OnClickEventCallback), EventCallback.Factory.Create(parentComponent, async () =>
{
await tcs.Task;
}));
builder.CloseComponent();
};
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
await parentComponent.TriggerRenderAsync();
var eventHandlerId = renderer.Batches[0]
.ReferenceFrames
.First(frame => frame.AttributeName == "onclick")
.AttributeEventHandlerId;
// Act
var task = renderer.DispatchEventAsync(eventHandlerId, new DerivedEventArgs());
// Assert
Assert.Equal(TaskStatus.WaitingForActivation, task.Status);
tcs.SetResult(null);
await task; // Does not throw
}
[Fact]
public async Task DispatchEventAsync_EventCallbackOfT_AsynchronousCompletion()
{
// Arrange
var tcs = new TaskCompletionSource<object>();
DerivedEventArgs arg = null;
var renderer = new TestRenderer();
var parentComponent = new OuterEventComponent();
parentComponent.RenderFragment = (builder) =>
{
builder.OpenComponent<EventComponent>(0);
builder.AddAttribute(1, nameof(EventComponent.OnClickEventCallbackOfT), EventCallback.Factory.Create<DerivedEventArgs>(parentComponent, async (e) =>
{
arg = e;
await tcs.Task;
}));
builder.CloseComponent();
};
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
await parentComponent.TriggerRenderAsync();
var eventHandlerId = renderer.Batches[0]
.ReferenceFrames
.First(frame => frame.AttributeName == "onclick")
.AttributeEventHandlerId;
// Act
var task = renderer.DispatchEventAsync(eventHandlerId, new DerivedEventArgs());
// Assert
Assert.NotNull(arg);
Assert.Equal(TaskStatus.WaitingForActivation, task.Status);
tcs.SetResult(null);
await task; // Does not throw
}
[Fact]
public async Task DispatchEventAsync_Delegate_AsynchronousCancellation()
{
// Arrange
var tcs = new TaskCompletionSource<object>();
var renderer = new TestRenderer();
var parentComponent = new OuterEventComponent();
parentComponent.RenderFragment = (builder) =>
{
builder.OpenComponent<EventComponent>(0);
builder.AddAttribute(1, nameof(EventComponent.OnClickAsyncAction), (Func<Task>)(async () =>
{
await tcs.Task;
throw new TaskCanceledException();
}));
builder.CloseComponent();
};
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
await parentComponent.TriggerRenderAsync();
var eventHandlerId = renderer.Batches[0]
.ReferenceFrames
.First(frame => frame.AttributeName == "onclickaction")
.AttributeEventHandlerId;
// Act
var task = renderer.DispatchEventAsync(eventHandlerId, new DerivedEventArgs());
// Assert
Assert.Equal(TaskStatus.WaitingForActivation, task.Status);
tcs.SetResult(null);
await task; // Does not throw
Assert.Empty(renderer.HandledExceptions);
}
[Fact]
public async Task DispatchEventAsync_EventCallback_AsynchronousCancellation()
{
// Arrange
var tcs = new TaskCompletionSource<object>();
var renderer = new TestRenderer();
var parentComponent = new OuterEventComponent();
parentComponent.RenderFragment = (builder) =>
{
builder.OpenComponent<EventComponent>(0);
builder.AddAttribute(1, nameof(EventComponent.OnClickEventCallback), EventCallback.Factory.Create(parentComponent, async () =>
{
await tcs.Task;
throw new TaskCanceledException();
}));
builder.CloseComponent();
};
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
await parentComponent.TriggerRenderAsync();
var eventHandlerId = renderer.Batches[0]
.ReferenceFrames
.First(frame => frame.AttributeName == "onclick")
.AttributeEventHandlerId;
// Act
var task = renderer.DispatchEventAsync(eventHandlerId, new DerivedEventArgs());
// Assert
Assert.Equal(TaskStatus.WaitingForActivation, task.Status);
tcs.SetResult(null);
await task; // Does not throw
Assert.Empty(renderer.HandledExceptions);
}
[Fact]
public async Task DispatchEventAsync_EventCallbackOfT_AsynchronousCancellation()
{
// Arrange
var tcs = new TaskCompletionSource<object>();
DerivedEventArgs arg = null;
var renderer = new TestRenderer();
var parentComponent = new OuterEventComponent();
parentComponent.RenderFragment = (builder) =>
{
builder.OpenComponent<EventComponent>(0);
builder.AddAttribute(1, nameof(EventComponent.OnClickEventCallbackOfT), EventCallback.Factory.Create<DerivedEventArgs>(parentComponent, async (e) =>
{
arg = e;
await tcs.Task;
throw new TaskCanceledException();
}));
builder.CloseComponent();
};
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
await parentComponent.TriggerRenderAsync();
var eventHandlerId = renderer.Batches[0]
.ReferenceFrames
.First(frame => frame.AttributeName == "onclick")
.AttributeEventHandlerId;
// Act
var task = renderer.DispatchEventAsync(eventHandlerId, new DerivedEventArgs());
// Assert
Assert.NotNull(arg);
Assert.Equal(TaskStatus.WaitingForActivation, task.Status);
tcs.SetResult(null);
await task; // Does not throw
Assert.Empty(renderer.HandledExceptions);
}
[Fact]
public async Task DispatchEventAsync_Delegate_AsynchronousException()
{
// Arrange
var tcs = new TaskCompletionSource<object>();
var renderer = new TestRenderer();
var parentComponent = new OuterEventComponent();
parentComponent.RenderFragment = (builder) =>
{
builder.OpenComponent<EventComponent>(0);
builder.AddAttribute(1, nameof(EventComponent.OnClickAsyncAction), (Func<Task>)(async () =>
{
await tcs.Task;
throw new InvalidTimeZoneException();
}));
builder.CloseComponent();
};
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
await parentComponent.TriggerRenderAsync();
var eventHandlerId = renderer.Batches[0]
.ReferenceFrames
.First(frame => frame.AttributeName == "onclickaction")
.AttributeEventHandlerId;
// Act
var task = renderer.DispatchEventAsync(eventHandlerId, new DerivedEventArgs());
// Assert
Assert.Equal(TaskStatus.WaitingForActivation, task.Status);
tcs.SetResult(null);
await Assert.ThrowsAsync<InvalidTimeZoneException>(() => task);
}
[Fact]
public async Task DispatchEventAsync_EventCallback_AsynchronousException()
{
// Arrange
var tcs = new TaskCompletionSource<object>();
var renderer = new TestRenderer();
var parentComponent = new OuterEventComponent();
parentComponent.RenderFragment = (builder) =>
{
builder.OpenComponent<EventComponent>(0);
builder.AddAttribute(1, nameof(EventComponent.OnClickEventCallback), EventCallback.Factory.Create(parentComponent, async () =>
{
await tcs.Task;
throw new InvalidTimeZoneException();
}));
builder.CloseComponent();
};
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
await parentComponent.TriggerRenderAsync();
var eventHandlerId = renderer.Batches[0]
.ReferenceFrames
.First(frame => frame.AttributeName == "onclick")
.AttributeEventHandlerId;
// Act
var task = renderer.DispatchEventAsync(eventHandlerId, new DerivedEventArgs());
// Assert
Assert.Equal(TaskStatus.WaitingForActivation, task.Status);
tcs.SetResult(null);
await Assert.ThrowsAsync<InvalidTimeZoneException>(() => task);
}
[Fact]
public async Task DispatchEventAsync_EventCallbackOfT_AsynchronousException()
{
// Arrange
var tcs = new TaskCompletionSource<object>();
DerivedEventArgs arg = null;
var renderer = new TestRenderer();
var parentComponent = new OuterEventComponent();
parentComponent.RenderFragment = (builder) =>
{
builder.OpenComponent<EventComponent>(0);
builder.AddAttribute(1, nameof(EventComponent.OnClickEventCallbackOfT), EventCallback.Factory.Create<DerivedEventArgs>(parentComponent, async (e) =>
{
arg = e;
await tcs.Task;
throw new InvalidTimeZoneException();
}));
builder.CloseComponent();
};
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
await parentComponent.TriggerRenderAsync();
var eventHandlerId = renderer.Batches[0]
.ReferenceFrames
.First(frame => frame.AttributeName == "onclick")
.AttributeEventHandlerId;
// Act
var task = renderer.DispatchEventAsync(eventHandlerId, new DerivedEventArgs());
// Assert
Assert.NotNull(arg);
Assert.Equal(TaskStatus.WaitingForActivation, task.Status);
tcs.SetResult(null);
await Assert.ThrowsAsync<InvalidTimeZoneException>(() => task);
}
[Fact]
public async Task CannotDispatchEventsWithUnknownEventHandlers()
{
// Arrange
var renderer = new TestRenderer();
// Act/Assert
await Assert.ThrowsAsync<ArgumentException>(() =>
{
return renderer.DispatchEventAsync(0, new EventArgs());
});
}
[Fact]
public void ComponentsCanBeAssociatedWithMultipleRenderers()
{
// Arrange
var renderer1 = new TestRenderer();
var renderer2 = new TestRenderer();
var component = new MultiRendererComponent();
var renderer1ComponentId = renderer1.AssignRootComponentId(component);
renderer2.AssignRootComponentId(new TestComponent(null)); // Just so they don't get the same IDs
var renderer2ComponentId = renderer2.AssignRootComponentId(component);
// Act/Assert
component.TriggerRender();
var renderer1Batch = renderer1.Batches.Single();
var renderer1Diff = renderer1Batch.DiffsByComponentId[renderer1ComponentId].Single();
Assert.Collection(renderer1Diff.Edits,
edit =>
{
Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type);
AssertFrame.Text(renderer1Batch.ReferenceFrames[edit.ReferenceFrameIndex],
$"Hello from {nameof(MultiRendererComponent)}", 0);
});
var renderer2Batch = renderer2.Batches.Single();
var renderer2Diff = renderer2Batch.DiffsByComponentId[renderer2ComponentId].Single();
Assert.Collection(renderer2Diff.Edits,
edit =>
{
Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type);
AssertFrame.Text(renderer2Batch.ReferenceFrames[edit.ReferenceFrameIndex],
$"Hello from {nameof(MultiRendererComponent)}", 0);
});
}
[Fact]
public void PreservesChildComponentInstancesWithNoAttributes()
{
// Arrange: First render, capturing child component instance
var renderer = new TestRenderer();
var message = "Hello";
var component = new TestComponent(builder =>
{
builder.AddContent(0, message);
builder.OpenComponent<MessageComponent>(1);
builder.CloseComponent();
});
var rootComponentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
var nestedComponentFrame = renderer.Batches.Single()
.ReferenceFrames
.Single(frame => frame.FrameType == RenderTreeFrameType.Component);
var nestedComponentInstance = (MessageComponent)nestedComponentFrame.Component;
// Act: Second render
message = "Modified message";
component.TriggerRender();
// Assert
var batch = renderer.Batches[1];
var diff = batch.DiffsByComponentId[rootComponentId].Single();
Assert.Collection(diff.Edits,
edit =>
{
Assert.Equal(RenderTreeEditType.UpdateText, edit.Type);
Assert.Equal(0, edit.ReferenceFrameIndex);
});
AssertFrame.Text(batch.ReferenceFrames[0], "Modified message");
Assert.False(batch.DiffsByComponentId.ContainsKey(nestedComponentFrame.ComponentId));
}
[Fact]
public void UpdatesPropertiesOnRetainedChildComponentInstances()
{
// Arrange: First render, capturing child component instance
var renderer = new TestRenderer();
var objectThatWillNotChange = new object();
var firstRender = true;
var component = new TestComponent(builder =>
{
builder.OpenComponent<FakeComponent>(1);
builder.AddAttribute(2, nameof(FakeComponent.IntProperty), firstRender ? 123 : 256);
builder.AddAttribute(3, nameof(FakeComponent.ObjectProperty), objectThatWillNotChange);
builder.AddAttribute(4, nameof(FakeComponent.StringProperty), firstRender ? "String that will change" : "String that did change");
builder.CloseComponent();
});
var rootComponentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
var originalComponentFrame = renderer.Batches.Single()
.ReferenceFrames
.Single(frame => frame.FrameType == RenderTreeFrameType.Component);
var childComponentInstance = (FakeComponent)originalComponentFrame.Component;
// Assert 1: properties were assigned
Assert.Equal(123, childComponentInstance.IntProperty);
Assert.Equal("String that will change", childComponentInstance.StringProperty);
Assert.Same(objectThatWillNotChange, childComponentInstance.ObjectProperty);
// Act: Second render
firstRender = false;
component.TriggerRender();
// Assert
Assert.Equal(256, childComponentInstance.IntProperty);
Assert.Equal("String that did change", childComponentInstance.StringProperty);
Assert.Same(objectThatWillNotChange, childComponentInstance.ObjectProperty);
}
[Fact]
public void ReRendersChildComponentsWhenPropertiesChange()
{
// Arrange: First render
var renderer = new TestRenderer();
var firstRender = true;
var component = new TestComponent(builder =>
{
builder.OpenComponent<MessageComponent>(1);
builder.AddAttribute(2, nameof(MessageComponent.Message), firstRender ? "first" : "second");
builder.CloseComponent();
});
var rootComponentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
var childComponentId = renderer.Batches.Single()
.ReferenceFrames
.Single(frame => frame.FrameType == RenderTreeFrameType.Component)
.ComponentId;
// Act: Second render
firstRender = false;
component.TriggerRender();
var diff = renderer.Batches[1].DiffsByComponentId[childComponentId].Single();
// Assert
Assert.Collection(diff.Edits,
edit =>
{
Assert.Equal(RenderTreeEditType.UpdateText, edit.Type);
Assert.Equal(0, edit.ReferenceFrameIndex);
});
AssertFrame.Text(renderer.Batches[1].ReferenceFrames[0], "second");
}
[Fact]
public void ReRendersChildComponentWhenUnmatchedValuesChange()
{
// Arrange: First render
var renderer = new TestRenderer();
var firstRender = true;
var component = new TestComponent(builder =>
{
builder.OpenComponent<MyStrongComponent>(1);
builder.AddAttribute(1, "class", firstRender ? "first" : "second");
builder.AddAttribute(2, "id", "some_text");
builder.AddAttribute(3, nameof(MyStrongComponent.Text), "hi there.");
builder.CloseComponent();
});
var rootComponentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
var childComponentId = renderer.Batches.Single()
.ReferenceFrames
.Single(frame => frame.FrameType == RenderTreeFrameType.Component)
.ComponentId;
// Act: Second render
firstRender = false;
component.TriggerRender();
var diff = renderer.Batches[1].DiffsByComponentId[childComponentId].Single();
// Assert
Assert.Collection(diff.Edits,
edit =>
{
Assert.Equal(RenderTreeEditType.SetAttribute, edit.Type);
Assert.Equal(0, edit.ReferenceFrameIndex);
});
AssertFrame.Attribute(renderer.Batches[1].ReferenceFrames[0], "class", "second");
}
// This is a sanity check that diffs of "unmatched" values *just work* without any specialized
// code in the renderer to handle it. All of the data that's used in the diff is contained in
// the render tree, and the diff process does not need to inspect the state of the component.
[Fact]
public void ReRendersDoesNotReRenderChildComponentWhenUnmatchedValuesDoNotChange()
{
// Arrange: First render
var renderer = new TestRenderer();
var component = new TestComponent(builder =>
{
builder.OpenComponent<MyStrongComponent>(1);
builder.AddAttribute(1, "class", "cool-beans");
builder.AddAttribute(2, "id", "some_text");
builder.AddAttribute(3, nameof(MyStrongComponent.Text), "hi there.");
builder.CloseComponent();
});
var rootComponentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
var childComponentId = renderer.Batches.Single()
.ReferenceFrames
.Single(frame => frame.FrameType == RenderTreeFrameType.Component)
.ComponentId;
// Act: Second render
component.TriggerRender();
// Assert
Assert.False(renderer.Batches[1].DiffsByComponentId.ContainsKey(childComponentId));
}
[Fact]
public void RenderBatchIncludesListOfDisposedComponents()
{
// Arrange
var renderer = new TestRenderer();
var firstRender = true;
var component = new TestComponent(builder =>
{
if (firstRender)
{
// Nested descendants
builder.OpenComponent<ConditionalParentComponent<FakeComponent>>(100);
builder.AddAttribute(101, nameof(ConditionalParentComponent<FakeComponent>.IncludeChild), true);
builder.CloseComponent();
}
builder.OpenComponent<FakeComponent>(200);
builder.CloseComponent();
});
var rootComponentId = renderer.AssignRootComponentId(component);
// Act/Assert 1: First render, capturing child component IDs
component.TriggerRender();
var batch = renderer.Batches.Single();
var rootComponentDiff = batch.DiffsByComponentId[rootComponentId].Single();
var childComponentIds = rootComponentDiff
.Edits
.Select(edit => batch.ReferenceFrames[edit.ReferenceFrameIndex])
.Where(frame => frame.FrameType == RenderTreeFrameType.Component)
.Select(frame => frame.ComponentId)
.ToList();
var childComponent3 = batch.ReferenceFrames.Where(f => f.ComponentId == 3)
.Single().Component;
Assert.Equal(new[] { 1, 2 }, childComponentIds);
Assert.IsType<FakeComponent>(childComponent3);
// Act: Second render
firstRender = false;
component.TriggerRender();
// Assert: Applicable children are included in disposal list
Assert.Equal(2, renderer.Batches.Count);
Assert.Equal(new[] { 1, 3 }, renderer.Batches[1].DisposedComponentIDs);
// Act/Assert: If a disposed component requests a render, it's a no-op
var renderHandle = ((FakeComponent)childComponent3).RenderHandle;
renderHandle.Dispatcher.InvokeAsync(() => renderHandle.Render(builder
=> throw new NotImplementedException("Should not be invoked")));
Assert.Equal(2, renderer.Batches.Count);
}
[Fact]
public void RenderBatch_HandlesExceptionsFromAllDisposedComponents()
{
// Arrange
var renderer = new TestRenderer { ShouldHandleExceptions = true };
var exception1 = new Exception();
var exception2 = new Exception();
var firstRender = true;
var component = new TestComponent(builder =>
{
if (firstRender)
{
builder.AddContent(0, "Hello");
builder.OpenComponent<DisposableComponent>(1);
builder.AddAttribute(1, nameof(DisposableComponent.DisposeAction), (Action)(() => throw exception1));
builder.CloseComponent();
builder.OpenComponent<DisposableComponent>(2);
builder.AddAttribute(1, nameof(DisposableComponent.DisposeAction), (Action)(() => throw exception2));
builder.CloseComponent();
}
});
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
// Act: Second render
firstRender = false;
component.TriggerRender();
// Assert: Applicable children are included in disposal list
Assert.Equal(2, renderer.Batches.Count);
Assert.Equal(new[] { 1, 2 }, renderer.Batches[1].DisposedComponentIDs);
// Outer component is still alive and not disposed.
Assert.False(component.Disposed);
var aex = Assert.IsType<AggregateException>(Assert.Single(renderer.HandledExceptions));
Assert.Contains(exception1, aex.InnerExceptions);
Assert.Contains(exception2, aex.InnerExceptions);
}
[Fact]
public void RenderBatch_HandlesSynchronousExceptionsInAsyncDisposableComponents()
{
// Arrange
var renderer = new TestRenderer { ShouldHandleExceptions = true };
var exception1 = new InvalidOperationException();
var firstRender = true;
var component = new TestComponent(builder =>
{
if (firstRender)
{
builder.AddContent(0, "Hello");
builder.OpenComponent<AsyncDisposableComponent>(1);
builder.AddAttribute(1, nameof(AsyncDisposableComponent.AsyncDisposeAction), (Func<ValueTask>)(() => throw exception1));
builder.CloseComponent();
}
});
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
// Act: Second render
firstRender = false;
component.TriggerRender();
// Assert: Applicable children are included in disposal list
Assert.Equal(2, renderer.Batches.Count);
Assert.Equal(new[] { 1, }, renderer.Batches[1].DisposedComponentIDs);
// Outer component is still alive and not disposed.
Assert.False(component.Disposed);
var aex = Assert.IsType<AggregateException>(Assert.Single(renderer.HandledExceptions));
var innerException = Assert.Single(aex.Flatten().InnerExceptions);
Assert.Same(exception1, innerException);
}
[Fact]
public void RenderBatch_CanDisposeSynchronousAsyncDisposableImplementations()
{
// Arrange
var renderer = new TestRenderer { ShouldHandleExceptions = true };
var firstRender = true;
var component = new TestComponent(builder =>
{
if (firstRender)
{
builder.AddContent(0, "Hello");
builder.OpenComponent<AsyncDisposableComponent>(1);
builder.AddAttribute(1, nameof(AsyncDisposableComponent.AsyncDisposeAction), (Func<ValueTask>)(() => default));
builder.CloseComponent();
}
});
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
// Act: Second render
firstRender = false;
component.TriggerRender();
// Assert: Applicable children are included in disposal list
Assert.Equal(2, renderer.Batches.Count);
Assert.Equal(new[] { 1, }, renderer.Batches[1].DisposedComponentIDs);
// Outer component is still alive and not disposed.
Assert.False(component.Disposed);
Assert.Empty(renderer.HandledExceptions);
}
[Fact]
public void RenderBatch_CanDisposeAsynchronousAsyncDisposables()
{
// Arrange
var semaphore = new Semaphore(0, 1);
var renderer = new TestRenderer { ShouldHandleExceptions = true };
renderer.OnExceptionHandled = () => semaphore.Release();
var exception1 = new InvalidOperationException();
var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var firstRender = true;
var component = new TestComponent(builder =>
{
if (firstRender)
{
builder.AddContent(0, "Hello");
builder.OpenComponent<AsyncDisposableComponent>(1);
builder.AddAttribute(1, nameof(AsyncDisposableComponent.AsyncDisposeAction), (Func<ValueTask>)(async () => { await tcs.Task; }));
builder.CloseComponent();
}
});
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
// Act: Second render
firstRender = false;
component.TriggerRender();
// Assert: Applicable children are included in disposal list
Assert.Equal(2, renderer.Batches.Count);
Assert.Equal(new[] { 1, }, renderer.Batches[1].DisposedComponentIDs);
// Outer component is still alive and not disposed.
Assert.False(component.Disposed);
Assert.Empty(renderer.HandledExceptions);
// Continue execution
tcs.SetResult();
Assert.False(semaphore.WaitOne(10));
Assert.Empty(renderer.HandledExceptions);
}
[Fact]
public void RenderBatch_HandlesAsynchronousExceptionsInAsyncDisposableComponents()
{
// Arrange
var semaphore = new Semaphore(0, 1);
var renderer = new TestRenderer { ShouldHandleExceptions = true };
renderer.OnExceptionHandled = () => semaphore.Release();
var exception1 = new InvalidOperationException();
var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var firstRender = true;
var component = new TestComponent(builder =>
{
if (firstRender)
{
builder.AddContent(0, "Hello");
builder.OpenComponent<AsyncDisposableComponent>(1);
builder.AddAttribute(1, nameof(AsyncDisposableComponent.AsyncDisposeAction), (Func<ValueTask>)(async () => { await tcs.Task; throw exception1; }));
builder.CloseComponent();
}
});
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
// Act: Second render
firstRender = false;
component.TriggerRender();
// Assert: Applicable children are included in disposal list
Assert.Equal(2, renderer.Batches.Count);
Assert.Equal(new[] { 1, }, renderer.Batches[1].DisposedComponentIDs);
// Outer component is still alive and not disposed.
Assert.False(component.Disposed);
Assert.Empty(renderer.HandledExceptions);
// Continue execution
tcs.SetResult();
semaphore.WaitOne();
var aex = Assert.IsType<InvalidOperationException>(Assert.Single(renderer.HandledExceptions));
Assert.Same(exception1, aex);
}
[Fact]
public void RenderBatch_ReportsSynchronousCancelationsAsErrors()
{
// Arrange
var renderer = new TestRenderer { ShouldHandleExceptions = true };
var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var firstRender = true;
var component = new TestComponent(builder =>
{
if (firstRender)
{
builder.AddContent(0, "Hello");
builder.OpenComponent<AsyncDisposableComponent>(1);
builder.AddAttribute(1, nameof(AsyncDisposableComponent.AsyncDisposeAction), (Func<ValueTask>)(() => throw new TaskCanceledException()));
builder.CloseComponent();
}
});
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
// Act: Second render
firstRender = false;
component.TriggerRender();
// Assert: Applicable children are included in disposal list
Assert.Equal(2, renderer.Batches.Count);
Assert.Equal(new[] { 1, }, renderer.Batches[1].DisposedComponentIDs);
// Outer component is still alive and not disposed.
Assert.False(component.Disposed);
var aex = Assert.IsType<AggregateException>(Assert.Single(renderer.HandledExceptions));
Assert.IsType<TaskCanceledException>(Assert.Single(aex.Flatten().InnerExceptions));
}
[Fact]
public void RenderBatch_ReportsAsynchronousCancelationsAsErrors()
{
// Arrange
var semaphore = new Semaphore(0, 1);
var renderer = new TestRenderer { ShouldHandleExceptions = true };
renderer.OnExceptionHandled += () => semaphore.Release();
var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var firstRender = true;
var component = new TestComponent(builder =>
{
if (firstRender)
{
builder.AddContent(0, "Hello");
builder.OpenComponent<AsyncDisposableComponent>(1);
builder.AddAttribute(
1,
nameof(AsyncDisposableComponent.AsyncDisposeAction),
(Func<ValueTask>)(() => new ValueTask(tcs.Task)));
builder.CloseComponent();
}
});
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
// Act: Second render
firstRender = false;
component.TriggerRender();
// Assert: Applicable children are included in disposal list
Assert.Equal(2, renderer.Batches.Count);
Assert.Equal(new[] { 1, }, renderer.Batches[1].DisposedComponentIDs);
// Outer component is still alive and not disposed.
Assert.False(component.Disposed);
Assert.Empty(renderer.HandledExceptions);
// Cancel execution
tcs.SetCanceled();
semaphore.WaitOne();
var aex = Assert.IsType<TaskCanceledException>(Assert.Single(renderer.HandledExceptions));
}
[Fact]
public void RenderBatch_DoesNotDisposeComponentMultipleTimes()
{
// Arrange
var renderer = new TestRenderer { ShouldHandleExceptions = true };
var exception1 = new Exception();
var exception2 = new Exception();
var count1 = 0;
var count2 = 0;
var count3 = 0;
var count4 = 0;
var count5 = 0;
var firstRender = true;
var component = new TestComponent(builder =>
{
if (firstRender)
{
builder.AddContent(0, "Hello");
builder.OpenComponent<DisposableComponent>(1);
builder.AddAttribute(1, nameof(DisposableComponent.DisposeAction), (Action)(() => { count1++; }));
builder.CloseComponent();
builder.OpenComponent<DisposableComponent>(2);
builder.AddAttribute(1, nameof(DisposableComponent.DisposeAction), (Action)(() => { count2++; throw exception1; }));
builder.CloseComponent();
builder.OpenComponent<DisposableComponent>(3);
builder.AddAttribute(1, nameof(DisposableComponent.DisposeAction), (Action)(() => { count3++; }));
builder.CloseComponent();
}
builder.OpenComponent<DisposableComponent>(4);
builder.AddAttribute(1, nameof(DisposableComponent.DisposeAction), (Action)(() => { count4++; throw exception2; }));
builder.CloseComponent();
builder.OpenComponent<DisposableComponent>(5);
builder.AddAttribute(1, nameof(DisposableComponent.DisposeAction), (Action)(() => { count5++; }));
builder.CloseComponent();
});
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
// Act: Second render
firstRender = false;
component.TriggerRender();
// Assert: Applicable children are included in disposal list
Assert.Equal(2, renderer.Batches.Count);
Assert.Equal(new[] { 1, 2, 3 }, renderer.Batches[1].DisposedComponentIDs);
// Components "disposed" in the batch were all disposed, components that are still live were not disposed
Assert.Equal(1, count1);
Assert.Equal(1, count2);
Assert.Equal(1, count3);
Assert.Equal(0, count4);
Assert.Equal(0, count5);
// Outer component is still alive and not disposed.
Assert.False(component.Disposed);
var ex = Assert.IsType<Exception>(Assert.Single(renderer.HandledExceptions));
Assert.Same(exception1, ex);
// Act: Dispose renderer
renderer.Dispose();
Assert.Equal(2, renderer.HandledExceptions.Count);
ex = renderer.HandledExceptions[1];
Assert.Same(exception2, ex);
// Assert: Everything was disposed once.
Assert.Equal(1, count1);
Assert.Equal(1, count2);
Assert.Equal(1, count3);
Assert.Equal(1, count4);
Assert.Equal(1, count5);
Assert.True(component.Disposed);
}
[Fact]
public async Task DisposesEventHandlersWhenAttributeValueChanged()
{
// Arrange
var renderer = new TestRenderer();
var eventCount = 0;
Action<EventArgs> origEventHandler = args => { eventCount++; };
var component = new EventComponent { OnTest = origEventHandler };
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
var origEventHandlerId = renderer.Batches.Single()
.ReferenceFrames
.Where(f => f.FrameType == RenderTreeFrameType.Attribute)
.Single(f => f.AttributeEventHandlerId != 0)
.AttributeEventHandlerId;
// Act/Assert 1: Event handler fires when we trigger it
Assert.Equal(0, eventCount);
var renderTask = renderer.DispatchEventAsync(origEventHandlerId, args: null);
Assert.True(renderTask.IsCompletedSuccessfully);
Assert.Equal(1, eventCount);
await renderTask;
// Now change the attribute value
var newEventCount = 0;
component.OnTest = args => { newEventCount++; };
component.TriggerRender();
// Act/Assert 2: Can no longer fire the original event, but can fire the new event
await Assert.ThrowsAsync<ArgumentException>(() =>
{
return renderer.DispatchEventAsync(origEventHandlerId, args: null);
});
Assert.Equal(1, eventCount);
Assert.Equal(0, newEventCount);
renderTask = renderer.DispatchEventAsync(origEventHandlerId + 1, args: null);
Assert.True(renderTask.IsCompletedSuccessfully);
Assert.Equal(1, newEventCount);
await renderTask;
}
[Fact]
public async Task DisposesEventHandlersWhenAttributeRemoved()
{
// Arrange
var renderer = new TestRenderer();
var eventCount = 0;
Action<EventArgs> origEventHandler = args => { eventCount++; };
var component = new EventComponent { OnTest = origEventHandler };
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
var origEventHandlerId = renderer.Batches.Single()
.ReferenceFrames
.Where(f => f.FrameType == RenderTreeFrameType.Attribute)
.Single(f => f.AttributeEventHandlerId != 0)
.AttributeEventHandlerId;
// Act/Assert 1: Event handler fires when we trigger it
Assert.Equal(0, eventCount);
var renderTask = renderer.DispatchEventAsync(origEventHandlerId, args: null);
Assert.True(renderTask.IsCompletedSuccessfully);
Assert.Equal(1, eventCount);
await renderTask;
// Now remove the event attribute
component.OnTest = null;
component.TriggerRender();
// Act/Assert 2: Can no longer fire the original event
await Assert.ThrowsAsync<ArgumentException>(() =>
{
return renderer.DispatchEventAsync(origEventHandlerId, args: null);
});
Assert.Equal(1, eventCount);
}
[Fact]
public async Task DisposesEventHandlersWhenOwnerComponentRemoved()
{
// Arrange
var renderer = new TestRenderer();
var eventCount = 0;
Action<EventArgs> origEventHandler = args => { eventCount++; };
var component = new ConditionalParentComponent<EventComponent>
{
IncludeChild = true,
ChildParameters = new Dictionary<string, object>
{
{ nameof(EventComponent.OnTest), origEventHandler }
}
};
var rootComponentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
var batch = renderer.Batches.Single();
var rootComponentDiff = batch.DiffsByComponentId[rootComponentId].Single();
var rootComponentFrame = batch.ReferenceFrames[0];
var childComponentFrame = rootComponentDiff.Edits
.Select(e => batch.ReferenceFrames[e.ReferenceFrameIndex])
.Where(f => f.FrameType == RenderTreeFrameType.Component)
.Single();
var childComponentId = childComponentFrame.ComponentId;
var childComponentDiff = batch.DiffsByComponentId[childComponentFrame.ComponentId].Single();
var eventHandlerId = batch.ReferenceFrames
.Skip(childComponentDiff.Edits[0].ReferenceFrameIndex) // Search from where the child component frames start
.Where(f => f.FrameType == RenderTreeFrameType.Attribute)
.Single(f => f.AttributeEventHandlerId != 0)
.AttributeEventHandlerId;
// Act/Assert 1: Event handler fires when we trigger it
Assert.Equal(0, eventCount);
var renderTask = renderer.DispatchEventAsync(eventHandlerId, args: null);
Assert.True(renderTask.IsCompletedSuccessfully);
Assert.Equal(1, eventCount);
await renderTask;
// Now remove the EventComponent
component.IncludeChild = false;
component.TriggerRender();
// Act/Assert 2: Can no longer fire the original event
await Assert.ThrowsAsync<ArgumentException>(() =>
{
return renderer.DispatchEventAsync(eventHandlerId, args: null);
});
Assert.Equal(1, eventCount);
}
[Fact]
public async Task DisposesEventHandlersWhenAncestorElementRemoved()
{
// Arrange
var renderer = new TestRenderer();
var eventCount = 0;
Action<EventArgs> origEventHandler = args => { eventCount++; };
var component = new EventComponent { OnTest = origEventHandler };
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
var origEventHandlerId = renderer.Batches.Single()
.ReferenceFrames
.Where(f => f.FrameType == RenderTreeFrameType.Attribute)
.Single(f => f.AttributeEventHandlerId != 0)
.AttributeEventHandlerId;
// Act/Assert 1: Event handler fires when we trigger it
Assert.Equal(0, eventCount);
var renderTask = renderer.DispatchEventAsync(origEventHandlerId, args: null);
Assert.True(renderTask.IsCompletedSuccessfully);
Assert.Equal(1, eventCount);
await renderTask;
// Now remove the ancestor element
component.SkipElement = true;
component.TriggerRender();
// Act/Assert 2: Can no longer fire the original event
await Assert.ThrowsAsync<ArgumentException>(() =>
{
return renderer.DispatchEventAsync(origEventHandlerId, args: null);
});
Assert.Equal(1, eventCount);
}
[Fact]
public async Task AllRendersTriggeredSynchronouslyDuringEventHandlerAreHandledAsSingleBatch()
{
// Arrange: A root component with a child whose event handler explicitly queues
// a re-render of both the root component and the child
var renderer = new TestRenderer();
var eventCount = 0;
TestComponent rootComponent = null;
EventComponent childComponent = null;
rootComponent = new TestComponent(builder =>
{
builder.AddContent(0, "Child event count: " + eventCount);
builder.OpenComponent<EventComponent>(1);
builder.AddAttribute(2, nameof(EventComponent.OnTest), new Action<EventArgs>(args =>
{
eventCount++;
rootComponent.TriggerRender();
childComponent.TriggerRender();
}));
builder.CloseComponent();
});
var rootComponentId = renderer.AssignRootComponentId(rootComponent);
rootComponent.TriggerRender();
var origBatchReferenceFrames = renderer.Batches.Single().ReferenceFrames;
var childComponentFrame = origBatchReferenceFrames
.Single(f => f.Component is EventComponent);
var childComponentId = childComponentFrame.ComponentId;
childComponent = (EventComponent)childComponentFrame.Component;
var origEventHandlerId = origBatchReferenceFrames
.Where(f => f.FrameType == RenderTreeFrameType.Attribute)
.Last(f => f.AttributeEventHandlerId != 0)
.AttributeEventHandlerId;
Assert.Single(renderer.Batches);
// Act
var renderTask = renderer.DispatchEventAsync(origEventHandlerId, args: null);
// Assert
Assert.True(renderTask.IsCompletedSuccessfully);
await renderTask;
Assert.Equal(2, renderer.Batches.Count);
var batch = renderer.Batches.Last();
Assert.Collection(batch.DiffsInOrder,
diff =>
{
// First we triggered the root component to re-render
Assert.Equal(rootComponentId, diff.ComponentId);
Assert.Collection(diff.Edits, edit =>
{
Assert.Equal(RenderTreeEditType.UpdateText, edit.Type);
AssertFrame.Text(
batch.ReferenceFrames[edit.ReferenceFrameIndex],
"Child event count: 1");
});
},
diff =>
{
// Then the root re-render will have triggered an update to the child
Assert.Equal(childComponentId, diff.ComponentId);
Assert.Collection(diff.Edits, edit =>
{
Assert.Equal(RenderTreeEditType.UpdateText, edit.Type);
AssertFrame.Text(
batch.ReferenceFrames[edit.ReferenceFrameIndex],
"Render count: 2");
});
},
diff =>
{
// Finally we explicitly requested a re-render of the child
Assert.Equal(childComponentId, diff.ComponentId);
Assert.Collection(diff.Edits, edit =>
{
Assert.Equal(RenderTreeEditType.UpdateText, edit.Type);
AssertFrame.Text(
batch.ReferenceFrames[edit.ReferenceFrameIndex],
"Render count: 3");
});
});
}
[Fact]
public void ComponentCannotTriggerRenderBeforeRenderHandleAssigned()
{
// Arrange
var component = new TestComponent(builder => { });
// Act/Assert
var ex = Assert.Throws<InvalidOperationException>(() => component.TriggerRender());
Assert.Equal("The render handle is not yet assigned.", ex.Message);
}
[Fact]
public void ComponentCanTriggerRenderWhenNoBatchIsInProgress()
{
// Arrange
var renderer = new TestRenderer();
var renderCount = 0;
var component = new TestComponent(builder =>
{
builder.AddContent(0, $"Render count: {++renderCount}");
});
var componentId = renderer.AssignRootComponentId(component);
// Act/Assert: Can trigger initial render
Assert.Equal(0, renderCount);
component.TriggerRender();
Assert.Equal(1, renderCount);
var batch1 = renderer.Batches.Single();
var edit1 = batch1.DiffsByComponentId[componentId].Single().Edits.Single();
Assert.Equal(RenderTreeEditType.PrependFrame, edit1.Type);
AssertFrame.Text(batch1.ReferenceFrames[edit1.ReferenceFrameIndex],
"Render count: 1", 0);
// Act/Assert: Can trigger subsequent render
component.TriggerRender();
Assert.Equal(2, renderCount);
var batch2 = renderer.Batches.Skip(1).Single();
var edit2 = batch2.DiffsByComponentId[componentId].Single().Edits.Single();
Assert.Equal(RenderTreeEditType.UpdateText, edit2.Type);
AssertFrame.Text(batch2.ReferenceFrames[edit2.ReferenceFrameIndex],
"Render count: 2", 0);
}
[Fact]
public void ComponentCanTriggerRenderWhenExistingBatchIsInProgress()
{
// Arrange
var renderer = new TestRenderer();
TestComponent parent = null;
var parentRenderCount = 0;
parent = new TestComponent(builder =>
{
builder.OpenComponent<ReRendersParentComponent>(0);
builder.AddAttribute(1, nameof(ReRendersParentComponent.Parent), parent);
builder.CloseComponent();
builder.AddContent(2, $"Parent render count: {++parentRenderCount}");
});
var parentComponentId = renderer.AssignRootComponentId(parent);
// Act
parent.TriggerRender();
// Assert
var batch = renderer.Batches.Single();
Assert.Equal(4, batch.DiffsInOrder.Count);
// First is the parent component's initial render
var diff1 = batch.DiffsInOrder[0];
Assert.Equal(parentComponentId, diff1.ComponentId);
Assert.Collection(diff1.Edits,
edit =>
{
Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type);
AssertFrame.Component<ReRendersParentComponent>(
batch.ReferenceFrames[edit.ReferenceFrameIndex]);
},
edit =>
{
Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type);
AssertFrame.Text(
batch.ReferenceFrames[edit.ReferenceFrameIndex],
"Parent render count: 1");
});
// Second is the child component's single render
var diff2 = batch.DiffsInOrder[1];
Assert.NotEqual(parentComponentId, diff2.ComponentId);
var diff2edit = diff2.Edits.Single();
Assert.Equal(RenderTreeEditType.PrependFrame, diff2edit.Type);
AssertFrame.Text(batch.ReferenceFrames[diff2edit.ReferenceFrameIndex],
"Child is here");
// Third is the parent's triggered render
var diff3 = batch.DiffsInOrder[2];
Assert.Equal(parentComponentId, diff3.ComponentId);
var diff3edit = diff3.Edits.Single();
Assert.Equal(RenderTreeEditType.UpdateText, diff3edit.Type);
AssertFrame.Text(batch.ReferenceFrames[diff3edit.ReferenceFrameIndex],
"Parent render count: 2");
// Fourth is child's rerender due to parent rendering
var diff4 = batch.DiffsInOrder[3];
Assert.NotEqual(parentComponentId, diff4.ComponentId);
Assert.Empty(diff4.Edits);
}
[Fact]
public void QueuedRenderIsSkippedIfComponentWasAlreadyDisposedInSameBatch()
{
// Arrange
var renderer = new TestRenderer();
var shouldRenderChild = true;
TestComponent component = null;
component = new TestComponent(builder =>
{
builder.AddContent(0, "Some frame so the child isn't at position zero");
if (shouldRenderChild)
{
builder.OpenComponent<RendersSelfAfterEventComponent>(1);
builder.AddAttribute(2, "onclick", (Action<object>)((object obj) =>
{
// First we queue (1) a re-render of the root component, then the child component
// will queue (2) its own re-render. But by the time (1) completes, the child will
// have been disposed, even though (2) is still in the queue
shouldRenderChild = false;
component.TriggerRender();
}));
builder.CloseComponent();
}
});
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
var childComponentId = renderer.Batches.Single()
.ReferenceFrames
.Where(f => f.ComponentId != 0)
.Single()
.ComponentId;
var origEventHandlerId = renderer.Batches.Single()
.ReferenceFrames
.Where(f => f.FrameType == RenderTreeFrameType.Attribute && f.AttributeName == "onmycustomevent")
.Single(f => f.AttributeEventHandlerId != 0)
.AttributeEventHandlerId;
// Act
// The fact that there's no error here is the main thing we're testing
var renderTask = renderer.DispatchEventAsync(origEventHandlerId, args: null);
// Assert: correct render result
Assert.True(renderTask.IsCompletedSuccessfully);
var newBatch = renderer.Batches.Skip(1).Single();
Assert.Equal(1, newBatch.DisposedComponentIDs.Count);
Assert.Equal(1, newBatch.DiffsByComponentId.Count);
Assert.Collection(newBatch.DiffsByComponentId[componentId].Single().Edits,
edit =>
{
Assert.Equal(RenderTreeEditType.RemoveFrame, edit.Type);
Assert.Equal(1, edit.SiblingIndex);
});
}
[Fact]
public async Task CanCombineBindAndConditionalAttribute()
{
// This test represents https://github.com/dotnet/blazor/issues/624
// Arrange: Rendered with textbox enabled
var renderer = new TestRenderer();
var component = new BindPlusConditionalAttributeComponent();
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
var checkboxChangeEventHandlerId = renderer.Batches.Single()
.ReferenceFrames
.First(frame => frame.FrameType == RenderTreeFrameType.Attribute && frame.AttributeEventHandlerId != 0)
.AttributeEventHandlerId;
// Act: Toggle the checkbox
var eventArgs = new ChangeEventArgs { Value = true };
var renderTask = renderer.DispatchEventAsync(checkboxChangeEventHandlerId, eventArgs);
Assert.True(renderTask.IsCompletedSuccessfully);
var latestBatch = renderer.Batches.Last();
var latestDiff = latestBatch.DiffsInOrder.Single();
var referenceFrames = latestBatch.ReferenceFrames;
// Assert: Textbox's "disabled" attribute was removed
Assert.Equal(2, renderer.Batches.Count);
Assert.Equal(componentId, latestDiff.ComponentId);
Assert.Contains(latestDiff.Edits, edit =>
edit.SiblingIndex == 1
&& edit.RemovedAttributeName == "disabled");
await renderTask;
}
[Fact]
public void HandlesNestedElementCapturesDuringRefresh()
{
// This may seem like a very arbitrary test case, but at once stage there was a bug
// whereby the diff output was incorrect given a ref capture on an element whose
// parent element also had a ref capture
// Arrange
var attrValue = 0;
var component = new TestComponent(builder =>
{
builder.OpenElement(0, "parent elem");
builder.AddAttribute(1, "parent elem attr", attrValue);
builder.AddElementReferenceCapture(2, _ => { });
builder.OpenElement(3, "child elem");
builder.AddElementReferenceCapture(4, _ => { });
builder.AddContent(5, "child text");
builder.CloseElement();
builder.CloseElement();
});
var renderer = new TestRenderer();
renderer.AssignRootComponentId(component);
// Act: Update the attribute value on the parent
component.TriggerRender();
attrValue++;
component.TriggerRender();
// Assert
var latestBatch = renderer.Batches.Skip(1).Single();
var latestDiff = latestBatch.DiffsInOrder.Single();
Assert.Collection(latestDiff.Edits,
edit =>
{
Assert.Equal(RenderTreeEditType.SetAttribute, edit.Type);
Assert.Equal(0, edit.SiblingIndex);
AssertFrame.Attribute(latestBatch.ReferenceFrames[edit.ReferenceFrameIndex],
"parent elem attr", 1);
});
}
[Fact]
public void CallsAfterRenderOnEachRender()
{
// Arrange
var onAfterRenderCallCountLog = new List<int>();
var component = new AfterRenderCaptureComponent();
var renderer = new TestRenderer
{
OnUpdateDisplay = _ => onAfterRenderCallCountLog.Add(component.OnAfterRenderCallCount)
};
renderer.AssignRootComponentId(component);
// Act
component.TriggerRender();
// Assert
// When the display was first updated, OnAfterRender had not yet been called
Assert.Equal(new[] { 0 }, onAfterRenderCallCountLog);
// But OnAfterRender was called since then
Assert.Equal(1, component.OnAfterRenderCallCount);
// Act/Assert 2: On a subsequent render, the same happens again
component.TriggerRender();
Assert.Equal(new[] { 0, 1 }, onAfterRenderCallCountLog);
Assert.Equal(2, component.OnAfterRenderCallCount);
}
[Fact]
public void CallsAfterRenderAfterTheUIHasFinishedUpdatingAsynchronously()
{
// Arrange
var @event = new ManualResetEventSlim();
var tcs = new TaskCompletionSource<object>();
var afterRenderTcs = new TaskCompletionSource<object>();
var onAfterRenderCallCountLog = new List<int>();
var component = new AsyncAfterRenderComponent(afterRenderTcs.Task)
{
OnAfterRenderComplete = () => @event.Set(),
};
var renderer = new AsyncUpdateTestRenderer()
{
OnUpdateDisplayAsync = _ => tcs.Task,
};
renderer.AssignRootComponentId(component);
// Act
component.TriggerRender();
tcs.SetResult(null);
afterRenderTcs.SetResult(null);
// We need to wait here because the completions from SetResult will be scheduled.
@event.Wait(Timeout);
// Assert
Assert.True(component.Called);
}
[Fact]
public void CallsAfterRenderAfterTheUIHasFinishedUpdatingSynchronously()
{
// Arrange
var @event = new ManualResetEventSlim();
var afterRenderTcs = new TaskCompletionSource<object>();
var onAfterRenderCallCountLog = new List<int>();
var component = new AsyncAfterRenderComponent(afterRenderTcs.Task)
{
OnAfterRenderComplete = () => @event.Set(),
};
var renderer = new AsyncUpdateTestRenderer()
{
OnUpdateDisplayAsync = _ => Task.CompletedTask
};
renderer.AssignRootComponentId(component);
// Act
component.TriggerRender();
afterRenderTcs.SetResult(null);
// We need to wait here because the completions from SetResult will be scheduled.
@event.Wait(Timeout);
// Assert
Assert.True(component.Called);
}
[Fact]
public void DoesNotCallOnAfterRenderForComponentsNotRendered()
{
// Arrange
var showComponent3 = true;
var parentComponent = new TestComponent(builder =>
{
// First child will be re-rendered because we'll change its param
builder.OpenComponent<AfterRenderCaptureComponent>(0);
builder.AddAttribute(1, "some param", showComponent3);
builder.CloseComponent();
// Second child will not be re-rendered because nothing changes
builder.OpenComponent<AfterRenderCaptureComponent>(2);
builder.CloseComponent();
// Third component will be disposed
if (showComponent3)
{
builder.OpenComponent<AfterRenderCaptureComponent>(3);
builder.CloseComponent();
}
});
var renderer = new TestRenderer();
var parentComponentId = renderer.AssignRootComponentId(parentComponent);
// Act: First render
parentComponent.TriggerRender();
// Assert: All child components were notified of "after render"
var batch1 = renderer.Batches.Single();
var parentComponentEdits1 = batch1.DiffsByComponentId[parentComponentId].Single().Edits;
var childComponents = parentComponentEdits1
.Select(
edit => (AfterRenderCaptureComponent)batch1.ReferenceFrames[edit.ReferenceFrameIndex].Component)
.ToArray();
Assert.Equal(1, childComponents[0].OnAfterRenderCallCount);
Assert.Equal(1, childComponents[1].OnAfterRenderCallCount);
Assert.Equal(1, childComponents[2].OnAfterRenderCallCount);
// Act: Second render
showComponent3 = false;
parentComponent.TriggerRender();
// Assert: Only the re-rendered component was notified of "after render"
var batch2 = renderer.Batches.Skip(1).Single();
Assert.Equal(2, batch2.DiffsInOrder.Count); // Parent and first child
Assert.Equal(1, batch2.DisposedComponentIDs.Count); // Third child
Assert.Equal(2, childComponents[0].OnAfterRenderCallCount); // Retained and re-rendered
Assert.Equal(1, childComponents[1].OnAfterRenderCallCount); // Retained and not re-rendered
Assert.Equal(1, childComponents[2].OnAfterRenderCallCount); // Disposed
}
[Fact]
public void CanTriggerRenderingSynchronouslyFromInsideAfterRenderCallback()
{
// Arrange
AfterRenderCaptureComponent component = null;
component = new AfterRenderCaptureComponent
{
OnAfterRenderLogic = () =>
{
if (component.OnAfterRenderCallCount < 10)
{
component.TriggerRender();
}
}
};
var renderer = new TestRenderer();
renderer.AssignRootComponentId(component);
// Act
component.TriggerRender();
// Assert
Assert.Equal(10, component.OnAfterRenderCallCount);
}
[Fact]
public async Task CanTriggerEventHandlerDisposedInEarlierPendingBatchAsync()
{
// This represents the scenario where the same event handler is being triggered
// rapidly, such as an input event while typing. It only applies to asynchronous
// batch updates, i.e., server-side Components.
// Sequence:
// 1. The client dispatches event X twice (say) in quick succession
// 2. The server receives the first instance, handles the event, and re-renders
// some component. The act of re-rendering causes the old event handler to be
// replaced by a new one, so the old one is flagged to be disposed.
// 3. The server receives the second instance. Even though the corresponding event
// handler is flagged to be disposed, we have to still be able to find and
// execute it without errors.
// Arrange
var renderer = new TestAsyncRenderer
{
NextUpdateDisplayReturnTask = Task.CompletedTask
};
var numEventsFired = 0;
EventComponent component = null;
Action<EventArgs> eventHandler = null;
eventHandler = _ =>
{
numEventsFired++;
// Replace the old event handler with a different one,
// (old the old handler ID will be disposed) then re-render.
component.OnTest = args => eventHandler(args);
component.TriggerRender();
};
component = new EventComponent { OnTest = eventHandler };
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
var eventHandlerId = renderer.Batches.Single()
.ReferenceFrames
.First(frame => frame.AttributeValue != null)
.AttributeEventHandlerId;
// Act/Assert 1: Event can be fired for the first time
var render1TCS = new TaskCompletionSource<object>();
renderer.NextUpdateDisplayReturnTask = render1TCS.Task;
await renderer.DispatchEventAsync(eventHandlerId, new EventArgs());
Assert.Equal(1, numEventsFired);
// Act/Assert 2: *Same* event handler ID can be reused prior to completion of
// preceding UI update
var render2TCS = new TaskCompletionSource<object>();
renderer.NextUpdateDisplayReturnTask = render2TCS.Task;
await renderer.DispatchEventAsync(eventHandlerId, new EventArgs());
Assert.Equal(2, numEventsFired);
// Act/Assert 3: After we complete the first UI update in which a given
// event handler ID is disposed, we can no longer reuse that event handler ID
// From here we can't see when the async disposal is completed. Just give it plenty of time (Task.Yield isn't enough).
// There is a small chance in which the continuations from TaskCompletionSource run asynchronously.
// In that case we might not be able to see the results from RemoveEventHandlerIds as they might run asynchronously.
// For that case, we are going to queue a continuation on render1TCS.Task, include a 1s delay and await the resulting
// task to offer the best chance that we get to see the error in all cases.
var awaitableTask = render1TCS.Task.ContinueWith(_ => Task.Delay(1000)).Unwrap();
render1TCS.SetResult(null);
await awaitableTask;
var ex = await Assert.ThrowsAsync<ArgumentException>(() =>
{
return renderer.DispatchEventAsync(eventHandlerId, new EventArgs());
});
Assert.Contains($"There is no event handler associated with this event. EventId: '{eventHandlerId}'.", ex.Message);
Assert.Equal(2, numEventsFired);
}
[Fact]
public void ExceptionsThrownSynchronouslyCanBeHandledSynchronously()
{
// Arrange
var renderer = new TestRenderer { ShouldHandleExceptions = true };
var component = new NestedAsyncComponent();
var exception = new InvalidTimeZoneException();
// Act/Assert
var componentId = renderer.AssignRootComponentId(component);
var task = renderer.RenderRootComponentAsync(componentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
[nameof(NestedAsyncComponent.EventActions)] = new Dictionary<int, IList<NestedAsyncComponent.ExecutionAction>>
{
[0] = new[]
{
new NestedAsyncComponent.ExecutionAction
{
Event = NestedAsyncComponent.EventType.OnInitAsyncAsync,
EventAction = () => throw exception,
},
}
},
[nameof(NestedAsyncComponent.WhatToRender)] = new Dictionary<int, Func<NestedAsyncComponent, RenderFragment>>
{
[0] = CreateRenderFactory(Array.Empty<int>()),
},
}));
Assert.True(task.IsCompletedSuccessfully);
Assert.Equal(new[] { exception }, renderer.HandledExceptions);
}
[Fact]
public void ExceptionsThrownSynchronouslyCanBeHandled()
{
// Arrange
var renderer = new TestRenderer { ShouldHandleExceptions = true };
var component = new NestedAsyncComponent();
var exception = new InvalidTimeZoneException();
// Act/Assert
var componentId = renderer.AssignRootComponentId(component);
var renderTask = renderer.RenderRootComponentAsync(componentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
[nameof(NestedAsyncComponent.EventActions)] = new Dictionary<int, IList<NestedAsyncComponent.ExecutionAction>>
{
[0] = new[]
{
new NestedAsyncComponent.ExecutionAction
{
Event = NestedAsyncComponent.EventType.OnInitAsyncAsync,
EventAction = () => throw exception,
},
}
},
[nameof(NestedAsyncComponent.WhatToRender)] = new Dictionary<int, Func<NestedAsyncComponent, RenderFragment>>
{
[0] = CreateRenderFactory(Array.Empty<int>()),
},
}));
Assert.True(renderTask.IsCompletedSuccessfully);
Assert.Equal(new[] { exception }, renderer.HandledExceptions);
}
[Fact]
public void ExceptionsReturnedUsingTaskFromExceptionCanBeHandled()
{
// Arrange
var renderer = new TestRenderer { ShouldHandleExceptions = true };
var component = new NestedAsyncComponent();
var exception = new InvalidTimeZoneException();
// Act/Assert
var componentId = renderer.AssignRootComponentId(component);
var renderTask = renderer.RenderRootComponentAsync(componentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
[nameof(NestedAsyncComponent.EventActions)] = new Dictionary<int, IList<NestedAsyncComponent.ExecutionAction>>
{
[0] = new[]
{
new NestedAsyncComponent.ExecutionAction
{
Event = NestedAsyncComponent.EventType.OnInitAsyncAsync,
EventAction = () => Task.FromException<(int, NestedAsyncComponent.EventType)>(exception),
},
}
},
[nameof(NestedAsyncComponent.WhatToRender)] = new Dictionary<int, Func<NestedAsyncComponent, RenderFragment>>
{
[0] = CreateRenderFactory(Array.Empty<int>()),
},
}));
Assert.True(renderTask.IsCompletedSuccessfully);
Assert.Equal(new[] { exception }, renderer.HandledExceptions);
}
[Fact]
public async Task ExceptionsThrownAsynchronouslyDuringFirstRenderCanBeHandled()
{
// Arrange
var renderer = new TestRenderer { ShouldHandleExceptions = true };
var component = new NestedAsyncComponent();
var tcs = new TaskCompletionSource<int>();
var exception = new InvalidTimeZoneException();
// Act/Assert
var componentId = renderer.AssignRootComponentId(component);
var renderTask = renderer.RenderRootComponentAsync(componentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
[nameof(NestedAsyncComponent.EventActions)] = new Dictionary<int, IList<NestedAsyncComponent.ExecutionAction>>
{
[0] = new[]
{
new NestedAsyncComponent.ExecutionAction
{
Event = NestedAsyncComponent.EventType.OnInitAsyncAsync,
EventAction = async () =>
{
await tcs.Task;
throw exception;
}
},
}
},
[nameof(NestedAsyncComponent.WhatToRender)] = new Dictionary<int, Func<NestedAsyncComponent, RenderFragment>>
{
[0] = CreateRenderFactory(Array.Empty<int>()),
},
}));
Assert.False(renderTask.IsCompleted);
tcs.SetResult(0);
await renderTask;
Assert.Same(exception, Assert.Single(renderer.HandledExceptions).GetBaseException());
}
[Fact]
public async Task ExceptionsThrownAsynchronouslyAfterFirstRenderCanBeHandled()
{
// This differs from the "during first render" case, because some aspects of the rendering
// code paths are special cased for the first render because of prerendering.
// Arrange
var @event = new ManualResetEventSlim();
var renderer = new TestRenderer()
{
ShouldHandleExceptions = true,
OnExceptionHandled = () => { @event.Set(); },
};
var taskToAwait = Task.CompletedTask;
var component = new TestComponent(builder =>
{
builder.OpenComponent<ComponentThatAwaitsTask>(0);
builder.AddAttribute(1, nameof(ComponentThatAwaitsTask.TaskToAwait), taskToAwait);
builder.CloseComponent();
});
var componentId = renderer.AssignRootComponentId(component);
await renderer.RenderRootComponentAsync(componentId); // Not throwing on first render
var asyncExceptionTcs = new TaskCompletionSource<object>();
taskToAwait = asyncExceptionTcs.Task;
await renderer.Dispatcher.InvokeAsync(component.TriggerRender);
// Act
var exception = new InvalidOperationException();
@event.Reset();
asyncExceptionTcs.SetException(exception);
// We need to wait here because the continuations of SetException will be scheduled to run asynchronously.
@event.Wait(Timeout);
// Assert
Assert.Same(exception, Assert.Single(renderer.HandledExceptions).GetBaseException());
}
[Fact]
public async Task ExceptionsThrownAsynchronouslyFromMultipleComponentsCanBeHandled()
{
// Arrange
var renderer = new TestRenderer { ShouldHandleExceptions = true };
var component = new NestedAsyncComponent();
var exception1 = new InvalidTimeZoneException();
var exception2 = new UriFormatException();
var tcs = new TaskCompletionSource<int>();
// Act/Assert
var componentId = renderer.AssignRootComponentId(component);
var renderTask = renderer.RenderRootComponentAsync(componentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
[nameof(NestedAsyncComponent.EventActions)] = new Dictionary<int, IList<NestedAsyncComponent.ExecutionAction>>
{
[0] = Array.Empty<NestedAsyncComponent.ExecutionAction>(),
[1] = new List<NestedAsyncComponent.ExecutionAction>
{
new NestedAsyncComponent.ExecutionAction
{
Event = NestedAsyncComponent.EventType.OnInitAsyncAsync,
EventAction = async () =>
{
await tcs.Task;
throw exception1;
}
},
},
[2] = new List<NestedAsyncComponent.ExecutionAction>
{
new NestedAsyncComponent.ExecutionAction
{
Event = NestedAsyncComponent.EventType.OnInitAsyncAsync,
EventAction = async () =>
{
await tcs.Task;
throw exception2;
}
},
},
},
[nameof(NestedAsyncComponent.WhatToRender)] = new Dictionary<int, Func<NestedAsyncComponent, RenderFragment>>
{
[0] = CreateRenderFactory(new[] { 1, 2, }),
[1] = CreateRenderFactory(Array.Empty<int>()),
[2] = CreateRenderFactory(Array.Empty<int>()),
},
}));
Assert.False(renderTask.IsCompleted);
tcs.SetResult(0);
await renderTask;
Assert.Equal(2, renderer.HandledExceptions.Count);
Assert.Contains(exception1, renderer.HandledExceptions);
Assert.Contains(exception2, renderer.HandledExceptions);
}
[Fact]
public void ExceptionsThrownSynchronouslyFromMultipleComponentsCanBeHandled()
{
// Arrange
var renderer = new TestRenderer { ShouldHandleExceptions = true };
var component = new NestedAsyncComponent();
var exception1 = new InvalidTimeZoneException();
var exception2 = new UriFormatException();
// Act/Assert
var componentId = renderer.AssignRootComponentId(component);
var renderTask = renderer.RenderRootComponentAsync(componentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
[nameof(NestedAsyncComponent.EventActions)] = new Dictionary<int, IList<NestedAsyncComponent.ExecutionAction>>
{
[0] = Array.Empty<NestedAsyncComponent.ExecutionAction>(),
[1] = new List<NestedAsyncComponent.ExecutionAction>
{
new NestedAsyncComponent.ExecutionAction
{
Event = NestedAsyncComponent.EventType.OnInitAsyncAsync,
EventAction = () =>
{
throw exception1;
}
},
},
[2] = new List<NestedAsyncComponent.ExecutionAction>
{
new NestedAsyncComponent.ExecutionAction
{
Event = NestedAsyncComponent.EventType.OnInitAsyncAsync,
EventAction = () =>
{
throw exception2;
}
},
},
},
[nameof(NestedAsyncComponent.WhatToRender)] = new Dictionary<int, Func<NestedAsyncComponent, RenderFragment>>
{
[0] = CreateRenderFactory(new[] { 1, 2, }),
[1] = CreateRenderFactory(Array.Empty<int>()),
[2] = CreateRenderFactory(Array.Empty<int>()),
},
}));
Assert.True(renderTask.IsCompletedSuccessfully);
Assert.Equal(2, renderer.HandledExceptions.Count);
Assert.Contains(exception1, renderer.HandledExceptions);
Assert.Contains(exception2, renderer.HandledExceptions);
}
[Fact]
public async Task ExceptionsThrownFromHandleAfterRender_Sync_AreHandled()
{
// Arrange
var renderer = new TestRenderer { ShouldHandleExceptions = true };
var component = new NestedAsyncComponent();
var exception = new InvalidTimeZoneException();
var taskCompletionSource = new TaskCompletionSource<int>();
// Act/Assert
var componentId = renderer.AssignRootComponentId(component);
var renderTask = renderer.RenderRootComponentAsync(componentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
[nameof(NestedAsyncComponent.EventActions)] = new Dictionary<int, IList<NestedAsyncComponent.ExecutionAction>>
{
[0] = new[]
{
new NestedAsyncComponent.ExecutionAction
{
Event = NestedAsyncComponent.EventType.OnAfterRenderAsyncSync,
EventAction = () =>
{
throw exception;
},
}
},
[1] = new[]
{
new NestedAsyncComponent.ExecutionAction
{
Event = NestedAsyncComponent.EventType.OnAfterRenderAsyncSync,
EventAction = () =>
{
taskCompletionSource.TrySetResult(0);
return Task.FromResult((1, NestedAsyncComponent.EventType.OnAfterRenderAsyncSync));
},
}
}
},
[nameof(NestedAsyncComponent.WhatToRender)] = new Dictionary<int, Func<NestedAsyncComponent, RenderFragment>>
{
[0] = CreateRenderFactory(new[] { 1 }),
[1] = CreateRenderFactory(Array.Empty<int>()),
},
}));
Assert.True(renderTask.IsCompletedSuccessfully);
// OnAfterRenderAsync happens in the background. Make it more predictable, by gating it until we're ready to capture exceptions.
await taskCompletionSource.Task.TimeoutAfter(TimeSpan.FromSeconds(10));
Assert.Same(exception, Assert.Single(renderer.HandledExceptions).GetBaseException());
}
[Fact]
public async Task ExceptionsThrownFromHandleAfterRender_Async_AreHandled()
{
// Arrange
var renderer = new TestRenderer { ShouldHandleExceptions = true };
var component = new NestedAsyncComponent();
var exception = new InvalidTimeZoneException();
var taskCompletionSource = new TaskCompletionSource<int>();
// Act/Assert
var componentId = renderer.AssignRootComponentId(component);
var renderTask = renderer.RenderRootComponentAsync(componentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
[nameof(NestedAsyncComponent.EventActions)] = new Dictionary<int, IList<NestedAsyncComponent.ExecutionAction>>
{
[0] = new[]
{
new NestedAsyncComponent.ExecutionAction
{
Event = NestedAsyncComponent.EventType.OnAfterRenderAsyncAsync,
EventAction = async () =>
{
await Task.Yield();
throw exception;
},
}
},
[1] = new[]
{
new NestedAsyncComponent.ExecutionAction
{
Event = NestedAsyncComponent.EventType.OnAfterRenderAsyncAsync,
EventAction = async () =>
{
await Task.Yield();
taskCompletionSource.TrySetResult(0);
return (1, NestedAsyncComponent.EventType.OnAfterRenderAsyncAsync);
},
}
}
},
[nameof(NestedAsyncComponent.WhatToRender)] = new Dictionary<int, Func<NestedAsyncComponent, RenderFragment>>
{
[0] = CreateRenderFactory(new[] { 1 }),
[1] = CreateRenderFactory(Array.Empty<int>()),
},
}));
Assert.True(renderTask.IsCompletedSuccessfully);
// OnAfterRenderAsync happens in the background. Make it more predictable, by gating it until we're ready to capture exceptions.
await taskCompletionSource.Task.TimeoutAfter(TimeSpan.FromSeconds(10));
Assert.Same(exception, Assert.Single(renderer.HandledExceptions).GetBaseException());
}
[Fact]
public async Task ExceptionThrownFromConstructor()
{
// Arrange
var renderer = new TestRenderer { ShouldHandleExceptions = true };
var component = new TestComponent(builder =>
{
builder.OpenComponent<ConstructorThrowingComponent>(0);
builder.CloseComponent();
});
// Act/Assert
var componentId = renderer.AssignRootComponentId(component);
var renderTask = renderer.RenderRootComponentAsync(componentId);
await renderTask;
Assert.True(renderTask.IsCompletedSuccessfully);
Assert.Same(ConstructorThrowingComponent.Exception, Assert.Single(renderer.HandledExceptions).GetBaseException());
}
private class ConstructorThrowingComponent : IComponent
{
public static readonly Exception Exception = new InvalidTimeZoneException();
public ConstructorThrowingComponent()
{
throw Exception;
}
public void Attach(RenderHandle renderHandle)
{
throw new NotImplementedException();
}
public Task SetParametersAsync(ParameterView parameters)
{
throw new NotImplementedException();
}
}
[Fact]
public async Task ExceptionThrownFromAttach()
{
// Arrange
var renderer = new TestRenderer { ShouldHandleExceptions = true };
var component = new TestComponent(builder =>
{
builder.OpenComponent<AttachThrowingComponent>(0);
builder.CloseComponent();
});
// Act/Assert
var componentId = renderer.AssignRootComponentId(component);
var renderTask = renderer.RenderRootComponentAsync(componentId);
await renderTask;
Assert.True(renderTask.IsCompletedSuccessfully);
Assert.Same(AttachThrowingComponent.Exception, Assert.Single(renderer.HandledExceptions).GetBaseException());
}
private class AttachThrowingComponent : IComponent
{
public static readonly Exception Exception = new InvalidTimeZoneException();
public void Attach(RenderHandle renderHandle)
{
throw Exception;
}
public Task SetParametersAsync(ParameterView parameters)
{
throw new NotImplementedException();
}
}
[Fact]
public void SynchronousCancelledTasks_HandleAfterRender_Works()
{
// Arrange
var renderer = new TestRenderer { ShouldHandleExceptions = true };
var component = new NestedAsyncComponent();
var tcs = new TaskCompletionSource<(int, NestedAsyncComponent.EventType)>();
tcs.TrySetCanceled();
// Act/Assert
var componentId = renderer.AssignRootComponentId(component);
var renderTask = renderer.RenderRootComponentAsync(componentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
[nameof(NestedAsyncComponent.EventActions)] = new Dictionary<int, IList<NestedAsyncComponent.ExecutionAction>>
{
[0] = new[]
{
new NestedAsyncComponent.ExecutionAction
{
Event = NestedAsyncComponent.EventType.OnAfterRenderAsyncAsync,
EventAction = () => tcs.Task,
}
},
},
[nameof(NestedAsyncComponent.WhatToRender)] = new Dictionary<int, Func<NestedAsyncComponent, RenderFragment>>
{
[0] = CreateRenderFactory(Array.Empty<int>()),
},
}));
// Rendering should finish synchronously
Assert.True(renderTask.IsCompletedSuccessfully);
Assert.Empty(renderer.HandledExceptions);
}
[Fact]
public void AsynchronousCancelledTasks_HandleAfterRender_Works()
{
// Arrange
var renderer = new TestRenderer { ShouldHandleExceptions = true };
var component = new NestedAsyncComponent();
var tcs = new TaskCompletionSource<(int, NestedAsyncComponent.EventType)>();
// Act/Assert
var componentId = renderer.AssignRootComponentId(component);
var renderTask = renderer.RenderRootComponentAsync(componentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
[nameof(NestedAsyncComponent.EventActions)] = new Dictionary<int, IList<NestedAsyncComponent.ExecutionAction>>
{
[0] = new[]
{
new NestedAsyncComponent.ExecutionAction
{
Event = NestedAsyncComponent.EventType.OnAfterRenderAsyncAsync,
EventAction = () => tcs.Task,
}
},
},
[nameof(NestedAsyncComponent.WhatToRender)] = new Dictionary<int, Func<NestedAsyncComponent, RenderFragment>>
{
[0] = CreateRenderFactory(Array.Empty<int>()),
},
}));
// Rendering should be complete.
Assert.True(renderTask.IsCompletedSuccessfully);
tcs.TrySetCanceled();
Assert.Empty(renderer.HandledExceptions);
}
[Fact]
public async Task CanceledTasksInHandleAfterRender_AreIgnored()
{
// Arrange
var renderer = new TestRenderer { ShouldHandleExceptions = true };
var component = new NestedAsyncComponent();
var taskCompletionSource = new TaskCompletionSource<int>();
var cancellationTokenSource = new CancellationTokenSource();
cancellationTokenSource.Cancel();
// Act/Assert
var componentId = renderer.AssignRootComponentId(component);
await renderer.RenderRootComponentAsync(componentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
[nameof(NestedAsyncComponent.EventActions)] = new Dictionary<int, IList<NestedAsyncComponent.ExecutionAction>>
{
[0] = new[]
{
new NestedAsyncComponent.ExecutionAction
{
Event = NestedAsyncComponent.EventType.OnAfterRenderAsyncSync,
EventAction = () =>
{
taskCompletionSource.TrySetResult(0);
cancellationTokenSource.Token.ThrowIfCancellationRequested();
return default;
},
}
},
},
[nameof(NestedAsyncComponent.WhatToRender)] = new Dictionary<int, Func<NestedAsyncComponent, RenderFragment>>
{
[0] = CreateRenderFactory(Array.Empty<int>()),
},
}));
await taskCompletionSource.Task.TimeoutAfter(TimeSpan.FromSeconds(10));
Assert.Empty(renderer.HandledExceptions);
}
[Fact]
public void DisposingRenderer_DisposesTopLevelComponents()
{
// Arrange
var renderer = new TestRenderer();
var component = new DisposableComponent();
renderer.AssignRootComponentId(component);
// Act
renderer.Dispose();
// Assert
Assert.True(component.Disposed);
}
[Fact]
public void DisposingRenderer_DisregardsAttemptsToStartMoreRenderBatches()
{
// Arrange
var renderer = new TestRenderer();
var component = new TestComponent(builder =>
{
builder.OpenElement(0, "my element");
builder.AddContent(1, "some text");
builder.CloseElement();
});
// Act
renderer.AssignRootComponentId(component);
renderer.Dispose();
component.TriggerRender();
// Assert
Assert.Empty(renderer.Batches);
}
[Fact]
public void WhenRendererIsDisposed_ComponentRenderRequestsAreSkipped()
{
// The important point of this is that user code in components may continue to call
// StateHasChanged (e.g., after an async task completion), and we don't want that to
// show up as an error. In general, components should skip rendering after disposal.
// This test shows that we don't add any new entries to the render queue after disposal.
// There's a different test showing that if the render queue entry was already added
// before a component got individually disposed, that render queue entry gets skipped.
// Arrange
var renderer = new TestRenderer();
var component = new DisposableComponent();
renderer.AssignRootComponentId(component);
// Act
renderer.Dispose();
component.TriggerRender();
// Assert: no exception, no batch produced
Assert.Empty(renderer.Batches);
}
[Fact]
public void DisposingRenderer_DisposesNestedComponents()
{
// Arrange
var renderer = new TestRenderer();
var component = new TestComponent(builder =>
{
builder.AddContent(0, "Hello");
builder.OpenComponent<DisposableComponent>(1);
builder.CloseComponent();
});
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
var batch = renderer.Batches.Single();
var componentFrame = batch.ReferenceFrames
.Single(frame => frame.FrameType == RenderTreeFrameType.Component);
var nestedComponent = Assert.IsType<DisposableComponent>(componentFrame.Component);
// Act
renderer.Dispose();
// Assert
Assert.True(component.Disposed);
Assert.True(nestedComponent.Disposed);
}
[Fact]
public void DisposingRenderer_CapturesExceptionsFromAllRegisteredComponents()
{
// Arrange
var renderer = new TestRenderer { ShouldHandleExceptions = true };
var exception1 = new Exception();
var exception2 = new Exception();
var component = new TestComponent(builder =>
{
builder.AddContent(0, "Hello");
builder.OpenComponent<DisposableComponent>(1);
builder.AddAttribute(1, nameof(DisposableComponent.DisposeAction), (Action)(() => throw exception1));
builder.CloseComponent();
builder.OpenComponent<DisposableComponent>(2);
builder.AddAttribute(1, nameof(DisposableComponent.DisposeAction), (Action)(() => throw exception2));
builder.CloseComponent();
});
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
// Act &A Assert
renderer.Dispose();
// All components must be disposed even if some throw as part of being disposed.
Assert.True(component.Disposed);
var aex = Assert.IsType<AggregateException>(Assert.Single(renderer.HandledExceptions));
Assert.Contains(exception1, aex.InnerExceptions);
Assert.Contains(exception2, aex.InnerExceptions);
}
[Fact]
public async Task DisposingRenderer_CapturesSyncExceptionsFromAllRegisteredAsyncDisposableComponents()
{
// Arrange
var renderer = new TestRenderer { ShouldHandleExceptions = true };
var exception1 = new InvalidOperationException();
var disposed = false;
var component = new TestComponent(builder =>
{
builder.AddContent(0, "Hello");
builder.OpenComponent<AsyncDisposableComponent>(1);
builder.AddAttribute(1, nameof(AsyncDisposableComponent.AsyncDisposeAction), (Func<ValueTask>)(() => { disposed = true; throw exception1; }));
builder.CloseComponent();
});
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
// Act
await renderer.DisposeAsync();
// Assert
Assert.True(disposed);
var handledException = Assert.Single(renderer.HandledExceptions);
Assert.Same(exception1, handledException);
}
[Fact]
public async Task DisposingRenderer_CapturesAsyncExceptionsFromAllRegisteredAsyncDisposableComponents()
{
// Arrange
var renderer = new TestRenderer { ShouldHandleExceptions = true };
var exception1 = new InvalidOperationException();
var disposed = false;
var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var component = new TestComponent(builder =>
{
builder.AddContent(0, "Hello");
builder.OpenComponent<AsyncDisposableComponent>(1);
builder.AddAttribute(1, nameof(AsyncDisposableComponent.AsyncDisposeAction), (Func<ValueTask>)(async () => { await tcs.Task; disposed = true; throw exception1; }));
builder.CloseComponent();
});
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
// Act
var disposal = renderer.DisposeAsync();
Assert.False(disposed);
Assert.False(disposal.IsCompleted);
tcs.TrySetResult();
await disposal;
// Assert
Assert.True(disposed);
var handledException = Assert.Single(renderer.HandledExceptions);
Assert.Same(exception1, handledException);
}
[Theory]
[InlineData(null)] // No existing attribute to update
[InlineData("old property value")] // Has existing attribute to update
public void EventFieldInfoCanPatchTreeSoDiffDoesNotUpdateAttribute(string oldValue)
{
// Arrange: Render a component with an event handler
var renderer = new TestRenderer();
var component = new BoundPropertyComponent { BoundString = oldValue };
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
var eventHandlerId = renderer.Batches.Single()
.ReferenceFrames
.First(frame => frame.FrameType == RenderTreeFrameType.Attribute && frame.AttributeEventHandlerId > 0)
.AttributeEventHandlerId;
// Act: Fire event and re-render
var eventFieldInfo = new EventFieldInfo
{
FieldValue = "new property value",
ComponentId = componentId
};
var dispatchEventTask = renderer.DispatchEventAsync(eventHandlerId, eventFieldInfo, new ChangeEventArgs
{
Value = "new property value"
});
Assert.True(dispatchEventTask.IsCompletedSuccessfully);
// Assert: Property was updated, but the diff doesn't include changing the
// element attribute, since we told it the element attribute was already updated
Assert.Equal("new property value", component.BoundString);
Assert.Equal(2, renderer.Batches.Count);
var batch2 = renderer.Batches[1];
Assert.Collection(batch2.DiffsInOrder.Single().Edits.ToArray(), edit =>
{
// The only edit is updating the event handler ID, since the test component
// deliberately uses a capturing lambda. The whole point of this test is to
// show that the diff does *not* update the BoundString value attribute.
Assert.Equal(RenderTreeEditType.SetAttribute, edit.Type);
var attributeFrame = batch2.ReferenceFrames[edit.ReferenceFrameIndex];
AssertFrame.Attribute(attributeFrame, "ontestevent", typeof(Action<ChangeEventArgs>));
Assert.NotEqual(default, attributeFrame.AttributeEventHandlerId);
Assert.NotEqual(eventHandlerId, attributeFrame.AttributeEventHandlerId);
});
}
[Fact]
public void EventFieldInfoWorksWhenEventHandlerIdWasSuperseded()
{
// Arrange: Render a component with an event handler
// We want the renderer to think none of the "UpdateDisplay" calls ever complete, because we
// want to keep reusing the same eventHandlerId and not let it get disposed
var renderCompletedTcs = new TaskCompletionSource<object>();
var renderer = new TestRenderer { NextRenderResultTask = renderCompletedTcs.Task };
var component = new BoundPropertyComponent { BoundString = "old property value" };
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
var eventHandlerId = renderer.Batches.Single()
.ReferenceFrames
.First(frame => frame.FrameType == RenderTreeFrameType.Attribute && frame.AttributeEventHandlerId > 0)
.AttributeEventHandlerId;
// Act: Fire event and re-render *repeatedly*, without changing to use a newer event handler ID,
// even though we know the event handler ID is getting updated in successive diffs
for (var i = 0; i < 10; i++)
{
var newPropertyValue = $"new property value {i}";
var fieldInfo = new EventFieldInfo
{
ComponentId = componentId,
FieldValue = newPropertyValue,
};
var dispatchEventTask = renderer.DispatchEventAsync(eventHandlerId, fieldInfo, new ChangeEventArgs
{
Value = newPropertyValue
});
Assert.True(dispatchEventTask.IsCompletedSuccessfully);
// Assert: Property was updated, but the diff doesn't include changing the
// element attribute, since we told it the element attribute was already updated
Assert.Equal(newPropertyValue, component.BoundString);
Assert.Equal(i + 2, renderer.Batches.Count);
var latestBatch = renderer.Batches.Last();
Assert.Collection(latestBatch.DiffsInOrder.Single().Edits.ToArray(), edit =>
{
// The only edit is updating the event handler ID, since the test component
// deliberately uses a capturing lambda. The whole point of this test is to
// show that the diff does *not* update the BoundString value attribute.
Assert.Equal(RenderTreeEditType.SetAttribute, edit.Type);
var attributeFrame = latestBatch.ReferenceFrames[edit.ReferenceFrameIndex];
AssertFrame.Attribute(attributeFrame, "ontestevent", typeof(Action<ChangeEventArgs>));
Assert.NotEqual(default, attributeFrame.AttributeEventHandlerId);
Assert.NotEqual(eventHandlerId, attributeFrame.AttributeEventHandlerId);
});
}
}
[Fact]
public void CannotStartOverlappingBatches()
{
// Arrange
var renderer = new InvalidRecursiveRenderer();
var component = new CallbackOnRenderComponent(() =>
{
// The renderer disallows one batch to be started inside another, because that
// would violate all kinds of state tracking invariants. It's not something that
// would ever happen except if you subclass the renderer and do something unsupported
// that commences batches from inside each other.
renderer.ProcessPendingRender();
});
var componentId = renderer.AssignRootComponentId(component);
// Act/Assert
var ex = Assert.Throws<InvalidOperationException>(
() => renderer.RenderRootComponent(componentId));
Assert.Contains("Cannot start a batch when one is already in progress.", ex.Message);
}
[Fact]
public void CannotAccessParameterViewAfterSynchronousReturn()
{
// Arrange
var renderer = new TestRenderer();
var rootComponent = new TestComponent(builder =>
{
builder.OpenComponent<ParameterViewIllegalCapturingComponent>(0);
builder.AddAttribute(1, nameof(ParameterViewIllegalCapturingComponent.SomeParam), 0);
builder.CloseComponent();
});
var rootComponentId = renderer.AssignRootComponentId(rootComponent);
// Note that we're not waiting for the async render to complete, since we want to assert
// about the situation immediately after the component yields the thread
renderer.RenderRootComponentAsync(rootComponentId);
// Act/Assert
var capturingComponent = (ParameterViewIllegalCapturingComponent)renderer.GetCurrentRenderTreeFrames(rootComponentId).Array[0].Component;
var parameterView = capturingComponent.CapturedParameterView;
// All public APIs on capturingComponent should be electrified now
// Internal APIs don't have to be, because we won't call them at the wrong time
Assert.Throws<InvalidOperationException>(() => parameterView.GetEnumerator());
Assert.Throws<InvalidOperationException>(() => parameterView.GetValueOrDefault<object>("anything"));
Assert.Throws<InvalidOperationException>(() => parameterView.SetParameterProperties(new object()));
Assert.Throws<InvalidOperationException>(() => parameterView.ToDictionary());
var ex = Assert.Throws<InvalidOperationException>(() => parameterView.TryGetValue<object>("anything", out _));
// It's enough to assert about one of the messages
Assert.Equal($"The {nameof(ParameterView)} instance can no longer be read because it has expired. {nameof(ParameterView)} can only be read synchronously and must not be stored for later use.", ex.Message);
}
[Fact]
public void CanUseCustomComponentActivatorFromConstructorParameter()
{
// Arrange
var serviceProvider = new TestServiceProvider();
var componentActivator = new TestComponentActivator<MessageComponent>();
var renderer = new TestRenderer(serviceProvider, componentActivator);
// Act: Ask for TestComponent
var suppliedComponent = renderer.InstantiateComponent<TestComponent>();
// Assert: We actually receive MessageComponent
Assert.IsType<MessageComponent>(suppliedComponent);
Assert.Collection(componentActivator.RequestedComponentTypes,
requestedType => Assert.Equal(typeof(TestComponent), requestedType));
}
[Fact]
public void CanUseCustomComponentActivatorFromServiceProvider()
{
// Arrange
var serviceProvider = new TestServiceProvider();
var componentActivator = new TestComponentActivator<MessageComponent>();
serviceProvider.AddService<IComponentActivator>(componentActivator);
var renderer = new TestRenderer(serviceProvider);
// Act: Ask for TestComponent
var suppliedComponent = renderer.InstantiateComponent<TestComponent>();
// Assert: We actually receive MessageComponent
Assert.IsType<MessageComponent>(suppliedComponent);
Assert.Collection(componentActivator.RequestedComponentTypes,
requestedType => Assert.Equal(typeof(TestComponent), requestedType));
}
[Fact]
public async Task ThrowsIfComponentProducesInvalidRenderTree()
{
// Arrange
var renderer = new TestRenderer();
var component = new TestComponent(builder =>
{
builder.OpenElement(0, "myElem");
});
var rootComponentId = renderer.AssignRootComponentId(component);
// Act/Assert
var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => renderer.RenderRootComponentAsync(rootComponentId));
Assert.StartsWith($"Render output is invalid for component of type '{typeof(TestComponent).FullName}'. A frame of type 'Element' was left unclosed.", ex.Message);
}
[Fact]
public void RenderingExceptionsCanBeHandledByClosestErrorBoundary()
{
// Arrange
var renderer = new TestRenderer();
var exception = new InvalidTimeZoneException("Error during render");
var rootComponentId = renderer.AssignRootComponentId(new TestComponent(builder =>
{
TestErrorBoundary.RenderNestedErrorBoundaries(builder, builder =>
{
builder.OpenComponent<ErrorThrowingComponent>(0);
builder.AddAttribute(1, nameof(ErrorThrowingComponent.ThrowDuringRender), exception);
builder.CloseComponent();
});
}));
// Act
renderer.RenderRootComponent(rootComponentId);
// Assert
var batch = renderer.Batches.Single();
var errorThrowingComponentId = batch.GetComponentFrames<ErrorThrowingComponent>().Single().ComponentId;
var componentFrames = batch.GetComponentFrames<TestErrorBoundary>();
Assert.Collection(componentFrames.Select(f => (TestErrorBoundary)f.Component),
component => Assert.Null(component.ReceivedException),
component => Assert.Same(exception, component.ReceivedException));
// The failed subtree is disposed
Assert.Equal(errorThrowingComponentId, batch.DisposedComponentIDs.Single());
}
[Fact]
public void SetParametersAsyncExceptionsCanBeHandledByClosestErrorBoundary_Sync()
{
// Arrange
var renderer = new TestRenderer();
Exception exception = null;
var rootComponent = new TestComponent(builder =>
{
TestErrorBoundary.RenderNestedErrorBoundaries(builder, builder =>
{
builder.OpenComponent<ErrorThrowingComponent>(0);
builder.AddAttribute(1, nameof(ErrorThrowingComponent.ThrowDuringParameterSettingSync), exception);
builder.CloseComponent();
});
});
var rootComponentId = renderer.AssignRootComponentId(rootComponent);
renderer.RenderRootComponent(rootComponentId);
var errorBoundaries = renderer.Batches.Single().GetComponentFrames<TestErrorBoundary>()
.Select(f => (TestErrorBoundary)f.Component);
var errorThrowingComponentId = renderer.Batches.Single()
.GetComponentFrames<ErrorThrowingComponent>().Single().ComponentId;
// Act
exception = new InvalidTimeZoneException("Error during SetParametersAsync");
rootComponent.TriggerRender();
// Assert
Assert.Equal(2, renderer.Batches.Count);
Assert.Collection(errorBoundaries,
component => Assert.Null(component.ReceivedException),
component => Assert.Same(exception, component.ReceivedException));
// The failed subtree is disposed
Assert.Equal(errorThrowingComponentId, renderer.Batches[1].DisposedComponentIDs.Single());
}
[Fact]
public async Task SetParametersAsyncExceptionsCanBeHandledByClosestErrorBoundary_Async()
{
// Arrange
var renderer = new TestRenderer();
var exception = new InvalidTimeZoneException("Error during SetParametersAsync");
TaskCompletionSource exceptionTcs = null;
var rootComponent = new TestComponent(builder =>
{
TestErrorBoundary.RenderNestedErrorBoundaries(builder, builder =>
{
builder.OpenComponent<ErrorThrowingComponent>(0);
builder.AddAttribute(1, nameof(ErrorThrowingComponent.ThrowDuringParameterSettingAsync), exceptionTcs?.Task);
builder.CloseComponent();
});
});
var rootComponentId = renderer.AssignRootComponentId(rootComponent);
renderer.RenderRootComponent(rootComponentId);
var errorBoundaries = renderer.Batches.Single().GetComponentFrames<TestErrorBoundary>()
.Select(f => (TestErrorBoundary)f.Component).ToArray();
var errorThrowingComponentId = renderer.Batches.Single()
.GetComponentFrames<ErrorThrowingComponent>().Single().ComponentId;
// Act/Assert 1: No synchronous errors
exceptionTcs = new TaskCompletionSource();
rootComponent.TriggerRender();
Assert.Equal(2, renderer.Batches.Count);
// Act/Assert 2: Asynchronous error
exceptionTcs.SetException(exception);
await errorBoundaries[1].ReceivedErrorTask;
Assert.Equal(3, renderer.Batches.Count);
Assert.Collection(errorBoundaries,
component => Assert.Null(component.ReceivedException),
component => Assert.Same(exception, component.ReceivedException));
// The failed subtree is disposed
Assert.Equal(errorThrowingComponentId, renderer.Batches[2].DisposedComponentIDs.Single());
}
[Fact]
public void EventDispatchExceptionsCanBeHandledByClosestErrorBoundary_Sync()
{
// Arrange
var renderer = new TestRenderer();
var exception = new InvalidTimeZoneException("Error during event");
var rootComponentId = renderer.AssignRootComponentId(new TestComponent(builder =>
{
TestErrorBoundary.RenderNestedErrorBoundaries(builder, builder =>
{
builder.OpenComponent<ErrorThrowingComponent>(0);
builder.AddAttribute(1, nameof(ErrorThrowingComponent.ThrowDuringEventSync), exception);
builder.CloseComponent();
});
}));
renderer.RenderRootComponent(rootComponentId);
var errorBoundaries = renderer.Batches.Single().GetComponentFrames<TestErrorBoundary>()
.Select(f => (TestErrorBoundary)f.Component);
var errorThrowingComponentId = renderer.Batches.Single()
.GetComponentFrames<ErrorThrowingComponent>().Single().ComponentId;
var eventHandlerId = renderer.Batches.Single().ReferenceFrames
.Single(f => f.FrameType == RenderTreeFrameType.Attribute && f.AttributeName == "onmakeerror")
.AttributeEventHandlerId;
// Act
var task = renderer.DispatchEventAsync(eventHandlerId, new EventArgs());
// Assert
Assert.True(task.IsCompletedSuccessfully);
Assert.Equal(2, renderer.Batches.Count);
Assert.Collection(errorBoundaries,
component => Assert.Null(component.ReceivedException),
component => Assert.Same(exception, component.ReceivedException));
// The failed subtree is disposed
Assert.Equal(errorThrowingComponentId, renderer.Batches[1].DisposedComponentIDs.Single());
}
[Fact]
public async Task EventDispatchExceptionsCanBeHandledByClosestErrorBoundary_Async()
{
// Arrange
var renderer = new TestRenderer();
var exception = new InvalidTimeZoneException("Error during event");
var exceptionTcs = new TaskCompletionSource();
var rootComponentId = renderer.AssignRootComponentId(new TestComponent(builder =>
{
TestErrorBoundary.RenderNestedErrorBoundaries(builder, builder =>
{
builder.OpenComponent<ErrorThrowingComponent>(0);
builder.AddAttribute(1, nameof(ErrorThrowingComponent.ThrowDuringEventAsync), exceptionTcs.Task);
builder.CloseComponent();
});
}));
renderer.RenderRootComponent(rootComponentId);
var errorBoundaries = renderer.Batches.Single().GetComponentFrames<TestErrorBoundary>()
.Select(f => (TestErrorBoundary)f.Component);
var errorThrowingComponentId = renderer.Batches.Single()
.GetComponentFrames<ErrorThrowingComponent>().Single().ComponentId;
var eventHandlerId = renderer.Batches.Single().ReferenceFrames
.Single(f => f.FrameType == RenderTreeFrameType.Attribute && f.AttributeName == "onmakeerror")
.AttributeEventHandlerId;
// Act/Assert 1: No error synchronously
var dispatchEventTask = renderer.DispatchEventAsync(eventHandlerId, new EventArgs());
Assert.Single(renderer.Batches);
Assert.Collection(errorBoundaries,
component => Assert.Null(component.ReceivedException),
component => Assert.Null(component.ReceivedException));
// Act/Assert 2: Error is handled asynchronously
exceptionTcs.SetException(exception);
await dispatchEventTask;
Assert.Equal(2, renderer.Batches.Count);
Assert.Collection(errorBoundaries,
component => Assert.Null(component.ReceivedException),
component => Assert.Same(exception, component.ReceivedException));
// The failed subtree is disposed
Assert.Equal(errorThrowingComponentId, renderer.Batches[1].DisposedComponentIDs.Single());
}
[Fact]
public async Task EventDispatchExceptionsCanBeHandledByClosestErrorBoundary_AfterDisposal()
{
// Arrange
var renderer = new TestRenderer();
var disposeChildren = false;
var exception = new InvalidTimeZoneException("Error during event");
var exceptionTcs = new TaskCompletionSource();
var rootComponent = new TestComponent(builder =>
{
if (!disposeChildren)
{
TestErrorBoundary.RenderNestedErrorBoundaries(builder, builder =>
{
builder.OpenComponent<ErrorThrowingComponent>(0);
builder.AddAttribute(1, nameof(ErrorThrowingComponent.ThrowDuringEventAsync), exceptionTcs.Task);
builder.CloseComponent();
});
}
});
var rootComponentId = renderer.AssignRootComponentId(rootComponent);
renderer.RenderRootComponent(rootComponentId);
var errorBoundaries = renderer.Batches.Single().GetComponentFrames<TestErrorBoundary>()
.Select(f => (TestErrorBoundary)f.Component);
var errorThrowingComponentId = renderer.Batches.Single()
.GetComponentFrames<ErrorThrowingComponent>().Single().ComponentId;
var eventHandlerId = renderer.Batches.Single().ReferenceFrames
.Single(f => f.FrameType == RenderTreeFrameType.Attribute && f.AttributeName == "onmakeerror")
.AttributeEventHandlerId;
// Act/Assert 1: No error synchronously
var dispatchEventTask = renderer.DispatchEventAsync(eventHandlerId, new EventArgs());
Assert.Single(renderer.Batches);
Assert.Collection(errorBoundaries,
component => Assert.Null(component.ReceivedException),
component => Assert.Null(component.ReceivedException));
// Act 2: Before the async error occurs, dispose the hierarchy containing the error boundary and erroring component
disposeChildren = true;
rootComponent.TriggerRender();
Assert.Equal(2, renderer.Batches.Count);
Assert.Contains(errorThrowingComponentId, renderer.Batches.Last().DisposedComponentIDs);
// Assert 2: Error is still handled
exceptionTcs.SetException(exception);
await dispatchEventTask;
Assert.Equal(2, renderer.Batches.Count); // Didn't re-render as the error boundary was already gone
Assert.Collection(errorBoundaries,
component => Assert.Null(component.ReceivedException),
component => Assert.Same(exception, component.ReceivedException));
}
[Fact]
public async Task CanRemoveRootComponents()
{
// Arrange
var renderer = new TestRenderer();
var rootComponent = new TestComponent(builder =>
{
builder.OpenComponent<DisposableComponent>(0);
builder.CloseComponent();
builder.OpenComponent<AsyncDisposableComponent>(1);
builder.CloseComponent();
});
var unrelatedComponent = new DisposableComponent();
var rootComponentId = renderer.AssignRootComponentId(rootComponent);
var unrelatedRootComponentId = renderer.AssignRootComponentId(unrelatedComponent);
rootComponent.TriggerRender();
unrelatedComponent.TriggerRender();
Assert.Equal(2, renderer.Batches.Count);
var nestedDisposableComponentFrame = renderer.Batches[0]
.GetComponentFrames<DisposableComponent>().Single();
var nestedAsyncDisposableComponentFrame = renderer.Batches[0]
.GetComponentFrames<AsyncDisposableComponent>().Single();
// Act
_ = renderer.Dispatcher.InvokeAsync(() => renderer.RemoveRootComponent(rootComponentId));
// Assert: we disposed the specified root component and its descendants, but not
// the other root component
Assert.Equal(3, renderer.Batches.Count);
var batch = renderer.Batches.Last();
Assert.Equal(new[]
{
rootComponentId,
nestedDisposableComponentFrame.ComponentId,
nestedAsyncDisposableComponentFrame.ComponentId,
}, batch.DisposedComponentIDs);
// Assert: component instances were disposed properly
Assert.True(((DisposableComponent)nestedDisposableComponentFrame.Component).Disposed);
Assert.True(((AsyncDisposableComponent)nestedAsyncDisposableComponentFrame.Component).Disposed);
// Assert: it's no longer known as a component
await renderer.Dispatcher.InvokeAsync(() =>
{
var ex = Assert.Throws<ArgumentException>(() =>
renderer.RemoveRootComponent(rootComponentId));
Assert.Equal($"The renderer does not have a component with ID {rootComponentId}.", ex.Message);
});
}
[Fact]
public async Task CannotRemoveSameRootComponentMultipleTimesSynchronously()
{
// Arrange
var renderer = new TestRenderer();
var rootComponent = new AsyncDisposableComponent
{
// Show that, even if the component tries to delay its disposal by returning
// a task that never completes, it still gets removed from the renderer synchronously
AsyncDisposeAction = () => new ValueTask(new TaskCompletionSource().Task)
};
var rootComponentId = renderer.AssignRootComponentId(rootComponent);
// Act/Assert
var didRunTestLogic = false; // Don't just trust the dispatcher here - verify it runs our callback
await renderer.Dispatcher.InvokeAsync(() =>
{
renderer.RemoveRootComponent(rootComponentId);
// Even though we didn't await anything, it's synchronously unavailable for re-removal
var ex = Assert.Throws<ArgumentException>(() =>
renderer.RemoveRootComponent(rootComponentId));
Assert.Equal($"The renderer does not have a component with ID {rootComponentId}.", ex.Message);
didRunTestLogic = true;
});
Assert.True(didRunTestLogic);
}
[Fact]
public async Task CannotRemoveNonRootComponentsDirectly()
{
// Arrange
var renderer = new TestRenderer();
var rootComponent = new TestComponent(builder =>
{
builder.OpenComponent<DisposableComponent>(0);
builder.CloseComponent();
});
var rootComponentId = renderer.AssignRootComponentId(rootComponent);
rootComponent.TriggerRender();
var nestedComponentFrame = renderer.Batches[0]
.GetComponentFrames<DisposableComponent>().Single();
var nestedComponent = (DisposableComponent)nestedComponentFrame.Component;
// Act/Assert
await renderer.Dispatcher.InvokeAsync(() =>
{
var ex = Assert.Throws<InvalidOperationException>(() =>
renderer.RemoveRootComponent(nestedComponentFrame.ComponentId));
Assert.Equal("The specified component is not a root component", ex.Message);
});
Assert.False(nestedComponent.Disposed);
}
[Fact]
public void RemoveRootComponentHandlesDisposalExceptions()
{
// Arrange
var autoResetEvent = new AutoResetEvent(false);
var renderer = new TestRenderer { ShouldHandleExceptions = true };
renderer.OnExceptionHandled = () => autoResetEvent.Set();
var exception1 = new InvalidTimeZoneException();
var exception2Tcs = new TaskCompletionSource();
var rootComponent = new TestComponent(builder =>
{
builder.AddContent(0, "Hello");
builder.OpenComponent<DisposableComponent>(1);
builder.AddAttribute(1, nameof(DisposableComponent.DisposeAction), (Action)(() => throw exception1));
builder.CloseComponent();
builder.OpenComponent<AsyncDisposableComponent>(2);
builder.AddAttribute(1, nameof(AsyncDisposableComponent.AsyncDisposeAction), (Func<ValueTask>)(async () => await exception2Tcs.Task));
builder.CloseComponent();
});
var rootComponentId = renderer.AssignRootComponentId(rootComponent);
rootComponent.TriggerRender();
Assert.Single(renderer.Batches);
var nestedDisposableComponentFrame = renderer.Batches[0]
.GetComponentFrames<DisposableComponent>().Single();
var nestedAsyncDisposableComponentFrame = renderer.Batches[0]
.GetComponentFrames<AsyncDisposableComponent>().Single();
// Act
renderer.Dispatcher.InvokeAsync(() => renderer.RemoveRootComponent(rootComponentId));
// Assert: we get the synchronous exception synchronously
Assert.Same(exception1, Assert.Single(renderer.HandledExceptions));
// Assert: we get the asynchronous exception asynchronously
var exception2 = new InvalidTimeZoneException();
autoResetEvent.Reset();
exception2Tcs.SetException(exception2);
autoResetEvent.WaitOne();
Assert.Equal(2, renderer.HandledExceptions.Count);
Assert.Same(exception2, renderer.HandledExceptions[1]);
}
[Fact]
public void DisposeCallsComponentDisposeOnSyncContext()
{
// Arrange
var renderer = new TestRenderer();
var wasOnSyncContext = false;
var component = new DisposableComponent
{
DisposeAction = () =>
{
wasOnSyncContext = renderer.Dispatcher.CheckAccess();
}
};
// Act
var componentId = renderer.AssignRootComponentId(component);
renderer.Dispose();
// Assert
Assert.True(wasOnSyncContext);
}
[Fact]
public async Task DisposeAsyncCallsComponentDisposeAsyncOnSyncContext()
{
// Arrange
var renderer = new TestRenderer();
var wasOnSyncContext = false;
var component = new AsyncDisposableComponent
{
AsyncDisposeAction = () =>
{
wasOnSyncContext = renderer.Dispatcher.CheckAccess();
return ValueTask.CompletedTask;
}
};
// Act
var componentId = renderer.AssignRootComponentId(component);
await renderer.DisposeAsync();
// Assert
Assert.True(wasOnSyncContext);
}
[Fact]
public async Task NoHotReloadListenersAreRegistered_WhenMetadataUpdatesAreNotSupported()
{
// Arrange
await using var renderer = new TestRenderer();
var hotReloadManager = new HotReloadManager { MetadataUpdateSupported = false };
renderer.HotReloadManager = hotReloadManager;
var component = new TestComponent(builder =>
{
builder.OpenElement(0, "h2");
builder.AddContent(1, "some text");
builder.CloseElement();
});
// Act
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
Assert.False(hotReloadManager.IsSubscribedTo);
await renderer.DisposeAsync();
}
[Fact]
public async Task DisposingRenderer_UnsubsribesFromHotReloadManager()
{
// Arrange
var renderer = new TestRenderer();
var hotReloadManager = new HotReloadManager { MetadataUpdateSupported = true };
renderer.HotReloadManager = hotReloadManager;
var component = new TestComponent(builder =>
{
builder.OpenElement(0, "h2");
builder.AddContent(1, "some text");
builder.CloseElement();
});
// Act
var componentId = renderer.AssignRootComponentId(component);
component.TriggerRender();
Assert.True(hotReloadManager.IsSubscribedTo);
await renderer.DisposeAsync();
// Assert
Assert.False(hotReloadManager.IsSubscribedTo);
}
private class TestComponentActivator<TResult> : IComponentActivator where TResult : IComponent, new()
{
public List<Type> RequestedComponentTypes { get; } = new List<Type>();
public IComponent CreateInstance(Type componentType)
{
RequestedComponentTypes.Add(componentType);
return new TResult();
}
}
private class NoOpRenderer : Renderer
{
public NoOpRenderer() : base(new TestServiceProvider(), NullLoggerFactory.Instance)
{
}
public override Dispatcher Dispatcher { get; } = Dispatcher.CreateDefault();
public new int AssignRootComponentId(IComponent component)
=> base.AssignRootComponentId(component);
protected override void HandleException(Exception exception)
=> throw new NotImplementedException();
protected override Task UpdateDisplayAsync(in RenderBatch renderBatch)
=> Task.CompletedTask;
}
private class TestComponent : IComponent, IDisposable
{
private RenderHandle _renderHandle;
private readonly RenderFragment _renderFragment;
public TestComponent(RenderFragment renderFragment)
{
_renderFragment = renderFragment;
}
public void Attach(RenderHandle renderHandle)
{
_renderHandle = renderHandle;
}
public Task SetParametersAsync(ParameterView parameters)
{
TriggerRender();
return Task.CompletedTask;
}
public void TriggerRender()
{
var t = _renderHandle.Dispatcher.InvokeAsync(() => _renderHandle.Render(_renderFragment));
// This should always be run synchronously
Assert.True(t.IsCompleted);
if (t.IsFaulted)
{
var exception = t.Exception.Flatten().InnerException;
while (exception is AggregateException e)
{
exception = e.InnerException;
}
ExceptionDispatchInfo.Capture(exception).Throw();
}
}
public bool Disposed { get; private set; }
void IDisposable.Dispose() => Disposed = true;
}
private class MessageComponent : AutoRenderComponent
{
[Parameter]
public string Message { get; set; }
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
builder.AddContent(0, Message);
}
}
private class MyStrongComponent : AutoRenderComponent
{
[Parameter(CaptureUnmatchedValues = true)] public IDictionary<string, object> Attributes { get; set; }
[Parameter] public string Text { get; set; }
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
builder.OpenElement(0, "strong");
builder.AddMultipleAttributes(1, Attributes);
builder.AddContent(2, Text);
builder.CloseElement();
}
}
private class FakeComponent : IComponent
{
[Parameter]
public int IntProperty { get; set; }
[Parameter]
public string StringProperty { get; set; }
[Parameter]
public object ObjectProperty { get; set; }
public RenderHandle RenderHandle { get; private set; }
public void Attach(RenderHandle renderHandle)
=> RenderHandle = renderHandle;
public Task SetParametersAsync(ParameterView parameters)
{
parameters.SetParameterProperties(this);
return Task.CompletedTask;
}
}
private class EventComponent : AutoRenderComponent, IComponent, IHandleEvent
{
[Parameter]
public Action<EventArgs> OnTest { get; set; }
[Parameter]
public Func<EventArgs, Task> OnTestAsync { get; set; }
[Parameter]
public Action<DerivedEventArgs> OnClick { get; set; }
[Parameter]
public Func<DerivedEventArgs, Task> OnClickAsync { get; set; }
[Parameter]
public Action OnClickAction { get; set; }
[Parameter]
public Func<Task> OnClickAsyncAction { get; set; }
[Parameter]
public EventCallback OnClickEventCallback { get; set; }
[Parameter]
public EventCallback<DerivedEventArgs> OnClickEventCallbackOfT { get; set; }
[Parameter]
public Delegate OnArbitraryDelegateEvent { get; set; }
public bool SkipElement { get; set; }
private int renderCount = 0;
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
builder.OpenElement(0, "grandparent");
if (!SkipElement)
{
builder.OpenElement(1, "parent");
builder.OpenElement(2, "some element");
if (OnTest != null)
{
builder.AddAttribute(3, "ontest", OnTest);
}
else if (OnTestAsync != null)
{
builder.AddAttribute(3, "ontest", OnTestAsync);
}
if (OnClick != null)
{
builder.AddAttribute(4, "onclick", OnClick);
}
else if (OnClickAsync != null)
{
builder.AddAttribute(4, "onclick", OnClickAsync);
}
else if (OnClickEventCallback.HasDelegate)
{
builder.AddAttribute(4, "onclick", OnClickEventCallback);
}
else if (OnClickEventCallbackOfT.HasDelegate)
{
builder.AddAttribute(4, "onclick", OnClickEventCallbackOfT);
}
if (OnClickAction != null)
{
builder.AddAttribute(5, "onclickaction", OnClickAction);
}
else if (OnClickAsyncAction != null)
{
builder.AddAttribute(5, "onclickaction", OnClickAsyncAction);
}
if (OnArbitraryDelegateEvent != null)
{
builder.AddAttribute(6, "onarbitrarydelegateevent", OnArbitraryDelegateEvent);
}
builder.CloseElement();
builder.CloseElement();
}
builder.CloseElement();
builder.AddContent(6, $"Render count: {++renderCount}");
}
public Task HandleEventAsync(EventCallbackWorkItem callback, object arg)
{
// Notice, we don't re-render.
return callback.InvokeAsync(arg);
}
}
private class ConditionalParentComponent<T> : AutoRenderComponent where T : IComponent
{
[Parameter]
public bool IncludeChild { get; set; }
[Parameter]
public IDictionary<string, object> ChildParameters { get; set; }
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
builder.AddContent(0, "Parent here");
if (IncludeChild)
{
builder.OpenComponent<T>(1);
if (ChildParameters != null)
{
foreach (var kvp in ChildParameters)
{
builder.AddAttribute(2, kvp.Key, kvp.Value);
}
}
builder.CloseComponent();
}
}
}
private class ReRendersParentComponent : AutoRenderComponent
{
[Parameter]
public TestComponent Parent { get; set; }
private bool _isFirstTime = true;
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
if (_isFirstTime) // Don't want an infinite loop
{
_isFirstTime = false;
Parent.TriggerRender();
}
builder.AddContent(0, "Child is here");
}
}
private class RendersSelfAfterEventComponent : IComponent, IHandleEvent
{
[Parameter]
public Action<object> OnClick { get; set; }
private RenderHandle _renderHandle;
public void Attach(RenderHandle renderHandle)
=> _renderHandle = renderHandle;
public Task SetParametersAsync(ParameterView parameters)
{
parameters.SetParameterProperties(this);
Render();
return Task.CompletedTask;
}
public Task HandleEventAsync(EventCallbackWorkItem callback, object arg)
{
var task = callback.InvokeAsync(arg);
Render();
return task;
}
private void Render()
=> _renderHandle.Render(builder =>
{
builder.OpenElement(0, "my button");
builder.AddAttribute(1, "onmycustomevent", EventCallback.Factory.Create(this, eventArgs => OnClick(eventArgs)));
builder.CloseElement();
});
}
private class MultiRendererComponent : IComponent
{
private readonly List<RenderHandle> _renderHandles
= new List<RenderHandle>();
public void Attach(RenderHandle renderHandle)
=> _renderHandles.Add(renderHandle);
public Task SetParametersAsync(ParameterView parameters)
{
return Task.CompletedTask;
}
public void TriggerRender()
{
foreach (var renderHandle in _renderHandles)
{
renderHandle.Dispatcher.InvokeAsync(() => renderHandle.Render(builder =>
{
builder.AddContent(0, $"Hello from {nameof(MultiRendererComponent)}");
}));
}
}
}
private class BindPlusConditionalAttributeComponent : AutoRenderComponent, IHandleEvent
{
public bool CheckboxEnabled;
public string SomeStringProperty;
public Task HandleEventAsync(EventCallbackWorkItem callback, object arg)
{
var task = callback.InvokeAsync(arg);
TriggerRender();
return task;
}
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
builder.OpenElement(0, "input");
builder.AddAttribute(1, "type", "checkbox");
builder.AddAttribute(2, "value", BindConverter.FormatValue(CheckboxEnabled));
builder.AddAttribute(3, "onchange", EventCallback.Factory.CreateBinder<bool>(this, __value => CheckboxEnabled = __value, CheckboxEnabled));
builder.CloseElement();
builder.OpenElement(4, "input");
builder.AddAttribute(5, "value", BindConverter.FormatValue(SomeStringProperty));
builder.AddAttribute(6, "onchange", EventCallback.Factory.CreateBinder<string>(this, __value => SomeStringProperty = __value, SomeStringProperty));
builder.AddAttribute(7, "disabled", !CheckboxEnabled);
builder.CloseElement();
}
}
private class AfterRenderCaptureComponent : AutoRenderComponent, IComponent, IHandleAfterRender
{
public Action OnAfterRenderLogic { get; set; }
public int OnAfterRenderCallCount { get; private set; }
public Task OnAfterRenderAsync()
{
OnAfterRenderCallCount++;
OnAfterRenderLogic?.Invoke();
return Task.CompletedTask;
}
Task IComponent.SetParametersAsync(ParameterView parameters)
{
TriggerRender();
return Task.CompletedTask;
}
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
}
}
private class DisposableComponent : AutoRenderComponent, IDisposable
{
public bool Disposed { get; private set; }
[Parameter]
public Action DisposeAction { get; set; }
public void Dispose()
{
Disposed = true;
DisposeAction?.Invoke();
}
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
}
}
private class AsyncDisposableComponent : AutoRenderComponent, IAsyncDisposable
{
public bool Disposed { get; private set; }
[Parameter]
public Func<ValueTask> AsyncDisposeAction { get; set; }
public ValueTask DisposeAsync()
{
Disposed = true;
return AsyncDisposeAction == null ? default : AsyncDisposeAction.Invoke();
}
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
}
}
class TestAsyncRenderer : TestRenderer
{
public Task NextUpdateDisplayReturnTask { get; set; }
protected override Task UpdateDisplayAsync(in RenderBatch renderBatch)
{
base.UpdateDisplayAsync(renderBatch);
return NextUpdateDisplayReturnTask;
}
}
private class AsyncComponent : IComponent
{
private RenderHandle _renderHandler;
public AsyncComponent(Task taskToAwait, int number)
{
_taskToAwait = taskToAwait;
Number = number;
}
private readonly Task _taskToAwait;
public int Number { get; set; }
public void Attach(RenderHandle renderHandle)
{
_renderHandler = renderHandle;
}
public async Task SetParametersAsync(ParameterView parameters)
{
int n;
while (Number > 0)
{
n = Number;
_renderHandler.Render(CreateFragment);
Number--;
await _taskToAwait;
};
// Cheap closure
void CreateFragment(RenderTreeBuilder builder)
{
builder.OpenElement(0, "p");
builder.AddContent(1, n);
builder.CloseElement();
}
}
}
private class OuterEventComponent : IComponent, IHandleEvent
{
private RenderHandle _renderHandle;
public RenderFragment RenderFragment { get; set; }
public Action OnEvent { get; set; }
public int SomeMethodCallCount { get; set; }
public void SomeMethod()
{
SomeMethodCallCount++;
}
public void Attach(RenderHandle renderHandle)
{
_renderHandle = renderHandle;
}
public Task HandleEventAsync(EventCallbackWorkItem callback, object arg)
{
var task = callback.InvokeAsync(arg);
OnEvent?.Invoke();
return task;
}
public Task SetParametersAsync(ParameterView parameters)
{
return TriggerRenderAsync();
}
public Task TriggerRenderAsync() => _renderHandle.Dispatcher.InvokeAsync(() => _renderHandle.Render(RenderFragment));
}
private void AssertStream(int expectedId, (int id, NestedAsyncComponent.EventType @event)[] logStream)
{
// OnInit runs first
Assert.Equal((expectedId, NestedAsyncComponent.EventType.OnInit), logStream[0]);
// OnInit async completes
Assert.Single(logStream.Skip(1),
e => e == (expectedId, NestedAsyncComponent.EventType.OnInitAsyncAsync) || e == (expectedId, NestedAsyncComponent.EventType.OnInitAsyncSync));
var parametersSetEvent = logStream.Where(le => le == (expectedId, NestedAsyncComponent.EventType.OnParametersSet)).ToArray();
// OnParametersSet gets called at least once
Assert.NotEmpty(parametersSetEvent);
var parametersSetAsyncEvent = logStream
.Where(le => le == (expectedId, NestedAsyncComponent.EventType.OnParametersSetAsyncAsync) ||
le == (expectedId, NestedAsyncComponent.EventType.OnParametersSetAsyncSync))
.ToArray();
// OnParametersSetAsync async gets called at least once
Assert.NotEmpty(parametersSetAsyncEvent);
// The same number of OnParametersSet and OnParametersSetAsync get produced
Assert.Equal(parametersSetEvent.Length, parametersSetAsyncEvent.Length);
// The log ends with an OnParametersSetAsync event
Assert.True(logStream.Last() == (expectedId, NestedAsyncComponent.EventType.OnParametersSetAsyncSync) ||
logStream.Last() == (expectedId, NestedAsyncComponent.EventType.OnParametersSetAsyncAsync));
}
private Func<NestedAsyncComponent, RenderFragment> CreateRenderFactory(int[] childrenToRender)
{
// For some reason nameof doesn't work inside a nested lambda, so capturing the value here.
var eventActionsName = nameof(NestedAsyncComponent.EventActions);
var whatToRenderName = nameof(NestedAsyncComponent.WhatToRender);
var testIdName = nameof(NestedAsyncComponent.TestId);
var logName = nameof(NestedAsyncComponent.Log);
return component => builder =>
{
builder.OpenElement(0, "div");
builder.AddContent(1, $"Id: {component.TestId} BuildRenderTree, {Guid.NewGuid()}");
foreach (var child in childrenToRender)
{
builder.OpenComponent<NestedAsyncComponent>(2);
builder.AddAttribute(3, eventActionsName, component.EventActions);
builder.AddAttribute(4, whatToRenderName, component.WhatToRender);
builder.AddAttribute(5, testIdName, child);
builder.AddAttribute(6, logName, component.Log);
builder.CloseComponent();
}
builder.CloseElement();
};
}
private class NestedAsyncComponent : ComponentBase
{
[Parameter] public IDictionary<int, IList<ExecutionAction>> EventActions { get; set; }
[Parameter] public IDictionary<int, Func<NestedAsyncComponent, RenderFragment>> WhatToRender { get; set; }
[Parameter] public int TestId { get; set; }
[Parameter] public ConcurrentQueue<(int testId, EventType @event)> Log { get; set; }
protected override void OnInitialized()
{
if (TryGetEntry(EventType.OnInit, out var entry))
{
var result = entry.EventAction();
Assert.True(result.IsCompleted, "Task must complete synchronously.");
LogResult(result.Result);
}
}
protected override async Task OnInitializedAsync()
{
if (TryGetEntry(EventType.OnInitAsyncSync, out var entrySync))
{
var result = entrySync.EventAction();
Assert.True(result.IsCompleted, "Task must complete synchronously.");
LogResult(result.Result);
}
else if (TryGetEntry(EventType.OnInitAsyncAsync, out var entryAsync))
{
var result = await entryAsync.EventAction();
LogResult(result);
}
}
protected override void OnParametersSet()
{
if (TryGetEntry(EventType.OnParametersSet, out var entry))
{
var result = entry.EventAction();
Assert.True(result.IsCompleted, "Task must complete synchronously.");
LogResult(result.Result);
}
base.OnParametersSet();
}
protected override async Task OnParametersSetAsync()
{
if (TryGetEntry(EventType.OnParametersSetAsyncSync, out var entrySync))
{
var result = entrySync.EventAction();
Assert.True(result.IsCompleted, "Task must complete synchronously.");
LogResult(result.Result);
}
else if (TryGetEntry(EventType.OnParametersSetAsyncAsync, out var entryAsync))
{
var result = await entryAsync.EventAction();
LogResult(result);
}
}
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
var renderFactory = WhatToRender[TestId];
renderFactory(this)(builder);
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (TryGetEntry(EventType.OnAfterRenderAsyncSync, out var entrySync))
{
var result = entrySync.EventAction();
Assert.True(result.IsCompleted, "Task must complete synchronously.");
LogResult(result.Result);
}
if (TryGetEntry(EventType.OnAfterRenderAsyncAsync, out var entryAsync))
{
var result = await entryAsync.EventAction();
LogResult(result);
}
}
private bool TryGetEntry(EventType eventType, out ExecutionAction entry)
{
var entries = EventActions[TestId];
if (entries == null)
{
throw new InvalidOperationException("Failed to find entries for component with Id: " + TestId);
}
entry = entries.FirstOrDefault(e => e.Event == eventType);
return entry != null;
}
private void LogResult((int, EventType) entry)
{
Log?.Enqueue(entry);
}
public class ExecutionAction
{
public EventType Event { get; set; }
public Func<Task<(int id, EventType @event)>> EventAction { get; set; }
public static ExecutionAction On(int id, EventType @event, bool async = false)
{
if (!async)
{
return new ExecutionAction
{
Event = @event,
EventAction = () => Task.FromResult((id, @event))
};
}
else
{
return new ExecutionAction
{
Event = @event,
EventAction = async () =>
{
await Task.Yield();
return (id, @event);
}
};
}
}
}
public enum EventType
{
OnInit,
OnInitAsyncSync,
OnInitAsyncAsync,
OnParametersSet,
OnParametersSetAsyncSync,
OnParametersSetAsyncAsync,
OnAfterRenderAsyncSync,
OnAfterRenderAsyncAsync,
}
}
private class ComponentThatAwaitsTask : ComponentBase
{
[Parameter] public Task TaskToAwait { get; set; }
protected override async Task OnParametersSetAsync()
{
await TaskToAwait;
}
}
private class AsyncUpdateTestRenderer : TestRenderer
{
public Func<RenderBatch, Task> OnUpdateDisplayAsync { get; set; }
protected override Task UpdateDisplayAsync(in RenderBatch renderBatch)
{
return OnUpdateDisplayAsync(renderBatch);
}
}
private class AsyncAfterRenderComponent : AutoRenderComponent, IHandleAfterRender
{
private readonly Task _task;
public AsyncAfterRenderComponent(Task task)
{
_task = task;
}
public bool Called { get; private set; }
public Action OnAfterRenderComplete { get; set; }
public async Task OnAfterRenderAsync()
{
await _task;
Called = true;
OnAfterRenderComplete?.Invoke();
}
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
builder.OpenElement(0, "p");
builder.CloseElement();
}
}
class BoundPropertyComponent : AutoRenderComponent
{
public string BoundString { get; set; }
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
var unrelatedThingToMakeTheLambdaCapture = new object();
builder.OpenElement(0, "element with event");
builder.AddAttribute(1, nameof(BoundString), BoundString);
builder.AddAttribute(2, "ontestevent", new Action<ChangeEventArgs>((ChangeEventArgs eventArgs) =>
{
BoundString = (string)eventArgs.Value;
TriggerRender();
GC.KeepAlive(unrelatedThingToMakeTheLambdaCapture);
}));
builder.SetUpdatesAttributeName(nameof(BoundString));
builder.CloseElement();
}
}
private class DerivedEventArgs : EventArgs
{
}
class CallbackOnRenderComponent : AutoRenderComponent
{
private readonly Action _callback;
public CallbackOnRenderComponent(Action callback)
{
_callback = callback;
}
protected override void BuildRenderTree(RenderTreeBuilder builder)
=> _callback();
}
class InvalidRecursiveRenderer : TestRenderer
{
public new void ProcessPendingRender()
=> base.ProcessPendingRender();
}
class ParameterViewIllegalCapturingComponent : IComponent
{
public ParameterView CapturedParameterView { get; private set; }
[Parameter] public int SomeParam { get; set; }
public void Attach(RenderHandle renderHandle)
{
}
public Task SetParametersAsync(ParameterView parameters)
{
CapturedParameterView = parameters;
// Return a task that never completes to show that access is forbidden
// after the synchronous return, not just after the returned task completes
return new TaskCompletionSource<object>().Task;
}
}
private class TestErrorBoundary : AutoRenderComponent, IErrorBoundary
{
private readonly TaskCompletionSource receivedErrorTaskCompletionSource = new();
public Exception ReceivedException { get; private set; }
public Task ReceivedErrorTask => receivedErrorTaskCompletionSource.Task;
[Parameter] public RenderFragment ChildContent { get; set; }
protected override void BuildRenderTree(RenderTreeBuilder builder)
=> ChildContent(builder);
public void HandleException(Exception error)
{
ReceivedException = error;
receivedErrorTaskCompletionSource.SetResult();
}
public static void RenderNestedErrorBoundaries(RenderTreeBuilder builder, RenderFragment innerContent)
{
// Create an error boundary
builder.OpenComponent<TestErrorBoundary>(0);
builder.AddAttribute(1, nameof(TestErrorBoundary.ChildContent), (RenderFragment)(builder =>
{
// ... containing another error boundary, containing the content
builder.OpenComponent<TestErrorBoundary>(0);
builder.AddAttribute(1, nameof(TestErrorBoundary.ChildContent), innerContent);
builder.CloseComponent();
}));
builder.CloseComponent();
}
}
private class ErrorThrowingComponent : AutoRenderComponent, IHandleEvent
{
[Parameter] public Exception ThrowDuringRender { get; set; }
[Parameter] public Exception ThrowDuringEventSync { get; set; }
[Parameter] public Task ThrowDuringEventAsync { get; set; }
[Parameter] public Exception ThrowDuringParameterSettingSync { get; set; }
[Parameter] public Task ThrowDuringParameterSettingAsync { get; set; }
public override async Task SetParametersAsync(ParameterView parameters)
{
_ = base.SetParametersAsync(parameters);
if (ThrowDuringParameterSettingSync is not null)
{
throw ThrowDuringParameterSettingSync;
}
if (ThrowDuringParameterSettingAsync is not null)
{
await ThrowDuringParameterSettingAsync;
}
}
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
if (ThrowDuringRender is not null)
{
throw ThrowDuringRender;
}
builder.OpenElement(0, "someelem");
builder.AddAttribute(1, "onmakeerror", EventCallback.Factory.Create(this, () => { }));
builder.AddContent(1, "Hello");
builder.CloseElement();
}
public async Task HandleEventAsync(EventCallbackWorkItem item, object arg)
{
if (ThrowDuringEventSync is not null)
{
throw ThrowDuringEventSync;
}
if (ThrowDuringEventAsync is not null)
{
await ThrowDuringEventAsync;
}
}
}
private class CallbackDuringSetParametersAsyncComponent : AutoRenderComponent
{
public int RenderCount { get; private set; }
public Func<Task> Callback { get; set; }
public override async Task SetParametersAsync(ParameterView parameters)
{
await Callback();
await base.SetParametersAsync(parameters);
}
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
RenderCount++;
}
}
}
}
| 42.120183 | 217 | 0.573261 | [
"Apache-2.0"
] | a14907/AspNetCore | src/Components/Components/test/RendererTest.cs | 239,369 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using JetBrains.Annotations;
namespace Faithlife.Utility
{
/// <summary>
/// Provides methods for manipulating strings.
/// </summary>
[SuppressMessage("Usage", "CA2213:Disposable fields should be disposed", Justification = "Uses DisposableUtility.")]
public static class StringUtility
{
/// <summary>
/// Calls string.StartsWith with StringComparison.Ordinal.
/// </summary>
public static bool StartsWithOrdinal(this string source, string value) => source.StartsWith(value, StringComparison.Ordinal);
/// <summary>
/// Calls string.EndsWith with StringComparison.Ordinal.
/// </summary>
public static bool EndsWithOrdinal(this string source, string value) => source.EndsWith(value, StringComparison.Ordinal);
/// <summary>
/// Calls string.IndexOf with StringComparison.Ordinal.
/// </summary>
public static int IndexOfOrdinal(this string source, string value) => source.IndexOf(value, StringComparison.Ordinal);
/// <summary>
/// Calls string.IndexOf with StringComparison.Ordinal.
/// </summary>
public static int IndexOfOrdinal(this string source, string value, int startIndex) => source.IndexOf(value, startIndex, StringComparison.Ordinal);
/// <summary>
/// Calls string.IndexOf with StringComparison.Ordinal.
/// </summary>
public static int IndexOfOrdinal(this string source, string value, int startIndex, int count) => source.IndexOf(value, startIndex, count, StringComparison.Ordinal);
/// <summary>
/// Calls string.IndexOf with StringComparison.Ordinal.
/// </summary>
[SuppressMessage("Usage", "FL0002:Use StringComparison overload", Justification = "Analyzer bug.")]
#if NETSTANDARD2_0
public static int IndexOfOrdinal(this string source, char value) => source.IndexOf(value);
#else
public static int IndexOfOrdinal(this string source, char value) => source.IndexOf(value, StringComparison.Ordinal);
#endif
/// <summary>
/// Calls string.LastIndexOf with StringComparison.Ordinal.
/// </summary>
public static int LastIndexOfOrdinal(this string source, string value) => source.LastIndexOf(value, StringComparison.Ordinal);
/// <summary>
/// Calls string.LastIndexOf with StringComparison.Ordinal.
/// </summary>
public static int LastIndexOfOrdinal(this string source, string value, int startIndex) => source.LastIndexOf(value, startIndex, StringComparison.Ordinal);
/// <summary>
/// Calls string.LastIndexOf with StringComparison.Ordinal.
/// </summary>
public static int LastIndexOfOrdinal(this string source, string value, int startIndex, int count) => source.LastIndexOf(value, startIndex, count, StringComparison.Ordinal);
/// <summary>
/// Calls string.Replace with StringComparison.Ordinal.
/// </summary>
public static string ReplaceOrdinal(this string source, string oldValue, string newValue)
{
#if NETSTANDARD || NETCOREAPP2_1
return source.Replace(oldValue, newValue);
#else
return source.Replace(oldValue, newValue, StringComparison.Ordinal);
#endif
}
/// <summary>
/// Compares two specified <see cref="string"/> objects by comparing successive Unicode code points. This method differs from
/// <see cref="string.CompareOrdinal(string, string)"/> in that this method considers supplementary characters (which are
/// encoded as two surrogate code units) to be greater than characters in the base multilingual plane (because they have higher
/// Unicode code points). This method sorts strings in code point order, which is the same as a byte-wise comparison of UTF-8 or
/// UTF-32 encoded strings.
/// </summary>
/// <param name="left">The first string.</param>
/// <param name="right">The second string.</param>
/// <returns>Less than zero if <paramref name="left"/> is less than <paramref name="right"/>; zero if the strings are equal;
/// greater than zero if <paramref name="left"/> is greater than <paramref name="right"/>.</returns>
public static int CompareByCodePoint(string? left, string? right)
{
// null sorts less than anything else (same as String.CompareOrdinal)
if (left is null)
return right is null ? 0 : -1;
else if (right is null)
return 1;
// get the length of both strings
var leftLength = left.Length;
var rightLength = right.Length;
// compare at most the number of characters the strings have in common
var maxIndex = Math.Min(leftLength, rightLength);
for (var index = 0; index < maxIndex; index++)
{
var leftChar = left[index];
var rightChar = right[index];
// algorithm from the Unicode Standard 5.0, Section 5.17 (Binary Order), page 183
if (leftChar != rightChar)
return unchecked((char) (leftChar + s_mapUtf16FixUp[leftChar >> 11]) - (char) (rightChar + s_mapUtf16FixUp[rightChar >> 11]));
}
// the shorter string (if any) is less than the other
return leftLength - rightLength;
}
/// <summary>
/// Creates a <see cref="StringComparer" /> ignoring or honoring the strings' case, and using culture-specific information
/// to influence the comparison.
/// </summary>
/// <returns>The comparer.</returns>
/// <param name="cultureInfo">Culture info.</param>
/// <param name="ignoreCase">If set to <c>true</c> ignore case.</param>
public static StringComparer CreateComparer(CultureInfo cultureInfo, bool ignoreCase) =>
StringComparer.Create(cultureInfo, ignoreCase);
/// <summary>
/// Performs a full case folding as defined by Section 5.18 of the Unicode Standard 5.0.
/// </summary>
/// <param name="value">The string to be case-folded.</param>
/// <returns>A case-folded version of the input string. This value may be longer than the input.</returns>
/// <remarks><para>This function is generated from the Unicode case folding data by Tools/src/GenerateCaseFolding.</para>
/// <para>From http://unicode.org/reports/tr21/tr21-5.html#Caseless_Matching: Case-folding is the process of mapping
/// strings to a canonical form where case differences are erased. Case-folding allows for fast caseless matches in lookups,
/// since only binary comparison is required. Case-folding is more than just conversion to lowercase.</para>
/// <para>Case folding is not culture aware. String comparisons that should be culture aware should not use this method.</para></remarks>
public static string FoldCase(this string value)
{
// check parameters
if (value is null)
throw new ArgumentNullException(nameof(value));
// process each character in the input string
var sb = new StringBuilder();
foreach (var codeUnit in value)
{
if (codeUnit < 0x100)
{
if (codeUnit >= 0x0041 && codeUnit <= 0x005a)
sb.Append((char) (codeUnit + 32));
else if (codeUnit == 0x00b5)
sb.Append('\u03bc');
else if (codeUnit >= 0x00c0 && codeUnit <= 0x00d6)
sb.Append((char) (codeUnit + 32));
else if (codeUnit >= 0x00d8 && codeUnit <= 0x00de)
sb.Append((char) (codeUnit + 32));
else if (codeUnit == 0x00df)
sb.Append("\u0073\u0073");
else
sb.Append(codeUnit);
}
else if (codeUnit < 0x590)
{
if (codeUnit >= 0x0100 && codeUnit <= 0x012e && codeUnit % 2 == 0)
sb.Append((char) (codeUnit + 1));
else if (codeUnit == 0x0130)
sb.Append("\u0069\u0307");
else if (codeUnit >= 0x0132 && codeUnit <= 0x0136 && codeUnit % 2 == 0)
sb.Append((char) (codeUnit + 1));
else if (codeUnit >= 0x0139 && codeUnit <= 0x0147 && codeUnit % 2 == 1)
sb.Append((char) (codeUnit + 1));
else if (codeUnit == 0x0149)
sb.Append("\u02bc\u006e");
else if (codeUnit >= 0x014a && codeUnit <= 0x0176 && codeUnit % 2 == 0)
sb.Append((char) (codeUnit + 1));
else if (codeUnit == 0x0178)
sb.Append('\u00ff');
else if (codeUnit >= 0x0179 && codeUnit <= 0x017d && codeUnit % 2 == 1)
sb.Append((char) (codeUnit + 1));
else if (codeUnit == 0x017f)
sb.Append('\u0073');
else if (codeUnit == 0x0181)
sb.Append('\u0253');
else if (codeUnit >= 0x0182 && codeUnit <= 0x0184 && codeUnit % 2 == 0)
sb.Append((char) (codeUnit + 1));
else if (codeUnit == 0x0186)
sb.Append('\u0254');
else if (codeUnit == 0x0187)
sb.Append('\u0188');
else if (codeUnit >= 0x0189 && codeUnit <= 0x018a)
sb.Append((char) (codeUnit + 205));
else if (codeUnit == 0x018b)
sb.Append('\u018c');
else if (codeUnit == 0x018e)
sb.Append('\u01dd');
else if (codeUnit == 0x018f)
sb.Append('\u0259');
else if (codeUnit == 0x0190)
sb.Append('\u025b');
else if (codeUnit == 0x0191)
sb.Append('\u0192');
else if (codeUnit == 0x0193)
sb.Append('\u0260');
else if (codeUnit == 0x0194)
sb.Append('\u0263');
else if (codeUnit == 0x0196)
sb.Append('\u0269');
else if (codeUnit == 0x0197)
sb.Append('\u0268');
else if (codeUnit == 0x0198)
sb.Append('\u0199');
else if (codeUnit == 0x019c)
sb.Append('\u026f');
else if (codeUnit == 0x019d)
sb.Append('\u0272');
else if (codeUnit == 0x019f)
sb.Append('\u0275');
else if (codeUnit >= 0x01a0 && codeUnit <= 0x01a4 && codeUnit % 2 == 0)
sb.Append((char) (codeUnit + 1));
else if (codeUnit == 0x01a6)
sb.Append('\u0280');
else if (codeUnit == 0x01a7)
sb.Append('\u01a8');
else if (codeUnit == 0x01a9)
sb.Append('\u0283');
else if (codeUnit == 0x01ac)
sb.Append('\u01ad');
else if (codeUnit == 0x01ae)
sb.Append('\u0288');
else if (codeUnit == 0x01af)
sb.Append('\u01b0');
else if (codeUnit >= 0x01b1 && codeUnit <= 0x01b2)
sb.Append((char) (codeUnit + 217));
else if (codeUnit >= 0x01b3 && codeUnit <= 0x01b5 && codeUnit % 2 == 1)
sb.Append((char) (codeUnit + 1));
else if (codeUnit == 0x01b7)
sb.Append('\u0292');
else if (codeUnit >= 0x01b8 && codeUnit <= 0x01bc && codeUnit % 4 == 0)
sb.Append((char) (codeUnit + 1));
else if (codeUnit == 0x01c4)
sb.Append('\u01c6');
else if (codeUnit == 0x01c5)
sb.Append('\u01c6');
else if (codeUnit == 0x01c7)
sb.Append('\u01c9');
else if (codeUnit == 0x01c8)
sb.Append('\u01c9');
else if (codeUnit == 0x01ca)
sb.Append('\u01cc');
else if (codeUnit >= 0x01cb && codeUnit <= 0x01db && codeUnit % 2 == 1)
sb.Append((char) (codeUnit + 1));
else if (codeUnit >= 0x01de && codeUnit <= 0x01ee && codeUnit % 2 == 0)
sb.Append((char) (codeUnit + 1));
else if (codeUnit == 0x01f0)
sb.Append("\u006a\u030c");
else if (codeUnit == 0x01f1)
sb.Append('\u01f3');
else if (codeUnit >= 0x01f2 && codeUnit <= 0x01f4 && codeUnit % 2 == 0)
sb.Append((char) (codeUnit + 1));
else if (codeUnit == 0x01f6)
sb.Append('\u0195');
else if (codeUnit == 0x01f7)
sb.Append('\u01bf');
else if (codeUnit >= 0x01f8 && codeUnit <= 0x021e && codeUnit % 2 == 0)
sb.Append((char) (codeUnit + 1));
else if (codeUnit == 0x0220)
sb.Append('\u019e');
else if (codeUnit >= 0x0222 && codeUnit <= 0x0232 && codeUnit % 2 == 0)
sb.Append((char) (codeUnit + 1));
else if (codeUnit == 0x023a)
sb.Append('\u2c65');
else if (codeUnit == 0x023b)
sb.Append('\u023c');
else if (codeUnit == 0x023d)
sb.Append('\u019a');
else if (codeUnit == 0x023e)
sb.Append('\u2c66');
else if (codeUnit == 0x0241)
sb.Append('\u0242');
else if (codeUnit == 0x0243)
sb.Append('\u0180');
else if (codeUnit == 0x0244)
sb.Append('\u0289');
else if (codeUnit == 0x0245)
sb.Append('\u028c');
else if (codeUnit >= 0x0246 && codeUnit <= 0x024e && codeUnit % 2 == 0)
sb.Append((char) (codeUnit + 1));
else if (codeUnit == 0x0345)
sb.Append('\u03b9');
else if (codeUnit == 0x0386)
sb.Append('\u03ac');
else if (codeUnit >= 0x0388 && codeUnit <= 0x038a)
sb.Append((char) (codeUnit + 37));
else if (codeUnit == 0x038c)
sb.Append('\u03cc');
else if (codeUnit >= 0x038e && codeUnit <= 0x038f)
sb.Append((char) (codeUnit + 63));
else if (codeUnit == 0x0390)
sb.Append("\u03b9\u0308\u0301");
else if (codeUnit >= 0x0391 && codeUnit <= 0x03a1)
sb.Append((char) (codeUnit + 32));
else if (codeUnit >= 0x03a3 && codeUnit <= 0x03ab)
sb.Append((char) (codeUnit + 32));
else if (codeUnit == 0x03b0)
sb.Append("\u03c5\u0308\u0301");
else if (codeUnit == 0x03c2)
sb.Append('\u03c3');
else if (codeUnit == 0x03d0)
sb.Append('\u03b2');
else if (codeUnit == 0x03d1)
sb.Append('\u03b8');
else if (codeUnit == 0x03d5)
sb.Append('\u03c6');
else if (codeUnit == 0x03d6)
sb.Append('\u03c0');
else if (codeUnit >= 0x03d8 && codeUnit <= 0x03ee && codeUnit % 2 == 0)
sb.Append((char) (codeUnit + 1));
else if (codeUnit == 0x03f0)
sb.Append('\u03ba');
else if (codeUnit == 0x03f1)
sb.Append('\u03c1');
else if (codeUnit == 0x03f4)
sb.Append('\u03b8');
else if (codeUnit == 0x03f5)
sb.Append('\u03b5');
else if (codeUnit == 0x03f7)
sb.Append('\u03f8');
else if (codeUnit == 0x03f9)
sb.Append('\u03f2');
else if (codeUnit == 0x03fa)
sb.Append('\u03fb');
else if (codeUnit >= 0x03fd && codeUnit <= 0x03ff)
sb.Append((char) (codeUnit - 130));
else if (codeUnit >= 0x0400 && codeUnit <= 0x040f)
sb.Append((char) (codeUnit + 80));
else if (codeUnit >= 0x0410 && codeUnit <= 0x042f)
sb.Append((char) (codeUnit + 32));
else if (codeUnit >= 0x0460 && codeUnit <= 0x0480 && codeUnit % 2 == 0)
sb.Append((char) (codeUnit + 1));
else if (codeUnit >= 0x048a && codeUnit <= 0x04be && codeUnit % 2 == 0)
sb.Append((char) (codeUnit + 1));
else if (codeUnit == 0x04c0)
sb.Append('\u04cf');
else if (codeUnit >= 0x04c1 && codeUnit <= 0x04cd && codeUnit % 2 == 1)
sb.Append((char) (codeUnit + 1));
else if (codeUnit >= 0x04d0 && codeUnit <= 0x0512 && codeUnit % 2 == 0)
sb.Append((char) (codeUnit + 1));
else if (codeUnit >= 0x0531 && codeUnit <= 0x0556)
sb.Append((char) (codeUnit + 48));
else if (codeUnit == 0x0587)
sb.Append("\u0565\u0582");
else
sb.Append(codeUnit);
}
else if (codeUnit >= 0x10a0 && codeUnit <= 0x10c5)
{
sb.Append((char) (codeUnit + 7264));
}
else if (codeUnit >= 0x1e00)
{
if (codeUnit >= 0x1e00 && codeUnit <= 0x1e94 && codeUnit % 2 == 0)
sb.Append((char) (codeUnit + 1));
else if (codeUnit == 0x1e96)
sb.Append("\u0068\u0331");
else if (codeUnit == 0x1e97)
sb.Append("\u0074\u0308");
else if (codeUnit == 0x1e98)
sb.Append("\u0077\u030a");
else if (codeUnit == 0x1e99)
sb.Append("\u0079\u030a");
else if (codeUnit == 0x1e9a)
sb.Append("\u0061\u02be");
else if (codeUnit == 0x1e9b)
sb.Append('\u1e61');
else if (codeUnit >= 0x1ea0 && codeUnit <= 0x1ef8 && codeUnit % 2 == 0)
sb.Append((char) (codeUnit + 1));
else if (codeUnit >= 0x1f08 && codeUnit <= 0x1f0f)
sb.Append((char) (codeUnit - 8));
else if (codeUnit >= 0x1f18 && codeUnit <= 0x1f1d)
sb.Append((char) (codeUnit - 8));
else if (codeUnit >= 0x1f28 && codeUnit <= 0x1f2f)
sb.Append((char) (codeUnit - 8));
else if (codeUnit >= 0x1f38 && codeUnit <= 0x1f3f)
sb.Append((char) (codeUnit - 8));
else if (codeUnit >= 0x1f48 && codeUnit <= 0x1f4d)
sb.Append((char) (codeUnit - 8));
else if (codeUnit == 0x1f50)
sb.Append("\u03c5\u0313");
else if (codeUnit == 0x1f52)
sb.Append("\u03c5\u0313\u0300");
else if (codeUnit == 0x1f54)
sb.Append("\u03c5\u0313\u0301");
else if (codeUnit == 0x1f56)
sb.Append("\u03c5\u0313\u0342");
else if (codeUnit >= 0x1f59 && codeUnit <= 0x1f5f && codeUnit % 2 == 1)
sb.Append((char) (codeUnit - 8));
else if (codeUnit >= 0x1f68 && codeUnit <= 0x1f6f)
sb.Append((char) (codeUnit - 8));
else if (codeUnit == 0x1f80)
sb.Append("\u1f00\u03b9");
else if (codeUnit == 0x1f81)
sb.Append("\u1f01\u03b9");
else if (codeUnit == 0x1f82)
sb.Append("\u1f02\u03b9");
else if (codeUnit == 0x1f83)
sb.Append("\u1f03\u03b9");
else if (codeUnit == 0x1f84)
sb.Append("\u1f04\u03b9");
else if (codeUnit == 0x1f85)
sb.Append("\u1f05\u03b9");
else if (codeUnit == 0x1f86)
sb.Append("\u1f06\u03b9");
else if (codeUnit == 0x1f87)
sb.Append("\u1f07\u03b9");
else if (codeUnit == 0x1f88)
sb.Append("\u1f00\u03b9");
else if (codeUnit == 0x1f89)
sb.Append("\u1f01\u03b9");
else if (codeUnit == 0x1f8a)
sb.Append("\u1f02\u03b9");
else if (codeUnit == 0x1f8b)
sb.Append("\u1f03\u03b9");
else if (codeUnit == 0x1f8c)
sb.Append("\u1f04\u03b9");
else if (codeUnit == 0x1f8d)
sb.Append("\u1f05\u03b9");
else if (codeUnit == 0x1f8e)
sb.Append("\u1f06\u03b9");
else if (codeUnit == 0x1f8f)
sb.Append("\u1f07\u03b9");
else if (codeUnit == 0x1f90)
sb.Append("\u1f20\u03b9");
else if (codeUnit == 0x1f91)
sb.Append("\u1f21\u03b9");
else if (codeUnit == 0x1f92)
sb.Append("\u1f22\u03b9");
else if (codeUnit == 0x1f93)
sb.Append("\u1f23\u03b9");
else if (codeUnit == 0x1f94)
sb.Append("\u1f24\u03b9");
else if (codeUnit == 0x1f95)
sb.Append("\u1f25\u03b9");
else if (codeUnit == 0x1f96)
sb.Append("\u1f26\u03b9");
else if (codeUnit == 0x1f97)
sb.Append("\u1f27\u03b9");
else if (codeUnit == 0x1f98)
sb.Append("\u1f20\u03b9");
else if (codeUnit == 0x1f99)
sb.Append("\u1f21\u03b9");
else if (codeUnit == 0x1f9a)
sb.Append("\u1f22\u03b9");
else if (codeUnit == 0x1f9b)
sb.Append("\u1f23\u03b9");
else if (codeUnit == 0x1f9c)
sb.Append("\u1f24\u03b9");
else if (codeUnit == 0x1f9d)
sb.Append("\u1f25\u03b9");
else if (codeUnit == 0x1f9e)
sb.Append("\u1f26\u03b9");
else if (codeUnit == 0x1f9f)
sb.Append("\u1f27\u03b9");
else if (codeUnit == 0x1fa0)
sb.Append("\u1f60\u03b9");
else if (codeUnit == 0x1fa1)
sb.Append("\u1f61\u03b9");
else if (codeUnit == 0x1fa2)
sb.Append("\u1f62\u03b9");
else if (codeUnit == 0x1fa3)
sb.Append("\u1f63\u03b9");
else if (codeUnit == 0x1fa4)
sb.Append("\u1f64\u03b9");
else if (codeUnit == 0x1fa5)
sb.Append("\u1f65\u03b9");
else if (codeUnit == 0x1fa6)
sb.Append("\u1f66\u03b9");
else if (codeUnit == 0x1fa7)
sb.Append("\u1f67\u03b9");
else if (codeUnit == 0x1fa8)
sb.Append("\u1f60\u03b9");
else if (codeUnit == 0x1fa9)
sb.Append("\u1f61\u03b9");
else if (codeUnit == 0x1faa)
sb.Append("\u1f62\u03b9");
else if (codeUnit == 0x1fab)
sb.Append("\u1f63\u03b9");
else if (codeUnit == 0x1fac)
sb.Append("\u1f64\u03b9");
else if (codeUnit == 0x1fad)
sb.Append("\u1f65\u03b9");
else if (codeUnit == 0x1fae)
sb.Append("\u1f66\u03b9");
else if (codeUnit == 0x1faf)
sb.Append("\u1f67\u03b9");
else if (codeUnit == 0x1fb2)
sb.Append("\u1f70\u03b9");
else if (codeUnit == 0x1fb3)
sb.Append("\u03b1\u03b9");
else if (codeUnit == 0x1fb4)
sb.Append("\u03ac\u03b9");
else if (codeUnit == 0x1fb6)
sb.Append("\u03b1\u0342");
else if (codeUnit == 0x1fb7)
sb.Append("\u03b1\u0342\u03b9");
else if (codeUnit >= 0x1fb8 && codeUnit <= 0x1fb9)
sb.Append((char) (codeUnit - 8));
else if (codeUnit >= 0x1fba && codeUnit <= 0x1fbb)
sb.Append((char) (codeUnit - 74));
else if (codeUnit == 0x1fbc)
sb.Append("\u03b1\u03b9");
else if (codeUnit == 0x1fbe)
sb.Append('\u03b9');
else if (codeUnit == 0x1fc2)
sb.Append("\u1f74\u03b9");
else if (codeUnit == 0x1fc3)
sb.Append("\u03b7\u03b9");
else if (codeUnit == 0x1fc4)
sb.Append("\u03ae\u03b9");
else if (codeUnit == 0x1fc6)
sb.Append("\u03b7\u0342");
else if (codeUnit == 0x1fc7)
sb.Append("\u03b7\u0342\u03b9");
else if (codeUnit >= 0x1fc8 && codeUnit <= 0x1fcb)
sb.Append((char) (codeUnit - 86));
else if (codeUnit == 0x1fcc)
sb.Append("\u03b7\u03b9");
else if (codeUnit == 0x1fd2)
sb.Append("\u03b9\u0308\u0300");
else if (codeUnit == 0x1fd3)
sb.Append("\u03b9\u0308\u0301");
else if (codeUnit == 0x1fd6)
sb.Append("\u03b9\u0342");
else if (codeUnit == 0x1fd7)
sb.Append("\u03b9\u0308\u0342");
else if (codeUnit >= 0x1fd8 && codeUnit <= 0x1fd9)
sb.Append((char) (codeUnit - 8));
else if (codeUnit >= 0x1fda && codeUnit <= 0x1fdb)
sb.Append((char) (codeUnit - 100));
else if (codeUnit == 0x1fe2)
sb.Append("\u03c5\u0308\u0300");
else if (codeUnit == 0x1fe3)
sb.Append("\u03c5\u0308\u0301");
else if (codeUnit == 0x1fe4)
sb.Append("\u03c1\u0313");
else if (codeUnit == 0x1fe6)
sb.Append("\u03c5\u0342");
else if (codeUnit == 0x1fe7)
sb.Append("\u03c5\u0308\u0342");
else if (codeUnit >= 0x1fe8 && codeUnit <= 0x1fe9)
sb.Append((char) (codeUnit - 8));
else if (codeUnit >= 0x1fea && codeUnit <= 0x1feb)
sb.Append((char) (codeUnit - 112));
else if (codeUnit == 0x1fec)
sb.Append('\u1fe5');
else if (codeUnit == 0x1ff2)
sb.Append("\u1f7c\u03b9");
else if (codeUnit == 0x1ff3)
sb.Append("\u03c9\u03b9");
else if (codeUnit == 0x1ff4)
sb.Append("\u03ce\u03b9");
else if (codeUnit == 0x1ff6)
sb.Append("\u03c9\u0342");
else if (codeUnit == 0x1ff7)
sb.Append("\u03c9\u0342\u03b9");
else if (codeUnit >= 0x1ff8 && codeUnit <= 0x1ff9)
sb.Append((char) (codeUnit - 128));
else if (codeUnit >= 0x1ffa && codeUnit <= 0x1ffb)
sb.Append((char) (codeUnit - 126));
else if (codeUnit == 0x1ffc)
sb.Append("\u03c9\u03b9");
else if (codeUnit == 0x2126)
sb.Append('\u03c9');
else if (codeUnit == 0x212a)
sb.Append('\u006b');
else if (codeUnit == 0x212b)
sb.Append('\u00e5');
else if (codeUnit == 0x2132)
sb.Append('\u214e');
else if (codeUnit >= 0x2160 && codeUnit <= 0x216f)
sb.Append((char) (codeUnit + 16));
else if (codeUnit == 0x2183)
sb.Append('\u2184');
else if (codeUnit >= 0x24b6 && codeUnit <= 0x24cf)
sb.Append((char) (codeUnit + 26));
else if (codeUnit >= 0x2c00 && codeUnit <= 0x2c2e)
sb.Append((char) (codeUnit + 48));
else if (codeUnit == 0x2c60)
sb.Append('\u2c61');
else if (codeUnit == 0x2c62)
sb.Append('\u026b');
else if (codeUnit == 0x2c63)
sb.Append('\u1d7d');
else if (codeUnit == 0x2c64)
sb.Append('\u027d');
else if (codeUnit >= 0x2c67 && codeUnit <= 0x2c6b && codeUnit % 2 == 1)
sb.Append((char) (codeUnit + 1));
else if (codeUnit >= 0x2c75 && codeUnit <= 0x2c80 && codeUnit % 11 == 7)
sb.Append((char) (codeUnit + 1));
else if (codeUnit >= 0x2c82 && codeUnit <= 0x2ce2 && codeUnit % 2 == 0)
sb.Append((char) (codeUnit + 1));
else if (codeUnit == 0xfb00)
sb.Append("\u0066\u0066");
else if (codeUnit == 0xfb01)
sb.Append("\u0066\u0069");
else if (codeUnit == 0xfb02)
sb.Append("\u0066\u006c");
else if (codeUnit == 0xfb03)
sb.Append("\u0066\u0066\u0069");
else if (codeUnit == 0xfb04)
sb.Append("\u0066\u0066\u006c");
else if (codeUnit == 0xfb05)
sb.Append("\u0073\u0074");
else if (codeUnit == 0xfb06)
sb.Append("\u0073\u0074");
else if (codeUnit == 0xfb13)
sb.Append("\u0574\u0576");
else if (codeUnit == 0xfb14)
sb.Append("\u0574\u0565");
else if (codeUnit == 0xfb15)
sb.Append("\u0574\u056b");
else if (codeUnit == 0xfb16)
sb.Append("\u057e\u0576");
else if (codeUnit == 0xfb17)
sb.Append("\u0574\u056d");
else if (codeUnit >= 0xff21 && codeUnit <= 0xff3a)
sb.Append((char) (codeUnit + 32));
else
sb.Append(codeUnit);
}
else
{
sb.Append(codeUnit);
}
}
return sb.ToString();
}
/// <summary>
/// Formats the string using the invariant culture.
/// </summary>
/// <param name="format">The format string.</param>
/// <param name="args">The format arguments.</param>
/// <returns>The formatted string.</returns>
[StringFormatMethod("format")]
public static string FormatInvariant(this string format, params object?[] args) => string.Format(CultureInfo.InvariantCulture, format, args);
/// <summary>
/// Joins the specified strings into one string.
/// </summary>
/// <param name="strings">The strings.</param>
/// <returns>All of the strings concatenated with no separator.</returns>
public static string Join(this IEnumerable<string?> strings)
{
return Join(strings, default);
}
/// <summary>
/// Joins the specified strings using the specified separator.
/// </summary>
/// <param name="strings">The strings.</param>
/// <param name="separator">The separator. (The empty string is used if null.)</param>
/// <returns>All of the strings concatenated with the specified separator.</returns>
public static string Join(this IEnumerable<string?> strings, string? separator)
{
if (strings is null)
throw new ArgumentNullException(nameof(strings));
using var enumerator = strings.GetEnumerator();
if (enumerator.MoveNext())
{
var sb = new StringBuilder(enumerator.Current);
while (enumerator.MoveNext())
{
sb.Append(separator);
sb.Append(enumerator.Current);
}
return sb.ToString();
}
return "";
}
/// <summary>
/// Joins the specified strings into one string.
/// </summary>
/// <param name="array">The strings.</param>
/// <returns>All of the strings concatenated with no separator.</returns>
public static string Join(this string[] array) => string.Join(string.Empty, array);
/// <summary>
/// Joins the specified strings using the specified separator.
/// </summary>
/// <param name="array">The strings.</param>
/// <param name="separator">The separator. (The empty string is used if null.)</param>
/// <returns>All of the strings concatenated with the specified separator.</returns>
public static string Join(this string[] array, string separator) => string.Join(separator, array);
/// <summary>
/// Joins the specified strings using the specified separator format.
/// </summary>
/// <param name="strings">The strings.</param>
/// <param name="separatorFormat">The separator format, e.g. "{0}, {1}".</param>
/// <returns>All of the strings concatenated with the specified separator format.</returns>
public static string JoinFormat(this IEnumerable<string> strings, string separatorFormat)
{
if (separatorFormat is null)
throw new ArgumentNullException(nameof(separatorFormat));
return strings.Aggregate(string.Empty, (acc, src) => acc.Length == 0 ? src : separatorFormat.FormatInvariant(acc, src));
}
/// <summary>
/// Gets a hash code for the specified string; this hash code is guaranteed not to change in future.
/// </summary>
/// <param name="value">The string to hash.</param>
/// <returns>A hash code for the specified string</returns>
/// <remarks>Based on SuperFastHash: http://www.azillionmonkeys.com/qed/hash.html</remarks>
public static int GetPersistentHashCode(this string? value)
{
unchecked
{
// check for degenerate input
if (value is null || value.Length == 0)
return 0;
var length = value.Length;
var hash = (uint) length;
var nRemainder = length & 1;
length >>= 1;
// main loop
var index = 0;
for (; length > 0; length--)
{
hash += value[index];
var temp = (uint) (value[index + 1] << 11) ^ hash;
hash = (hash << 16) ^ temp;
index += 2;
hash += hash >> 11;
}
// handle odd string length
if (nRemainder == 1)
{
hash += value[index];
hash ^= hash << 11;
hash += hash >> 17;
}
// Force "avalanching" of final 127 bits
hash ^= hash << 3;
hash += hash >> 5;
hash ^= hash << 4;
hash += hash >> 17;
hash ^= hash << 25;
hash += hash >> 6;
return (int) hash;
}
}
/// <summary>
/// Reverses the specified string.
/// </summary>
/// <param name="value">The string to reverse.</param>
/// <returns>The input string, reversed.</returns>
/// <remarks>This method correctly reverses strings containing supplementary characters (which are encoded with two surrogate code units).</remarks>
public static string Reverse(this string value)
{
if (value is null)
throw new ArgumentNullException(nameof(value));
// allocate a buffer to hold the output
var output = new char[value.Length];
for (int outputIndex = 0, inputIndex = value.Length - 1; outputIndex < value.Length; outputIndex++, inputIndex--)
{
// check for surrogate pair
if (value[inputIndex] >= 0xDC00 && value[inputIndex] <= 0xDFFF &&
inputIndex > 0 && value[inputIndex - 1] >= 0xD800 && value[inputIndex - 1] <= 0xDBFF)
{
// preserve the order of the surrogate pair code units
output[outputIndex + 1] = value[inputIndex];
output[outputIndex] = value[inputIndex - 1];
outputIndex++;
inputIndex--;
}
else
{
output[outputIndex] = value[inputIndex];
}
}
return new string(output);
}
/// <summary>
/// Splits the string on whitespace.
/// </summary>
/// <param name="value">The string.</param>
/// <returns>The array of substrings.</returns>
/// <remarks>See the documentation for string.Split for the white-space characters recognized by this method.</remarks>
public static string[] SplitOnWhitespace(this string value) => value.Split(null);
/// <summary>
/// Splits the string on whitespace.
/// </summary>
/// <param name="value">The string.</param>
/// <param name="options">The options.</param>
/// <returns>The array of substrings.</returns>
/// <remarks>See the documentation for string.Split for the white-space characters recognized by this method.</remarks>
public static string[] SplitOnWhitespace(this string value, StringSplitOptions options) => value.Split((char[]?) null, options);
/// <summary>
/// Compresses a string.
/// </summary>
/// <param name="text">The text.</param>
/// <returns>null if text is null, empty byte[] if text is empty, otherwise the compressed byte array.</returns>
[return: NotNullIfNotNull("text")]
public static byte[]? Compress(string? text)
{
if (text is null)
return null;
if (text.Length == 0)
return Array.Empty<byte>();
using var stream = new MemoryStream();
using (var textWriter = CreateCompressingTextWriter(stream, Ownership.None))
textWriter.Write(text);
return stream.ToArray();
}
/// <summary>
/// Decompresses a compressed string.
/// </summary>
/// <param name="compressedText">The compressed string.</param>
/// <returns>null if compressedText is null, empty string if compressedText length is 0, otherwise the decompressed text.</returns>
/// <remarks>The compressed text should have been created with the Compress or CreateCompressingTextWriter methods.</remarks>
[return: NotNullIfNotNull("compressedText")]
public static string? Decompress(byte[]? compressedText)
{
if (compressedText is null)
return null;
if (compressedText.Length == 0)
return "";
const string invalidFormatMessage = "The compressed string has an invalid format.";
try
{
using var stream = new MemoryStream(compressedText, 0, compressedText.Length, false);
using var textReader = CreateDecompressingTextReader(stream, Ownership.None);
return textReader.ReadToEnd();
}
catch (InvalidDataException x)
{
throw new FormatException(invalidFormatMessage, x);
}
catch (EndOfStreamException x)
{
throw new FormatException(invalidFormatMessage, x);
}
catch (DecoderFallbackException x)
{
throw new FormatException(invalidFormatMessage, x);
}
}
/// <summary>
/// Creates a TextWriter that writes compressed text to a stream that matches the format used by Compress.
/// </summary>
/// <param name="stream">The stream.</param>
/// <param name="ownership">The ownership of the stream.</param>
/// <returns>The TextWriter.</returns>
/// <remarks>The stream must be seekable so that the stream header can be finalized once the compression
/// is copmlete. The contents of the stream are not valid until the TextWriter has been closed.</remarks>
public static TextWriter CreateCompressingTextWriter(Stream stream, Ownership ownership) =>
new CompressingTextWriter(stream, ownership);
/// <summary>
/// Creates a TextReader that reads compressed text from a stream that matches the format used by Compress.
/// </summary>
/// <param name="stream">The stream.</param>
/// <param name="ownership">The ownership of the stream.</param>
/// <returns>The TextReader.</returns>
public static TextReader CreateDecompressingTextReader(Stream stream, Ownership ownership) =>
new DecompressingTextReader(stream, ownership);
private sealed class CompressingTextWriter : TextWriter
{
public CompressingTextWriter(Stream stream, Ownership ownership)
: base(CultureInfo.InvariantCulture)
{
if (stream is null)
throw new ArgumentNullException(nameof(stream));
if (!stream.CanWrite)
throw new ArgumentException("Stream must support writing.", nameof(stream));
if (!stream.CanSeek)
throw new ArgumentException("Stream must support seeking.", nameof(stream));
m_stream = stream;
m_ownership = ownership;
m_encoding = Encoding.UTF8;
m_encoder = m_encoding.GetEncoder();
}
public override Encoding Encoding => m_encoding;
public override void Write(char value) => Write(new[] { value }, 0, 1);
public override void Write(char[] buffer, int index, int count)
{
VerifyNotDisposed();
// loop until all characters are processed
while (count > 0)
{
// convert characters to UTF-8
var bytes = new byte[m_encoding.GetMaxByteCount(count)];
m_encoder.Convert(buffer, index, count, bytes, 0, bytes.Length, false, out var charsUsed, out var bytesUsed, out _);
// write UTF-8 to stream
WriteToStream(bytes, bytesUsed);
// continue loop
index += charsUsed;
count -= charsUsed;
}
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing && !m_isDisposed)
{
// only dispose once
m_isDisposed = true;
// flush encoder
var completed = false;
while (!completed)
{
var bytes = new byte[m_encoding.GetMaxByteCount(0)];
m_encoder.Convert(Array.Empty<char>(), 0, 0, bytes, 0, bytes.Length, true, out _, out var bytesUsed, out completed);
WriteToStream(bytes, bytesUsed);
}
if (m_holdingStream is not null)
{
// write holding stream without compression
var uncompressedByteCount = (int) m_holdingStream.Length;
m_stream.WriteByte(c_compressedStringUsingUtf8);
m_stream.Write(BitConverter.GetBytes(uncompressedByteCount), 0, 4);
m_stream.Write(m_holdingStream.ToArray(), 0, uncompressedByteCount);
DisposableUtility.Dispose(ref m_holdingStream);
}
else if (m_zipStream is not null)
{
// flush and dispose compression stream
DisposableUtility.Dispose(ref m_zipStream);
// write uncompressed byte count to the header
var endPosition = m_stream.Position;
m_stream.Position = m_uncompressedByteCountSeekPosition;
m_stream.Write(BitConverter.GetBytes(m_uncompressedByteCount), 0, 4);
m_stream.Position = endPosition;
}
// flush or dispose the stream
if (m_ownership == Ownership.Owns)
m_stream.Dispose();
else
m_stream.Flush();
}
}
finally
{
base.Dispose(disposing);
}
}
private void WriteToStream(byte[] bytes, int count)
{
// make sure we're writing something
if (count != 0)
{
// don't compress short strings
m_uncompressedByteCount += count;
if (m_zipStream is null && m_uncompressedByteCount < c_minimumByteCountToCompress)
{
m_holdingStream ??= new MemoryStream();
m_holdingStream.Write(bytes, 0, count);
}
else
{
// write the header if we haven't already, storing the seek position of the uncompressed byte count
if (m_zipStream is null)
{
// the first byte is the version; the next four bytes is the uncompressed byte count
// (based on http://www.csharphelp.com/2007/09/compress-and-decompress-strings-in-c/)
m_stream.WriteByte(c_compressedStringUsingGzip);
m_uncompressedByteCountSeekPosition = m_stream.Position;
m_stream.Write(BitConverter.GetBytes(0), 0, 4);
m_zipStream = GzipUtility.CreateCompressingWriteStream(m_stream, Ownership.None);
// write any held bytes
if (m_holdingStream is not null)
{
m_zipStream.Write(m_holdingStream.ToArray(), 0, (int) m_holdingStream.Length);
DisposableUtility.Dispose(ref m_holdingStream);
}
}
m_zipStream.Write(bytes, 0, count);
}
}
}
private void VerifyNotDisposed()
{
if (m_isDisposed)
throw new ObjectDisposedException("CompressingTextWriter");
}
private const int c_minimumByteCountToCompress = 512;
private readonly Stream m_stream;
private readonly Ownership m_ownership;
private readonly Encoding m_encoding;
private readonly Encoder m_encoder;
private MemoryStream? m_holdingStream;
private Stream? m_zipStream;
private long m_uncompressedByteCountSeekPosition;
private int m_uncompressedByteCount;
private bool m_isDisposed;
}
private sealed class DecompressingTextReader : TextReader
{
public DecompressingTextReader(Stream stream, Ownership ownership)
{
if (stream is null)
throw new ArgumentNullException(nameof(stream));
if (!stream.CanRead)
throw new ArgumentException("Stream must support reading.", nameof(stream));
m_stream = stream;
m_ownership = ownership;
m_encoding = Encoding.UTF8;
m_decoder = m_encoding.GetDecoder();
ReadHeader();
}
public override int Peek()
{
VerifyNotDisposed();
// read current character unless at end of stream
return m_buffer is null ? -1 : m_buffer[m_bufferIndex];
}
public override int Read()
{
VerifyNotDisposed();
// check for end of stream
if (m_buffer is null)
return -1;
// read current character and advance
int next = m_buffer[m_bufferIndex];
AdvanceBufferIndex(1);
return next;
}
public override int Read(char[] buffer, int index, int count)
{
VerifyNotDisposed();
// check for end of stream
if (m_buffer is null)
return 0;
// limit count to characters remaining in buffer
var maxCount = m_bufferLength - m_bufferIndex;
if (count > maxCount)
count = maxCount;
// copy characters to buffer and advance
Array.Copy(m_buffer, m_bufferIndex, buffer, index, count);
AdvanceBufferIndex(count);
return count;
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing && !m_isDisposed)
{
// only dispose once
m_isDisposed = true;
// flush and dispose decompression stream, if any
DisposableUtility.Dispose(ref m_unzipStream);
// flush or dispose the stream
if (m_ownership == Ownership.Owns)
m_stream.Dispose();
else
m_stream.Flush();
}
}
finally
{
base.Dispose(disposing);
}
}
private void ReadHeader()
{
// check the first byte
var firstByte = m_stream.ReadByte();
if (firstByte == -1)
{
// the stream is empty, which represents the empty string
}
else if (firstByte == c_compressedStringUsingGzip || firstByte == c_compressedStringUsingUtf8)
{
// read uncompressed byte count
var uncompressedByteCountBuffer = new byte[4];
var bytesRead = m_stream.ReadBlock(uncompressedByteCountBuffer, 0, 4);
if (bytesRead != 4)
throw new InvalidDataException("The compressed string has a bad header.");
m_uncompressedByteCount = BitConverter.ToInt32(uncompressedByteCountBuffer, 0);
// if there is anything to decompress, start decompressing
if (m_uncompressedByteCount != 0)
{
if (firstByte == c_compressedStringUsingGzip)
m_unzipStream = GzipUtility.CreateDecompressingReadStream(m_stream, Ownership.None);
ReadNextBuffer();
}
}
else
{
throw new InvalidDataException("The compressed string has an invalid version.");
}
}
private void AdvanceBufferIndex(int count)
{
m_bufferIndex += count;
// read the next buffer when we get to the end
if (m_bufferIndex == m_bufferLength)
ReadNextBuffer();
}
private void ReadNextBuffer()
{
// decompress some UTF-8
var byteCount = Math.Min(m_uncompressedByteCount - m_uncompressedByteIndex, 4096);
var bytes = new byte[byteCount];
(m_unzipStream ?? m_stream).ReadExactly(bytes, 0, byteCount);
m_uncompressedByteIndex += byteCount;
// prepare character buffer
m_buffer = new char[m_encoding.GetMaxCharCount(byteCount)];
m_bufferIndex = 0;
m_bufferLength = 0;
// loop over bytes
var byteIndex = 0;
while (byteCount > 0)
{
// convert UTF-8 to characters
var flush = m_uncompressedByteIndex == m_uncompressedByteCount;
m_decoder.Convert(bytes, byteIndex, byteCount, m_buffer, m_bufferLength, m_buffer.Length - m_bufferLength, flush, out var bytesUsed, out var charsUsed, out _);
byteIndex += bytesUsed;
byteCount -= bytesUsed;
m_bufferLength += charsUsed;
}
// if no characters are left, we are at the end of the stream
if (m_bufferLength == 0)
m_buffer = null;
}
private void VerifyNotDisposed()
{
if (m_isDisposed)
throw new ObjectDisposedException("CompressingTextWriter");
}
private readonly Stream m_stream;
private readonly Ownership m_ownership;
private readonly Encoding m_encoding;
private readonly Decoder m_decoder;
private Stream? m_unzipStream;
private int m_uncompressedByteCount;
private int m_uncompressedByteIndex;
private char[]? m_buffer;
private int m_bufferIndex;
private int m_bufferLength;
private bool m_isDisposed;
}
private const int c_compressedStringUsingGzip = 1;
private const int c_compressedStringUsingUtf8 = 2;
private static readonly ReadOnlyCollection<int> s_mapUtf16FixUp = new ReadOnlyCollection<int>(new[]
{
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0x2000, 0xf800, 0xf800, 0xf800, 0xf800,
});
}
}
| 35.455583 | 174 | 0.635712 | [
"MIT"
] | journeyman32/FaithlifeUtility | src/Faithlife.Utility/StringUtility.cs | 43,504 | C# |
using FluentAssertions;
using NUnit.Framework;
using Vostok.Clusterclient.Core.Ordering.Storage;
namespace Vostok.Clusterclient.Core.Tests.Ordering.Storage
{
[TestFixture]
internal class ReplicaStorageProviderFactory_Tests
{
[Test]
public void Should_return_per_process_provider_for_process_scope()
{
ReplicaStorageProviderFactory.Create(ReplicaStorageScope.Process).Should().BeOfType<PerProcessReplicaStorageProvider>();
}
[Test]
public void Should_return_per_instance_provider_for_instance_scope()
{
ReplicaStorageProviderFactory.Create(ReplicaStorageScope.Instance).Should().BeOfType<PerInstanceReplicaStorageProvider>();
}
[Test]
public void Should_always_return_same_per_process_provider()
{
var provider1 = ReplicaStorageProviderFactory.Create(ReplicaStorageScope.Process);
var provider2 = ReplicaStorageProviderFactory.Create(ReplicaStorageScope.Process);
provider2.Should().BeSameAs(provider1);
}
[Test]
public void Should_always_return_different_per_instance_providers()
{
var provider1 = ReplicaStorageProviderFactory.Create(ReplicaStorageScope.Instance);
var provider2 = ReplicaStorageProviderFactory.Create(ReplicaStorageScope.Instance);
provider2.Should().NotBeSameAs(provider1);
}
}
} | 36.1 | 134 | 0.714681 | [
"MIT"
] | minya/clusterclient.core | Vostok.ClusterClient.Core.Tests/Ordering/Storage/ReplicaStorageProviderFactory_Tests.cs | 1,444 | C# |
using System;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace SocketIo.SocketTypes
{
internal abstract class BaseNetworkProtocol
{
public bool Listening => _listening;
protected bool _listening = false;
protected string IpAddress = null;
protected int NetworkTimeout = 0;
protected ushort SendPort = 0;
protected ushort ReceivePort = 0;
protected SocketIo ParentSocket { get; set; }
public BaseNetworkProtocol(string ip, ushort sendPort, ushort receivePort, int timeout, SocketIo parentSocket)
{
Setup(ip, sendPort, receivePort, timeout);
ParentSocket = parentSocket;
}
internal void Setup(string ip, ushort sendPort, ushort receivePort, int timeout)
{
IpAddress = ip;
NetworkTimeout = timeout;
SendPort = sendPort;
ReceivePort = receivePort;
}
/// <summary>
/// Listens to incoming UDP packets on the ReceivePort and passes them to the HandleMessage in a Parallel task
/// </summary>
public abstract Task ListenAsync(IPEndPoint ReceiveEndPoint);
/// <summary>
/// Sends the message and doesn't wait for input, that should be handled in Listen
/// </summary>
/// <param name="msg"></param>
/// <param name="endpoint"></param>
public abstract Task SendAsync(SocketMessage msg, IPEndPoint endpoint);
/// <summary>
/// Sends the message and doesn't wait for input, that should be handled in Listen
/// </summary>
/// <param name="msg"></param>
/// <param name="endpoint"></param>
public abstract void Send(SocketMessage msg, IPEndPoint endpoint);
public abstract void Close();
}
internal static class AsyncTimeouts
{
public static async Task<T> WithCancellation<T>(this Task<T> task, CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<bool>();
using (cancellationToken.Register(
s => ((TaskCompletionSource<bool>)s).TrySetResult(true), tcs))
if (task != await Task.WhenAny(task, tcs.Task))
throw new OperationCanceledException(cancellationToken);
return await task;
}
public static async Task WithCancellation(this Task task, CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<bool>();
using (cancellationToken.Register(
s => ((TaskCompletionSource<bool>)s).TrySetResult(true), tcs))
if (task != await Task.WhenAny(task, tcs.Task))
throw new OperationCanceledException(cancellationToken);
await task;
}
public static IDisposable CreateTimeoutScope(this IDisposable disposable, TimeSpan timeSpan)
{
var cancellationTokenSource = new CancellationTokenSource(timeSpan);
var cancellationTokenRegistration = cancellationTokenSource.Token.Register(disposable.Dispose);
return new DisposableScope(
() =>
{
cancellationTokenRegistration.Dispose();
cancellationTokenSource.Cancel();
cancellationTokenSource.Dispose();
disposable.Dispose();
});
}
public sealed class DisposableScope : IDisposable
{
private readonly Action _closeScopeAction;
public DisposableScope(Action closeScopeAction)
{
_closeScopeAction = closeScopeAction;
}
public void Dispose()
{
_closeScopeAction();
}
}
}
}
| 28.616071 | 112 | 0.722309 | [
"MIT"
] | 263613093/SocketIo.Core | src/SocketIo.Core/Sockets/SocketTypes/BaseNetworkProtocol.cs | 3,207 | C# |
#region BSD License
/*
* Use of this source code is governed by a BSD-style
* license or other governing licenses that can be found in the LICENSE.md file or at
* https://raw.githubusercontent.com/Krypton-Suite/Extended-Toolkit/master/LICENSE
*/
#endregion
namespace Krypton.Toolkit.Suite.Extended.Software.Updater.NetSparkle
{
/// <summary>
/// This class handles all registry values which are used from sparkle to handle
/// update intervalls. All values are stored in HKCU\Software\Vendor\AppName which
/// will be read ot from the assembly information. All values are of the REG_SZ
/// type, no matter what their "logical" type is. The following options are
/// available:
///
/// CheckForUpdate - Boolean - Whether NetSparkle should check for updates
/// LastCheckTime - time_t - Time of last check
/// SkipThisVersion - String - If the user skipped an update, then the version to ignore is stored here (e.g. "1.4.3")
/// DidRunOnce - Boolean - Check only one time when the app launched
/// </summary>
public class RegistryConfiguration : Configuration
{
private const string DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
private string _registryPath;
/// <summary>
/// The constructor reads out all configured values
/// </summary>
/// <param name="referenceAssembly">the reference assembly name</param>
public RegistryConfiguration(string referenceAssembly)
: this(referenceAssembly, true)
{ }
/// <inheritdoc/>
public RegistryConfiguration(string referenceAssembly, bool isReflectionBasedAssemblyAccessorUsed)
: this(referenceAssembly, isReflectionBasedAssemblyAccessorUsed, string.Empty)
{ }
/// <summary>
/// Constructor
/// </summary>
/// <param name="referenceAssembly">the name of hte reference assembly</param>
/// <param name="isReflectionBasedAssemblyAccessorUsed"><c>true</c> if reflection is used to access the assembly.</param>
/// <param name="registryPath"><c>true</c> if reflection is used to access the assembly.</param>
public RegistryConfiguration(string referenceAssembly, bool isReflectionBasedAssemblyAccessorUsed, string registryPath)
: base(referenceAssembly, isReflectionBasedAssemblyAccessorUsed)
{
_registryPath = registryPath;
try
{
// build the reg path
string regPath = BuildRegistryPath();
// load the values
LoadValuesFromPath(regPath);
}
catch (NetSparkleException)
{
// disable update checks when exception was called
CheckForUpdate = false;
throw;
}
}
/// <summary>
/// Touches to profile time
/// </summary>
public override void TouchProfileTime()
{
base.TouchProfileTime();
// save the values
SaveValuesToPath(BuildRegistryPath());
}
/// <summary>
/// Touches the check time to now, should be used after a check directly
/// </summary>
public override void TouchCheckTime()
{
base.TouchCheckTime();
// save the values
SaveValuesToPath(BuildRegistryPath());
}
/// <summary>
/// This method allows to skip a specific version
/// </summary>
/// <param name="version">the version to skeip</param>
public override void SetVersionToSkip(string version)
{
base.SetVersionToSkip(version);
SaveValuesToPath(BuildRegistryPath());
}
/// <summary>
/// Reloads the configuration object
/// </summary>
public override void Reload()
{
LoadValuesFromPath(BuildRegistryPath());
}
/// <summary>
/// This function build a valid registry path in dependecy to the
/// assembly information
/// </summary>
public virtual string BuildRegistryPath()
{
if (!string.IsNullOrEmpty(_registryPath))
{
return _registryPath;
}
else
{
AssemblyAccessor accessor = new AssemblyAccessor(ReferenceAssembly, UseReflectionBasedAssemblyAccessor);
if (string.IsNullOrEmpty(accessor.AssemblyCompany) || string.IsNullOrEmpty(accessor.AssemblyProduct))
{
throw new NetSparkleException("Error: NetSparkle is missing the company or productname tag in " + ReferenceAssembly);
}
_registryPath = "Software\\" + accessor.AssemblyCompany + "\\" + accessor.AssemblyProduct + "\\AutoUpdate";
return _registryPath;
}
}
private string ConvertDateToString(DateTime dt)
{
return dt.ToString(DateTimeFormat, CultureInfo.InvariantCulture);
}
private DateTime ConvertStringToDate(string str)
{
return DateTime.ParseExact(str, DateTimeFormat, CultureInfo.InvariantCulture);
}
/// <summary>
/// This method loads the values from registry
/// </summary>
/// <param name="regPath">the registry path</param>
/// <returns><c>true</c> if the items were loaded</returns>
private bool LoadValuesFromPath(string regPath)
{
RegistryKey key = Registry.CurrentUser.OpenSubKey(regPath);
if (key == null)
{
SaveDidRunOnceAsTrue(regPath);
return false;
}
else
{
// read out
string strCheckForUpdate = key.GetValue("CheckForUpdate", "True") as string;
string strLastCheckTime = key.GetValue("LastCheckTime", ConvertDateToString(new DateTime(0))) as string;
string strSkipThisVersion = key.GetValue("SkipThisVersion", "") as string;
string strDidRunOnc = key.GetValue("DidRunOnce", "False") as string;
string strProfileTime = key.GetValue("LastProfileUpdate", ConvertDateToString(new DateTime(0))) as string;
string strPreviousVersion = key.GetValue("PreviousVersionRun", "") as string;
// convert the right datatypes
CheckForUpdate = Convert.ToBoolean(strCheckForUpdate);
try
{
LastCheckTime = ConvertStringToDate(strLastCheckTime);
}
catch (FormatException)
{
LastCheckTime = new DateTime(0);
}
LastVersionSkipped = strSkipThisVersion;
DidRunOnce = Convert.ToBoolean(strDidRunOnc);
IsFirstRun = !DidRunOnce;
PreviousVersionOfSoftwareRan = strPreviousVersion;
if (IsFirstRun)
{
SaveDidRunOnceAsTrue(regPath);
}
else
{
SaveValuesToPath(regPath); // so PreviousVersionRun is saved
}
try
{
LastConfigUpdate = ConvertStringToDate(strProfileTime);
}
catch (FormatException)
{
LastConfigUpdate = new DateTime(0);
}
}
return true;
}
private void SaveDidRunOnceAsTrue(string regPath)
{
var initialValue = DidRunOnce;
DidRunOnce = true;
SaveValuesToPath(regPath); // save it so next time we load DidRunOnce is true
DidRunOnce = initialValue; // so data is correct to user of Configuration class
}
/// <summary>
/// This method store the information into registry
/// </summary>
/// <param name="regPath">the registry path</param>
/// <returns><c>true</c> if the values were saved to the registry</returns>
private bool SaveValuesToPath(string regPath)
{
RegistryKey key = Registry.CurrentUser.CreateSubKey(regPath);
if (key == null)
{
return false;
}
// convert to regsz
string strCheckForUpdate = true.ToString(); // always check for updates next time!
string strLastCheckTime = ConvertDateToString(LastCheckTime);
string strSkipThisVersion = LastVersionSkipped;
string strDidRunOnc = DidRunOnce.ToString();
string strProfileTime = ConvertDateToString(LastConfigUpdate);
string strPreviousVersion = InstalledVersion;
// set the values
key.SetValue("CheckForUpdate", strCheckForUpdate, RegistryValueKind.String);
key.SetValue("LastCheckTime", strLastCheckTime, RegistryValueKind.String);
key.SetValue("SkipThisVersion", strSkipThisVersion, RegistryValueKind.String);
key.SetValue("DidRunOnce", strDidRunOnc, RegistryValueKind.String);
key.SetValue("LastProfileUpdate", strProfileTime, RegistryValueKind.String);
key.SetValue("PreviousVersionRun", strPreviousVersion, RegistryValueKind.String);
return true;
}
}
} | 40.194093 | 137 | 0.584506 | [
"BSD-3-Clause"
] | Krypton-Suite/Extended-Toolk | Source/Krypton Toolkit/Main/Krypton.Toolkit.Suite.Extended.Software.Updater/NetSparkle/Core/Configurations/RegistryConfiguration.cs | 9,528 | C# |
// <copyright file="AssemblyInfo.cs" company="OpenCensus Authors">
// Copyright 2018, OpenCensus Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System.Runtime.CompilerServices;
[assembly: System.CLSCompliant(true)]
[assembly: InternalsVisibleTo("OpenCensus.Exporter.Stackdriver.Tests" + AssemblyInfo.PublicKey)]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2" + AssemblyInfo.MoqPublicKey)]
#if SIGNED
internal static class AssemblyInfo
{
public const string PublicKey = ", PublicKey=002400000480000094000000060200000024000052534131000400000100010051C1562A090FB0C9F391012A32198B5E5D9A60E9B80FA2D7B434C9E5CCB7259BD606E66F9660676AFC6692B8CDC6793D190904551D2103B7B22FA636DCBB8208839785BA402EA08FC00C8F1500CCEF28BBF599AA64FFB1E1D5DC1BF3420A3777BADFE697856E9D52070A50C3EA5821C80BEF17CA3ACFFA28F89DD413F096F898";
public const string MoqPublicKey = ", PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7";
}
#else
internal static class AssemblyInfo
{
public const string PublicKey = "";
public const string MoqPublicKey = "";
}
#endif
| 50.72973 | 374 | 0.837507 | [
"Apache-2.0"
] | fhalim/opencensus-csharp | src/OpenCensus.Exporter.Stackdriver/AssemblyInfo.cs | 1,879 | C# |
////////////////////////////////
//
// Copyright 2018 Battelle Energy Alliance, LLC
//
//
////////////////////////////////
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DataLayer
{
using System;
using System.Collections.Generic;
public partial class VIEW_QUESTIONS_STATUS
{
public int Question_Or_Requirement_Id { get; set; }
public Nullable<bool> HasComment { get; set; }
public Nullable<bool> MarkForReview { get; set; }
public Nullable<bool> HasDocument { get; set; }
public int docnum { get; set; }
public Nullable<bool> HasDiscovery { get; set; }
public int findingnum { get; set; }
public int Assessment_Id { get; set; }
public int Answer_Id { get; set; }
}
}
| 32.277778 | 85 | 0.518933 | [
"MIT"
] | Harshilpatel134/cisagovdocker | CSETWebApi/CSETWeb_Api/DataLayer/VIEW_QUESTIONS_STATUS.cs | 1,162 | C# |
using UnityEngine;
using UnityEngine.UI;
namespace Nobi.UiRoundedCorners {
[ExecuteInEditMode]
[RequireComponent(typeof(RectTransform))]
public class ImageWithRoundedCorners : MonoBehaviour {
private static int Props;
public float radius;
private Material material;
[HideInInspector, SerializeField] private Image image;
private void Awake()
{
Props = Shader.PropertyToID("_WidthHeightRadius");
}
private void OnValidate() {
Validate();
Refresh();
}
private void OnDestroy() {
DestroyHelper.Destroy(material);
image = null;
material = null;
}
private void OnEnable() {
Validate();
Refresh();
}
private void OnRectTransformDimensionsChange() {
if (enabled && material != null) {
Refresh();
}
}
public void Validate() {
if (material == null) {
var shader = Shader.Find("UI/RoundedCorners/RoundedCorners");
if (shader == null)
shader = MeatKitPlugin.bundle.LoadAsset<Shader>("RoundedCorners");
material = new Material(shader);
}
if (image == null) {
image = GetComponent<Image>();
}
if (image != null) {
image.material = material;
}
}
public void Refresh() {
var rect = ((RectTransform)transform).rect;
material.SetVector(Props, new Vector4(rect.width, rect.height, radius, 0));
}
}
} | 22.015385 | 86 | 0.614955 | [
"MIT"
] | muskit/H3VR-Desktop-Freecam | Assets/Unity-UI-Rounded-Corners/UiRoundedCorners/ImageWithRoundedCorners.cs | 1,433 | C# |
using NuPattern;
using NuPattern.Diagnostics;
using NuPattern.Runtime;
using NuPattern.Runtime.ToolkitInterface;
using NuPattern.Runtime.Validation;
using ServiceStackToolkit.Automation.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
namespace ServiceStackToolkit.Automation.ValidationRules
{
/// <summary>
/// A custom element validation rule that verifies instances of elements.
/// </summary>
[DisplayName(@"Resource Verb Has ID RequestField")]
[Category("ServiceStack Toolkit")]
[Description(@"Validates that the Verb (if GET, PUT, DELETE) has an Id request field.")]
[CLSCompliant(false)]
public class VerbIdRequestFieldValidator : ValidationRule
{
private const string IdFieldName = @"Id";
private static readonly ITracer tracer = Tracer.Get<VerbIdRequestFieldValidator>();
/// <summary>
/// Gets or sets the current element to validate.
/// </summary>
[Required]
[Import(AllowDefault = true)]
public IProductElement CurrentElement
{
get;
set;
}
/// <summary>
/// Evaluates the violations for the rule.
/// </summary>
/// <remarks></remarks>
public override IEnumerable<ValidationResult> Validate()
{
var errors = new List<ValidationResult>();
this.ValidateObject();
tracer.Info(
"Validating VerbIdRequestFieldValidator on current element '{0}'", this.CurrentElement.InstanceName);
var verb = this.CurrentElement.As<IVerb>();
var hasIdRequestField = (verb.RequestContract != null)
&& verb.RequestContract.RequestFields.Any(rf => rf.InstanceName.Equals(IdFieldName, StringComparison.InvariantCulture)
&& rf.DataType.Equals(typeof(string).FullName, StringComparison.OrdinalIgnoreCase));
if (((verb.VerbType.Equals("GET") && !verb.HasMany)
|| (verb.VerbType.Equals("PUT")
|| verb.VerbType.Equals("DELETE"))) && !hasIdRequestField)
{
errors.Add(new ValidationResult(
string.Format(CultureInfo.CurrentCulture, Resources.VerbIdRequestFieldValidator_IdRequestFieldMissing,
this.CurrentElement.InstanceName, IdFieldName, typeof(string).FullName)));
}
tracer.Info(
"Validated VerbIdRequestFieldValidator on current element '{0}', as '{1}'", this.CurrentElement.InstanceName, !errors.Any());
return errors;
}
}
}
| 37.472973 | 141 | 0.647313 | [
"Unlicense"
] | jezzsantos/servicestacktoolkit | src/ServiceStackToolkit.Automation/ValidationRules/VerbIdRequestFieldValidator.cs | 2,775 | C# |
using Microsoft.AspNetCore.Builder;
namespace Ocelot.Headers.Middleware
{
public static class ClaimsToHeadersMiddlewareExtensions
{
public static IApplicationBuilder UseClaimsToHeadersMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<ClaimsToHeadersMiddleware>();
}
}
}
| 26.615385 | 104 | 0.736994 | [
"MIT"
] | Amoeslund/Ocelot | src/Ocelot/Headers/Middleware/ClaimsToHeadersMiddlewareExtensions.cs | 348 | C# |
using CleanArchitecture.Application.Common.Interfaces;
using CleanArchitecture.Domain.Common;
using MassTransit;
using Microsoft.Extensions.Logging;
namespace CleanArchitecture.Infrastructure.Services;
public class DomainEventService : IDomainEventService
{
private readonly ILogger<DomainEventService> _logger;
private readonly IPublishEndpoint _publishEndpoint;
public DomainEventService(ILogger<DomainEventService> logger, IPublishEndpoint publishEndpoint)
{
_logger = logger;
_publishEndpoint = publishEndpoint;
}
public async Task Publish(DomainEvent domainEvent)
{
_logger.LogInformation("Publishing domain event. Event - {Event}", domainEvent.GetType().Name);
await _publishEndpoint.Publish(domainEvent, domainEvent.GetType());
}
} | 33.625 | 103 | 0.774473 | [
"MIT"
] | suleymanozev/CleanArchitecture | src/Infrastructure/Services/DomainEventService.cs | 809 | C# |
namespace Unosquare.Net
{
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
#if SSL
using System.Security.Cryptography.X509Certificates;
#endif
internal sealed class HttpConnection
{
internal const int BufferSize = 8192;
private readonly Timer _timer;
private readonly EndPointListener _epl;
private Socket _sock;
private MemoryStream _ms;
private byte[] _buffer;
private HttpListenerContext _context;
private StringBuilder _currentLine;
private RequestStream _iStream;
private ResponseStream _oStream;
private bool _contextBound;
private int _sTimeout = 90000; // 90k ms for first request, 15k ms from then on
private IPEndPoint _localEp;
private HttpListener _lastListener;
private InputState _inputState = InputState.RequestLine;
private LineState _lineState = LineState.None;
private int _position;
#if SSL
private X509Certificate _cert;
IMonoSslStream ssl_stream;
#endif
#if SSL
public HttpConnection(Socket sock, EndPointListener epl, bool secure, X509Certificate cert)
#else
public HttpConnection(Socket sock, EndPointListener epl)
#endif
{
_sock = sock;
_epl = epl;
#if SSL
IsSecure = secure;
if (!secure)
{
Stream = new NetworkStream(sock, false);
}
else
{
_cert = cert;
ssl_stream = epl.Listener.CreateSslStream(new NetworkStream(sock, false), false, (t, c, ch, e) =>
{
if (c == null)
return true;
var c2 = c as X509Certificate2;
if (c2 == null)
c2 = new X509Certificate2(c.GetRawCertData());
client_cert = c2;
client_cert_errors = new int[] { (int)e };
return true;
});
stream = ssl_stream.AuthenticatedStream;
}
#else
Stream = new NetworkStream(sock, false);
#endif
_timer = new Timer(OnTimeout, null, Timeout.Infinite, Timeout.Infinite);
Init();
}
#if SSL
internal int[] ClientCertificateErrors { get; }
internal X509Certificate2 ClientCertificate { get; }
#endif
public int Reuses { get; private set; }
public Stream Stream { get; }
public IPEndPoint LocalEndPoint => _localEp ?? (_localEp = (IPEndPoint)_sock.LocalEndPoint);
public IPEndPoint RemoteEndPoint => (IPEndPoint)_sock?.RemoteEndPoint;
#if SSL
public bool IsSecure { get; }
#endif
public ListenerPrefix Prefix { get; set; }
public async Task BeginReadRequest()
{
if (_buffer == null)
_buffer = new byte[BufferSize];
try
{
if (Reuses == 1)
_sTimeout = 15000;
_timer.Change(_sTimeout, Timeout.Infinite);
var data = await Stream.ReadAsync(_buffer, 0, BufferSize).ConfigureAwait(false);
await OnReadInternal(data).ConfigureAwait(false);
}
catch
{
_timer.Change(Timeout.Infinite, Timeout.Infinite);
CloseSocket();
Unbind();
}
}
public RequestStream GetRequestStream(long contentLength)
{
if (_iStream != null) return _iStream;
var buffer = _ms.ToArray();
var length = (int) _ms.Length;
_ms = null;
_iStream = new RequestStream(Stream, buffer, _position, length - _position, contentLength);
return _iStream;
}
public ResponseStream GetResponseStream() => _oStream ??
(_oStream =
new ResponseStream(Stream, _context.HttpListenerResponse, _context.Listener?.IgnoreWriteExceptions ?? true));
internal void Close(bool forceClose = false)
{
if (_sock != null)
{
GetResponseStream()?.Dispose();
_oStream = null;
}
if (_sock == null) return;
forceClose |= !_context.Request.KeepAlive;
if (!forceClose)
forceClose = _context.Response.Headers["connection"] == "close";
if (!forceClose)
{
if (_context.HttpListenerRequest.FlushInput().GetAwaiter().GetResult())
{
Reuses++;
Unbind();
Init();
#pragma warning disable 4014
BeginReadRequest();
#pragma warning restore 4014
return;
}
}
var s = _sock;
_sock = null;
try
{
s?.Shutdown(SocketShutdown.Both);
}
catch
{
// ignored
}
finally
{
s?.Dispose();
}
Unbind();
RemoveConnection();
}
private void Init()
{
#if SSL
if (ssl_stream != null)
{
ssl_stream.AuthenticateAsServer(cert, true, (SslProtocols)ServicePointManager.SecurityProtocol, false);
}
#endif
_contextBound = false;
_iStream = null;
_oStream = null;
Prefix = null;
_ms = new MemoryStream();
_position = 0;
_inputState = InputState.RequestLine;
_lineState = LineState.None;
_context = new HttpListenerContext(this);
}
private void OnTimeout(object unused)
{
CloseSocket();
Unbind();
}
private async Task OnReadInternal(int offset)
{
_timer.Change(Timeout.Infinite, Timeout.Infinite);
// Continue reading until full header is received.
// Especially important for multipart requests when the second part of the header arrives after a tiny delay
// because the web browser has to measure the content length first.
var parsedBytes = 0;
while (true)
{
try
{
await _ms.WriteAsync(_buffer, parsedBytes, offset - parsedBytes).ConfigureAwait(false);
if (_ms.Length > 32768)
{
Close(true);
return;
}
}
catch
{
CloseSocket();
Unbind();
return;
}
if (offset == 0)
{
CloseSocket();
Unbind();
return;
}
if (ProcessInput(_ms))
{
if (!_context.HaveError)
_context.HttpListenerRequest.FinishInitialization();
if (_context.HaveError || !_epl.BindContext(_context))
{
Close(true);
return;
}
var listener = _context.Listener;
if (_lastListener != listener)
{
RemoveConnection();
listener.AddConnection(this);
_lastListener = listener;
}
_contextBound = true;
listener.RegisterContext(_context);
return;
}
parsedBytes = offset;
offset += await Stream.ReadAsync(_buffer, offset, BufferSize - offset).ConfigureAwait(false);
}
}
private void RemoveConnection()
{
if (_lastListener == null)
_epl.RemoveConnection(this);
else
_lastListener.RemoveConnection(this);
}
// true -> done processing
// false -> need more input
private bool ProcessInput(MemoryStream ms)
{
var buffer = ms.ToArray();
var len = (int)ms.Length;
var used = 0;
while (true)
{
if (_context.HaveError)
return true;
if (_position >= len)
break;
string line;
try
{
line = ReadLine(buffer, _position, len - _position, ref used);
_position += used;
}
catch
{
_context.ErrorMessage = "Bad request";
return true;
}
if (line == null)
break;
if (line == string.Empty)
{
if (_inputState == InputState.RequestLine)
continue;
_currentLine = null;
return true;
}
if (_inputState == InputState.RequestLine)
{
_context.HttpListenerRequest.SetRequestLine(line);
_inputState = InputState.Headers;
}
else
{
try
{
_context.HttpListenerRequest.AddHeader(line);
}
catch (Exception e)
{
_context.ErrorMessage = e.Message;
return true;
}
}
}
if (used == len)
{
ms.SetLength(0);
_position = 0;
}
return false;
}
private string ReadLine(byte[] buffer, int offset, int len, ref int used)
{
if (_currentLine == null)
_currentLine = new StringBuilder(128);
var last = offset + len;
used = 0;
for (var i = offset; i < last && _lineState != LineState.Lf; i++)
{
used++;
var b = buffer[i];
switch (b)
{
case 13:
_lineState = LineState.Cr;
break;
case 10:
_lineState = LineState.Lf;
break;
default:
_currentLine.Append((char)b);
break;
}
}
if (_lineState != LineState.Lf) return null;
_lineState = LineState.None;
var result = _currentLine.ToString();
_currentLine.Length = 0;
return result;
}
private void Unbind()
{
if (!_contextBound) return;
_epl.UnbindContext(_context);
_contextBound = false;
}
private void CloseSocket()
{
if (_sock == null)
return;
try
{
_sock.Dispose();
}
finally
{
_sock = null;
}
RemoveConnection();
}
private enum InputState
{
RequestLine,
Headers,
}
private enum LineState
{
None,
Cr,
Lf,
}
}
} | 28.397163 | 166 | 0.449883 | [
"MIT"
] | ThomasPiskol/embedio | src/Unosquare.Labs.EmbedIO/System.Net/HttpConnection.cs | 12,014 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Riganti.Selenium.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotVVM.Testing.Abstractions;
namespace DotVVM.Samples.Tests.Complex
{
[TestClass]
public class DataTemplateTests : AppSeleniumTest
{
[TestMethod]
public void Complex_EmptyDataTemplate_RepeaterGridView()
{
RunInAllBrowsers(browser => {
browser.NavigateToUrl(SamplesRouteUrls.ComplexSamples_EmptyDataTemplate_RepeaterGridView);
browser.Wait();
void isDisplayed(string id) => browser.CheckIfIsDisplayed("#" + id);
void isHidden(string id) => browser.CheckIfIsNotDisplayed("#" + id);
void isNotPresent(string id) => browser.FindElements("#" + id + " > *").ThrowIfDifferentCountThan(0);
isHidden("marker1_parent");
isDisplayed("marker1");
isNotPresent("marker2_parent");
isDisplayed("marker2");
isHidden("marker3_parent");
isDisplayed("marker3");
isNotPresent("marker4_parent");
isDisplayed("marker4");
isDisplayed("nonempty_marker1_parent");
isHidden("nonempty_marker1");
isDisplayed("nonempty_marker2_parent");
isNotPresent("nonempty_marker2");
isDisplayed("nonempty_marker3_parent");
isHidden("nonempty_marker3");
isDisplayed("nonempty_marker4_parent");
isNotPresent("nonempty_marker4");
isHidden("null_marker1_parent");
isDisplayed("null_marker1");
isNotPresent("null_marker2_parent");
isDisplayed("null_marker2");
isHidden("null_marker3_parent");
isDisplayed("null_marker3");
isNotPresent("null_marker4_parent");
isDisplayed("null_marker4");
});
}
}
}
| 32.4 | 117 | 0.593067 | [
"Apache-2.0"
] | adamjez/dotvvm | src/DotVVM.Samples.Tests/Complex/DataTemplateTests.cs | 2,108 | C# |
using System;
using System.Data;
using System.Data.SqlClient;
using HRM.BOL;
namespace HRM.DAL
{
public class AssetTypesDAL
{
public int Save(AssetTypesBOL objAlw)
{
DataAccess objDA = new DataAccess();
SqlParameter[] objParam = new SqlParameter[4];
int i = -1;
try
{
objParam[++i] = new SqlParameter("@AssetTypeID", objAlw.AssetTypeID);
objParam[++i] = new SqlParameter("@AssetType", objAlw.AssetType);
objParam[++i] = new SqlParameter("@CreatedBy", objAlw.CreatedBy);
objParam[++i] = new SqlParameter("@Status", "Y");
objDA.sqlCmdText = "hrm_AssetTypes_INSERT_UPDATE";
objDA.sqlParam = objParam;
return int.Parse(objDA.ExecuteScalar().ToString());
}
catch (Exception ex)
{
throw ex;
}
}
public int Delete(int nAlwID)
{
DataAccess objDA = new DataAccess();
SqlParameter[] objParam = new SqlParameter[1];
try
{
objParam[0] = new SqlParameter("@AssetTypeID", nAlwID);
objDA.sqlCmdText = "hrm_AssetTypes_DELETE";
objDA.sqlParam = objParam;
return objDA.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
}
public DataTable SelectAll(int nAlwID)
{
DataAccess objDA = new DataAccess();
SqlParameter[] objParam = new SqlParameter[1];
try
{
if (nAlwID > 0)
{
objParam[0] = new SqlParameter("@AssetTypeID", nAlwID);
objDA.sqlParam = objParam;
}
objDA.sqlCmdText = "hrm_AssetTypes_SELECT";
return objDA.ExecuteDataSet().Tables[0];
}
catch (Exception ex)
{
throw ex;
}
}
}
}
| 29.106667 | 86 | 0.462666 | [
"MIT"
] | jencyraj/HumanResourceManagementProject | src/HRM.DAL/AssetTypesDAL.cs | 2,185 | 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 transfer-2018-11-05.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.Transfer.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Transfer.Model.Internal.MarshallTransformations
{
/// <summary>
/// WorkflowStep Marshaller
/// </summary>
public class WorkflowStepMarshaller : IRequestMarshaller<WorkflowStep, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(WorkflowStep requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetCopyStepDetails())
{
context.Writer.WritePropertyName("CopyStepDetails");
context.Writer.WriteObjectStart();
var marshaller = CopyStepDetailsMarshaller.Instance;
marshaller.Marshall(requestObject.CopyStepDetails, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetCustomStepDetails())
{
context.Writer.WritePropertyName("CustomStepDetails");
context.Writer.WriteObjectStart();
var marshaller = CustomStepDetailsMarshaller.Instance;
marshaller.Marshall(requestObject.CustomStepDetails, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetDeleteStepDetails())
{
context.Writer.WritePropertyName("DeleteStepDetails");
context.Writer.WriteObjectStart();
var marshaller = DeleteStepDetailsMarshaller.Instance;
marshaller.Marshall(requestObject.DeleteStepDetails, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetTagStepDetails())
{
context.Writer.WritePropertyName("TagStepDetails");
context.Writer.WriteObjectStart();
var marshaller = TagStepDetailsMarshaller.Instance;
marshaller.Marshall(requestObject.TagStepDetails, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetType())
{
context.Writer.WritePropertyName("Type");
context.Writer.Write(requestObject.Type);
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static WorkflowStepMarshaller Instance = new WorkflowStepMarshaller();
}
} | 34.09434 | 106 | 0.640841 | [
"Apache-2.0"
] | EbstaLimited/aws-sdk-net | sdk/src/Services/Transfer/Generated/Model/Internal/MarshallTransformations/WorkflowStepMarshaller.cs | 3,614 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Musics___Server.Usersinfos;
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using Utility.Musics;
using Utility.Network;
using Utility.Network.Users;
namespace Musics___Server.Usersinfos.Tests
{
[TestClass()]
public class UsersInfosTests
{
[TestMethod()]
public void CreateVoteByNodeTest()
{
//3f8c88f5cad87ebbae3ad701842c876e
Authentification.AuthentificationService a = new Authentification.AuthentificationService();
a.SetupAuth();
a.SignupUser(new Utility.Network.Users.CryptedCredentials("User1", "abc"));
XmlDocument doc = new XmlDocument();
doc.Load(@"users.xml");
XmlNodeList nodes = doc.DocumentElement.SelectNodes("User");
UsersInfos.CreateVoteByNode("MusicMID", doc, nodes[0]);
doc.Save(@"users.xml");
Assert.AreEqual("3f8c88f5cad87ebbae3ad701842c876e", Function.GetMD5(@"users.xml"));
}
[TestMethod()]
public void RemoveVoteByNodeTest()
{
//e0424ec3aad221f0f22836728db397f7
Authentification.AuthentificationService a = new Authentification.AuthentificationService();
a.SetupAuth();
a.SignupUser(new Utility.Network.Users.CryptedCredentials("User1", "abc"));
XmlDocument doc = new XmlDocument();
doc.Load(@"users.xml");
XmlNodeList nodes = doc.DocumentElement.SelectNodes("User");
UsersInfos.CreateVoteByNode("MusicMID", doc, nodes[0]);
UsersInfos.RemoveVoteByNode("MusicMID", nodes[0]);
doc.Save(@"users.xml");
Assert.AreEqual("e0424ec3aad221f0f22836728db397f7", Function.GetMD5(@"users.xml"));
}
[TestMethod()]
public void AddVoteMusicTest()
{
Authentification.AuthentificationService a = new Authentification.AuthentificationService();
a.SetupAuth();
a.SignupUser(new Utility.Network.Users.CryptedCredentials("User1", "abc"));
UsersInfos.AddVoteMusic("MusicMID", "abC");
Assert.AreEqual("e0c5d6856147fbaf2888fc1720e9f7c8", Function.GetMD5(@"users.xml"));
UsersInfos.AddVoteMusic("MusicMID", "abc");
Assert.AreEqual("3f8c88f5cad87ebbae3ad701842c876e", Function.GetMD5(@"users.xml"));
UsersInfos.AddVoteMusic("MusicMID", "abc");
Assert.AreEqual("e0424ec3aad221f0f22836728db397f7", Function.GetMD5(@"users.xml"));
}
[TestMethod()]
public void VoteExistTest()
{
Authentification.AuthentificationService a = new Authentification.AuthentificationService();
a.SetupAuth();
a.SignupUser(new Utility.Network.Users.CryptedCredentials("User1", "abc"));
Assert.AreEqual(false, UsersInfos.VoteExist("IncorrectMID", "abc"));
Assert.AreEqual(false, UsersInfos.VoteExist("MusicMID", "IncorrectUID"));
Assert.AreEqual(false, UsersInfos.VoteExist("MusicMID", "abc"));
UsersInfos.AddVoteMusic("MusicMID", "abc");
Assert.AreEqual(false, UsersInfos.VoteExist("IncorrectMID", "abc"));
Assert.AreEqual(false, UsersInfos.VoteExist("MusicMID", "IncorrectUID"));
Assert.AreEqual(true, UsersInfos.VoteExist("MusicMID", "abc"));
}
[TestMethod()]
public void GetAllUsersTest()
{
Authentification.AuthentificationService a = new Authentification.AuthentificationService();
a.SetupAuth();
a.SignupUser(new Utility.Network.Users.CryptedCredentials("User1", "abc"));
a.SignupUser(new Utility.Network.Users.CryptedCredentials("User2", "abc2"));
var getall = UsersInfos.GetAllUsers();
Assert.AreEqual(true, getall[0].Name == "User1");
Assert.AreEqual(true, getall[0].UID == "abc");
Assert.AreEqual(true, getall[1].Name == "User2");
Assert.AreEqual(true, getall[1].UID == "abc2");
}
[TestMethod()]
public void GetUserTest()
{
Authentification.AuthentificationService a = new Authentification.AuthentificationService();
a.SetupAuth();
a.SignupUser(new Utility.Network.Users.CryptedCredentials("User1", "abc"));
var getuser = UsersInfos.GetUser("abc");
Assert.AreEqual(true, getuser.Name == "User1");
Assert.AreEqual(true, getuser.UID == "abc");
var getuser2 = UsersInfos.GetUser("abC");
Assert.AreEqual(true, getuser2 == null);
}
[TestMethod()]
public void SearchUserTest()
{
Authentification.AuthentificationService a = new Authentification.AuthentificationService();
a.SetupAuth();
a.SignupUser(new Utility.Network.Users.CryptedCredentials("User1", "abc"));
var getuser = UsersInfos.SearchUser("User1");
Assert.AreEqual(true, getuser[0].Name == "User1");
Assert.AreEqual(true, getuser[0].UID == "abc");
}
[TestMethod()]
public void GetRankOfUserTest()
{
Authentification.AuthentificationService a = new Authentification.AuthentificationService();
a.SetupAuth();
a.SignupUser(new Utility.Network.Users.CryptedCredentials("User1", "abc"));
Assert.AreEqual(true, UsersInfos.GetRankOfUser("abc") == Rank.Viewer);
Assert.AreEqual(true, UsersInfos.GetRankOfUser("abC") == Rank.Viewer);//TODO: add some test for other rank
}
[TestCleanup]
public void TestCleanup()
{
File.Delete(@"users.xml");
}
[TestMethod()]
public void SetRankOfUserTest()
{
//59fdab60bac3fb5c3bdf9e8cb772e637
Authentification.AuthentificationService a = new Authentification.AuthentificationService();
a.SetupAuth();
a.SignupUser(new Utility.Network.Users.CryptedCredentials("User1", "abc"));
UsersInfos.SetRankOfUser("abc", Rank.Creator);
Assert.AreEqual("59fdab60bac3fb5c3bdf9e8cb772e637", Function.GetMD5(@"users.xml"));
}
[Obsolete]
//[TestMethod()]
public void SaveUserPlaylistTest()
{
//76fdfae945157b5ec9732d9416c080c4
Authentification.AuthentificationService a = new Authentification.AuthentificationService();
a.SetupAuth();
User ur = new User(new Utility.Network.Users.CryptedCredentials("User1", "abc"));
a.SignupUser(ur);
var m = new Music("Music1", new Author("Albert", "path2"), new Album(new Author("Albert", "path2"), "AlbertAlum"), "path", 0);
Playlist pl = new Playlist(ur, "Playlist1", new List<Music>() { m }, false)
{
Rating = 1
};
UsersInfos.SaveUserPlaylist("abc", pl);
Assert.AreEqual("76fdfae945157b5ec9732d9416c080c4", Function.GetMD5(@"users.xml"));
}
//[TestMethod()]
[Obsolete]
public void RatePlaylistTest()
{
//2e1047e01b9f0d927651f33ec8ddce63
Authentification.AuthentificationService a = new Authentification.AuthentificationService();
a.SetupAuth();
User ur = new User(new Utility.Network.Users.CryptedCredentials("User1", "abc"));
a.SignupUser(ur);
var m = new Music("Music1", new Author("Albert", "path2"), new Album(new Author("Albert", "path2"), "AlbertAlum"), "path", 0);
Playlist pl = new Playlist(ur, "Playlist1", new List<Music>() { m }, false)
{
Rating = 1
};
UsersInfos.SaveUserPlaylist("abc", pl);
UsersInfos.RatePlaylist(pl.MID, false);
Assert.AreEqual("2e1047e01b9f0d927651f33ec8ddce63", Function.GetMD5(@"users.xml"));
UsersInfos.RatePlaylist(pl.MID, true);
Assert.AreEqual("76fdfae945157b5ec9732d9416c080c4", Function.GetMD5(@"users.xml"));
}
}
} | 41.459596 | 138 | 0.615057 | [
"MIT"
] | MalauD/Musics-Free-musics-player | Musics - ServerTests/Users/UsersInfosTests.cs | 8,211 | C# |
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace Smellyriver.TankInspector.Common.Wpf.Behaviors.DragDrop
{
public class DropTargetInsertionAdorner : DropTargetAdorner
{
public DropTargetInsertionAdorner(UIElement adornedElement)
: base(adornedElement)
{
}
protected override void OnRender(DrawingContext drawingContext)
{
ItemsControl itemsControl = this.DropInfo.VisualTarget as ItemsControl;
if (itemsControl != null)
{
// Get the position of the item at the insertion index. If the insertion point is
// to be after the last item, then get the position of the last item and add an
// offset later to draw it at the end of the list.
ItemsControl itemParent;
if (this.DropInfo.VisualTargetItem != null)
{
itemParent = ItemsControl.ItemsControlFromItemContainer(this.DropInfo.VisualTargetItem);
}
else
{
itemParent = itemsControl;
}
int index = Math.Min(this.DropInfo.InsertIndex, itemParent.Items.Count - 1);
UIElement itemContainer = (UIElement)itemParent.ItemContainerGenerator.ContainerFromIndex(index);
if (itemContainer != null)
{
Rect itemRect = new Rect(itemContainer.TranslatePoint(new Point(), AdornedElement),
itemContainer.RenderSize);
Point point1, point2;
double rotation = 0;
if (this.DropInfo.VisualTargetOrientation == Orientation.Vertical)
{
if (this.DropInfo.InsertIndex == itemParent.Items.Count)
{
itemRect.Y += itemContainer.RenderSize.Height;
}
point1 = new Point(itemRect.X, itemRect.Y);
point2 = new Point(itemRect.Right, itemRect.Y);
}
else
{
if (this.DropInfo.InsertIndex == itemParent.Items.Count)
{
itemRect.X += itemContainer.RenderSize.Width;
}
point1 = new Point(itemRect.X, itemRect.Y);
point2 = new Point(itemRect.X, itemRect.Bottom);
rotation = 90;
}
drawingContext.DrawLine(m_Pen, point1, point2);
DrawTriangle(drawingContext, point1, rotation);
DrawTriangle(drawingContext, point2, 180 + rotation);
}
}
}
void DrawTriangle(DrawingContext drawingContext, Point origin, double rotation)
{
drawingContext.PushTransform(new TranslateTransform(origin.X, origin.Y));
drawingContext.PushTransform(new RotateTransform(rotation));
drawingContext.DrawGeometry(m_Pen.Brush, null, m_Triangle);
drawingContext.Pop();
drawingContext.Pop();
}
static DropTargetInsertionAdorner()
{
// Create the pen and triangle in a static constructor and freeze them to improve performance.
const int triangleSize = 3;
m_Pen = new Pen(Brushes.Gray, 2);
m_Pen.Freeze();
LineSegment firstLine = new LineSegment(new Point(0, -triangleSize), false);
firstLine.Freeze();
LineSegment secondLine = new LineSegment(new Point(0, triangleSize), false);
secondLine.Freeze();
PathFigure figure = new PathFigure { StartPoint = new Point(triangleSize, 0) };
figure.Segments.Add(firstLine);
figure.Segments.Add(secondLine);
figure.Freeze();
m_Triangle = new PathGeometry();
m_Triangle.Figures.Add(figure);
m_Triangle.Freeze();
}
static Pen m_Pen;
static PathGeometry m_Triangle;
}
}
| 37.223214 | 113 | 0.556009 | [
"MIT"
] | smellyriver/tank-inspector-pro | src/Smellyriver.TankInspector.Common.Wpf/Behaviors/DragDrop/DropTargetInsertionAdorner.cs | 4,171 | C# |
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace StackExchange.Redis.Tests
{
public class Failover : TestBase, IAsyncLifetime
{
protected override string GetConfiguration() => GetMasterReplicaConfig().ToString();
public Failover(ITestOutputHelper output) : base(output)
{
}
public Task DisposeAsync() => Task.CompletedTask;
public async Task InitializeAsync()
{
using (var mutex = Create())
{
var shouldBeMaster = mutex.GetServer(TestConfig.Current.FailoverMasterServerAndPort);
if (shouldBeMaster.IsReplica)
{
Log(shouldBeMaster.EndPoint + " should be master, fixing...");
shouldBeMaster.MakeMaster(ReplicationChangeOptions.SetTiebreaker);
}
var shouldBeReplica = mutex.GetServer(TestConfig.Current.FailoverReplicaServerAndPort);
if (!shouldBeReplica.IsReplica)
{
Log(shouldBeReplica.EndPoint + " should be a replica, fixing...");
shouldBeReplica.ReplicaOf(shouldBeMaster.EndPoint);
await Task.Delay(2000).ForAwait();
}
}
}
private static ConfigurationOptions GetMasterReplicaConfig()
{
return new ConfigurationOptions
{
AllowAdmin = true,
SyncTimeout = 100000,
EndPoints =
{
{ TestConfig.Current.FailoverMasterServer, TestConfig.Current.FailoverMasterPort },
{ TestConfig.Current.FailoverReplicaServer, TestConfig.Current.FailoverReplicaPort },
}
};
}
[Fact]
public async Task ConfigureAsync()
{
using (var muxer = Create())
{
await Task.Delay(1000).ForAwait();
Log("About to reconfigure.....");
await muxer.ConfigureAsync().ForAwait();
Log("Reconfigured");
}
}
[Fact]
public async Task ConfigureSync()
{
using (var muxer = Create())
{
await Task.Delay(1000).ForAwait();
Log("About to reconfigure.....");
muxer.Configure();
Log("Reconfigured");
}
}
[Fact]
public async Task ConfigVerifyReceiveConfigChangeBroadcast()
{
_ = GetConfiguration();
using (var sender = Create(allowAdmin: true))
using (var receiver = Create(syncTimeout: 2000))
{
int total = 0;
receiver.ConfigurationChangedBroadcast += (s, a) =>
{
Log("Config changed: " + (a.EndPoint == null ? "(none)" : a.EndPoint.ToString()));
Interlocked.Increment(ref total);
};
// send a reconfigure/reconnect message
long count = sender.PublishReconfigure();
GetServer(receiver).Ping();
GetServer(receiver).Ping();
await Task.Delay(1000).ConfigureAwait(false);
Assert.True(count == -1 || count >= 2, "subscribers");
Assert.True(Interlocked.CompareExchange(ref total, 0, 0) >= 1, "total (1st)");
Interlocked.Exchange(ref total, 0);
// and send a second time via a re-master operation
var server = GetServer(sender);
if (server.IsReplica) Skip.Inconclusive("didn't expect a replica");
server.MakeMaster(ReplicationChangeOptions.Broadcast);
await Task.Delay(1000).ConfigureAwait(false);
GetServer(receiver).Ping();
GetServer(receiver).Ping();
Assert.True(Interlocked.CompareExchange(ref total, 0, 0) >= 1, "total (2nd)");
}
}
[Fact]
public async Task DereplicateGoesToPrimary()
{
ConfigurationOptions config = GetMasterReplicaConfig();
config.ConfigCheckSeconds = 5;
using (var conn = ConnectionMultiplexer.Connect(config))
{
var primary = conn.GetServer(TestConfig.Current.FailoverMasterServerAndPort);
var secondary = conn.GetServer(TestConfig.Current.FailoverReplicaServerAndPort);
primary.Ping();
secondary.Ping();
primary.MakeMaster(ReplicationChangeOptions.SetTiebreaker);
secondary.MakeMaster(ReplicationChangeOptions.None);
await Task.Delay(100).ConfigureAwait(false);
primary.Ping();
secondary.Ping();
using (var writer = new StringWriter())
{
conn.Configure(writer);
string log = writer.ToString();
Writer.WriteLine(log);
bool isUnanimous = log.Contains("tie-break is unanimous at " + TestConfig.Current.FailoverMasterServerAndPort);
if (!isUnanimous) Skip.Inconclusive("this is timing sensitive; unable to verify this time");
}
// k, so we know everyone loves 6379; is that what we get?
var db = conn.GetDatabase();
RedisKey key = Me();
Assert.Equal(primary.EndPoint, db.IdentifyEndpoint(key, CommandFlags.PreferMaster));
Assert.Equal(primary.EndPoint, db.IdentifyEndpoint(key, CommandFlags.DemandMaster));
Assert.Equal(primary.EndPoint, db.IdentifyEndpoint(key, CommandFlags.PreferReplica));
var ex = Assert.Throws<RedisConnectionException>(() => db.IdentifyEndpoint(key, CommandFlags.DemandReplica));
Assert.StartsWith("No connection is active/available to service this operation: EXISTS " + Me(), ex.Message);
Writer.WriteLine("Invoking MakeMaster()...");
primary.MakeMaster(ReplicationChangeOptions.Broadcast | ReplicationChangeOptions.ReplicateToOtherEndpoints | ReplicationChangeOptions.SetTiebreaker, Writer);
Writer.WriteLine("Finished MakeMaster() call.");
await Task.Delay(100).ConfigureAwait(false);
Writer.WriteLine("Invoking Ping() (post-master)");
primary.Ping();
secondary.Ping();
Writer.WriteLine("Finished Ping() (post-master)");
Assert.True(primary.IsConnected, $"{primary.EndPoint} is not connected.");
Assert.True(secondary.IsConnected, $"{secondary.EndPoint} is not connected.");
Writer.WriteLine($"{primary.EndPoint}: {primary.ServerType}, Mode: {(primary.IsReplica ? "Replica" : "Master")}");
Writer.WriteLine($"{secondary.EndPoint}: {secondary.ServerType}, Mode: {(secondary.IsReplica ? "Replica" : "Master")}");
// Create a separate multiplexer with a valid view of the world to distinguish between failures of
// server topology changes from failures to recognize those changes
Writer.WriteLine("Connecting to secondary validation connection.");
using (var conn2 = ConnectionMultiplexer.Connect(config))
{
var primary2 = conn2.GetServer(TestConfig.Current.FailoverMasterServerAndPort);
var secondary2 = conn2.GetServer(TestConfig.Current.FailoverReplicaServerAndPort);
Writer.WriteLine($"Check: {primary2.EndPoint}: {primary2.ServerType}, Mode: {(primary2.IsReplica ? "Replica" : "Master")}");
Writer.WriteLine($"Check: {secondary2.EndPoint}: {secondary2.ServerType}, Mode: {(secondary2.IsReplica ? "Replica" : "Master")}");
Assert.False(primary2.IsReplica, $"{primary2.EndPoint} should be a master (verification connection).");
Assert.True(secondary2.IsReplica, $"{secondary2.EndPoint} should be a replica (verification connection).");
var db2 = conn2.GetDatabase();
Assert.Equal(primary2.EndPoint, db2.IdentifyEndpoint(key, CommandFlags.PreferMaster));
Assert.Equal(primary2.EndPoint, db2.IdentifyEndpoint(key, CommandFlags.DemandMaster));
Assert.Equal(secondary2.EndPoint, db2.IdentifyEndpoint(key, CommandFlags.PreferReplica));
Assert.Equal(secondary2.EndPoint, db2.IdentifyEndpoint(key, CommandFlags.DemandReplica));
}
await UntilCondition(TimeSpan.FromSeconds(20), () => !primary.IsReplica && secondary.IsReplica);
Assert.False(primary.IsReplica, $"{primary.EndPoint} should be a master.");
Assert.True(secondary.IsReplica, $"{secondary.EndPoint} should be a replica.");
Assert.Equal(primary.EndPoint, db.IdentifyEndpoint(key, CommandFlags.PreferMaster));
Assert.Equal(primary.EndPoint, db.IdentifyEndpoint(key, CommandFlags.DemandMaster));
Assert.Equal(secondary.EndPoint, db.IdentifyEndpoint(key, CommandFlags.PreferReplica));
Assert.Equal(secondary.EndPoint, db.IdentifyEndpoint(key, CommandFlags.DemandReplica));
}
}
#if DEBUG
[Fact]
public async Task SubscriptionsSurviveMasterSwitchAsync()
{
void TopologyFail() => Skip.Inconclusive("Replication tolopogy change failed...and that's both inconsistent and not what we're testing.");
if (RunningInCI)
{
Skip.Inconclusive("TODO: Fix race in broadcast reconfig a zero latency.");
}
using (var a = Create(allowAdmin: true, shared: false))
using (var b = Create(allowAdmin: true, shared: false))
{
RedisChannel channel = Me();
Log("Using Channel: " + channel);
var subA = a.GetSubscriber();
var subB = b.GetSubscriber();
long masterChanged = 0, aCount = 0, bCount = 0;
a.ConfigurationChangedBroadcast += delegate
{
Log("A noticed config broadcast: " + Interlocked.Increment(ref masterChanged));
};
b.ConfigurationChangedBroadcast += delegate
{
Log("B noticed config broadcast: " + Interlocked.Increment(ref masterChanged));
};
subA.Subscribe(channel, (_, message) =>
{
Log("A got message: " + message);
Interlocked.Increment(ref aCount);
});
subB.Subscribe(channel, (_, message) =>
{
Log("B got message: " + message);
Interlocked.Increment(ref bCount);
});
Assert.False(a.GetServer(TestConfig.Current.FailoverMasterServerAndPort).IsReplica, $"A Connection: {TestConfig.Current.FailoverMasterServerAndPort} should be a master");
if (!a.GetServer(TestConfig.Current.FailoverReplicaServerAndPort).IsReplica)
{
TopologyFail();
}
Assert.True(a.GetServer(TestConfig.Current.FailoverReplicaServerAndPort).IsReplica, $"A Connection: {TestConfig.Current.FailoverReplicaServerAndPort} should be a replica");
Assert.False(b.GetServer(TestConfig.Current.FailoverMasterServerAndPort).IsReplica, $"B Connection: {TestConfig.Current.FailoverMasterServerAndPort} should be a master");
Assert.True(b.GetServer(TestConfig.Current.FailoverReplicaServerAndPort).IsReplica, $"B Connection: {TestConfig.Current.FailoverReplicaServerAndPort} should be a replica");
Log("Failover 1 Complete");
var epA = subA.SubscribedEndpoint(channel);
var epB = subB.SubscribedEndpoint(channel);
Log(" A: " + EndPointCollection.ToString(epA));
Log(" B: " + EndPointCollection.ToString(epB));
subA.Publish(channel, "A1");
subB.Publish(channel, "B1");
Log(" SubA ping: " + subA.Ping());
Log(" SubB ping: " + subB.Ping());
// If redis is under load due to this suite, it may take a moment to send across.
await UntilCondition(TimeSpan.FromSeconds(5), () => Interlocked.Read(ref aCount) == 2 && Interlocked.Read(ref bCount) == 2).ForAwait();
Assert.Equal(2, Interlocked.Read(ref aCount));
Assert.Equal(2, Interlocked.Read(ref bCount));
Assert.Equal(0, Interlocked.Read(ref masterChanged));
try
{
Interlocked.Exchange(ref masterChanged, 0);
Interlocked.Exchange(ref aCount, 0);
Interlocked.Exchange(ref bCount, 0);
Log("Changing master...");
using (var sw = new StringWriter())
{
a.GetServer(TestConfig.Current.FailoverReplicaServerAndPort).MakeMaster(ReplicationChangeOptions.All, sw);
Log(sw.ToString());
}
Log("Waiting for connection B to detect...");
await UntilCondition(TimeSpan.FromSeconds(10), () => b.GetServer(TestConfig.Current.FailoverMasterServerAndPort).IsReplica).ForAwait();
subA.Ping();
subB.Ping();
Log("Falover 2 Attempted. Pausing...");
Log(" A " + TestConfig.Current.FailoverMasterServerAndPort + " status: " + (a.GetServer(TestConfig.Current.FailoverMasterServerAndPort).IsReplica ? "Replica" : "Master"));
Log(" A " + TestConfig.Current.FailoverReplicaServerAndPort + " status: " + (a.GetServer(TestConfig.Current.FailoverReplicaServerAndPort).IsReplica ? "Replica" : "Master"));
Log(" B " + TestConfig.Current.FailoverMasterServerAndPort + " status: " + (b.GetServer(TestConfig.Current.FailoverMasterServerAndPort).IsReplica ? "Replica" : "Master"));
Log(" B " + TestConfig.Current.FailoverReplicaServerAndPort + " status: " + (b.GetServer(TestConfig.Current.FailoverReplicaServerAndPort).IsReplica ? "Replica" : "Master"));
if (!a.GetServer(TestConfig.Current.FailoverMasterServerAndPort).IsReplica)
{
TopologyFail();
}
Log("Falover 2 Complete.");
Assert.True(a.GetServer(TestConfig.Current.FailoverMasterServerAndPort).IsReplica, $"A Connection: {TestConfig.Current.FailoverMasterServerAndPort} should be a replica");
Assert.False(a.GetServer(TestConfig.Current.FailoverReplicaServerAndPort).IsReplica, $"A Connection: {TestConfig.Current.FailoverReplicaServerAndPort} should be a master");
await UntilCondition(TimeSpan.FromSeconds(10), () => b.GetServer(TestConfig.Current.FailoverMasterServerAndPort).IsReplica).ForAwait();
var sanityCheck = b.GetServer(TestConfig.Current.FailoverMasterServerAndPort).IsReplica;
if (!sanityCheck)
{
Log("FAILURE: B has not detected the topology change.");
foreach (var server in b.GetServerSnapshot().ToArray())
{
Log(" Server" + server.EndPoint);
Log(" State: " + server.ConnectionState);
Log(" IsReplica: " + !server.IsReplica);
Log(" Type: " + server.ServerType);
}
//Skip.Inconclusive("Not enough latency.");
}
Assert.True(sanityCheck, $"B Connection: {TestConfig.Current.FailoverMasterServerAndPort} should be a replica");
Assert.False(b.GetServer(TestConfig.Current.FailoverReplicaServerAndPort).IsReplica, $"B Connection: {TestConfig.Current.FailoverReplicaServerAndPort} should be a master");
Log("Pause complete");
Log(" A outstanding: " + a.GetCounters().TotalOutstanding);
Log(" B outstanding: " + b.GetCounters().TotalOutstanding);
subA.Ping();
subB.Ping();
await Task.Delay(5000).ForAwait();
epA = subA.SubscribedEndpoint(channel);
epB = subB.SubscribedEndpoint(channel);
Log("Subscription complete");
Log(" A: " + EndPointCollection.ToString(epA));
Log(" B: " + EndPointCollection.ToString(epB));
var aSentTo = subA.Publish(channel, "A2");
var bSentTo = subB.Publish(channel, "B2");
Log(" A2 sent to: " + aSentTo);
Log(" B2 sent to: " + bSentTo);
subA.Ping();
subB.Ping();
Log("Ping Complete. Checking...");
await UntilCondition(TimeSpan.FromSeconds(10), () => Interlocked.Read(ref aCount) == 2 && Interlocked.Read(ref bCount) == 2).ForAwait();
Log("Counts so far:");
Log(" aCount: " + Interlocked.Read(ref aCount));
Log(" bCount: " + Interlocked.Read(ref bCount));
Log(" masterChanged: " + Interlocked.Read(ref masterChanged));
Assert.Equal(2, Interlocked.Read(ref aCount));
Assert.Equal(2, Interlocked.Read(ref bCount));
// Expect 10, because a sees a, but b sees a and b due to replication
Assert.Equal(10, Interlocked.CompareExchange(ref masterChanged, 0, 0));
}
catch
{
LogNoTime("");
Log("ERROR: Something went bad - see above! Roooooolling back. Back it up. Baaaaaack it on up.");
LogNoTime("");
throw;
}
finally
{
Log("Restoring configuration...");
try
{
a.GetServer(TestConfig.Current.FailoverMasterServerAndPort).MakeMaster(ReplicationChangeOptions.All);
await Task.Delay(1000).ForAwait();
}
catch { /* Don't bomb here */ }
}
}
}
#endif
}
}
| 51.615804 | 194 | 0.559785 | [
"Apache-2.0"
] | alexSatov/StackExchange.Redis | tests/StackExchange.Redis.Tests/Failover.cs | 18,945 | C# |
namespace Seed.Models.V1.DTOs
{
public class UserToSignInDto
{
public string EmailAddress { get; set; }
public string Password { get; set; }
}
}
| 19.333333 | 48 | 0.614943 | [
"MIT"
] | HeyBaldur/CoRM | Seed.Models/V1/DTOs/UserToSignInDto.cs | 176 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using static QuickInfo.NodeFactory;
namespace QuickInfo
{
public class AirportCodes : IProcessor
{
private (string, int)[] airportsIndex;
public AirportCodes()
{
airportsIndex = SortedSearch.CreateIndex(data.Select((t, i) => (t, i)), a => GetFields(a));
}
public object GetResult(Query query)
{
if (query.IsHelp)
{
return HelpTable(
("LAX", "Airport code"));
}
var input = query.OriginalInputTrim;
if (string.Equals(input, "color", StringComparison.OrdinalIgnoreCase))
{
return null;
}
if (input.Length == 3 && input.IsSingleWord())
{
int index = SortedSearch.FindItem(data, input, t => t.code);
if (index >= 0 && index < data.Length)
{
return Airport(index);
}
}
if (input.Length >= 3)
{
var airports = GetAirports(input.SplitIntoWords());
if (airports != null)
{
return airports;
}
}
return null;
}
private object GetAirports(IEnumerable<string> words)
{
if (words.Count() > 4)
{
return null;
}
var positions = SortedSearch.FindItems(airportsIndex, words, t => t.Item1, t => t.Item2);
if (positions.Any())
{
var airports = positions
.OrderBy(i => i)
.Take(10)
.Select(i => Airport(i))
.ToArray();
return airports;
}
return null;
}
private object Airport(int index)
{
var result = new List<object>();
var airport = data[index];
var name = airport.englishName;
if (name == "")
{
name = airport.name;
}
result.Add(SectionHeader(name));
var location = airport.city1;
if (airport.state != "")
{
location = location + ", " + airport.state;
}
location = location + ", " + airport.country;
result.Add(location);
result.Add(Answer("Airport code: " + airport.code.ToUpperInvariant()));
var link = "https://airportcod.es/#airport/" + airport.code;
result.Add(Hyperlink(link));
return result;
}
private IEnumerable<string> GetFields((string code, string name, string englishName, string state, string country, string city1, string city2, string city3) a)
{
yield return a.code;
if (a.city1 != "")
{
yield return a.city1;
}
if (a.city2 != "")
{
yield return a.city2;
}
if (a.city3 != "")
{
yield return a.city3;
}
if (a.state != "")
{
yield return a.state;
}
if (a.country != "")
{
yield return a.country;
}
var name = a.englishName;
if (name == "")
{
name = a.name;
}
foreach (var word in name.SplitIntoWords())
{
yield return word;
}
}
// taken from the awesome https://airportcod.es/ with permission from Lynn Fisher:
// https://twitter.com/lynnandtonic/status/970365291954806784
private static readonly (string code, string name, string englishName, string state, string country, string city1, string city2, string city3)[] data =
{
("aal", "Aalborg Lufthavn", "Aalborg Airport", "", "Denmark", "Aalborg", "Nørresundby", ""),
("aar", "Aarhus Airport", "", "", "Denmark", "Aarhus", "Tirstrup", ""),
("aba", "Abakan International Airport", "", "", "Russia", "Abakan", "", ""),
("abc", "Aeropuerto de Albacete", "Albacete Airport", "", "Spain", "Albacete", "Castilla-La Mancha", ""),
("abe", "Lehigh Valley International Airport", "", "Pennsylvania", "USA", "Allentown", "", ""),
("abi", "Abilene Regional Airport", "", "Texas", "USA", "Abilene", "", ""),
("abj", "Aéroport International Félix Houphouët-Boigny", "Félix Houphouët-Boigny International Airport", "", "Ivory Coast", "Abidjan", "Port-Bouet", "Côte d'Ivoire"),
("abq", "Albuquerque International Sunport", "", "New Mexico", "USA", "Albuquerque", "", ""),
("abv", "Nnamdi Azikiwe International Airport", "", "", "Nigeria", "Abuja", "", ""),
("abz", "Aberdeen International Airport", "", "Scotland", "UK", "Aberdeen", "Dyce", ""),
("aca", "Aeropuerto Internacional General Juan N. Álvarez", "General Juan N. Álvarez International Airport", "Guerrero", "Mexico", "Acapulco", "", ""),
("acc", "Kotoka International Airport", "Kotoka International Airport", "", "Ghana", "Accra", "", ""),
("ace", "Aeropuerto de Lanzarote", "Lanzarote Airport", "Canary Islands", "Spain", "Lanzarote", "Arrecife", "San Bartolomé"),
("ack", "Nantucket Memorial Airport", "", "Massachusetts", "USA", "Nantucket", "", ""),
("acy", "Atlantic City International Airport", "", "New Jersey", "USA", "Atlantic City", "Egg Harbor Township", ""),
("add", "Addis Ababa Bole International Airport", "", "", "Ethiopia", "Addis Ababa", "Bole", ""),
("adl", "Adelaide Airport", "", "South Australia", "Australia", "Adelaide", "", ""),
("aep", "Aeroparque Jorge Newbery", "Jorge Newbery Airfield", "", "Argentina", "Buenos Aires", "Palermo", ""),
("aer", "Sochi International Airport", "", "", "Russia", "Sochi", "", ""),
("aes", "Ålesund lufthavn, Vigra", "Alesund Airport, Vigra", "", "Norway", "Ålesund", "Vigra", ""),
("aex", "Alexandria International Airport", "", "Louisiana", "USA", "Alexandria", "", ""),
("aga", "Agadir–Al Massira Airport", "", "", "Morocco", "Agadir", "", ""),
("agb", "Flughafen Augsburg", "Augsburg Airport", "", "Germany", "Augsburg", "Affing", ""),
("agc", "Allegheny County Airport", "", "Pennsylvania", "USA", "West Mifflin", "Pittsburgh", ""),
("agp", "Aeropuerto de Málaga-Costa del Sol", "Málaga–Costa del Sol Airport", "", "Spain", "Málaga", "Costa del Sol", ""),
("ags", "Augusta Regional Airport", "", "Georgia", "USA", "Augusta", "", ""),
("agu", "Aeropuerto Internacional Lic. Jesús Terán Peredo", "Lic. Jesús Terán Peredo International Airport", "AG", "Mexico", "Aguascalientes", "", ""),
("ahb", "Abha Regional Airport", "", "Asir Province", "Saudi Arabia", "Abha", "", ""),
("ajf", "Al-Jawf Domestic Airport", "", "Al Jawf Province", "Saudi Arabia", "Sakakah", "Al-Jawf", ""),
("ajl", "Lengpui Airport", "", "Mizoram", "India", "Aizawl", "Aijal", ""),
("aju", "Aeroporto Aracaju–Santa Maria", "Aracaju–Santa Maria Airport", "Sergipe", "Brazil", "Aracaju", "", ""),
("akc", "Akron Fulton International Airport", "", "Ohio", "USA", "Akron", "", ""),
("akl", "Auckland Airport", "", "", "New Zealand", "Auckland", "Mangere", ""),
("akx", "Aktobe Airport", "", "", "Kazakhstan", "Aktobe", "", ""),
("ala", "Almaty International Airport", "", "", "Kazakhstan", "Almaty", "", ""),
("alb", "Albany International Airport", "", "New York", "USA", "Albany", "Colonie", ""),
("alc", "Aeropuerto de Alicante-Elche", "Alicante–Elche Airport", "", "Spain", "Alicante", "Elche", "Valencia"),
("alg", "Houari Boumediene Airport", "", "", "Algeria", "Algiers", "", ""),
("ama", "Rick Husband Amarillo International Airport", "", "Texas", "USA", "Amarillo", "", ""),
("amd", "Sardar Vallabhbhai Patel International Airport", "", "Gujarat", "India", "Ahmedabad", "", ""),
("amm", "Queen Alia International Airport", "", "", "Jordan", "Amman", "Zizya", ""),
("amq", "Bandar Udara Pattimura", "Pattimura Airport", "Maluku", "Indonesia", "Ambon", "", ""),
("ams", "Luchthaven Schiphol", "Amsterdam Airport Schiphol", "", "Netherlands", "Amsterdam", "Haarlemmermeer", "Schiphol"),
("anc", "Ted Stevens Anchorage International Airport", "", "Alaska", "USA", "Anchorage", "", ""),
("ang", "Aéroport international d'Angoulême-Cognac", "Angoulême – Cognac International Airport", "", "France", "Angoulême", "Champniers", ""),
("anr", "Internationale Luchthaven Antwerpen", "Antwerp International Airport", "", "Belgium", "Antwerp", "Antwerpen", "Deurne"),
("ans", "Aeropuerto Andahuaylas", "Andahuaylas Airport", "Apurímac", "Peru", "Andahuaylas", "", ""),
("anu", "V. C. Bird International Airport", "", "", "Antigua and Barbuda", "Saint John’s", "", ""),
("aoi", "Aeroporto Raffaello Sanzio di Ancona-Falconara ", "Ancona Falconara Raffaello Sanzio Airport", "", "Italy", "Ancona", "Falconara Marittima", ""),
("apa", "Centennial Airport", "", "Colorado", "USA", "Denver", "Aurora", "Dove Valley"),
("apw", "Faleolo International Airport", "", "", "Samoa", "Apia", "", ""),
("aqj", "King Hussein International Airport", "", "", "Jordan", "Aqaba", "", ""),
("aqp", "Aeropuerto Internacional Alférez Alfredo Rodríguez Ballón", "Alférez Alfredo Rodríguez Ballón International Airport", "", "Peru", "Arequipa", "", ""),
("arn", "Stockholm-Arlanda flygplats", "Stockholm Arlanda Airport", "", "Sweden", "Stockholm", "Märsta", "Arlanda"),
("art", "Watertown International Airport", "", "New York", "USA", "Watertown", "", ""),
("asb", "Ashgabat International Airport", "", "", "Turkmenistan", "Ashgabat", "", ""),
("ase", "Aspen–Pitkin County Airport", "", "Colorado", "USA", "Aspen", "", ""),
("asm", "Asmara International Airport", "", "", "Eritrea", "Asmara", "", ""),
("asu", "Aeropuerto Internacional Silvio Pettirossi", "Silvio Pettirossi International Airport", "", "Paraguay", "Asunción", "Luque", ""),
("ata", "Aeropuerto Comandante FAP Germán Arias Graziani", "Comandante FAP Germán Arias Graziani Airport", "Ancash", "Peru", "Huaraz", "Anta", ""),
("ath", "Athens International Airport, Eleftherios Venizelos", "", "", "Greece", "Athens", "", ""),
("atl", "Hartsfield–Jackson International Airport", "", "Georgia", "USA", "Atlanta", "", ""),
("atq", "Sri Guru Ram Das Jee International Airport", "", "Punjab", "India", "Amritsar", "", ""),
("atw", "Appleton International Airport", "", "Wisconsin", "USA", "Appleton", "Greenville", ""),
("aua", "Internationale luchthaven Koningin Beatrix", "Queen Beatrix International Airport", "Aruba", "Netherlands", "Oranjestad", "", ""),
("auh", "Abu Dhabi International Airport", "", "", "United Arab Emirates", "Abu Dhabi", "", ""),
("aus", "Austin–Bergstrom International Airport", "", "Texas", "USA", "Austin", "", ""),
("avl", "Asheville Regional Airport", "", "North Carolina", "USA", "Asheville", "", ""),
("avp", "Wilkes-Barre/Scranton International Airport", "", "Pennsylvania", "USA", "Avoca", "Scranton", ""),
("awz", "Ahvaz International Airport", "", "", "Iran", "Ahvaz", "Ahwaz", ""),
("ayp", "Aeropuerto Coronel FAP Alfredo Mendívil Duarte", "Coronel FAP Alfredo Mendívil Duarte Airport", "", "Peru", "Ayacucho", "", ""),
("ayt", "Antalya Havalimanı", "Antalya Airport", "", "Turkey", "Antalya", "", ""),
("aza", "Phoenix-Mesa Gateway Airport", "", "Arizona", "USA", "Phoenix", "Mesa", ""),
("azo", "Kalamazoo/Battle Creek International Airport", "", "Michigan", "USA", "Kalamazoo", "Battle Creek", ""),
("bah", "Bahrain International Airport", "", "", "Bahrain", "Muharraq", "", ""),
("bal", "Batman Havaalanı", "Batman Airport", "", "Turkey", "Batman", "", ""),
("baq", "Aeropuerto Internacional Ernesto Cortissoz", "Ernesto Cortissoz International Airport", "", "Colombia", "Barranquilla", "Soledad", ""),
("bat", "Aeroporto Chafei Amsei", "Chafei Amsei Airport", "São Paulo", "Brazil", "Barretos", "", ""),
("bcb", "Virginia Tech Montgomery Executive Airport", "", "Virginia", "USA", "Blacksburg", "Christiansburg", ""),
("bcn", "Aeropuerto de Barcelona-El Prat", "Barcelona–El Prat Airport", "", "Spain", "Barcelona", "El Prat de Llobregat", ""),
("bda", "L.F. Wade International Airport", "", "", "UK", "Bermuda", "St. David's Island", ""),
("bdi", "Bird Island Airport", "", "", "Seychelles", "Bird Island", "", ""),
("bdl", "Bradley International Airport", "", "Connecticut", "USA", "Hartford", "Windsor Locks", "Springfield"),
("bdo", "Bandar Udara Internasional Husein Sastranegara", "Husein Sastranegara International Airport", "West Java", "Indonesia", "Bandung", "", ""),
("bds", "Brindisi - Aeroporto del Salento", "Brindisi - Salento Airport", "", "Italy", "Brindisi", "Salento", ""),
("beb", "Port-adhair Beinn na Faoghla", "Benbecula Airport", "Scotland", "UK", "Benbecula", "Balivanich", ""),
("bed", "Laurence G. Hanscom Field", "", "Massachusetts", "USA", "Bedford", "", ""),
("beg", "Aerodrom Beograd - Nikola Tesla", "Belgrade Nikola Tesla Airport", "", "Serbia", "Belgrade", "", ""),
("bel", "Aeroporto Internacional Júlio Cezar Ribeiro", "Júlio Cezar Ribeiro International Airport", "Pará", "Brazil", "Belém", "Val de Cans", ""),
("ber", "Flughafen Berlin Brandenburg ", "Berlin Brandenburg Airport", "", "Germany", "Berlin", "Schönefeld", "Brandenburg"),
("bey", "Beirut–Rafic Hariri International Airport", "", "", "Lebanon", "Beirut", "", ""),
("bff", "Western Nebraska Regional Airport", "", "Nebraska", "USA", "Scottsbluff", "", ""),
("bfi", "King County International Airport / Boeing Field", "", "Washington", "USA", "Seattle", "", ""),
("bfl", "Meadows Field Airport", "", "California", "USA", "Bakersfield ", "Oildale", ""),
("bfs", "Belfast International Airport", "", "Northern Ireland", "UK", "Belfast", "Aldergrove", ""),
("bga", "Aeropuerto Internacional de Palonegro", "Palonegro International Airport", "", "Colombia", "Bucaramanga", "Lebrija", ""),
("bgi", "Grantley Adams International Airport", "", "", "Barbados", "Bridgetown", "Seawell", "Christ Church"),
("bgo", "Bergen lufthavn, Flesland", "Bergen Airport, Flesland", "", "Norway", "Bergen", "Flesland", ""),
("bgr", "Bangor International Airport", "", "Maine", "USA", "Bangor", "", ""),
("bgw", "Baghdad International Airport", "", "", "Iraq", "Baghdad", "", ""),
("bgy", "Aeroporto di Bergamo-Orio al Serio Il Caravaggio", "Il Caravaggio International Airport", "", "Italy", "Bergamo", "Orio al Serio", "Milan"),
("bhd", "George Best Belfast City Airport", "", "Northern Ireland", "UK", "Belfast", "", ""),
("bhm", "Birmingham–Shuttlesworth International Airport", "", "Alabama", "USA", "Birmingham", "", ""),
("bhx", "Birmingham Airport", "", "England", "UK", "Birmingham", "", ""),
("bil", "Billings Logan International Airport", "", "Montana", "USA", "Billings", "", ""),
("bio", "Aeropuerto de Bilbao", "Bilbao Airport", "", "Spain", "Bilbao", "Biscay", ""),
("bjc", "Rocky Mountain Metropolitan Airport", "", "Colorado", "USA", "Denver", "", ""),
("bjl", "Banjul International Airport", "", "", "the Gambia", "Banjul", "", ""),
("bjm", "Aéroport international de Bujumbura", "Bujumbura International Airport", "", "Burundi", "Bujumbura", "", ""),
("bjx", "Aeropuerto Internacional de Guanajuato", "Guanajuato International Airport", "Guanajuato", "Mexico", "Guanajuato", "Silao", ""),
("bkf", "Lake Brooks Seaplane Base", "", "Alaska", "USA", "Katmai National Park", "Brooks Camp", ""),
("bki", "Lapangan Terbang Antarabangsa Kota Kinabalu", "Kota Kinabalu International Airport", "Sabah", "Malaysia", "Kota Kinabalu", "", ""),
("bkk", "Suvarnabhumi Airport", "", "", "Thailand", "Bangkok", "", ""),
("bko", "Aéroport international de Bamako–Sénou", "Bamako–Sénou International Airport", "", "Mali", "Bamako", "", ""),
("bli", "Bellingham International Airport", "", "Washington", "USA", "Bellingham", "", ""),
("blk", "Blackpool Airport", "", "England", "UK", "Blackpool", "", ""),
("blq", "Aeroporto di Bologna-Guglielmo Marconi", "Bologna Guglielmo Marconi Airport", "", "Italy", "Bologna", "", ""),
("blr", "Kempegowda International Airport", "", "Karnataka", "India", "Bengaluru", "Bangalore", "Devanahalli"),
("bma", "Stockholm-Bromma flygplats", "Stockholm Bromma Airport", "", "Sweden", "Stockholm", "Bromma", ""),
("bmi", "Central Illinois Regional Airport", "", "Illinois", "USA", "Bloomington", "", ""),
("bmv", "Sân bay Buôn Ma Thuột", "Buon Ma Thuot Airport", "", "Vietnam", "Buon Ma Thuot", "", ""),
("bna", "Nashville International Airport", "", "Tennessee", "USA", "Nashville", "", ""),
("bnd", "Bandar Abbas International Airport", "", "", "Iran", "Bandar Abbas", "", ""),
("bne", "Brisbane Airport", "", "Queensland", "Australia", "Brisbane", "", ""),
("bnx", "Banja Luka International Airport", "", "", "Bosnia and Herzegovina", "Banja Luka", "Mahovljani", ""),
("bob", "Bora Bora Airport", "", "French Polynesia", "France", "Bora Bora", "Motu Mute", ""),
("bod", "Aéroport de Bordeaux-Mérignac", "Bordeaux-Mérignac Airport", "", "France", "Bordeaux", "Mérignac", ""),
("bog", "Aeropuerto Internacional El Dorado", "El Dorado International Airport", "", "Colombia", "Bogotá", "", ""),
("boh", "Bournemouth Airport", "", "England", "UK", "Bournemouth", "Hurn", ""),
("boi", "Boise Airport", "", "Idaho", "USA", "Boise", "", ""),
("bom", "Chhatrapati Shivaji International Airport", "", "Maharashtra", "India", "Mumbai", "", ""),
("bon", "Luchthaven Flamingo", "Flamingo International Airport", "ABC islands", "Netherlands", "Bonaire", "Kralendijk", ""),
("bos", "Logan International Airport", "", "Massachusetts", "USA", "Boston", "Paradise", ""),
("bpn", "Bandar Udara Internasional Sultan Aji Muhammad Sulaiman", "Sultan Aji Muhammad Sulaiman International Airport", "", "Indonesia", "Balikpapan", "East Kalimantan", ""),
("bpt", "Jack Brooks Regional Airport", "", "Texas", "USA", "Beaumont", "Port Arthur", ""),
("bqh", "Biggin Hill Airport", "", "England", "UK", "London", "Bromley", ""),
("bra", "Aeroporto de Barreiras", "Barreiras Airport", "Bahia", "Brazil", "Barreiras", "", ""),
("bre", "Flughafen Bremen", "Bremen Airport", "", "Germany", "Bremen", "", ""),
("bro", "Brownsville/South Padre Island International Airport", "", "Texas", "USA", "Brownsville", "South Padre Island", ""),
("brq", "Letiště Brno–Tuřany", "Brno–Tuřany Airport", "", "Czech Republic", "Brno", "Tuřany", ""),
("brr", "Port-adhair Bharraigh", "Barra Airport", "Scotland", "UK", "Barra", "Outer Hebrides", ""),
("brs", "Bristol Airport", "", "England", "UK", "Bristol", "Lulsgate Bottom", ""),
("bru", "Luchthaven Brussel-Nationaal", "", "", "Belgium", "Brussels", "Zaventem", "Machelen"),
("brw", "Wiley Post–Will Rogers Memorial Airport", "", "Alaska", "USA", "Barrow", "", ""),
("bsb", "Aeroporto Internacional de Brasília–Pres. Juscelino Kubitschek", "Brasilia–Presidente Juscelino Kubitschek International Airport", "", "Brazil", "Brasília", "", ""),
("bsl", "EuroAirport Basel–Mulhouse–Freiburg", "", "France", "Switzerland", "Basel", "Saint-Louis", "Freiburg"),
("btj", "Bandar Udara Internasional Sultan Iskandar Muda", "Sultan Iskander Muda International Airport", "", "Indonesia", "Banda Aceh", "Blang Bintang", "Aceh Basar"),
("btm", "Bert Mooney Airport", "", "Montana", "USA", "Butte", "", ""),
("btr", "Baton Rouge Metropolitan Airport", "", "Louisiana", "USA", "Baton Rouge", "", ""),
("bts", "Letisko M. R. Štefánika", "M. R. Štefánik Airport", "", "Slovakia", "Bratislava", "", ""),
("btv", "Burlington International Airport", "", "Vermont", "USA", "Burlington", "", ""),
("bud", "Budapest Liszt Ferenc Nemzetközi Repülőtér", "Budapest Ferenc Liszt International Airport", "", "Hungary", "Budapest", "", ""),
("buf", "Buffalo Niagara International Airport", "", "New York", "USA", "Buffalo", "Cheektowaga", "Niagara Falls"),
("bur", "Bob Hope Airport", "", "California", "USA", "Burbank", "Los Angeles", "Hollywood"),
("but", "Bathpalathang Airport", "", "", "Bhutan", "Jakar", "", ""),
("bva", "Aéroport de Beauvais-Tillé", "Beauvais-Tillé Airport", "", "France", "Beauvais", "Tillé", ""),
("bvb", "Aeroporto International Atlas Brasil Cantanhede", "Atlas Brasil Cantanhede International Airport", "Roraima", "Brazil", "Boa Vista", "", ""),
("bvc", "Aeroporto Internacional Aristides Pereira", "Aristides Pereira International Airport", "", "Cape Verde", "Sal Rei", "Boa Vista", ""),
("bwe", "Flughafen Braunschweig-Wolfsburg", "Braunschweig-Wolfsburg Airport", "", "Germany", "Braunschweig", "", ""),
("bwi", "Baltimore/Washington International Thurgood Marshall Airport", "", "Maryland", "USA", "Baltimore", "Glen Burnie", "Washington D.C."),
("bwn", "Brunei International Airport", "", "", "Brunei", "Bandar Seri Begawan", "", ""),
("byj", "Aeroporto de Beja", "Beja Airport", "", "Portugal", "Beja", "", ""),
("bze", "Philip S. W. Goldson International Airport", "", "", "Belize", "Belize City", "Ladyville", ""),
("bzn", "Bozeman Yellowstone International Airport", "", "Montana", "USA", "Bozeman", "Belgrade", ""),
("bzv", "Maya-Maya Airport", "", "", "Republic of the Congo", "Brazzaville", "Congo", ""),
("cae", "Columbia Metropolitan Airport", "", "South Carolina", "USA", "Columbia", "Cayce", "Lexington County"),
("cah", "Sân bay Cà Mau", "Ca Mau Airport", "", "Vietnam", "Cà Mau", "", ""),
("cai", "Cairo International Airport", "", "", "Egypt", "Cairo", "", ""),
("cak", "Akron–Canton Airport", "", "Ohio", "USA", "Akron", "Canton", "Green"),
("can", "Guangzhou Baiyun International Airport", "", "Guangdong", "China", "Guangzhou", "", ""),
("cbb", "Aeropuerto Internacional Jorge Wilstermann", "Jorge Wilstermann International Airport", "", "Bolivia", "Cochabamba", "", ""),
("cbg", "Cambridge Airport", "", "England", "UK", "Cambridge", "Teversham", ""),
("cbr", "Canberra International Airport", "", "Australian Capital Territory", "Australia", "Canberra", "Queanbeyan", ""),
("ccf", "Aéroport de Carcassonne", "Carcassonne Airport", "", "France", "Carcassonne", "", ""),
("ccj", "Calicut International Airport", "", "Kerala", "India", "Karipur", "Kozhikode", "Malappuram"),
("cck", "Cocos (Keeling) Islands Airport", "", "Cocos (Keeling) Islands", "Australia", "West Island", "", ""),
("ccp", "Aeropuerto Carriel Sur", "Carriel Sur International Airport", "", "Chile", "Concepción", "", ""),
("ccs", "Aeropuerto Internacional de Maiquetia “Simón Bolívar”", "Simón Bolívar International Airport", "", "Venezuela", "Caracas", "Maiquetía", ""),
("ccu", "Netaji Subhas Chandra Bose International Airport", "", "West Bengal", "India", "Kolkata", "Calcutta", ""),
("cdg", "Aéroport de Paris-Charles-de-Gaulle", "Charles de Gaulle Airport", "", "France", "Paris", "", ""),
("ceb", "Paliparang Pandaigdig ng Mactan–Cebu", "Mactan–Cebu International Airport", "", "Philippines", "Cebu", "Lapu-Lapu City", "Mactan Island"),
("cek", "Chelyabinsk Airport", "", "", "Russia", "Chelyabinsk", "", ""),
("cfb", "Aeroporto Internacional de Cabo Frio", "Cabo Frio International Airport", "Rio de Janeiro", "Brazil", "Cabo Frio", "", ""),
("cfd", "Coulter Field", "", "Texas", "USA", "Bryan", "", ""),
("cgh", "Aeroporto de São Paulo/Congonhas", "Congonhas Airport", "São Paulo", "Brazil", "São Paulo", "Sao Paulo", ""),
("cgk", "Bandar Udara Internasional Soekarno–Hatta", "Soekarno–Hatta International Airport", "Banten", "Indonesia", "Jakarta", "Tangerang", "Jabodetabek"),
("cgn", "Flughafen Köln/Bonn", "Cologne Bonn Airport", "", "Germany", "Cologne", "Bonn", ""),
("cgr", "Aeroporto Internacional de Campo Grande", "Campo Grande International Airport", "Mato Grosso do Sul", "Brazil", "Campo Grande", "", ""),
("cha", "Chattanooga Metropolitan Airport", "", "Tennessee", "USA", "Chattanooga", "", ""),
("chc", "Christchurch International Airport", "", "", "New Zealand", "Christchurch", "Harewood", ""),
("chm", "Aeropuerto Teniente FAP Jaime Montreuil Morales", "Teniente FAP Jaime Montreuil Morales Airport", "Ancash", "Peru", "Chimbote", "", ""),
("chr", "Aéroport de Châteauroux-Centre", "Châteauroux-Centre Airport", "", "France", "Châteauroux", "", ""),
("chs", "Charleston International Airport", "", "South Carolina", "USA", "Charleston", "North Charleston", ""),
("cia", "Ciampino–Aeroporto Internazionale G. B. Pastine", "Ciampino–G. B. Pastine International Airport", "", "Italy", "Rome", "Ciampino", ""),
("cid", "The Eastern Iowa Airport", "", "Iowa", "USA", "Cedar Rapids", "", ""),
("cit", "Shymkent International Airport", "", "", "Kazakhstan", "Shymkent", "", ""),
("cix", "Aeropuerto Internacional Capitán FAP José Abelardo Quiñones Gonzáles", "Capitán FAP José Abelardo Quiñones Gonzáles International Airport", "Lambayeque", "Peru", "Chiclayo", "", ""),
("cja", "Aeropuerto Mayor General FAP Armando Revoredo Iglesias", "Mayor General FAP Armando Revoredo Iglesias Airport", "", "Peru", "Cajamarca", "", ""),
("cju", "Jeju International Airport", "", "Korea", "South Korea", "Jeju", "Cheju", ""),
("ckb", "North Central West Virginia Airport", "", "West Virginia", "USA", "Clarksburg", "Bridgeport", ""),
("ckg", "Chongqing Jiangbei International Airport", "", "Yubei District", "China", "Chongqing", "Jiangbei", ""),
("cky", "Conakry International Airport", "", "", "Guinea", "Conakry", "", ""),
("cld", "McClellan-Palomar Airport", "", "California", "USA", "Carlsbad", "", ""),
("cle", "Hopkins International Airport", "", "Ohio", "USA", "Cleveland", "", ""),
("clj", "Aeroportul International “Avram Iancu” Cluj", "Cluj International Airport", "", "Romania", "Cluj-Napoca", "", ""),
("cll", "Easterwood Airport", "", "Texas", "USA", "College Station", "", ""),
("clo", "Aeropuerto Internacional Alfonso Bonilla Aragón", "Alfonso Bonilla Aragón International Airport", "", "Colombia", "Santiago de Cali", "Cali", "Palmira"),
("clt", "Douglas International Airport", "", "North Carolina", "USA", "Charlotte", "", ""),
("cmb", "Bandaranaike International Airport", "", "Western Province", "Sri Lanka", "Colombo", "Katunayake", ""),
("cmh", "Port Columbus International Airport", "", "Ohio", "USA", "Columbus", "", ""),
("cmi", "University of Illinois Willard Airport", "", "Illinois", "USA", "Champaign-Urbana", "Savoy", ""),
("cmn", "Mohammed V International Airport", "", "", "Morocco", "Casablanca", "Nouasseur", "Nouaceur"),
("cmx", "Houghton County Memorial Airport", "", "Michigan", "USA", "Calumet", "", ""),
("cnf", "Aeroporto Internacional Tancredo Neves - Confins", "Tancredo Neves/Confins International Airport", "Minas Gerais", "Brazil", "Belo Horizonte", "Confins", ""),
("cng", "Base aérienne 709 Cognac-Châteaubernard", "Cognac – Châteaubernard Air Base", "", "France", "Cognac", "Châteaubernard", ""),
("cnx", "Chiang Mai International Airport", "", "", "Thailand", "Chiang Mai", "Lamphun", ""),
("cok", "Cochin International Airport", "", "Kerala", "India", "Kochi", "Cochin", ""),
("coo", "Aéroport International de Cotonou", "Cotonou International Airport", "", "Benin", "Cotonou", "", ""),
("cor", "Aeropuerto Internacional de Córdoba", "Ingeniero Aeronáutico Ambrosio L.V. Taravella International Airport", "", "Argentina", "Córdoba", "Cordoba", ""),
("cph", "Københavns Lufthavn, Kastrup", "Copenhagen Airport, Kastrup", "Tårnby", "Denmark", "Copenhagen", "Kastrup", ""),
("cpt", "Cape Town International Airport", "", "", "South Africa", "Cape Town", "", ""),
("cpv", "Aeroporto Presidente João Suassuna", "Presidente João Suassuna Airport", "Paraíba", "Brazil", "Campina Grande", "", ""),
("cqm", "Aeropuerto Central Ciudad Real", "Ciudad Real Central Airport", "", "Spain", "Ciudad Real", "Puertollano", ""),
("crk", "Paliparang Pandaigdig ng Clark", "Clark International Airport", "", "Philippines", "Manila", "Clark Freeport Zone", "Mabalacat City"),
("crl", "Aéroport de Charleroi Bruxelles Sud", "Brussels South Charleroi Airport", "", "Belgium", "Charleroi", "Gosselies", ""),
("crp", "Corpus Christi International Airport", "", "Texas", "USA", "Corpus Christi", "", ""),
("crw", "Yeager Airport", "", "West Virginia", "USA", "Charleston", "", ""),
("cta", "Aeroporto di Catania-Fontanarossa", "Catania–Fontanarossa Airport", "", "Italy", "Catania", "", ""),
("ctg", "Aeropuerto Internacional Rafael Núñez", "Rafael Núñez International Airport", "Bolívar", "Colombia", "Cartagena", "", ""),
("cts", "New Chitose Airport", "", "", "Japan", "Sapporo", "Chitose", "Tomakomai"),
("ctu", "Chengdu Shuangliu International Airport", "", "Sichuan", "China", "Chengdu", "Shuangliu", ""),
("cul", "Aeropuerto Internacional Federal de Bachigualato", "Bachigualato Federal International Airport", "Sinaloa", "Mexico", "Culiacán", "Navolato", ""),
("cun", "Aeropuerto Internacional de Cancún", "Cancún International Airport", "Quintana Roo", "Mexico", "Cancún", "", ""),
("cuz", "Aeropuerto Internacional Alejandro Velasco Astete", "Alejandro Velasco Astete International Airport", "", "Peru", "Cusco", "", ""),
("cvf", "Altiport de Courchevel", "Courchevel Altiport", "", "France", "Courchevel", "Saint-Bon-Tarentaise", "French Alps"),
("cvg", "Cincinnati/Northern Kentucky International Airport", "", "Kentucky", "USA", "Hebron", "Cincinnati", "Ohio"),
("cvu", "Aeródromo de Corvo", "Corvo Airport", "Azores", "Portugal", "Vila do Corvo", "Corvo", ""),
("cwb", "Aeroporto Internacional de Curitiba - Afonso Pena", "Afonso Pena International Airport", "Paraná", "Brazil", "Curitiba", "São José dos Pinhais", ""),
("cwl", "Maes Awyr Caerdydd", "Cardiff Airport", "Wales", "UK", "Cardiff", "", ""),
("cxr", "Sân bay Quốc tế Cam Ranh", "Cam Ranh International Airport", "", "Vietnam", "Khanh Hoa", "", ""),
("dab", "Daytona Beach International Airport", "", "Florida", "USA", "Daytona Beach", "", ""),
("dac", "Hazrat Shahjalal International Airport", "", "", "Bangladesh", "Dhaka", "Kurmitola", ""),
("dad", "Sân bay Quốc tế Đà Nẵng", "Da Nang International Airport", "", "Vietnam", "Da Nang", "", ""),
("dal", "Dallas Love Field", "", "Texas", "USA", "Dallas", "Fort Worth", "Arlington"),
("dam", "Damascus International Airport", "", "", "Syria", "Damascus", "", ""),
("dar", "Julius Nyerere International Airport", "", "", "Tanzania", "Dar es Salaam", "", ""),
("day", "James M. Cox Dayton International Airport", "", "Ohio", "USA", "Dayton", "", ""),
("dbq", "Dubuque Regional Airport", "", "Iowa", "USA", "Dubuque", "", ""),
("dbv", "Zračna luka Dubrovnik/Čilipi", "Dubrovnik Airport", "", "Croatia", "Dubrovnik", "Čilipi", ""),
("dca", "Ronald Reagan Washington National Airport", "", "Virginia", "USA", "Washington D.C.", "Arlington County", ""),
("deb", "Debreceni Nemzetközi Repülőtér", "Debrecen International Airport", "", "Hungary", "Debrecen", "", ""),
("del", "Indira Gandhi International Airport", "", "Delhi", "India", "New Delhi", "Delhi", ""),
("den", "Denver International Airport", "", "Colorado", "USA", "Denver", "", ""),
("det", "Coleman A. Young International Airport", "", "Michigan", "USA", "Detroit", "", ""),
("dfw", "Dallas/Fort Worth International Airport", "", "Texas", "USA", "Dallas–Fort Worth", "Fort Worth", ""),
("dil", "Aeroporto Internacional Presidente Nicolau Lobato", "Presidente Nicolau Lobato International Airport", "Timor-Leste", "East Timor", "Dili", "", ""),
("din", "Sân bay Điện Biên Phủ", "Dien Bien Phu Airport", "", "Vietnam", "Dien Bien Phu", "", ""),
("dkr", "Léopold Sédar Senghor International Airport", "", "", "Senegal", "Dakar", "Yoff", ""),
("dla", "Aéroport International de Douala", "Douala International Airport", "", "Cameroon", "Douala", "", ""),
("dlh", "Duluth International Airport", "", "Minnesota", "USA", "Duluth", "", ""),
("dme", "Domodedovo International Airport", "", "", "Russia", "Moscow", "", ""),
("dmk", "Don Mueang International Airport", "", "", "Thailand", "Bangkok", "Don Mueang", ""),
("dmm", "King Fahd International Airport", "", "Eastern Province", "Saudi Arabia", "Dammam", "", ""),
("dnd", "Port-adhair Dhùn Dèagh", "Dundee Airport", "Scotland", "UK", "Dundee", "", ""),
("dnk", "Dnipropetrovsk International Airport", "", "", "Ukraine", "Dnipropetrovsk", "", ""),
("dnr", "Aéroport de Dinard–Pleurtuit–Saint-Malo", "Dinard–Pleurtuit–Saint-Malo Airport", "", "France", "Saint-Malo", "Dinard", "Pleurtuit"),
("doh", "Hamad International Airport", "", "", "Qatar", "Doha", "", ""),
("dom", "Douglas–Charles Airport", "Melville Hall Airport", "", "Dominica", "Marigot", "Roseau", ""),
("dps", "Bandar Udara Internasional Ngurah Rai", "Ngurah Rai International Airport", "Bali", "Indonesia", "Denpasar", "Badung", ""),
("drw", "Darwin International Airport", "", "Northern Territory", "Australia", "Darwn", "Marrara", ""),
("dsa", "Robin Hood Airport Doncaster Sheffield", "", "England", "UK", "Finningley", "Doncaster", "Sheffield"),
("dsm", "Des Moines International Airport", "", "Iowa", "USA", "Des Moines", "", ""),
("dtm", "Flughafen Dortmund", "Dortmund Airport", "", "Germany", "Dortmund", "", ""),
("dtn", "Shreveport Downtown Airport", "", "Louisiana", "USA", "Shreveport", "", ""),
("dtw", "Detroit Metropolitan Wayne County Airport", "", "Michigan", "USA", "Detroit", "", ""),
("dub", "Aerfort Bhaile Átha Cliath", "Dublin Airport", "", "Ireland", "Dublin", "Collinstown", ""),
("dud", "Dunedin International Airport", "", "", "New Zealand", "Dunedin", "Momona", "Otago"),
("dus", "Flughafen Düsseldorf", "Düsseldorf Airport", "", "Germany", "Düsseldorf", "Dusseldorf", ""),
("dvo", "Paliparang Pandaigdig ng Francisco Bangoy", "Francisco Bangoy International Airport", "Mindanao", "Philippines", "Davao City", "Catitipan", ""),
("dwc", "Al Maktoum International Airport", "", "", "United Arab Emirates", "Dubai", "Jebel Ali", ""),
("dxb", "Dubai International Airport", "", "", "United Arab Emirates", "Dubai", "Al Garhoud", ""),
("dxr", "Danbury Municipal Airport", "", "Connecticut", "USA", "Danbury", "", ""),
("dyu", "Dushanbe International Airport", "", "", "Tajikistan", "Dushanbe", "", ""),
("dza", "Aéroport de Dzaoudzi-Pamandzi", "Dzaoudzi-Pamandzi International Airport", "Mayotte", "France", "Dzaoudzi", "Pamanzi", ""),
("eas", "Aeropuerto de San Sebastián", "San Sebastián Airport", "", "Spain", "San Sebastián", "Hondarribia", ""),
("eat", "Pangborn Memorial Airport", "", "Washington", "USA", "Wenatchee", "", ""),
("ebb", "Entebbe International Airport", "", "", "Uganda", "Entebbe", "Kampala", ""),
("ebl", "Erbil International Airport", "", "", "Iraq", "Erbil", "", ""),
("ecp", "Northwest Florida Beaches International Airport", "", "Florida", "USA", "Panama City", "", ""),
("edi", "Port-adhair Dhùn Èideann", "Edinburgh Airport", "Scotland", "UK", "Edinburgh", "", ""),
("egc", "Aéroport de Bergerac Dordogne Périgord", "Bergerac Dordogne Périgord Airport", "", "France", "Bergerac", "", ""),
("ege", "Eagle County Regional Airport", "", "Colorado", "USA", "Eagle", "Gypsum", ""),
("ein", "Vliegbasis Eindhoven", "Eindhoven Airport", "", "Netherlands", "Eindhoven", "", ""),
("elp", "El Paso International Airport", "", "Texas", "USA", "El Paso", "", ""),
("ema", "East Midlands Airport", "", "England", "UK", "Nottingham", "Castle Donington", "Leicestershire"),
("ens", "Enschede Vliegbasis Twente", "Enschede Airport Twente", "", "Netherlands", "Enschede", "", ""),
("enu", "Akanu Ibiam International Airport", "", "", "Nigeria", "Enugu", "", ""),
("eoh", "Aeropuerto Olaya Herrera", "Olaya Herrera Airport", "", "Colombia", "Medellín", "", ""),
("eri", "Erie International Airport", "", "Pennsylvania", "USA", "Erie", "", ""),
("esb", "Esenboğa Uluslararası Havalimanı", "Esenboga International Airport", "", "Turkey", "Ankara", "", ""),
("eug", "Eugene Airport", "", "Oregon", "USA", "Eugene", "", ""),
("eux", "F. D. Roosevelt Airport", "", "", "Netherlands", "Sint Eustatius", "Oranjestad", ""),
("evn", "Zvart'nots' Mijazgayin Odanavakayan", "Zvartnots International Airport", "", "Armenia", "Yerevan", "Zvartnots", ""),
("ewr", "Liberty International Airport", "", "New Jersey", "USA", "Newark", "", ""),
("ext", "Exeter International Airport", "", "England", "UK", "Exeter", "Devon", ""),
("eyw", "Key West International Airport", "", "Florida", "USA", "Key West", "", ""),
("eze", "Aeropuerto Internacional Ministro Pistarini", "Ministro Pistarini International Airport", "", "Argentina", "Buenos Aires", "Ezeiza", ""),
("fae", "Vága Floghavn", "Vágar Airport", "Faroe Islands", "Denmark", "Sørvágur", "Tórshavn", "Vagar"),
("fao", "Aeroporto Internacional de Faro", "Faro International Airport", "Algarve", "Portugal", "Faro", "", ""),
("far", "Hector International Airport", "", "North Dakota", "USA", "Fargo", "Moorhead", ""),
("fat", "Fresno Yosemite International Airport", "", "California", "USA", "Fresno", "", ""),
("fca", "Glacier Park International Airport", "", "Montana", "USA", "Kalispell", "Flathead County", ""),
("fco", "Fiumicino – Aeroporto Internazionale Leonardo da Vinci", "Leonardo da Vinci International Airport", "", "Italy", "Rome", "", ""),
("fdf", "Aéroport International Martinique Aimé Césaire", "Martinique Aimé Césaire International Airport", "Martinique", "France", "Fort-de-France", "Le Lamentin", ""),
("fdh", "Flughafen Friedrichshafen", "Friedrichshafen Airport", "", "Germany", "Friedrichshafen", "Lake Constance", ""),
("fez", "Fes–Saïss Airport", "", "", "Morocco", "Fes", "Saïss", "Saiss"),
("ffa", "First Flight Airport", "", "North Carolina", "USA", "Kill Devil Hills", "", ""),
("fie", "Fair Isle Airport", "", "Scotland", "UK", "Fair Isle", "Shetland", ""),
("fih", "N'Djili International Airport", "", "", "Democratic Republic of the Congo", "Kinshasa", "Congo", ""),
("fkb", "Flughafen Karlsruhe/Baden-Baden", "Baden Airpark", "", "Germany", "Rheinmünster", "Karlsruhe", "Baden-Baden"),
("fkl", "Venango Regional Airport", "", "Pennsylvania", "USA", "Franklin", "Oil City", ""),
("flg", "Flagstaff Pulliam Airport", "", "Arizona", "USA", "Flagstaff", "", ""),
("fll", "Fort Lauderdale–Hollywood International Airport", "", "Florida", "USA", "Fort Lauderdale", "Miami", "Broward County"),
("fln", "Aeroporto Internacional de Florianópolis–Hercílio Luz", "Florianópolis–Hercílio Luz International Airport", "Santa Catarina", "Brazil", "Florianópolis", "Florianopolis", ""),
("flr", "Aeroporto di Firenze-Peretola", "Florence Airport, Peretola", "Tuscany", "Italy", "Florence", "Peretola", ""),
("flw", "Aeroporto das Flores", "Flores Airport", "Azores", "Portugal", "Santa Cruz das Flores", "Flores", ""),
("fmm", "Allgäu-Airport Memmingen", "Memmingen Airport", "", "Germany", "Memmingen", "", ""),
("fmo", "Flughafen Münster/Osnabrück", "Münster Osnabrück International Airport", "NRW", "Germany", "Münster", "Osnabrück", "Greven"),
("fna", "Lungi International Airport", "", "", "Sierra Leone", "Freetown", "Lungi", ""),
("fnc", "Aeroporto da Madeira", "Madeira Airport", "Região Autónoma da Madeira", "Portugal", "Funchal", "Santa Catarina", "Santa Cruz"),
("fnt", "Bishop International Airport", "", "Michigan", "USA", "Flint", "", ""),
("fod", "Fort Dodge Regional Airport", "", "Iowa", "USA", "Fort Dodge", "", ""),
("for", "Aeroporto Internacional Pinto Martins", "Pinto Martins International Airport", "Ceará", "Brazil", "Fortaleza", "", ""),
("fra", "Flughafen Frankfurt am Main", "Frankfurt Airport", "", "Germany", "Frankfurt", "", ""),
("fru", "Manas International Airport", "", "", "Kyrgyzstan", "Bishkek", "", ""),
("fsc", "Aéroport Figari-Sud Corse", "Figari South Corsica Airport", "", "France", "Porto-Vecchio", "Figari", "Corse-du-Sud"),
("fsd", "Sioux Falls Regional Airport", "", "South Dakota", "USA", "Sioux Falls", "", ""),
("fsp", "Aéroport de Saint-Pierre", "Saint-Pierre Airport", "", "France", "Saint-Pierre, Saint Pierre and Miquelon", "", ""),
("fsz", "Shizuoka Airport", "", "", "Japan", "Shizuoka", "Makinohara", "Shimada"),
("fue", "Aeropuerto de Fuerteventura", "Fuerteventura Airport", "Canary Islands", "Spain", "Fuerteventura", "El Matorral", "Puerto del Rosario"),
("fuk", "Fukuoka Airport", "", "", "Japan", "Fukuoka", "", ""),
("fun", "Funafuti International Airport", "", "", "Tuvalu", "Funafuti", "", ""),
("fwa", "Fort Wayne International Airport", "", "Indiana", "USA", "Fort Wayne", "", ""),
("gan", "Gan International Airport", "", "Addu Atoll", "Maldives", "Gan", "", ""),
("gau", "Lokpriya Gopinath Bordoloi International Airport", "", "Assam", "India", "Guwahati", "Gowhatty", "Gauhati"),
("gbe", "Sir Seretse Khama International Airport", "", "", "Botswana", "Gaborone", "", ""),
("gci", "Guernsey Airport", "", "Channel Islands", "UK", "Guernsey", "Forest", ""),
("gcm", "Owen Roberts International Airport", "", "England", "UK", "George Town", "Grand Cayman", ""),
("gcw", "Grand Canyon West Airport", "", "Arizona", "USA", "Grand Canyon", "Peach Springs", ""),
("gdl", "Aeropuerto Internacional de Guadalajara", "Guadalajara International Airport", "Jalisco", "Mexico", "Guadalajara", "", ""),
("gdn", "Port Lotniczy Gdańsk im. Lecha Wałęsy", "Gdansk Lech Walesa Airport", "", "Poland", "Gdańsk", "", ""),
("geg", "Spokane International Airport", "", "Washington", "USA", "Spokane", "", ""),
("geo", "Cheddi Jagan International Airport", "", "", "Guyana", "Georgetown", "Timehri", ""),
("ggt", "Exuma International Airport", "", "", "Bahamas", "Great Exuma", "Moss Town", "George Town"),
("gib", "Gibraltar International Airport", "", "", "UK", "Gibraltar", "", ""),
("gig", "Aeroporto Internacional do Galeão–Antonio Carlos Jobim", "Galeão–Antonio Carlos Jobim International Airport", "Rio de Janeiro", "Brazil", "Rio de Janeiro", "", ""),
("giz", "King Abdullah bin Abdulaziz Airport", "", "Jizan Province", "Saudi Arabia", "Jizan", "Gizan", "Jazan"),
("gjt", "Grand Junction Regional Airport", "", "Colorado", "USA", "Grand Junction", "", ""),
("gla", "Port-adhair Eadar-nàiseanta Ghlaschu", "Glasgow Airport", "Scotland", "UK", "Glasgow", "", ""),
("glo", "Gloucestershire Airport", "", "England", "UK", "Gloucester", "Staverton", ""),
("glu", "Gelephu Airport", "", "", "Bhutan", "Gelephu", "", ""),
("gmp", "Gimpo International Airport", "", "Korea", "South Korea", "Seoul", "Gangseo District", ""),
("gmu", "Greenville Downtown Airport", "", "South Carolina", "USA", "Greenville", "", ""),
("gmz", "Aeropuerto de La Gomera", "La Gomera Airport", "Canary Islands", "Spain", "La Gomera", "Playa Santiago", ""),
("gnd", "Maurice Bishop International Airport", "", "", "Grenada", "St. George's", "Point Salines", ""),
("gnv", "Gainesville Regional Airport", "", "Florida", "USA", "Gainesville", "", ""),
("goa", "Aeroporto di Genova", "Cristoforo Colombo Airport", "", "Italy", "Genoa", "", ""),
("goi", "Goa International Airport", "", "Goa", "India", "Dabolim", "", ""),
("goj", "Strigino Nizhny Novgorod International Airport", "", "", "Russia", "Nizhny Novgorod", "Gorky", ""),
("goq", "Golmud Airport", "", "Qinghai", "China", "Golmud", "", ""),
("got", "Göteborg Landvetter Airport", "Goteborg Landvetter Airport", "", "Sweden", "Gothenburg", "Landvetter", ""),
("gov", "Gove Airport", "", "Northern Territory", "Australia", "Nhulunbuy", "Gove Peninsula", ""),
("gps", "Seymour Airport", "", "Galápagos Islands", "Ecuador", "Baltra", "", ""),
("gpt", "Gulfport–Biloxi International Airport", "", "Mississippi", "USA", "Gulfport–Biloxi", "Biloxi", ""),
("grb", "Austin Straubel International Airport", "", "Wisconsin", "USA", "Green Bay", "", ""),
("grk", "Killeen–Fort Hood Regional Airport", "", "Texas", "USA", "Killeen", "Fort Hood", ""),
("gro", "Aeropuerto de Girona-Costa Brava", "Girona–Costa Brava Airport", "", "Spain", "Girona", "Costa Brava", ""),
("grr", "Gerald R. Ford International Airport", "", "Michigan", "USA", "Grand Rapids", "", ""),
("gru", "Aeroporto Internacional Guarulhos–Governador André Franco Montoro", "Guarulhos–Governador André Franco Montoro International Airport", "SP", "Brazil", "São Paulo", "Sao Paulo", "Guarulhos"),
("grw", "Aeroporto de Graciosa", "Graciosa Airport", "Azores", "Portugal", "Graciosa", "Santa Cruz", ""),
("grx", "Aeropuerto Federico García Lorca Granada-Jaén", "Federico García Lorca Granada-Jaén Airport", "", "Spain", "Granada", "Jaén", ""),
("grz", "Flughafen Graz", "Graz Airport", "", "Austria", "Graz", "", ""),
("gso", "Piedmont Triad International Airport", "", "North Carolina", "USA", "Greensboro", "High Point", "Winston-Salem"),
("gsp", "Greenville–Spartanburg International Airport", "", "South Carolina", "USA", "Greenville", "Spartanburg", "Greer"),
("gtr", "Golden Triangle Regional Airport", "", "Mississippi", "USA", "Columbus", "Starkville", "West Point"),
("gua", "Aeropuerto Internacional La Aurora", "La Aurora International Airport", "", "Guatemala", "Guatemala City", "", ""),
("gum", "Antonio B. Won Pat International Airport", "", "Guam", "USA", "Barrigada and Tamuning", "", ""),
("gur", "Gurney Airport", "", "", "Papua New Guinea", "Alotau", "", ""),
("guw", "ATMA Atyrau Airport", "", "", "Kazakhstan", "Atyrau", "", ""),
("gva", "Aéroport international de Genève", "Geneva International Airport", "", "Switzerland", "Geneva", "Meyrin", "Le Grand-Saconnex"),
("gyd", "Heydar Aliyev International Airport", "", "", "Azerbaijan", "Baku", "", ""),
("gye", "Aeropuerto Internacional José Joaquín de Olmedo", "José Joaquín de Olmedo International Airport", "Guayas", "Ecuador", "Guayaquil", "", ""),
("gyn", "Aeroporto Internacional Santa Genoveva", "Santa Genoveva International Airport", "Goiás", "Brazil", "Goiânia", "Goiania", ""),
("gza", "Yasser Arafat International Airport", "", "", "Palestine", "Gaza", "", ""),
("hah", "Prince Said Ibrahim International Airport", "", "", "Comoros", "Moroni", "Hahaya", ""),
("haj", "Flughafen Hannover-Langenhagen", "Hannover Airport", "", "Germany", "Hannover", "Langenhagen", ""),
("ham", "Flughafen Hamburg", "Hamburg Airport", "", "Germany", "Hamburg", "", ""),
("han", "Nội Bài International Airport", "", "", "Vietnam", "Hanoi", "", ""),
("haq", "Hanimaadhoo International Airport", "", "Haa Dhaalu Atoll", "Maldives", "Hanimaadhoo", "", ""),
("hav", "Aeropuerto José Martí", "José Martí International Airport", "", "Cuba", "Havana", "", ""),
("hel", "Helsinki-Vantaan lentoasema", "Helsinki-Vantaa Airport", "", "Finland", "Helsinki", "Vantaa", ""),
("hft", "Hammerfest lufthavn", "Hammerfest Airport", "", "Norway", "Hammerfest", "", ""),
("hga", "Hargeisa Egal International Airport", "", "", "Somalia", "Hargeisa", "", ""),
("hgh", "Hangzhou Xiaoshan International Airport", "", "Xiaoshan District", "China", "Hangzhou", "Zhejiang", ""),
("hgl", "Flughafen Helgoland-Düne", "Heligoland Airport", "", "Germany", "Heligoland", "", ""),
("hhn", "Flughafen Frankfurt-Hahn", "Frankfurt–Hahn Airport", "Rhineland-Palatinate", "Germany", "Kirchberg", "", ""),
("hir", "Honiara International Airport", "", "", "Solomon Islands", "Honiara", "Guadalcanal", ""),
("hkd", "Hakodate Airport", "", "", "Japan", "Hakodate", "Hokkaido", ""),
("hkg", "Hong Kong International Airport", "", "", "China", "Hong Kong", "Chek Lap Kok", ""),
("hkt", "Phuket International Airport", "", "", "Thailand", "Phuket", "", ""),
("hlp", "Bandar Udara Halim Perdanakusuma", "Halim Perdanakusuma International Airport", "", "Indonesia", "Jakarta", "East Jakarta", ""),
("hmo", "Aeropuerto Internacional General Ignacio Pesqueira García", "General Ignacio Pesqueira García International Airport", "Sonora", "Mexico", "Hermosillo", "", ""),
("hnd", "Tokyo International Airport", "", "", "Japan", "Tokyo", "", ""),
("hnl", "Honolulu International Airport", "", "Hawaii", "USA", "Honolulu", "Oahu", ""),
("hnm", "Hana Airport", "", "Hawaii", "USA", "Hana", "", ""),
("hof", "Al-Ahsa International Airport", "", "Eastern Province", "Saudi Arabia", "Hofuf", "Al-Ahsa", ""),
("hog", "Frank País Airport", "", "", "Cuba", "Holguín", "Holguin", ""),
("hor", "Aeroporto Internacional da Horta", "Horta International Airport", "Azores", "Portugal", "Horta", "Castelo Branco", "Faial Island"),
("hot", "Memorial Field Airport", "", "Arkansas", "USA", "Hot Springs", "", ""),
("hou", "William P. Hobby Airport", "", "Texas", "USA", "Houston", "", ""),
("hov", "Ørsta–Volda lufthavn, Hovden", "Ørsta–Volda Airport, Hovdene", "", "Norway", "Ørsta", "Volda", "Hovdebygda"),
("hph", "Sân bay Quốc tế Cát Bi", "Cat Bi International Airport", "", "Vietnam", "Hai Phong", "", ""),
("hpn", "Westchester County Airport", "", "New York", "USA", "White Plains", "", ""),
("hqm", "Bowerman Airport", "", "Washington", "USA", "Hoquiam", "Grays Harbor County", ""),
("hre", "Harare International Airport", "", "", "Zimbabwe", "Harare", "", ""),
("hrg", "Hurghada International Airport", "", "", "Egypt", "Hurghada", "", ""),
("hri", "Mattala Rajapaksa International Airport", "", "", "Sri Lanka", "Hambantota", "Mattala", ""),
("hrl", "Valley International Airport", "", "Texas", "USA", "Harlingen", "", ""),
("hsv", "Huntsville International Airport", "", "Alabama", "USA", "Huntsville", "", ""),
("huf", "Terre Haute International Airport", "", "Indiana", "USA", "Terre Haute", "", ""),
("huh", "Huahine – Fare Airport", "", "French Polynesia", "France", "Huahine", "", ""),
("huu", "Aeropuerto Alférez FAP David Figueroa Fernandini", "Alférez FAP David Figueroa Fernandini Airport", "", "Peru", "Huánuco", "", ""),
("hya", "Barnstable Municipal Airport", "", "Massachusetts", "USA", "Cape Cod", "Hyannis", ""),
("hyd", "Rajiv Gandhi International Airport", "", "Telangana", "India", "Hyderabad", "", ""),
("iad", "Dulles International Airport", "", "Virginia", "USA", "Washington D.C.", "", ""),
("iah", "George Bush Intercontinental Airport", "", "Texas", "USA", "Houston", "", ""),
("ibz", "Aeropuerto de Ibiza", "Ibiza Airport", "", "Spain", "Ibiza", "Formentera", ""),
("icn", "Incheon International Airport", "", "Korea", "South Korea", "Seoul", "Jung District", ""),
("ict", "Dwight D. Eisenhower National Airport", "", "Kansas", "USA", "Wichita", "", ""),
("ida", "Idaho Falls Regional Airport", "", "Idaho", "USA", "Idaho Falls", "Bonneville County", ""),
("idr", "Devi Ahilyabai Holkar Airport", "", "Madhya Pradesh", "India", "Indore", "", ""),
("iev", "Kyiv International Airport", "", "", "Ukraine", "Kiev", "Zhuliany", ""),
("ifp", "Laughlin/Bullhead International Airport", "", "Arizona", "USA", "Bullhead City", "Laughlin", "Nevada"),
("igu", "Aeroporto Internacional de Foz do Iguaçu/Cataratas", "Foz do Iguaçu/Cataratas International Airport", "Paraná", "Brazil", "Foz do Iguaçu", "", ""),
("ika", "Tehran Imam Khomeini International Airport", "", "", "Iran", "Tehran", "Ahmadabad", ""),
("ild", "Aeroport Lleida-Alguaire", "Lleida-Alguaire Airport", "", "Spain", "Lleida", "Alguaire", ""),
("ind", "Indianapolis International Airport", "", "Indiana", "USA", "Indianapolis", "", ""),
("inn", "Flughafen Innsbruck", "Innsbruck Airport", "", "Austria", "Innsbruck", "", ""),
("inu", "Nauru International Airport", "", "", "Nauru", "Yaren", "", ""),
("inv", "Port-adhair Inbhir Nis", "Inverness Airport", "Scotland", "UK", "Inverness", "Dalcross", ""),
("iom", "Isle of Man Airport", "", "Isle of Man", "UK", "Ronaldsway", "", ""),
("ipc", "Mataveri International Airport", "", "", "Chile", "Easter Island", "Rapa Nui", "Isla de Pascua"),
("ipn", "Aeroporto da Usiminas", "Usiminas Airport", "Minas Gerais", "Brazil", "Ipatinga", "Santana do Paraíso", ""),
("iqq", "Aeropuerto Internacional Diego Aracena", "Diego Aracena International Airport", "", "Chile", "Iquique", "", ""),
("iqt", "Aeropuerto Internacional Coronel FAP Francisco Secada Vignetta", "Coronel FAP Francisco Secada Vignetta International Airport", "", "Peru", "Iquitos", "", ""),
("isb", "Benazir Bhutto International Airport", "", "Punjab", "Pakistan", "Islamabad", "Rawalpindi", ""),
("isc", "St Mary’s Airport", "", "England", "UK", "Isles of Scilly", "Cornwall", ""),
("isp", "Long Island MacArthur Airport", "", "New York", "USA", "Long Island", "Islip", ""),
("ist", "İstanbul Atatürk Havalimanı", "Istanbul Atatürk Airport", "", "Turkey", "Istanbul", "Yeşilköy", ""),
("itm", "Osaka International Airport", "", "", "Japan", "Osaka", "Itami", ""),
("ito", "Hilo International Airport", "", "Hawaii", "USA", "Hilo", "", ""),
("iwa", "Ivanovo Yuzhny Airport", "", "", "Russia", "Ivanovo", "", ""),
("ixa", "Agartala Airport", "", "Tripura", "India", "Agartala", "", ""),
("ixb", "Bagdogra Airport", "", "West Bengal", "India", "Bagdogra", "Siliguri", ""),
("ixc", "Chandigarh International Airport", "", "CH", "India", "Chandigarh", "", ""),
("ixm", "Madurai Airport", "", "Tamil Nadu", "India", "Madurai", "", ""),
("ixz", "Veer Savarkar International Airport", "", "Andaman and Nicobar Islands", "India", "Port Blair", "", ""),
("jac", "Jackson Hole Airport", "", "Wyoming", "USA", "Jackson", "Teton County", ""),
("jai", "Jaipur International Airport", "", "Rajasthan", "India", "Jaipur", "", ""),
("jau", "Aeropuerto Francisco Carlé", "Francisco Carlé Airport", "Junín", "Peru", "Jauja", "", ""),
("jax", "Jacksonville International Airport", "", "Florida", "USA", "Jacksonville", "", ""),
("jed", "King Abdulaziz International Airport", "", "", "Saudi Arabia", "Jeddah", "", ""),
("jer", "Jersey Airport", "", "", "Jersey", "Saint Peter", "Channel Islands", ""),
("jfk", "John F. Kennedy International Airport", "", "New York", "USA", "New York City", "", ""),
("jhm", "Kapalua Airport", "", "Hawaii", "USA", "Kapalua", "Lahaina", ""),
("jib", "Aéroport international de Djibouti–Ambouli", "Djibouti–Ambouli International Airport", "", "Djibouti", "Djibouti City", "Ambouli", ""),
("jnb", "O. R. Tambo International Airport", "", "", "South Africa", "Johannesburg", "Kempton Park", ""),
("jog", "Bandar Udara Internasional Adisucipto", "Adisucipto International Airport", "", "Indonesia", "Yogyakarta", "Central Java", ""),
("joi", "Aeroporto de Joinville-Lauro Carneiro de Loyola", "Joinville-Lauro Carneiro de Loyola Airport", "Santa Catarina", "Brazil", "Joinville", "", ""),
("jpa", "Aeroporto Internacional Presidente Castro Pinto", "Presidente Castro Pinto International Airport", "Paraíba", "Brazil", "João Pessoa", "Bayeux", ""),
("jsi", "Skiathos Airport, Alexandros Papadiamantis", "", "Thessaly", "Greece", "Skiathos", "", ""),
("jub", "Juba International Airport", "", "", "South Sudan", "Juba", "", ""),
("jul", "Aeropuerto Internacional Inca Manco Cápac", "Inca Manco Cápac International Airport", "Puno", "Peru", "Juliaca", "", ""),
("kan", "Mallam Aminu Kano International Airport", "", "", "Nigeria", "Kano", "", ""),
("kbl", "Hamid Karzai International Airport", "", "", "Afghanistan", "Kabul", "", ""),
("kbp", "Boryspil International Airport", "", "", "Ukraine", "Kiev", "Boryspil", ""),
("kbr", "Lapangan Terbang Sultan Ismail Petra", "Sultan Ismail Petra Airport", "Kelantan", "Malaysia", "Kota Bharu", "", ""),
("kef", "Keflavíkurflugvöllur", "Keflavík International Airport", "", "Iceland", "Keflavík", "Reykjavík", ""),
("ker", "Kerman International Airport", "", "", "Iran", "Kerman", "", ""),
("kgl", "Kigali International Airport", "", "", "Rwanda", "Kigali", "", ""),
("khh", "Kaohsiung International Airport", "", "", "Taiwan", "Kaohsiung", "", ""),
("khi", "Jinnah International Airport", "", "Sindh", "Pakistan", "Karachi", "", ""),
("kia", "Kilimanjaro International Airport", "", "Hai District", "Tanzania", "Arusha", "Moshi", ""),
("kih", "Kish International Airport", "", "", "Iran", "Kish Island", "", ""),
("kin", "Norman Manley International Airport", "", "", "Jamaica", "Kingston", "", ""),
("kiv", "Chișinău International Airport", "", "", "Moldova", "Chișinău", "Chisinau", ""),
("kix", "Kansai International Airport", "", "", "Japan", "Osaka", "", ""),
("kmg", "Kunming Changshui International Airport", "", "Guandu District", "China", "Kunming", "", ""),
("kno", "Bandar Udara Internasional Kualanamu", "Kualanamu International Airport", "", "Indonesia", "Medan", "Deli Serdang", ""),
("koa", "Kona International Airport", "", "Hawaii", "USA", "Kailua-Kona", "Kalaoa", "Kona"),
("kov", "Kokshetau Airport", "", "", "Kazakhstan", "Kokshetau", "", ""),
("krk", "Kraków Airport im. Jana Pawła II", "John Paul II International Airport", "", "Poland", "Kraków", "Balice", ""),
("krn", "Kiruna flygplats", "Kiruna Airport", "Norrbotten", "Sweden", "Kiruna", "", ""),
("krr", "Krasnodar International Airport", "", "", "Russia", "Krasnodar", "", ""),
("krs", "Kristiansand lufthavn, Kjevik", "Kristiansand Airport, Kjevik", "", "Norway", "Kristiansand", "Kjevik", "Tveit"),
("krt", "Khartoum International Airport", "", "", "Sudan", "Khartoum", "", ""),
("ksa", "Kosrae International Airport", "", "", "Micronesia", "Kosrae", "", ""),
("ksh", "Shahid Ashrafi Esfahani Airport", "", "", "Iran", "Kermanshah", "", ""),
("ksn", "Kostanay International Airport", "", "", "Kazakhstan", "Kostanay", "", ""),
("ktm", "Tribhuvan International Airport", "", "", "Nepal", "Kathmandu", "", ""),
("ktt", "Kittilän lentoasema", "Kittilä Airport", "", "Finland", "Kittilä", "", ""),
("ktw", "Międzynarodowy Port Lotniczy Katowice", "Katowice International Airport", "Silesian Voivodeship", "Poland", "Katowice", "Pyrzowice", ""),
("kuh", "Kushiro Airport", "", "", "Japan", "Kushiro", "Hokkaido", ""),
("kul", "Lapangan Terbang Antarabangsa Kuala Lumpur", "Kuala Lumpur International Airport", "", "Malaysia", "Kuala Lumpur", "Sepang", ""),
("kuo", "Kuopion lentoasema", "Kuopio Airport", "", "Finland", "Kuopio", "Siilinjärvi", ""),
("kwe", "Guiyang Longdongbao International Airport", "", "Guizhou Province", "China", "Guiyang", "Longdongbao", ""),
("kwi", "Kuwait International Airport", "", "Farwaniya", "Kuwait", "Kuwait City", "", ""),
("kzn", "Kazan International Airport", "", "", "Russia", "Kazan", "Tatarstan", ""),
("kzo", "Kyzylorda Airport", "", "", "Kazakhstan", "Kyzylorda", "", ""),
("lad", "Aeroporto Internacional 4 de Fevereiro", "Quatro de Fevereiro International Airport", "", "Angola", "Luanda", "", ""),
("laf", "Purdue University Airport", "", "Indiana", "USA", "Lafayette", "West Lafayette", ""),
("lan", "Capital Region International Airport", "", "Michigan", "USA", "Lansing", "DeWitt Township", ""),
("las", "McCarran International Airport", "", "Nevada", "USA", "Las Vegas", "Paradise", ""),
("lax", "Los Angeles International Airport", "", "California", "USA", "Los Angeles", "", ""),
("lba", "Leeds Bradford International Airport", "", "England", "UK", "Leeds", "Bradford", "Yorkshire"),
("lbb", "Lubbock Preston Smith International Airport", "", "Texas", "USA", "Lubbock", "", ""),
("lbc", "Flughafen Lübeck", "Lübeck Airport", "", "Germany", "Lübeck", "Lubeck", ""),
("lbf", "North Platte Regional Airport", "", "Nebraska", "USA", "North Platte", "", ""),
("lbj", "Bandar Udara Komodo", "Komodo Airport", "Flores Island", "Indonesia", "Labuan Bajo", "", ""),
("lbu", "Lapangan Terbang Labuan", "Labuan Airport", "", "Malaysia", "Labuan", "", ""),
("lbv", "Aéroport De Libreville au Gabon", "Libreville International Airport", "", "Gabon", "Libreville", "", ""),
("lca", "Larnaca International Airport", "", "", "Cyprus", "Larnaca", "", ""),
("lcg", "Aeroporto da Coruña-Alvedro", "A Coruña Airport", "", "Spain", "A Coruña", "Galicia", "Culleredo"),
("lck", "Rickenbacker International Airport", "", "Ohio", "USA", "Columbus", "Lockbourne", ""),
("lcy", "London City Airport", "", "England", "UK", "London", "Silvertown", ""),
("ldy", "City of Derry Airport", "", "Northern Ireland", "UK", "Derry", "Eglinton", "Londonderry"),
("led", "Aeroport Pulkovo", "Pulkovo International Airport", "", "Russia", "Saint Petersburg", "", ""),
("lei", "Aeropuerto de Almería", "Almería Airport", "", "Spain", "Almería", "Almeria", ""),
("lej", "Flughafen Leipzig/Halle", "Leipzig/Halle Airport", "", "Germany", "Leipzig", "Halle", "Schkeuditz"),
("len", "Aeropuerto de León", "León Airport", "", "Spain", "León", "Leon", ""),
("leu", "Aeropuerto de La Seu d'Urgell", "La Seu d'Urgell Airport", "", "Spain", "La Seu d'Urgell", "Catalonia", "Andorra"),
("lex", "Blue Grass Airport", "", "Kentucky", "USA", "Lexington", "", ""),
("lft", "Lafayette Regional Airport", "", "Louisiana", "USA", "Lafayette", "", ""),
("lfw", "Lomé–Tokoin Airport", "", "", "Togo", "Lomé", "", ""),
("lga", "LaGuardia Airport", "", "New York", "USA", "New York City", "", ""),
("lgb", "Long Beach Airport", "", "California", "USA", "Long Beach", "", ""),
("lgg", "Liège Airport", "", "", "Belgium", "Liège", "Liege", ""),
("lgk", "Lapangan Terbang Antarabangsa Langkawi", "Langkawi International Airport", "", "Malaysia", "Langkawi", "Perlis", ""),
("lgw", "Gatwick Airport", "", "England", "UK", "London", "Crawley", ""),
("lhe", "Allama Iqbal International Airport", "", "Punjab", "Pakistan", "Lahore", "", ""),
("lhr", "London Heathrow Airport", "", "England", "UK", "London", "", ""),
("lih", "Lihue Airport", "", "Hawaii", "USA", "Lihue", "Kauai", ""),
("lim", "Aeropuerto Internacional Jorge Chávez", "Jorge Chávez International Airport", "", "Peru", "Lima", "Callao", ""),
("lin", "Aeroporto di Milano-Linate", "Milan Linate Airport", "", "Italy", "Milan", "Linate", "Peschiera Borromeo"),
("lir", "Aeropuerto Internacional Daniel Oduber Quirós", "Daniel Oduber Quirós International Airport", "", "Costa Rica", "Liberia", "", ""),
("lis", "Aeroporto da Portela", "Lisbon Portela Airport", "", "Portugal", "Lisbon", "Portela", ""),
("lit", "Bill and Hillary Clinton National Airport", "", "Arkansas", "USA", "Little Rock", "Adams Field", "Clinton"),
("lju", "Letališče Jožeta Pučnika Ljubljana", "Ljubljana Jože Pučnik Airport", "", "Slovenia", "Ljubljana", "Zgornji Brnik", ""),
("lko", "Chaudhary Charan Singh International Airport", "", "Utter Pradesh", "India", "Lucknow", "", ""),
("llw", "Lilongwe International Airport", "", "", "Malawi", "Lilongwe", "", ""),
("lmn", "Lapangan Terbang Limbang", "Limbang Airport", "Sarawak", "Malaysia", "Limbang", "", ""),
("lmt", "Crater Lake - Klamath Regional Airport", "", "Oregon", "USA", "Klamath Falls", "", ""),
("lnk", "Lincoln Airport", "", "Nebraska", "USA", "Lincoln", "", ""),
("lop", "Lombok International Airport", "", "West Nusa Tenggara", "Indonesia", "Mataram", "", ""),
("los", "Murtala Muhammed International Airport", "", "", "Nigeria", "Lagos", "Ikeja", ""),
("lpa", "Aeropuerto de Gran Canaria", "Gran Canaria Airport", "Canary Islands", "Spain", "Gran Canaria", "Las Palmas", ""),
("lpb", "Aeropuerto Internacional El Alto", "El Alto International Airport", "", "Bolivia", "La Paz", "El Alto", ""),
("lpl", "Liverpool John Lennon Airport", "", "England", "UK", "Liverpool", "Speke", ""),
("lpq", "Luang Prabang International Airport", "", "", "Laos", "Luang Prabang", "", ""),
("lrd", "Laredo International Airport", "", "Texas", "USA", "Laredo", "", ""),
("lrh", "Aéroport de La Rochelle – Ile de Ré", "", "", "France", "La Rochelle", "", ""),
("lse", "La Crosse Regional Airport", "", "Wisconsin", "USA", "La Crosse", "", ""),
("ltn", "London Luton Airport", "", "England", "UK", "London", "Luton", ""),
("luk", "Cincinnati Municipal Airport", "", "Ohio", "USA", "Cincinnati", "", ""),
("lun", "Kenneth Kaunda International Airport", "", "", "Zambia", "Lusaka", "", ""),
("lux", "Aéroport de Luxembourg", "Luxembourg Findel Airport", "", "Luxembourg", "Luxembourg City", "", ""),
("lvi", "Harry Mwanga Nkumbula International Airport", "", "", "Zambia", "Livingstone", "Victoria Falls", ""),
("lwb", "Greenbrier Valley Airport", "", "West Virginia", "USA", "Lewisburg", "", ""),
("lwo", "Lviv Danylo Halytskyi International Airport", "", "", "Ukraine", "Lviv", "", ""),
("lxr", "Luxor International Airport", "", "", "Egypt", "Luxor", "", ""),
("lyr", "Svalbard lufthavn, Longyear", "Svalbard Airport, Longyear", "", "Norway", "Svalbard", "Longyearbyen", "Hotellneset"),
("lys", "Aéroport Lyon-Saint-Exupéry", "Lyon–Saint Exupéry Airport", "", "France", "Lyon", "Colombier-Saugnieu", ""),
("maa", "Chennai International Airport", "", "Tamil Nadu", "India", "Chennai", "Tirusulam", ""),
("mad", "Aeropuerto Adolfo Suárez Madrid-Barajas", "Adolfo Suárez Madrid–Barajas Airport", "", "Spain", "Madrid", "Barajas", ""),
("maf", "Midland International Air and Space Port", "", "Texas", "USA", "Midland", "Odessa", ""),
("mah", "Aeropuerto de Menorca", "Menorca Airport", "", "Spain", "Mahón", "Mahon", "Menorca"),
("maj", "Marshall Islands International Airport", "", "", "Marshall Islands", "Majuro", "", ""),
("man", "Manchester Airport", "", "England", "UK", "Manchester", "Ringway", ""),
("mao", "Aeroporto Internacional Brigadeiro Eduardo Gomes", "Brigadeiro Eduardo Gomes International Airport", "Amazonas", "Brazil", "Manaus", "", ""),
("mbj", "Sangster International Airport", "", "", "Jamaica", "Montego Bay", "", ""),
("mbs", "MBS International Airport", "", "Michigan", "USA", "Freeland", "", ""),
("mci", "Kansas City International Airport", "", "Missouri", "USA", "Kansas City", "", ""),
("mco", "Orlando International Airport", "", "Florida", "USA", "Orlando", "", ""),
("mct", "Muscat International Airport", "", "", "Oman", "Muscat", "", ""),
("mcw", "Mason City Municipal Airport", "", "Iowa", "USA", "Mason City", "", ""),
("mcz", "Aeroporto Internacional Maceió/Zumbi dos Palmares", "Maceió/Zumbi dos Palmares International Airport", "Alagoas", "Brazil", "Maceió", "", ""),
("mdc", "Bandar Udara Internasional Sam Ratulangi", "Sam Ratulangi International Airport", "", "Indonesia", "Manado", "East Kalimantan", ""),
("mde", "Aeropuerto Internacional José María Córdova", "José María Córdova International Airport", "", "Colombia", "Medellín", "Rionegro", ""),
("mdl", "Mandalay International Airport", "", "", "Myanmar", "Mandalay", "Tada-U", ""),
("mdq", "Aeropuerto Internacional de Mar del Plata “Ástor Piazzolla”", "Astor Piazzolla International Airport", "", "Argentina", "Mar del Plata", "", ""),
("mdt", "Harrisburg International Airport", "", "Pennsylvania", "USA", "Harrisburg", "Middletown", ""),
("mdw", "Midway International Airport", "", "Illinois", "USA", "Chicago", "", ""),
("mdz", "Aeropuerto Internacional Gobernador Francisco Gabrielli", "Governor Francisco Gabrielli International Airport", "", "Argentina", "Mendoza", "", ""),
("med", "Prince Mohammad bin Abdulaziz International Airport", "", "", "Saudi Arabia", "Medina", "", ""),
("mel", "Melbourne Airport", "", "Victoria", "Australia", "Melbourne", "Tullamarine", ""),
("mem", "Memphis International Airport", "", "Tennessee", "USA", "Memphis", "", ""),
("mex", "Aeropuerto Internacional Benito Juárez", "Benito Juárez International Airport", "Distrito Federal", "Mexico", "Mexico City", "", ""),
("mfd", "Mansfield Lahm Regional Airport", "", "Ohio", "USA", "Mansfield", "", ""),
("mga", "Aeropuerto Internacional Augusto C. Sandino", "Augusto César Sandino International Airport", "", "Nicaragua", "Managua", "", ""),
("mgl", "Flughafen Düsseldorf Mönchengladbach", "Düsseldorf Mönchengladbach Airport", "", "Germany", "Mönchengladbach", "Dusseldorf", ""),
("mgm", "Montgomery Regional Airport", "", "Alabama", "USA", "Montgomery", "", ""),
("mhd", "Shahid Hashemi Nejad Airport", "", "", "Iran", "Mashhad", "", ""),
("mht", "Manchester–Boston Regional Airport", "", "New Hampshire", "USA", "Manchester", "Londonberry", "Boston"),
("mia", "Miami International Airport", "", "Florida", "USA", "Miami", "", ""),
("mjv", "Aeropuerto de Murcia-San Javier", "Murcia-San Javier Airport", "", "Spain", "Murcia", "San Javier", ""),
("mke", "General Mitchell International Airport", "", "Wisconsin", "USA", "Milwaukee", "", ""),
("mkg", "Muskegon County Airport", "", "Michigan", "USA", "Norton Shores", "Muskegon County", ""),
("mla", "Ajruport Internazzjonali ta 'Malta", "Malta International Airport", "", "Malta", "Valletta", "Luqa", "Gudja"),
("mlb", "Melbourne International Airport", "", "Florida", "USA", "Melbourne", "", ""),
("mle", "Ibrahim Nasir International Airport", "", "Kaafu Atoll", "Maldives", "Male", "", ""),
("mlh", "EuroAirport Basel–Mulhouse–Freiburg", "", "Switzerland", "France", "Mulhouse", "Saint-Louis", "Freiburg"),
("mli", "Quad City International Airport", "", "Illinois", "USA", "Moline", "", ""),
("mln", "Aeropuerto de Melilla", "Melilla Airport", "", "Spain", "Melilla", "", ""),
("mlu", "Monroe Regional Airport", "", "Louisiana", "USA", "Monroe", "", ""),
("mme", "Durham Tees Valley Airport", "", "England", "UK", "Darlington", "Middlesbrough", ""),
("mmh", "Mammoth Yosemite Airport", "", "California", "USA", "Mammoth Lakes ", "", ""),
("mmx", "Malmö flygplats", "Malmö Airport", "", "Sweden", "Malmö", "Malmo", "Svedala"),
("mnl", "Paliparang Pandaigdig ng Ninoy Aquino", "Ninoy Aquino International Airport", "", "Philippines", "Manila", "Pasay", "Parañaque"),
("mob", "Mobile Regional Airport", "", "Alabama", "USA", "Mobile", "", ""),
("moo", "Moomba Airport", "", "South Australia", "Australia", "Moomba", "", ""),
("mpm", "Maputo International Airport", "", "", "Mozambique", "Maputo", "", ""),
("mqc", "Aéroport de Miquelon", "Miquelon Airport", "Saint Pierre and Miquelon", "France", "Miquelon", "", ""),
("mql", "Mildura Airport", "", "Victoria", "Australia", "Mildura", "", ""),
("mrs", "Aéroport de Marseille Provence", "Marseille Provence Airport", "", "France", "Marseille", "Marignane", ""),
("mru", "Sir Seewoosagur Ramgoolam International Airport", "", "", "Mauritius", "Plaine Magnien", "", ""),
("mry", "Monterey Regional Airport", "", "California", "USA", "Monterey", "", ""),
("msn", "Dane County Regional Airport", "", "Wisconsin", "USA", "Madison", "", ""),
("mso", "Missoula International Airport", "", "Montana", "USA", "Missoula", "", ""),
("msp", "Minneapolis–Saint Paul International Airport", "", "Minnesota", "USA", "Twin Cities", "Minneapolis", "St. Paul"),
("msq", "Minsk National Airport", "", "", "Belarus", "Minsk", "Kastrychnitski", ""),
("mst", "Maastricht Aachen Airport", "", "", "Netherlands", "Beek", "Maastricht", "Aachen"),
("msu", "Moshoeshoe I International Airport", "", "", "Lesotho", "Maseru", "Mazenod", ""),
("msy", "Louis Armstrong International Airport", "", "Louisiana", "USA", "New Orleans", "", ""),
("mtj", "Montrose Regional Airport", "", "Colorado", "USA", "Montrose", "", ""),
("mts", "Matsapha Airport", "", "", "Swaziland", "Manzini", "Matsapha", ""),
("mty", "Aeropuerto Internacional Mariano Escobedo", "Monterrey International Airport", "Nuevo León", "Mexico", "Monterrey", "Apodaca", ""),
("muc", "Flughafen München Franz Josef Strauß", "Munich Airport", "", "Germany", "Munich", "Freising", ""),
("mux", "Multan International Airport", "", "Punjab", "Pakistan", "Multan ", "", ""),
("mvd", "Aeropuerto Internacional de Carrasco/General Cesáreo L. Berisso", "Carrasco/General Cesáreo L. Berisso International Airport", "", "Uruguay", "Montevideo", "Canelones", ""),
("mvy", "Martha’s Vineyard Airport", "", "Massachusetts", "USA", "Martha’s Vineyard", "", ""),
("mxe", "Laurinburg–Maxton Airport", "", "North Carolina", "USA", "Maxton", "Rockingham", ""),
("mxp", "Aeroporto di Milano-Malpensa", "Milan–Malpensa Airport", "", "Italy", "Milan", "Ferno", ""),
("myf", "Montgomery Field Airport", "", "California", "USA", "San Diego", "", ""),
("myr", "Myrtle Beach International Airport", "", "South Carolina", "USA", "Myrtle Beach", "", ""),
("myt", "Myitkyina Airport", "", "", "Myanmar", "Myitkyina", "", ""),
("mzl", "Aeropuerto La Nubia", "La Nubia Airport", "", "Colombia", "Manizales", "", ""),
("nag", "Dr. Babasaheb Ambedkar International Airport", "", "Maharashtra", "India", "Nagpur", "", ""),
("nan", "Nadi International Airport", "", "", "Fiji", "Nadi", "Viti Levu", ""),
("nap", "Aeroporto Internazionale di Napoli", "Naples International Airport", "", "Italy", "Naples", "", ""),
("nas", "Lynden Pindling International Airport", "", "", "Bahamas", "Nassau", "", ""),
("nat", "Aeroporto Internacional Augusto Severo", "Augusto Severo International Airport", "Rio Grande do Norte", "Brazil", "Natal", "Parnamirim", ""),
("nbo", "Jomo Kenyatta International Airport", "", "", "Kenya", "Nairobi", "Embakasi", ""),
("nce", "Aéroport Nice Côte d'Azur", "Nice Côte d'Azur Airport", "", "France", "Nice", "Côte d'Azur", ""),
("ncl", "Newcastle International Airport", "", "England", "UK", "Newcastle", "Woolsington", ""),
("ndj", "N’Djamena International Airport", "", "", "Chad", "N’Djamena", "N'Djamena", ""),
("ndl", "N’Délé Airport", "", "", "Central African Republic", "N’Délé", "", ""),
("ngo", "Chūbu Centrair International Airport", "", "", "Japan", "Nagoya", "Tokoname City", ""),
("ngs", "Nagasaki Airport", "", "", "Japan", "Nagasaki", "Ōmura", ""),
("nic", "Nicosia International Airport", "", "", "Cyprus", "Nicosia", "", ""),
("nim", "Diori Hamani International Airport", "", "", "Niger", "Niamey", "", ""),
("nkc", "Nouakchott International Airport", "", "", "Mauritania", "Nouakchott", "", ""),
("nos", "Fascene Airport", "", "", "Madagascar", "Nosy Be", "", ""),
("nqy", "Newquay Cornwall Airport", "", "England", "UK", "Newquay", "Cornwall", ""),
("nrn", "Flughafen Weeze", "Weeze Airport", "North Rhine-Westphalia", "Germany", "Weeze", "", ""),
("nrt", "Narita International Airport", "", "", "Japan", "Tokyo", "", ""),
("nsn", "Nelson Airport", "", "", "New Zealand", "Nelson", "Annesbrook", ""),
("nte", "Aéroport Nantes Atlantique", "Nantes Atlantique Airport", "", "France", "Nantes", "Bouguenais", ""),
("nue", "Flughafen Nürnberg", "Nuremberg Airport", "Bavaria", "Germany", "Nuremberg", "Nürnberg", ""),
("nwi", "Norwich International Airport", "", "England", "UK", "Norwich", "Norfolk", ""),
("nyo", "Stockholm Skavsta flygplats", "Stockholm Skavsta Airport", "", "Sweden", "Stockholm", "Nyköping", ""),
("oak", "Oakland International Airport", "", "California", "USA", "Oakland", "", ""),
("obn", "Oban Airport", "", "Scotland", "UK", "Oban", "North Connel", ""),
("ods", "Odessa International Airport", "", "", "Ukraine", "Odessa", "", ""),
("ogg", "Kahului Airport", "", "Hawaii", "USA", "Kahului", "Maui", ""),
("ohd", "Aerodrom Ohrid “Sv. Apostol Pavle”", "Ohrid “St. Paul the Apostle” Airport", "", "Macedonia", "Ohrid", "Orovnik", ""),
("oka", "Naha Airport", "", "", "Japan", "Naha", "Okinawa", ""),
("okc", "Will Rogers World Airport", "", "Oklahoma", "USA", "Oklahoma City", "", ""),
("oma", "Eppley Airfield", "", "Nebraska", "USA", "Omaha", "", ""),
("ome", "Nome Airport", "", "Alaska", "USA", "Nome", "", ""),
("omo", "Mostar International Airport", "", "", "Bosnia and Herzegovina", "Mostar", "Ortiješ", ""),
("oms", "Omsk Tsentralny Airport", "", "Siberia", "Russia", "Omsk", "", ""),
("ont", "LA/Ontario International Airport", "", "California", "USA", "Ontario", "", ""),
("ool", "Gold Coast Airport", "Coolangatta Airport", "Queensland", "Australia", "Gold Coast", "Bilinga", ""),
("opo", "Aeroporto Francisco Sá Carneiro", "Francisco de Sá Carneiro Airport", "", "Portugal", "Porto", "Oporto", ""),
("orb", "Örebro flygplats", "Örebro Airport", "", "Sweden", "Örebro", "Orebro", ""),
("ord", "O’Hare International Airport", "", "Illinois", "USA", "Chicago", "", ""),
("orf", "Norfolk International Airport", "", "Virginia", "USA", "Norfolk", "", ""),
("orh", "Worcester Regional Airport", "", "Massachusetts", "USA", "Worcester", "", ""),
("ork", "Cork Airport", "", "", "Ireland", "Cork", "Ballygarvan", ""),
("ory", "Aéroport de Paris-Orly", "Paris Orly Airport", "", "France", "Paris", "Orly", "Villeneuve"),
("osl", "Oslo lufthavn", "Oslo Airport", "", "Norway", "Oslo", "Gardermoen", ""),
("ost", "Internationale Luchthaven Oostende-Brugge", "Ostend-Bruges International Airport", "", "Belgium", "Ostend", "Bruges", ""),
("otp", "Aeroportul Internațional Henri Coandă", "Bucharest Henri Coandǎ International Airport", "", "Romania", "Bucharest", "Otopeni", ""),
("oua", "Ouagadougou International Airport", "", "", "Burkina Faso", "Ouagadougou", "", ""),
("oul", "Oulun lentoasema", "Oulu Airport", "", "Finland", "Oulu", "", ""),
("ovb", "Novosibirsk Tolmachevo Airport", "", "", "Russia", "Novosibirsk", "", ""),
("ovd", "Aeropuerto de Asturias", "Asturias Airport", "", "Spain", "Asturias", "Oviedo", ""),
("oxb", "Aeroporto Internacional Osvaldo Vieira", "Osvaldo Vieira International Airport", "", "Guinea-Bissau", "Bissau", "", ""),
("oxf", "London Oxford Airport", "", "England", "UK", "Oxford", "Kidlington", ""),
("pae", "Snohomish County Airport", "", "Washington", "USA", "Everett", "Mukilteo", ""),
("pap", "Aéroport International Toussaint L'Ouverture", "Toussaint L'Ouverture International Airport", "", "Haiti", "Port-au-Prince", "Tabarre", ""),
("pbg", "Plattsburgh International Airport", "", "New York", "USA", "Plattsburgh", "", ""),
("pbh", "Paro International Airport", "", "", "Bhutan", "Paro", "", ""),
("pbi", "Palm Beach International Airport", "", "Florida", "USA", "Palm Beach", "Miami", ""),
("pbm", "Johan Adolf Pengel International Airport", "", "", "Suriname", "Paramaribo", "Zanderij", ""),
("pcl", "Aeropuerto Internacional Capitán FAP David Abensur Rengifo", "Capitán FAP David Abensur Rengifo International Airport", "Ucayalí", "Peru", "Pucallpa", "", ""),
("pdg", "Bandar Udara Internasional Minangkabau", "Minangkabau International Airport ", "West Sumatra", "Indonesia", "Padang", "", ""),
("pdl", "Aeroporto João Paulo II", "João Paulo II Airport", "Azores", "Portugal", "Ponta Delgada", "São Miguel", ""),
("pdp", "Aeropuerto Internacional Capitán de Corbeta Carlos A. Curbelo", "Capitán de Corbeta Carlos A. Curbelo International Airport", "", "Uruguay", "Punta del Este", "Piriápolis", ""),
("pdv", "Letishte Plovdiv", "Plovdiv Airport", "", "Bulgaria", "Plovdiv", "Krumovo", ""),
("pdx", "Portland International Airport", "", "Oregon", "USA", "Portland", "", ""),
("pee", "Perm International Airport", "", "", "Russia", "Perm", "", ""),
("pek", "Beijing Capital International Airport", "", "Chaoyang District", "China", "Beijing", "", ""),
("pem", "Aeropuerto Internacional Padre Aldamiz", "Padre Aldamiz International Airport", "Madre de Dios", "Peru", "Puerto Maldonado", "", ""),
("pen", "Lapangan Terbang Antarabangsa Pulau Pinang", "Penang International Airport", "Pulau Pinang", "Malaysia", "Pulau Pinang", "Bayan Lepas", ""),
("per", "Perth Airport", "", "Western Australia", "Australia", "Perth", "", ""),
("pew", "Bacha Khan International Airport", "", "Khyber Pakhtunkhwa", "Pakistan", "Peshawar", "", ""),
("pfb", "Aeroporto Lauro Kurtz", "Lauro Kurtz Airport", "Rio Grande do Sul", "Brazil", "Passo Fundo", "", ""),
("pfo", "Paphos International Airport", "", "", "Cyprus", "Paphos", "Timi", "Acheleia"),
("phc", "Port Harcourt International Airport", "", "", "Nigeria", "Port Harcourt", "Omagwa", ""),
("phf", "Newport News/Williamsburg International Airport", "", "Virginia", "USA", "Newport News", "Williamsburg", ""),
("phk", "Palm Beach County Glades Airport", "", "Florida", "USA", "Pahokee", "", ""),
("phl", "Philadelphia International Airport", "", "Pennsylvania", "USA", "Philadelphia", "", ""),
("phx", "Sky Harbor International Airport", "", "Arizona", "USA", "Phoenix", "", ""),
("pie", "St. Pete–Clearwater International Airport", "", "Florida", "USA", "Clearwater", "Pinellas County", "St. Petersburg"),
("pik", "Glasgow Prestwick Airport", "", "Scotland", "UK", "Glasgow", "Prestwick", ""),
("pio", "Aeropuerto Capitán FAP Renán Elías Olivera", "Capitán FAP Renán Elías Olivera Airport", "Ica", "Peru", "Pisco", "", ""),
("pit", "Pittsburgh International Airport", "", "Pennsylvania", "USA", "Pittsburgh", "Findlay", "Moon"),
("piu", "Aeropuerto Internacional Capitán FAP Guillermo Concha Iberico", "Capitán FAP Guillermo Concha Iberico International Airport", "", "Peru", "Piura", "", ""),
("pix", "Aeroporto do Pico", "Pico Airport", "Azores", "Portugal", "Pico", "Madalena", ""),
("plu", "Aeroporto Carlos Drummond de Andrade", "Carlos Drummond de Andrade Airport", "Minas Gerais", "Brazil", "Belo Horizonte", "Pampulha", ""),
("pmi", "Aeropuerto de Palma de Mallorca", "Palma de Mallorca Airport", "", "Spain", "Mallorca", "Palma de Mallorca", ""),
("pmw", "Aeroporto de Palmas-Brigadeiro Lysias Rodrigues", "Palmas-Brigadeiro Lysias Rodrigues Airport", "Tocantins", "Brazil", "Palmas", "", ""),
("pna", "Aeropuerto de Pamplona", "Pamplona Airport", "", "Spain", "Pamplona", "Noáin", "Esquiroz"),
("pnh", "Phnom Penh International Airport", "", "", "Cambodia", "Phnom Penh", "", ""),
("pni", "Pohnpei International Airport", "", "", "Micronesia", "Pohnpei Island", "", ""),
("pnk", "Bandar Udara Internasional Supadio", "Supadio International Airport ", "West Kalimantan", "Indonesia", "Pontianak", "", ""),
("pnq", "Pune Airport", "", "Maharashtra", "India", "Pune", "Poona", ""),
("pns", "Pensacola International Airport", "", "Florida", "USA", "Pensacola", "", ""),
("pnz", "Aeroporto de Petrolina–Senador Nilo Coelho", "Petrolina–Senador Nilo Coelho Airport", "Bahia", "Brazil", "Petrolina", "Juazeiro", ""),
("poa", "Aeroporto Internacional Salgado Filho", "Salgado Filho International Airport", "Rio Grande do Sul", "Brazil", "Porto Alegre", "São João", ""),
("pom", "Jacksons International Airport", "Port Moresby Airport", "", "Papua New Guinea", "Port Moresby", "", ""),
("poo", "Aeroporto Poços de Caldas", "Poços de Caldas Airport", "Minas Gerais", "Brazil", "Poços de Caldas", "Pocos de Caldas", ""),
("pos", "Piarco International Airport", "", "", "Trinidad and Tobago", "Piarco", "Port of Spain", ""),
("ppg", "Pago Pago International Airport", "Tafuna Airport", "American Samoa", "USA", "Pago Pago", "Tafuna", ""),
("ppt", "Fa'a'ā International Airport", "", "French Polynesia", "France", "Tahiti", "Pape'ete", ""),
("pqc", "Sân bay quốc tế Phú Quôc", "Phu Quoc International Airport", "", "Vietnam", "Phu Quoc", "", ""),
("prg", "Letiště Václava Havla Praha", "Václav Havel Airport Prague", "", "Czech Republic", "Prague", "Ruzyně", ""),
("prn", "Pristina International Airport Adem Jashari", "", "", "Kosovo", "Pristina", "", ""),
("psa", "Aeroporto Internazionale di Pisa", "Pisa International Airport", "", "Italy", "Pisa", "", ""),
("psc", "Tri-Cities Airport", "", "Washington", "USA", "Tri-Cities", "Pasco", "Richland"),
("pse", "Aeropuerto Mercedita", "Mercedita Airport", "Puerto Rico", "USA", "Ponce", "", ""),
("psp", "Palm Springs International Airport", "", "California", "USA", "Palm Springs", "", ""),
("ptk", "Oakland County International Airport", "", "Michigan", "USA", "Oakland County", "Waterford Township", ""),
("ptp", "Aérodrome de Pointe-à-Pitre Le Raizet", "Pointe-à-Pitre Le Raizet Airport", "Guadeloupe", "France", "Pointe-à-Pitre", "Grande-Terre", ""),
("pty", "Aeropuerto Internacional de Tocumen", "Tocumen International Airport", "", "Panama", "Panama City", "", ""),
("puf", "Aéroport Pau Pyrénées", "Pau Pyrénées Airport", "", "France", "Pau", "Uzein", ""),
("puq", "Aeropuerto Internacional Presidente Carlos Ibáñez", "Presidente Carlos Ibáñez International Airport", "", "Chile", "Punta Arenas", "", ""),
("pus", "Gimhae International Airport", "", "Korea", "South Korea", "Busan", "Pusan", ""),
("pvd", "Theodore Francis Green Memorial State Airport", "", "Rhode Island", "USA", "Providence", "Warwick", ""),
("pvg", "Shanghai Pudong International Airport", "", "", "China", "Shanghai", "Pudong", ""),
("pvr", "Aeropuerto Internacional Lic. Gustavo Díaz Ordaz", "Lic. Gustavo Díaz Ordaz International Airport", "Jalisco", "Mexico", "Puerto Vallarta", "", ""),
("pvu", "Provo Municipal Airport", "", "Utah", "USA", "Provo", "", ""),
("pwm", "Portland International Jetport", "", "Maine", "USA", "Portland", "Westbrook", ""),
("pxo", "Aeroporto de Porto Santo", "Porto Santo Airport", "Madeira", "Portugal", "Porto Santo", "", ""),
("pxu", "Sân bay Pleiku", "Pleiku Airport", "", "Vietnam", "Pleiku", "", ""),
("pzo", "Manuel Carlos Piar Guayana International Airport", "", "Bolívar", "Venezuela", "Ciudad Guayana", "Puerto Ordaz", "San Félix"),
("qro", "Aeropuerto Intercontinental de Querétaro", "Querétaro Intercontinental Airport", "Querétaro", "Mexico", "Querétaro", "", ""),
("rai", "Aeroporto Internacional Nelson Mandela", "Nelson Mandela International Airport", "", "Cape Verde", "Praia", "Santiago Island", ""),
("rak", "Marrakesh Menara Airport", "", "", "Morocco", "Marrakesh", "", ""),
("rba", "Rabat–Salé Airport", "", "", "Morocco", "Rabat", "Salé", ""),
("rbd", "Dallas Executive Airport", "", "Texas", "USA", "Dallas", "", ""),
("rdd", "Redding Municipal Airport", "", "California", "USA", "Redding", "", ""),
("rdu", "Raleigh–Durham International Airport", "", "North Carolina", "USA", "Raleigh", "Durham", ""),
("rec", "Aeroporto Internacional do Recife/Guararapes–Gilberto Freyre", "Recife/Guararapes–Gilberto Freyre International Airport", "Pernambuco", "Brazil", "Recife", "", ""),
("rep", "Siem Reap International Airport", "", "", "Cambodia", "Siem Reap", "", ""),
("rfd", "Chicago Rockford International Airport", "", "Illinois", "USA", "Rockford", "", ""),
("rgi", "Rangiroa Airport", "", "French Polynesia", "France", "Rangiroa", "", ""),
("rgn", "Yangon International Airport", "", "", "Myanmar", "Yangon", "Rangoon", "Mingaladon"),
("ric", "Richmond International Airport", "", "Virginia", "USA", "Richmond", "Sandston", ""),
("riv", "March Air Reserve Base", "", "California", "USA", "Riverside", "", ""),
("riw", "Riverton Regional Airport", "", "Wyoming", "USA", "Riverton", "", ""),
("rix", "Starptautiskā lidosta “Rīga”", "Riga International Airport”", "", "Latvia", "Riga", "", ""),
("rjl", "Aeropuerto de Logroño-Agoncillo", "Logroño-Agoncillo Airport", "", "Spain", "Logroño", "Agoncillo", ""),
("rlg", "Flughafen Rostock–Laage", "Rostock–Laage Airport", "", "Germany", "Rostock", "Laage", ""),
("rms", "Ramstein Air Base", "", "", "Germany", "Ramstein-Miesenbach", "Kaiserslautern", ""),
("rno", "Reno–Tahoe International Airport", "", "Nevada", "USA", "Reno", "Tahoe", ""),
("rns", "Aéroport de Rennes - Saint-Jacques", "Rennes Saint-Jacques Airport", "", "France", "Rennes", "", ""),
("rnt", "Renton Municipal Airport", "", "Washington", "USA", "Renton", "", ""),
("roa", "Roanoke–Blacksburg Regional Airport", "", "Virginia", "USA", "Roanoke", "", ""),
("roc", "Greater Rochester International Airport", "", "New York", "USA", "Rochester", "", ""),
("ror", "Roman Tmetuchl International Airport", "", "", "Palau", "Melekeok", "Airai", "Koror"),
("ros", "Aeropuerto Internacional Rosario Islas Malvinas", "Rosario – Islas Malvinas International Airport", "Santa Fe", "Argentina", "Rosario", "Funes", ""),
("rov", "Aeroport Rostov-na-Donu", "Rostov-on-Don Airport", "", "Russia", "Rostov-on-Don", "", ""),
("row", "Roswell International Air Center", "", "New Mexico", "USA", "Roswell", "", ""),
("rpr", "Swami Vivekananda International Airport", "", "Chhattisgarh", "India", "Raipur", "Mana", "Naya Raipur"),
("rrg", "Sir Gaëtan Duval Airport", "", "Rodrigues", "Mauritius", "Plaine Corail", "", ""),
("rst", "Rochester International Airport", "", "Minnesota", "USA", "Rochester", "", ""),
("rsw", "Southwest Florida International Airport", "", "Florida", "USA", "Fort Myers", "", ""),
("rtm", "Rotterdam The Hague Airport", "", "", "Netherlands", "Rotterdam", "The Hague", ""),
("ruh", "King Khalid International Airport", "", "", "Saudi Arabia", "Riyadh", "", ""),
("run", "Aéroport de la Réunion Roland Garros", "Roland Garros Airport", "Réunion", "France", "Saint-Denis", "", ""),
("ryg", "Moss lufthavn, Rygge", "Moss Airport, Rygge", "", "Norway", "Rygge", "Moss", ""),
("ryk", "Shaikh Zayed International Airport", "", "Punjab", "Pakistan", "Rahim Yar Khan", "", ""),
("rze", "Port Lotniczy Rzeszów-Jasionka", "Rzeszów–Jasionka Airport", "", "Poland", "Rzeszów", "Jasionka", ""),
("sab", "Juancho E. Yrausquin Airport", "", "", "Netherlands", "Saba", "", ""),
("saf", "Santa Fe Municipal Airport", "", "New Mexico", "USA", "Santa Fe", "", ""),
("sah", "Sana'a International Airport", "", "", "Yemen", "Sana'a", "", ""),
("sal", "Aeropuerto Internacional Monseñor Óscar Arnulfo Romero", "Monseñor Óscar Arnulfo Romero International Airport", "", "El Salvador", "San Salvador", "La Paz", ""),
("san", "Lindbergh Field", "", "California", "USA", "San Diego", "", ""),
("sat", "San Antonio International Airport", "", "Texas", "USA", "San Antonio", "", ""),
("sav", "Savannah/Hilton Head International Airport", "", "Georgia", "USA", "Savannah", "Hilton Head Island", ""),
("saw", "Sabiha Gökçen Uluslararası Havalimanı", "Istanbul Sabiha Gökçen International Airport", "", "Turkey", "Istanbul", "", ""),
("sba", "Santa Barbara Municipal Airport", "", "California", "USA", "Santa Barbara", "", ""),
("sbd", "San Bernardino International Airport", "", "California", "USA", "San Bernardino", "", ""),
("sbn", "South Bend International Airport", "", "Indiana", "USA", "South Bend", "", ""),
("sbp", "San Luis Obispo County Regional Airport", "", "California", "USA", "San Luis Obispo", "", ""),
("sce", "University Park Airport", "", "Pennsylvania", "USA", "State College", "Bellefonte", ""),
("scl", "Aeropuerto Internacional Comodoro Arturo Merino Benítez", "Comodoro Arturo Merino Benítez International Airport", "", "Chile", "Santiago", "Pudahuel", ""),
("sco", "International Airport Aktau", "", "", "Kazakhstan", "Aktau", "", ""),
("scq", "Aeroporto Internacional de Santiago de Compostela", "Santiago de Compostela Airport", "", "Spain", "Santiago de Compostela", "Galicia", "Lavacolla"),
("sct", "Socotra Airport", "", "", "Yemen", "Socotra", "Hadibu", ""),
("sdf", "Louisville International Airport", "", "Kentucky", "USA", "Louisville", "", ""),
("sdq", "Aeropuerto Internacional Las Américas", "Las Américas International Airport", "", "Dominican Republic", "Santo Domingo", "Punta Caucedo", "Boca Chica"),
("sdr", "Aeropuerto Seve Ballesteros - Santander", "Seve Ballesteros - Santander Airport", "", "Spain", "Santander", "Maliaño", ""),
("sdu", "Aeroporto Santos Dumont", "Santos Dumont Airport", "Rio de Janeiro", "Brazil", "Rio de Janeiro", "", ""),
("sea", "Seattle–Tacoma International Airport", "", "Washington", "USA", "Seattle", "Tacoma", "SeaTac"),
("sen", "London Southend Airport", "", "England", "UK", "London", "Southend", "Rochford"),
("sex", "Sembach Kaserne", "", "", "Germany", "Sembach", "", ""),
("sfa", "Aéroport International de Sfax-Thyna", "Sfax-Thyna International Airport", "", "Tunisia", "Sfax", "Thyna", ""),
("sfj", "Søndre Strømfjord Lufthavn", "Kangerlussuaq Airport", "Greenland", "Denmark", "Kangerlussuaq", "Qeqqata", ""),
("sfn", "Aeropuerto de Santa Fe - Sauce Viejo", "Sauce Viejo Airport", "", "Argentina", "Santa Fe", "", ""),
("sfo", "San Francisco International Airport", "", "California", "USA", "San Francisco", "", ""),
("sgc", "Surgut International Airport", "", "", "Russia", "Surgut", "", ""),
("sgf", "Springfield–Branson National Airport", "", "Missouri", "USA", "Springfield", "", ""),
("sgn", "Sân bay Quốc tế Tân Sơn Nhất", "", "", "Vietnam", "Ho Chi Minh City", "Saigon", ""),
("sgu", "St. George Regional Airport", "", "Utah", "USA", "St. George", "", ""),
("sgy", "Skagway Airport", "", "Alaska", "USA", "Skagway", "", ""),
("sha", "Shanghai Hongqiao International Airport", "", "", "China", "Shanghai", "Hongqiao", "Changning District"),
("shd", "Shenandoah Valley Regional Airport", "", "Virginia", "USA", "Staunton", "Weyers Cave", ""),
("shv", "Shreveport Regional Airport", "", "Louisiana", "USA", "Shreveport", "", ""),
("sid", "Aeroporto Internacional Amílcar Cabral", "Amílcar Cabral International Airport", "", "Cape Verde", "Espargos", "Sal Island", ""),
("sin", "Lapangan Terbang Changi Singapura", "Singapore Changi Airport", "", "Singapore", "Singapore", "Changi", ""),
("sip", "Simferopol International Airport", "", "", "Russia", "Simferopol", "", ""),
("sir", "Aéroport de Sion", "Sion Airport", "", "Switzerland", "Sion", "Rhone Valley", ""),
("sjc", "Norman Y. Mineta San Jose International Airport", "", "California", "USA", "San Jose", "", ""),
("sjd", "Aeropuerto Internacional de Los Cabos", "Los Cabos International Airport", "Baja California Sur", "Mexico", "San José del Cabo", "Cabo San Lucas", ""),
("sjj", "Sarajevo International Airport", "", "", "Bosnia and Herzegovina", "Sarajevo", "Butmir", ""),
("sjk", "Aeroporto de São José dos Campos-Professor Urbano Ernesto Stumpf", "São José dos Campos-Professor Urbano Ernesto Stumpf Airport", "São Paulo", "Brazil", "São José dos Campos", "", ""),
("sjo", "Aeropuerto Internacional Juan Santamaría", "Juan Santamaría International Airport", "", "Costa Rica", "San José", "San Jose", "Alajuela"),
("sju", "Aeropuerto Internacional Luis Muñoz Marín", "Luis Muñoz Marín International Airport", "Puerto Rico", "USA", "San Juan", "Carolina", ""),
("sjz", "Aérodromo de São Jorge", "São Jorge Airport", "Azores", "Portugal", "São Jorge", "Velas", ""),
("skb", "Robert L. Bradshaw International Airport", "", "", "Saint Kitts and Nevis", "Basseterre", "", ""),
("skg", "Thessaloniki International Airport, Macedonia", "", "", "Greece", "Thessaloniki", "Mikra", ""),
("skp", "Aerodrom Skopje “Aleksandar Veliki”", "Skopje “Alexander the Great” Airport", "", "Macedonia", "Skopje ", "Petrovec", ""),
("skz", "Sukkur Airport", "", "Sindh", "Pakistan", "Sukkur", "", ""),
("slc", "Salt Lake City International Airport", "", "Utah", "USA", "Salt Lake City", "", ""),
("slk", "Adirondack Regional Airport", "", "New York", "USA", "Saranac Lake", "Lake Placid", "Harrietstown"),
("slm", "Aeropuerto de Salamanca-Matacán", "Salamanca-Matacán Airport", "Castile and León", "Spain", "Salamanca", "Matacán", ""),
("sln", "Salina Regional Airport", "", "Kansas", "USA", "Salina", "", ""),
("slu", "George F. L. Charles Airport", "", "", "Saint Lucia", "Castries", "", ""),
("slz", "Aeroporto Internacional Marechal Cunha Machado", "Marechal Cunha Machado International Airport", "Maranhão", "Brazil", "São Luís", "", ""),
("sma", "Aeroporto de Santa Maria", "Santa Maria Airport", "Azores", "Portugal", "Vila do Porto", "Santa Maria", ""),
("smf", "Sacramento International Airport", "", "California", "USA", "Sacramento", "", ""),
("sna", "John Wayne International Airport", "", "California", "USA", "Orange County", "Santa Ana", ""),
("snn", "Shannon Airport", "", "", "Ireland", "Shannon", "", ""),
("sob", "Hévíz-Balaton Repülőtér", "Heviz-Balaton Airport", "", "Hungary", "Balaton", "Sármellék", "Sarmellek"),
("soc", "Bandar Udara Internasional Adisumarmo", "Adisumarmo International Airport", "", "Indonesia", "Surakarta", "Ngemplak", "Central Java"),
("sof", "Letishte Sofiya", "Sofia Airport", "", "Bulgaria", "Sofia", "Vrazhdebna", ""),
("soq", "Bandar Udara Domine Edward Osok", "Domine Edward Osok Airport", "West Papua", "Indonesia", "Sorong", "", ""),
("sou", "Southampton Airport", "", "England", "UK", "Southampton", "Eastleigh", ""),
("soy", "Stronsay Airport", "", "Scotland", "UK", "Stronsay", "Orkney Islands", ""),
("spg", "Albert Whitted Airport", "", "Florida", "USA", "Saint Petersburg", "Tampa Bay", ""),
("spu", "Zračna luka Split", "Split Airport", "", "Croatia", "Split", "Kaštela", "Kastela"),
("sql", "San Carlos Airport", "", "California", "USA", "San Carlos", "", ""),
("sre", "Aeropuerto Internacional Juana Azurduy de Padilla", "Juana Azurduy de Padilla International Airport", "", "Bolivia", "Sucre", "", ""),
("srg", "Bandar Udara Internasional Ahmad Yani", "Ahmad Yani International Airport", "", "Indonesia", "Semarang", "East Java", ""),
("srq", "Sarasota–Bradenton International Airport", "", "Florida", "USA", "Sarasota", "Bradenton", ""),
("ssa", "Aeroporto Internacional de Salvador-Deputado Luís Eduardo Magalhães ", "Salvador-Deputado Luís Eduardo Magalhães International Airport", "Bahia", "Brazil", "Salvador", "", ""),
("ssf", "Stinson Municipal Airport", "", "Texas", "USA", "San Antonio", "", ""),
("ssg", "Aeropuerto de Malabo", "Malabo Airport", "", "Equatorial Guinea", "Malabo", "Bioko", ""),
("ssh", "Sharm el-Sheikh International Airport", "", "", "Egypt", "Sharm el-Sheikh", "", ""),
("sti", "Aeropuerto Internacional del Cibao", "Cibao International Airport", "", "Dominican Republic", "Santiago de los Caballeros", "", ""),
("stl", "Lambert–St. Louis International Airport", "", "Missouri", "USA", "St. Louis", "", ""),
("stn", "London Stansted Airport", "", "England", "UK", "London", "Stansted Mountfitchet", ""),
("stp", "St. Paul Downtown Airport", "", "Minnesota", "USA", "Saint Paul", "Twin Cities", ""),
("str", "Flughafen Stuttgart - Manfred Rommel Flughafen", "Stuttgart Airport", "", "Germany", "Stuttgart", "", ""),
("sts", "Charles M. Schulz - Sonoma County Airport", "", "California", "USA", "Santa Rosa", "Sonoma County", ""),
("stt", "Cyril E. King Airport", "", "Virgin Islands", "USA", "Saint Thomas", "St. Thomas", ""),
("stx", "Henry E. Rohlsen Airport", "", "Virgin Islands", "USA", "Saint Croix", "St. Croix", ""),
("sub", "Bandar Udara Internasional Juanda", "Juanda International Airport", "East Java", "Indonesia", "Surabaya", "Sidoarjo", ""),
("sun", "Friedman Memorial Airport", "", "Idaho", "USA", "Hailey", "Sun Valley", "Ketchum"),
("suv", "Nausori International Airport", "", "", "Fiji", "Suva", "Nausori", "Viti Levu"),
("sux", "Sioux Gateway Airport", "", "Iowa", "USA", "Sioux City", "", ""),
("svd", "E. T. Joshua Airport", "", "", "Saint Vincent and the Grenadines", "Kingstown", "Arnos Vale", ""),
("svg", "Stavanger lufthavn, Sola", "Stavanger Airport, Sola", "", "Norway", "Stavanger", "Sola", ""),
("svo", "Sheremetyevo International Airport", "", "", "Russia", "Moscow", "Khimki", ""),
("svq", "Aeropuerto de Sevilla", "Seville Airport", "", "Spain", "Seville", "", ""),
("svx", "Koltsovo International Airport", "", "", "Russia", "Yekaterinburg", "Sverdlovsk", ""),
("swf", "Stewart International Airport", "", "New York", "USA", "Newburgh", "Hudson Valley", ""),
("sxb", "Aéroport International de Strasbourg", "Strasbourg International Airport", "", "France", "Strasbourg", "Entzheim", ""),
("sxf", "Flughafen Berlin-Schönefeld", "Berlin Schönefeld Airport", "", "Germany", "Berlin", "Schönefeld", "Schonefeld"),
("sxm", "Princess Juliana International Airport", "", "Saint Martin", "Netherlands", "Simpson Bay", "Sint Maarten", "France"),
("sxr", "Srinagar International Airport", "", "Jammu and Kashmir", "India", "Srinagar", "", ""),
("syd", "Sydney (Kingsford Smith) Airport", "", "New South Wales", "Australia", "Sydney", "", ""),
("syr", "Syracuse Hancock International Airport", "", "New York", "USA", "Syracuse", "", ""),
("syx", "Sanya Phoenix International Airport", "", "Hainan", "China", "Sanya", "", ""),
("syz", "Shiraz International Airport", "", "", "Iran", "Shiraz", "", ""),
("szb", "Lapangan Terbang Sultan Abdul Aziz Shah", "Sultan Abdul Aziz Shah Airport", "Selangor", "Malaysia", "Subang", "Kuala Lumpur", ""),
("szg", "Salzburg Airport W. A. Mozart", "", "", "Austria", "Salzburg", "", ""),
("tab", "A.N.R. Robinson International Airport", "", "", "Trinidad and Tobago", "Scarborough", "Crown Point", "Tobago"),
("tak", "Takamatsu Airport", "", "", "Japan", "Takamatsu", "", ""),
("tao", "Qingdao Liuting International Airport", "", "Chengyang District", "China", "Qingdao", "Shandong", ""),
("tas", "Toshkent Xalqaro Aeroporti", "Tashkent International Airport", "", "Uzbekistan", "Tashkent", "", ""),
("tbb", "Sân bay Đông Tác", "Dong Tac Airport", "", "Vietnam", "Tuy Hoa", "", ""),
("tbp", "Aeropuerto Capitán FAP Pedro Canga Rodríguez", "Capitán FAP Pedro Canga Rodríguez Airport", "", "Peru", "Tumbes", "", ""),
("tbs", "Tbilisi International Airport", "", "", "Georgia", "Tbilisi", "", ""),
("tbz", "Tabriz International Airport", "", "", "Iran", "Tabriz", "", ""),
("tcq", "Aeropuerto Internacional Coronel FAP Carlos Ciriani Santa Rosa", "Coronel FAP Carlos Ciriani Santa Rosa International Airport", "", "Peru", "Tacna", "", ""),
("ter", "Base Aérea das Lajes", "Lajes Field", "Azores", "Portugal", "Lajes", "Terceira", ""),
("tfn", "Aeropuerto de Tenerife Norte", "Tenerife North Airport", "Canary Islands", "Spain", "Tenerife", "Santa Cruz de Tenerife", ""),
("tfs", "Aeropuerto de Tenerife Sur Reina Sofía", "Tenerife South Reina Sofia Airport", "Canary Islands", "Spain", "Tenerife", "Playa de Las Américas", "Granadilla de Abona"),
("tgd", "Podgorica Airport", "", "", "Montenegro", "Podgorica", "Golubovci", ""),
("tgi", "Aeropuerto Tingo María", "Tingo Maria Airport", "Huánuco", "Peru", "Tingo María", "", ""),
("tgm", "Aeroportul Transilvania Târgu Mureș", "Transilvania Târgu Mureș Airport", "", "Romania", "Târgu Mureș", "Targu Mures", "Vidrasău"),
("tgu", "Aeropuerto Internacional Toncontín", "Toncontín International Airport", "", "Honduras", "Tegucigalpa", "", ""),
("thr", "Mehrabad International Airport", "", "", "Iran", "Tehran", "", ""),
("tia", "Tirana International Airport Nënë Tereza", "", "", "Albania", "Tirana", "Rinas", ""),
("tif", "Ta’if Regional Airport", "", "Mecca Province", "Saudi Arabia", "Ta’if", "Ta'if", "Taif"),
("tij", "Aeropuerto Internacional de Tijuana", "Tijuana International Airport", "Baja California", "Mexico", "Tijuana", "", ""),
("tip", "Tripoli International Airport", "", "", "Libya", "Tripoli", "Qasr bin Ghashir", ""),
("tjm", "Roshchino International Airport", "", "", "Russia", "Tyumen", "", ""),
("tkk", "Chuuk International Airport", "", "", "Micronesia", "Weno", "Chuuk", "Truk"),
("tll", "Lennart Meri Tallinna lennujaam", "Lennart Meri Tallinn Airport", "", "Estonia", "Tallinn", "", ""),
("tls", "Aéroport de Toulouse–Blagnac", "Toulouse–Blagnac Airport", "", "France", "Toulouse", "Blagnac", ""),
("tlv", "Ben Gurion Airport", "", "", "Israel", "Tel Aviv", "", ""),
("tms", "Aeroporto Internacional de São Tomé", "São Tomé International Airport", "", "São Tomé and Príncipe", "São Tomé", "Sao Tome", ""),
("tng", "Tangier Ibn Battouta Airport", "", "", "Morocco", "Tangier", "", ""),
("tnm", "Aeropuerto Teniente Rodolfo Marsh", "Teniente Rodolfo Marsh Airport", "", "Antarctica", "King George Island", "Villa Las Estrellas", ""),
("tnr", "Ivato International Airport", "", "", "Madagascar", "Antananarivo", "", ""),
("tnt", "Dade-Collier Training and Transition Airport", "", "Florida", "USA", "Miami", "Fort Lauderdale", ""),
("tol", "Toledo Express Airport", "", "Ohio", "USA", "Toledo", "Swanton", "Monclova"),
("tos", "Tromsø lufthavn, Langnes", "Tromso Airport, Langnes", "", "Norway", "Tromsø", "Langes", ""),
("tpa", "Tampa International Airport", "", "Florida", "USA", "Tampa", "", ""),
("tpe", "Taiwan Taoyuan International Airport", "", "", "Taiwan", "Taipei", "Taoyuan City", ""),
("tpp", "Aeropuerto Cadete FAP Guillermo del Castillo Paredes", "Cadete FAP Guillermo del Castillo Paredes Airport", "San Martín", "Peru", "Tarapoto", "", ""),
("trd", "Trondheim lufthavn, Værnes", "Trondheim Airport, Værnes", "", "Norway", "Trondheim", "Værnes", ""),
("tre", "Port-adhair Thirioah", "Tiree Airport", "Scotland", "UK", "Tiree", "Balemartine", ""),
("trf", "Sandefjord lufthavn, Torp", "Sandefjord Airport, Torp", "", "Norway", "Sandefjord", "Stokke", "Torp"),
("tri", "Tri-Cities Regional Airport", "", "Tennessee", "USA", "Blountville", "Bristol", "Johnson City"),
("trn", "Aeroporto di Torino Sandro Pertini", "Turin Airport Sandro Pertini", "", "Italy", "Turin", "", ""),
("trs", "Aeroporto di Trieste–Friuli Venezia Giulia", "Trieste – Friuli Venezia Giulia Airport", "", "Italy", "Trieste", "Ronchi dei Legionari", ""),
("tru", "Aeropuerto Internacional Capitán FAP Carlos Martínez de Pinillos", "Capitán FAP Carlos Martínez de Pinillos International Airport", "La Libertad", "Peru", "Trujillo", "", ""),
("trv", "Trivandrum International Airport", "", "Kerala", "India", "Thiruvananthapuram", "", ""),
("trw", "Bonriki International Airport", "", "", "Kiribati", "South Tarawa", "Tarawa", ""),
("tsa", "Taipei Songshan Airport", "", "", "Taiwan", "Taipei", "Songshan District", ""),
("tse", "Astana International Airport", "", "", "Kazakhstan", "Astana", "", ""),
("ttn", "Trenton–Mercer Airport", "", "New Jersey", "USA", "Trenton", "Ewing Township", ""),
("tul", "Tulsa International Airport", "", "Oklahoma", "USA", "Tulsa", "", ""),
("tun", "Tunis–Carthage International Airport", "", "", "Tunisia", "Tunis", "Carthage", ""),
("tus", "Tucson International Airport", "", "Arizona", "USA", "Tucson", "", ""),
("txl", "Flughafen Berlin-Tegel “Otto Lilienthal”", "Berlin Tegel Airport", "", "Germany", "Berlin", "Tegel", ""),
("tyl", "Aeropuerto Capitán FAP Víctor Montes Arias", "Capitán FAP Víctor Montes Arias Airport", "Piura", "Peru", "Talara", "", ""),
("tys", "McGhee Tyson Airport", "", "Tennessee", "USA", "Knoxville", "Alcoa", ""),
("tzl", "Tuzla International Airport", "", "", "Bosnia and Herzegovina", "Tuzla", "Zivinice", ""),
("ufa", "Ufa International Airport", "", "", "Russia", "Ufa", "Bashkortostan", ""),
("uih", "Sân bay Phù Cát", "Phu Cat Airport", "", "Vietnam", "Qui Nhon", "", ""),
("uio", "Aeropuerto Internacional Mariscal Sucre", "Mariscal Sucre International Airport", "Pichincha", "Ecuador", "Quito", "Tababela", ""),
("uln", "Chinggis Khaan International Airport", "", "", "Mongolia", "Ulaanbaatar", "", ""),
("upg", "Bandar Udara Internasional Sultan Hasanuddin", "Sultan Hasanuddin International Airport", "", "Indonesia", "Makassar", "South Sulawesi", ""),
("ura", "Oral Ak Zhol Airport", "", "", "Kazakhstan", "Oral", "Uralsk", ""),
("ush", "Aeropuerto Internacional de Ushuaia Malvinas Argentinas", "Ushuaia – Malvinas Argentinas International Airport", "", "Argentina", "Ushuaia", "", ""),
("usm", "Samui International Airport", "", "", "Thailand", "Ko Samui ", "", ""),
("uth", "Udon Thani International Airport", "", "", "Thailand", "Udon Thani", "", ""),
("uud", "Baikal International Airport", "", "", "Russia", "Ulan-Ude", "", ""),
("uus", "Yuzhno-Sakhalinsk Airport", "", "", "Russia", "Yuzhno-Sakhalinsk", "", ""),
("uvf", "Hewanorra International Airport", "", "", "Saint Lucia", "Vieux Fort", "", ""),
("vam", "Villa International Airport Maamigili", "", "Alif Dhaal Atoll", "Maldives", "Maamigili", "", ""),
("var", "Letishte Varna", "Varna Airport", "", "Bulgaria", "Varna", "Aksakovo", ""),
("vav", "Vava’u International Airport", "", "", "Tonga", "Vava’u", "Vava'u", ""),
("vca", "Sân bay Quốc tế Cần Thơ", "Can Tho International Airport", "", "Vietnam", "Can Tho", "", ""),
("vce", "Aeroporto di Venezia Marco Polo", "Venice Marco Polo Airport", "", "Italy", "Venice", "Tessera", ""),
("vcl", "Sân bay Chu Lai", "Chu Lai Airport", "", "Vietnam", "Tam Ky", "", ""),
("vcp", "Aeroporto Internacional de Viracopos/Campinas", "Viracopos International Airport", "SP", "Brazil", "Campinas", "São Paulo", "Sao Paulo"),
("vcs", "Sân bay Côn Đảo", "Con Dao Airport", "", "Vietnam", "Con Dao", "Con Son Island", ""),
("vde", "Aeropuerto de El Hierro", "El Hierro Airport", "Canary Islands", "Spain", "El Hierro", "Valverde", ""),
("vdh", "Sân bay Đồng Hới", "Dong Hoi Airport", "", "Vietnam", "Dong Hoi", "", ""),
("vgo", "Aeropuerto de Vigo", "Vigo Airport", "", "Spain", "Vigo", "Peinador", ""),
("vgt", "North Las Vegas Airport", "", "Nevada", "USA", "Las Vegas", "", ""),
("vie", "Flughafen Wien-Schwechat", "Vienna International Airport", "", "Austria", "Vienna", "Schwechat", ""),
("vii", "Sân bay Vinh", "Vinh Airport", "", "Vietnam", "Vinh", "", ""),
("vix", "Aeroporto de Vitória-Eurico de Aguiar Salles", "Vitória-Eurico de Aguiar Salles Airport", "Espírito Santo", "Brazil", "Vitória", "", ""),
("vkg", "Sân bay Rạch Giá", "Rach Gia Airport", "", "Vietnam", "Rach Gia", "", ""),
("vko", "Vnukovo International Airport", "", "", "Russia", "Moscow", "", ""),
("vlc", "Aeropuerto de Valencia", "Valencia Airport", "", "Spain", "Valencia", "Manises", ""),
("vli", "Bauerfield International Airport", "", "", "Vanuatu", "Port Vila", "", ""),
("vll", "Aeropuerto de Valladolid", "Valladolid International Airport", "Castile and Leon", "Spain", "Valladolid", "Villanubla", ""),
("vln", "Aeropuerto Internacional Arturo Michelena", "Arturo Michelena International Airport", "", "Venezuela", "Valencia", "", ""),
("vno", "Tarptautinis Vilniaus oro uostas", "Vilnius International Airport", "", "Lithuania", "Vilnius", "", ""),
("vns", "Lal Bahadur Shastri International Airport", "", "Utter Pradesh", "India", "Varanasi", "Benares", "Banaras"),
("vog", "Volgograd International Airport", "", "", "Russia", "Volgograd", "", ""),
("voz", "Voronezh-Chertovitskoye International Airport", "", "", "Russia", "Voronezh", "Lipetsk", "Tambov"),
("vps", "Destin–Fort Walton Beach Airport", "", "Florida", "USA", "Fort Walton Beach", "Destin", ""),
("vrn", "Aeroporto di Verona-Villafranca", "Verona Villafranca Airport", "", "Italy", "Verona", "Villafranca ", ""),
("vte", "Wattay International Airport", "", "", "Laos", "Vientiane", "", ""),
("vvi", "Aeropuerto Internacional Viru Viru", "Viru Viru International Airport", "", "Bolivia", "Santa Cruz de la Sierra", "", ""),
("waw", "Lotnisko Chopina w Warszawie", "Warsaw Chopin Airport", "", "Poland", "Warsaw", "Okęcie", "Chopin"),
("wdh", "Hosea Kutako International Airport", "", "", "Namibia", "Windhoek", "", ""),
("wgp", "Bandar Udara Umbu Mehang Kunda", "Umbu Mehang Kunda Airport", "East Nusa Tenggara", "Indonesia", "Waingapu", "Sumba", ""),
("wlg", "Wellington International Airport", "", "", "New Zealand", "Wellington", "Rongotai", ""),
("wmi", "Mazowiecki Port Lotniczy", "Warsaw–Modlin Mazovia Airport", "", "Poland", "Warsaw", "Nowy Dwór Mazowiecki", ""),
("wro", "Port Lotniczy Wrocław im. Mikołaja Kopernika", "Wroclaw–Copernicus Airport", "Lower Silesian Voivodeship", "Poland", "Wroclaw", "", ""),
("xch", "Christmas Island Airport", "", "", "Australia", "Christmas Island", "", ""),
("xiy", "Xi'an Xianyang International Airport", "", "Shaanxi", "China", "Xi'an", "Xianyang", "Weicheng District"),
("xmn", "Xiamen Gaoqi International Airport", "", "Huli District", "China", "Xiamen", "", ""),
("xna", "Northwest Arkansas Regional Airport", "", "Arkansas", "USA", "Fayetteville", "Springdale", "Highfill"),
("xnn", "Xining Caojiabao Airport", "", "Qinghai", "China", "Xining", "Huzhu", "Haidong"),
("xry", "Aeropuerto de Jerez", "Jerez Airport", "", "Spain", "Jerez de la Frontera", "", ""),
("yap", "Yap International Airport", "", "", "Micronesia", "Yap", "", ""),
("yaz", "Tofino/Long Beach Airport", "", "British Columbia", "Canada", "Tofino", "Long Beach", ""),
("ydt", "Boundary Bay Airport", "", "British Columbia", "Canada", "Vancouver", "Delta", ""),
("yeg", "Edmonton International Airport", "", "Alberta", "Canada", "Edmonton", "", ""),
("ygo", "Gods Lake Narrows Airport", "", "Manitoba", "Canada", "Gods Lake Narrows", "", ""),
("yhk", "Gjoa Haven Airport", "", "Nunavut", "Canada", "Gjoa Haven", "", ""),
("yhm", "John C. Munro Hamilton International Airport", "", "Ontario", "Canada", "Hamilton", "Mount Hope", "Toronto"),
("yhz", "Halifax Stanfield International Airport", "", "Nova Scotia", "Canada", "Halifax", "Enfield", ""),
("yip", "Willow Run Airport", "", "Michigan", "USA", "Ypsilanti", "", ""),
("yjs", "Samjiyŏn Airport", "", "Korea", "North Korea", "Samjiyŏn", "Samjiyon", "Ryanggang"),
("ylt", "Alert Airport", "", "Nunavut", "Canada", "Alert", "", ""),
("ylw", "Kelowna International Airport", "", "British Columbia", "Canada", "Kelowna", "", ""),
("ymm", "Fort McMurray International Airport", "", "Alberta", "Canada", "Fort McMurray", "", ""),
("ymx", "Aéroport international Montréal–Mirabel", "Montréal–Mirabel International Airport", "Quebec", "Canada", "Montreal", "Mirabel", ""),
("ynb", "Prince Abdul Mohsin bin Abdulaziz Airport", "", "Al Madinah Province", "Saudi Arabia", "Yanbu' Al Bahr", "", ""),
("yng", "Youngstown–Warren Regional Airport", "", "Ohio", "USA", "Youngstown", "Warren", ""),
("yon", "Yongphulla Airport", "", "", "Bhutan", "Trashigang", "", ""),
("yoo", "Oshawa Executive Airport", "", "Ontario", "Canada", "Oshawa", "Pickering", "Toronto"),
("yow", "Ottawa Macdonald–Cartier International Airport", "", "Ontario", "Canada", "Ottawa", "", ""),
("yqb", "Aéoport international Jean-Lesage de Québec", "Québec City Jean Lesage International Airport", "Quebec", "Canada", "Québec City", "", ""),
("yqm", "Greater Moncton International Airport", "", "New Brunswick", "Canada", "Moncton", "Dieppe", ""),
("yqr", "Regina International Airport", "", "Saskatchewan", "Canada", "Regina", "", ""),
("yqt", "Thunder Bay International Airport", "", "Ontario", "Canada", "Thunder Bay", "", ""),
("yqx", "Gander International Airport", "", "Newfoundland and Labrador", "Canada", "Gander", "", ""),
("yqy", "Sydney/J.A. Douglas McCurdy Airport", "", "Nova Scotia", "Canada", "Sydney", "", ""),
("ysb", "Sudbury Airport", "", "Ontario", "Canada", "Sudbury", "", ""),
("ysj", "Aéroport de Saint John", "Saint John Airport", "New Brunswick", "Canada", "Saint John", "", ""),
("ytz", "Billy Bishop Toronto City Airport", "", "Ontario", "Canada", "Toronto", "Toronto Division", ""),
("yul", "Aéroport international Pierre-Elliott-Trudeau de Montréal", "Montréal–Pierre Elliott Trudeau International Airport", "Quebec", "Canada", "Montreal", "Dorval", ""),
("yum", "Yuma International Airport", "", "Arizona", "USA", "Yuma", "", ""),
("yvr", "Vancouver International Airport", "", "British Columbia", "Canada", "Vancouver", "Richmond", ""),
("ywg", "James Armstrong Richardson International Airport", "", "Manitoba", "Canada", "Winnipeg", "", ""),
("yxe", "Saskatoon John G. Diefenbaker International Airport", "", "Saskatchewan", "Canada", "Saskatoon", "", ""),
("yxh", "Medicine Hat Airport", "", "Alberta", "Canada", "Medicine Hat", "", ""),
("yxu", "London International Airport", "", "Ontario", "Canada", "London", "", ""),
("yxx", "Abbotsford International Airport", "", "British Columbia", "Canada", "Abbotsford", "", ""),
("yxy", "Erik Nielsen Whitehorse International Airport", "", "Yukon", "Canada", "Whitehorse", "", ""),
("yyc", "Calgary International Airport", "", "Alberta", "Canada", "Calgary", "", ""),
("yyd", "Smithers Regional Airport", "", "British Columbia", "Canada", "Smithers", "", ""),
("yyj", "Victoria International Airport", "", "British Columbia", "Canada", "Victoria", "", ""),
("yyt", "St. John’s International Airport", "", "Newfoundland and Labrador", "Canada", "St. John’s", "", ""),
("yyz", "Pearson International Airport", "", "Ontario", "Canada", "Toronto", "Malton", "Mississauga"),
("yzf", "Yellowknife Airport", "", "Northwest Territories", "Canada", "Yellowknife", "", ""),
("zad", "Zračna luka Zadar/Zemunik", "Zadar Airport", "", "Croatia", "Zadar", "", ""),
("zag", "Međunarodna zračna luka Zagreb", "Zagreb International Airport", "", "Croatia", "Zagreb", "Pleso", ""),
("zaz", "Aeropuerto de Zaragoza", "Zaragoza Airport", "", "Spain", "Zaragoza", "", ""),
("zcl", "Aeropuerto Internacional General Leobardo C. Ruiz", "General Leobardo C. Ruiz International Airport", "", "Mexico", "Zacatecas", "Fresnillo", ""),
("zih", "Aeropuerto Internacional de Ixtapa-Zihuatanejo", "Ixtapa-Zihuatanejo International Airport", "Guerrero", "Mexico", "Zihuatanejo", "Ixtapa", ""),
("zlo", "Aeropuerto Internacional Playa de Oro", "Playa de Oro International Airport", "Colima", "Mexico", "Manzanillo", "", ""),
("zqn", "Queenstown Airport", "", "", "New Zealand", "Queenstown", "Frankton", ""),
("zrh", "Flughafen Zürich", "Zürich Airport", "", "Switzerland", "Zürich", "Zurich", ""),
};
}
}
| 104.017087 | 211 | 0.554785 | [
"MIT"
] | AlexanderKapitanovski/QuickInfo | src/QuickInfo/Processors/AirportCodes.cs | 128,741 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TrainersSalary
{
class TrainersSalary
{
static void Main()
{
var numberOfLecture = int.Parse(Console.ReadLine());
var budget = double.Parse(Console.ReadLine());
var Roli = 0;
var Trofon = 0;
var Sino = 0;
var Jelev = 0;
var RoYaL = 0;
var Others = 0;
for (int i = 0; i < numberOfLecture; i++)
{
var lecturer = Console.ReadLine();
if(lecturer == "Jelev")
Jelev++;
else if(lecturer == "RoYaL")
RoYaL++;
else if(lecturer == "Roli")
Roli++;
else if(lecturer == "Trofon")
Trofon++;
else if(lecturer == "Sino")
Sino++;
else
Others++;
}
var salaryForJelev = (budget / numberOfLecture) * (double)Jelev;
var salaryForRoYaL = (budget / numberOfLecture) * (double)RoYaL;
var salaryForRoli = (budget / numberOfLecture) * (double)Roli;
var salaryForTrofon = (budget / numberOfLecture) * (double)Trofon;
var salaryForSino = (budget / numberOfLecture) * (double)Sino;
var salaryForOthers = (budget / numberOfLecture) * (double)Others;
Console.WriteLine($"Jelev salary: {salaryForJelev:f2} lv");
Console.WriteLine($"RoYaL salary: {salaryForRoYaL:f2} lv");
Console.WriteLine($"Roli salary: {salaryForRoli:f2} lv");
Console.WriteLine($"Trofon salary: {salaryForTrofon:f2} lv");
Console.WriteLine($"Sino salary: {salaryForSino:f2} lv");
Console.WriteLine($"Others salary: {salaryForOthers:f2} lv");
}
}
}
| 36.296296 | 78 | 0.520408 | [
"MIT"
] | PavelRunchev/Programming-Fundamentals-2017 | Exam Programming basic/13.Exam 19 March 2017 Morning/TrainersSalary/TrainersSalary.cs | 1,962 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
namespace System.Data.Entity.Core.Mapping.Update.Internal
{
using System.Data.Entity.Core.Common;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Resources;
using System.Data.Entity.Utilities;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Text;
// <summary>
// requires: for structural types, member values are ordinally aligned with the members of the
// structural type.
// Stores a 'row' (or element within a row) being propagated through the update pipeline, including
// markup information and metadata. Internally, we maintain several different classes so that we only
// store the necessary state.
// - StructuralValue (complex types, entities, and association end keys): type and member values,
// one version for modified structural values and one version for unmodified structural values
// (a structural type is modified if its _type_ is changed, not its values
// - SimpleValue (scalar value): flags to describe the state of the value (is it a concurrency value,
// is it modified) and the value itself
// - ServerGenSimpleValue: adds back-prop information to the above (record and position in record
// so that we can set the value on back-prop)
// - KeyValue: the originating IEntityStateEntry also travels with keys. These entries are used purely for
// error reporting. We send them with keys so that every row containing an entity (which must also
// contain the key) has enough context to recover the state entry.
// </summary>
// <remarks>
// Not all memebers of a PropagatorResult are available for all specializations. For instance, GetSimpleValue
// is available only on simple types
// </remarks>
internal abstract class PropagatorResult
{
#region Constructors
// For testing purposes. Only nested classes should derive from propagator result
#endregion
#region Fields
internal const int NullIdentifier = -1;
internal const int NullOrdinal = -1;
#endregion
#region Properties
// <summary>
// Gets a value indicating whether this result is null.
// </summary>
internal abstract bool IsNull { get; }
// <summary>
// Gets a value indicating whether this is a simple (scalar) or complex
// structural) result.
// </summary>
internal abstract bool IsSimple { get; }
// <summary>
// Gets flags describing the behaviors for this element.
// </summary>
internal virtual PropagatorFlags PropagatorFlags
{
get { return PropagatorFlags.NoFlags; }
}
// <summary>
// Gets all state entries from which this result originated. Only set for key
// values (to ensure every row knows all of its source entries)
// </summary>
internal virtual IEntityStateEntry StateEntry
{
get { return null; }
}
// <summary>
// Gets record from which this result originated. Only set for server generated
// results (where the record needs to be synchronized).
// </summary>
internal virtual CurrentValueRecord Record
{
get { return null; }
}
// <summary>
// Gets structural type for non simple results. Only available for entity and complex type
// results.
// </summary>
internal virtual StructuralType StructuralType
{
get { return null; }
}
// <summary>
// Gets the ordinal within the originating record for this result. Only set
// for server generated results (otherwise, returns -1)
// </summary>
internal virtual int RecordOrdinal
{
get { return NullOrdinal; }
}
// <summary>
// Gets the identifier for this entry if it is a server-gen key value (otherwise
// returns -1)
// </summary>
internal virtual int Identifier
{
get { return NullIdentifier; }
}
// <summary>
// Where a single result corresponds to multiple key inputs, they are chained using this linked list.
// By convention, the first entry in the chain is the 'dominant' entry (the principal key).
// </summary>
internal virtual PropagatorResult Next
{
get { return null; }
}
#endregion
#region Methods
// <summary>
// Returns simple value stored in this result. Only valid when <see cref="IsSimple" /> is
// true.
// </summary>
// <returns> Concrete value. </returns>
internal virtual object GetSimpleValue()
{
throw EntityUtil.InternalError(
EntityUtil.InternalErrorCode.UpdatePipelineResultRequestInvalid, 0, "PropagatorResult.GetSimpleValue");
}
// <summary>
// Returns nested value. Only valid when <see cref="IsSimple" /> is false.
// </summary>
// <param name="ordinal"> Ordinal of value to return (ordinal based on type definition) </param>
// <returns> Nested result. </returns>
internal virtual PropagatorResult GetMemberValue(int ordinal)
{
throw EntityUtil.InternalError(
EntityUtil.InternalErrorCode.UpdatePipelineResultRequestInvalid, 0, "PropagatorResult.GetMemberValue");
}
// <summary>
// Returns nested value. Only valid when <see cref="IsSimple" /> is false.
// </summary>
// <param name="member"> Member for which to return a value </param>
// <returns> Nested result. </returns>
internal PropagatorResult GetMemberValue(EdmMember member)
{
var ordinal = TypeHelpers.GetAllStructuralMembers(StructuralType).IndexOf(member);
return GetMemberValue(ordinal);
}
// <summary>
// Returns all structural values. Only valid when <see cref="IsSimple" /> is false.
// </summary>
// <returns> Values of all structural members. </returns>
internal virtual PropagatorResult[] GetMemberValues()
{
throw EntityUtil.InternalError(
EntityUtil.InternalErrorCode.UpdatePipelineResultRequestInvalid, 0, "PropagatorResult.GetMembersValues");
}
// <summary>
// Produces a replica of this propagator result with different flags.
// </summary>
// <param name="flags"> New flags for the result. </param>
// <returns> This result with the given flags. </returns>
internal abstract PropagatorResult ReplicateResultWithNewFlags(PropagatorFlags flags);
// <summary>
// Copies this result replacing its value. Used for cast. Requires a simple result.
// </summary>
// <param name="value"> New value for result </param>
// <returns> Copy of this result with new value. </returns>
internal virtual PropagatorResult ReplicateResultWithNewValue(object value)
{
throw EntityUtil.InternalError(
EntityUtil.InternalErrorCode.UpdatePipelineResultRequestInvalid, 0, "PropagatorResult.ReplicateResultWithNewValue");
}
// <summary>
// Replaces parts of the structured result.
// </summary>
// <param name="map"> A replace-with map applied to simple (i.e. not structural) values. </param>
// <returns> Result with requested elements replaced. </returns>
internal abstract PropagatorResult Replace(Func<PropagatorResult, PropagatorResult> map);
// <summary>
// A result is merged with another when it is merged as part of an equi-join.
// </summary>
// <remarks>
// In theory, this should only ever be called on two keys (since we only join on
// keys). We throw in the base implementation, and override in KeyResult. By convention
// the principal key is always the first result in the chain (in case of an RIC). In
// addition, entity entries always appear before relationship entries.
// </remarks>
// <param name="other"> Result to merge with. </param>
// <returns> Merged result. </returns>
internal virtual PropagatorResult Merge(KeyManager keyManager, PropagatorResult other)
{
throw EntityUtil.InternalError(EntityUtil.InternalErrorCode.UpdatePipelineResultRequestInvalid, 0, "PropagatorResult.Merge");
}
internal virtual void SetServerGenValue(object value)
{
if (RecordOrdinal != NullOrdinal)
{
var targetRecord = Record;
// determine if type compensation is required
IExtendedDataRecord recordWithMetadata = targetRecord;
var member = recordWithMetadata.DataRecordInfo.FieldMetadata[RecordOrdinal].FieldType;
value = value ?? DBNull.Value; // records expect DBNull rather than null
value = AlignReturnValue(value, member);
targetRecord.SetValue(RecordOrdinal, value);
}
}
// <summary>
// Aligns a value returned from the store with the expected type for the member.
// </summary>
// <param name="value"> Value to convert. </param>
// <param name="member"> Metadata for the member being set. </param>
// <returns> Converted return value </returns>
internal object AlignReturnValue(object value, EdmMember member)
{
if (DBNull.Value.Equals(value))
{
// check if there is a nullability constraint on the value
if (BuiltInTypeKind.EdmProperty == member.BuiltInTypeKind
&&
!((EdmProperty)member).Nullable)
{
throw EntityUtil.Update(
Strings.Update_NullReturnValueForNonNullableMember(
member.Name,
member.DeclaringType.FullName), null);
}
}
else if (!Helper.IsSpatialType(member.TypeUsage))
{
Type clrType;
Type clrEnumType = null;
if (Helper.IsEnumType(member.TypeUsage.EdmType))
{
var underlyingType = Helper.AsPrimitive(member.TypeUsage.EdmType);
clrEnumType = Record.GetFieldType(RecordOrdinal);
clrType = underlyingType.ClrEquivalentType;
Debug.Assert(clrEnumType.IsEnum());
}
else
{
// convert the value to the appropriate CLR type
Debug.Assert(
BuiltInTypeKind.PrimitiveType == member.TypeUsage.EdmType.BuiltInTypeKind,
"we only allow return values that are instances of EDM primitive or enum types");
var primitiveType = (PrimitiveType)member.TypeUsage.EdmType;
clrType = primitiveType.ClrEquivalentType;
}
try
{
value = Convert.ChangeType(value, clrType, CultureInfo.InvariantCulture);
if (clrEnumType != null)
{
value = Enum.ToObject(clrEnumType, value);
}
}
catch (Exception e)
{
// we should not be wrapping all exceptions
if (e.RequiresContext())
{
var userClrType = clrEnumType ?? clrType;
throw EntityUtil.Update(
Strings.Update_ReturnValueHasUnexpectedType(
value.GetType().FullName,
userClrType.FullName,
member.Name,
member.DeclaringType.FullName), e);
}
throw;
}
}
// return the adjusted value
return value;
}
#if DEBUG
public override string ToString()
{
var builder = new StringBuilder();
if (PropagatorFlags.NoFlags != PropagatorFlags)
{
builder.Append(PropagatorFlags.ToString()).Append(":");
}
if (NullIdentifier != Identifier)
{
builder.Append("id").Append(Identifier.ToString(CultureInfo.InvariantCulture)).Append(":");
}
if (NullOrdinal != RecordOrdinal)
{
builder.Append("ord").Append(RecordOrdinal.ToString(CultureInfo.InvariantCulture)).Append(":");
}
if (IsSimple)
{
builder.AppendFormat(CultureInfo.InvariantCulture, "{0}", GetSimpleValue());
}
else
{
if (!Helper.IsRowType(StructuralType))
{
builder.Append(StructuralType.Name).Append(":");
}
builder.Append("{");
var first = true;
foreach (var memberValue in Helper.PairEnumerations(
TypeHelpers.GetAllStructuralMembers(StructuralType), GetMemberValues()))
{
if (first)
{
first = false;
}
else
{
builder.Append(", ");
}
builder.Append(memberValue.Key.Name).Append("=").Append(memberValue.Value);
}
builder.Append("}");
}
return builder.ToString();
}
#endif
#endregion
#region Nested types and factory methods
internal static PropagatorResult CreateSimpleValue(PropagatorFlags flags, object value)
{
return new SimpleValue(flags, value);
}
private class SimpleValue : PropagatorResult
{
internal SimpleValue(PropagatorFlags flags, object value)
{
m_flags = flags;
m_value = value ?? DBNull.Value;
}
private readonly PropagatorFlags m_flags;
protected readonly object m_value;
internal override PropagatorFlags PropagatorFlags
{
get { return m_flags; }
}
internal override bool IsSimple
{
get { return true; }
}
internal override bool IsNull
{
get
{
// The result is null if it is not associated with an identifier and
// the value provided by the user is also null.
return NullIdentifier == Identifier && DBNull.Value == m_value;
}
}
internal override object GetSimpleValue()
{
return m_value;
}
internal override PropagatorResult ReplicateResultWithNewFlags(PropagatorFlags flags)
{
return new SimpleValue(flags, m_value);
}
internal override PropagatorResult ReplicateResultWithNewValue(object value)
{
return new SimpleValue(PropagatorFlags, value);
}
internal override PropagatorResult Replace(Func<PropagatorResult, PropagatorResult> map)
{
return map(this);
}
}
internal static PropagatorResult CreateServerGenSimpleValue(
PropagatorFlags flags, object value, CurrentValueRecord record, int recordOrdinal)
{
return new ServerGenSimpleValue(flags, value, record, recordOrdinal);
}
private class ServerGenSimpleValue : SimpleValue
{
internal ServerGenSimpleValue(PropagatorFlags flags, object value, CurrentValueRecord record, int recordOrdinal)
: base(flags, value)
{
DebugCheck.NotNull(record);
m_record = record;
m_recordOrdinal = recordOrdinal;
}
private readonly CurrentValueRecord m_record;
private readonly int m_recordOrdinal;
internal override CurrentValueRecord Record
{
get { return m_record; }
}
internal override int RecordOrdinal
{
get { return m_recordOrdinal; }
}
internal override PropagatorResult ReplicateResultWithNewFlags(PropagatorFlags flags)
{
return new ServerGenSimpleValue(flags, m_value, Record, RecordOrdinal);
}
internal override PropagatorResult ReplicateResultWithNewValue(object value)
{
return new ServerGenSimpleValue(PropagatorFlags, value, Record, RecordOrdinal);
}
}
internal static PropagatorResult CreateKeyValue(PropagatorFlags flags, object value, IEntityStateEntry stateEntry, int identifier)
{
return new KeyValue(flags, value, stateEntry, identifier, null);
}
private class KeyValue : SimpleValue
{
internal KeyValue(PropagatorFlags flags, object value, IEntityStateEntry stateEntry, int identifier, KeyValue next)
: base(flags, value)
{
DebugCheck.NotNull(stateEntry);
m_stateEntry = stateEntry;
m_identifier = identifier;
m_next = next;
}
private readonly IEntityStateEntry m_stateEntry;
private readonly int m_identifier;
protected readonly KeyValue m_next;
internal override IEntityStateEntry StateEntry
{
get { return m_stateEntry; }
}
internal override int Identifier
{
get { return m_identifier; }
}
internal override CurrentValueRecord Record
{
get
{
// delegate to the state entry, which also has the record
return m_stateEntry.CurrentValues;
}
}
internal override PropagatorResult Next
{
get { return m_next; }
}
internal override PropagatorResult ReplicateResultWithNewFlags(PropagatorFlags flags)
{
return new KeyValue(flags, m_value, StateEntry, Identifier, m_next);
}
internal override PropagatorResult ReplicateResultWithNewValue(object value)
{
return new KeyValue(PropagatorFlags, value, StateEntry, Identifier, m_next);
}
internal virtual KeyValue ReplicateResultWithNewNext(KeyValue next)
{
if (m_next != null)
{
// push the next value to the end of the linked list
next = m_next.ReplicateResultWithNewNext(next);
}
return new KeyValue(PropagatorFlags, m_value, m_stateEntry, m_identifier, next);
}
internal override PropagatorResult Merge(KeyManager keyManager, PropagatorResult other)
{
var otherKey = other as KeyValue;
if (null == otherKey)
{
EntityUtil.InternalError(EntityUtil.InternalErrorCode.UpdatePipelineResultRequestInvalid, 0, "KeyValue.Merge");
}
// Determine which key (this or otherKey) is first in the chain. Principal keys take
// precedence over dependent keys and entities take precedence over relationships.
if (Identifier != otherKey.Identifier)
{
// Find principal (if any)
if (keyManager.GetPrincipals(otherKey.Identifier).Contains(Identifier))
{
return ReplicateResultWithNewNext(otherKey);
}
else
{
return otherKey.ReplicateResultWithNewNext(this);
}
}
else
{
// Entity takes precedence of relationship
if (null == m_stateEntry
|| m_stateEntry.IsRelationship)
{
return otherKey.ReplicateResultWithNewNext(this);
}
else
{
return ReplicateResultWithNewNext(otherKey);
}
}
}
}
internal static PropagatorResult CreateServerGenKeyValue(
PropagatorFlags flags, object value, IEntityStateEntry stateEntry, int identifier, int recordOrdinal)
{
return new ServerGenKeyValue(flags, value, stateEntry, identifier, recordOrdinal, null);
}
private class ServerGenKeyValue : KeyValue
{
internal ServerGenKeyValue(
PropagatorFlags flags, object value, IEntityStateEntry stateEntry, int identifier, int recordOrdinal, KeyValue next)
: base(flags, value, stateEntry, identifier, next)
{
m_recordOrdinal = recordOrdinal;
}
private readonly int m_recordOrdinal;
internal override int RecordOrdinal
{
get { return m_recordOrdinal; }
}
internal override PropagatorResult ReplicateResultWithNewFlags(PropagatorFlags flags)
{
return new ServerGenKeyValue(flags, m_value, StateEntry, Identifier, RecordOrdinal, m_next);
}
internal override PropagatorResult ReplicateResultWithNewValue(object value)
{
return new ServerGenKeyValue(PropagatorFlags, value, StateEntry, Identifier, RecordOrdinal, m_next);
}
internal override KeyValue ReplicateResultWithNewNext(KeyValue next)
{
if (m_next != null)
{
// push the next value to the end of the linked list
next = m_next.ReplicateResultWithNewNext(next);
}
return new ServerGenKeyValue(PropagatorFlags, m_value, StateEntry, Identifier, RecordOrdinal, next);
}
}
internal static PropagatorResult CreateStructuralValue(PropagatorResult[] values, StructuralType structuralType, bool isModified)
{
if (isModified)
{
return new StructuralValue(values, structuralType);
}
else
{
return new UnmodifiedStructuralValue(values, structuralType);
}
}
private class StructuralValue : PropagatorResult
{
internal StructuralValue(PropagatorResult[] values, StructuralType structuralType)
{
DebugCheck.NotNull(structuralType);
DebugCheck.NotNull(values);
Debug.Assert(values.Length == TypeHelpers.GetAllStructuralMembers(structuralType).Count);
m_values = values;
m_structuralType = structuralType;
}
private readonly PropagatorResult[] m_values;
protected readonly StructuralType m_structuralType;
internal override bool IsSimple
{
get { return false; }
}
internal override bool IsNull
{
get { return false; }
}
internal override StructuralType StructuralType
{
get { return m_structuralType; }
}
internal override PropagatorResult GetMemberValue(int ordinal)
{
return m_values[ordinal];
}
internal override PropagatorResult[] GetMemberValues()
{
return m_values;
}
internal override PropagatorResult ReplicateResultWithNewFlags(PropagatorFlags flags)
{
throw EntityUtil.InternalError(
EntityUtil.InternalErrorCode.UpdatePipelineResultRequestInvalid, 0, "StructuralValue.ReplicateResultWithNewFlags");
}
internal override PropagatorResult Replace(Func<PropagatorResult, PropagatorResult> map)
{
var newValues = ReplaceValues(map);
return null == newValues ? this : new StructuralValue(newValues, m_structuralType);
}
protected PropagatorResult[] ReplaceValues(Func<PropagatorResult, PropagatorResult> map)
{
var newValues = new PropagatorResult[m_values.Length];
var hasChange = false;
for (var i = 0; i < newValues.Length; i++)
{
var newValue = m_values[i].Replace(map);
if (!ReferenceEquals(newValue, m_values[i]))
{
hasChange = true;
}
newValues[i] = newValue;
}
return hasChange ? newValues : null;
}
}
private class UnmodifiedStructuralValue : StructuralValue
{
internal UnmodifiedStructuralValue(PropagatorResult[] values, StructuralType structuralType)
: base(values, structuralType)
{
}
internal override PropagatorFlags PropagatorFlags
{
get { return PropagatorFlags.Preserve; }
}
internal override PropagatorResult Replace(Func<PropagatorResult, PropagatorResult> map)
{
var newValues = ReplaceValues(map);
return null == newValues ? this : new UnmodifiedStructuralValue(newValues, m_structuralType);
}
}
#endregion
}
}
| 38.324286 | 144 | 0.564655 | [
"MIT"
] | dotnet/ef6tools | src/EntityFramework/Core/Mapping/Update/Internal/PropagatorResult.cs | 26,827 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GuideService.Guide.Dtos
{
public class PersonCreateDto
{
public string Name { get; set; }
public string Surname { get; set; }
public string Company { get; set; }
}
}
| 19.5 | 43 | 0.666667 | [
"Apache-2.0"
] | onselaydin/GuidMs | Guide/GuideService.Guide/Dtos/PersonCreateDto.cs | 314 | C# |
using System.ComponentModel.DataAnnotations;
namespace GamingWiki.Models
{
using static Common.DataConstants;
public class Class
{
public int Id { get; set; }
[Required]
[MaxLength(CharacterClassMaxLength)]
public string Name { get; set; }
}
}
| 19.666667 | 45 | 0.644068 | [
"MIT"
] | AtiVassileva/GamingWiki | src/GamingWiki.Models/Class.cs | 297 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace OpenCvSharp.Blob
{
/// <summary>
/// Render mode of cvRenderBlobs
/// </summary>
[Flags]
public enum RenderBlobsMode : ushort
{
/// <summary>
/// No flags (=0)
/// </summary>
None = 0,
/// <summary>
/// Render each blog with a different color.
/// [CV_BLOB_RENDER_COLOR]
/// </summary>
Color = CvBlobConst.CV_BLOB_RENDER_COLOR,
/// <summary>
/// Render centroid.
/// CV_BLOB_RENDER_CENTROID]
/// </summary>
Centroid = CvBlobConst.CV_BLOB_RENDER_CENTROID,
/// <summary>
/// Render bounding box.
/// [CV_BLOB_RENDER_BOUNDING_BOX]
/// </summary>
BoundingBox = CvBlobConst.CV_BLOB_RENDER_BOUNDING_BOX,
/// <summary>
/// Render angle.
/// [CV_BLOB_RENDER_ANGLE]
/// </summary>
Angle = CvBlobConst.CV_BLOB_RENDER_ANGLE,
/// <summary>
/// Print blob data to log out.
/// [CV_BLOB_RENDER_TO_LOG]
/// </summary>
ToLog = CvBlobConst.CV_BLOB_RENDER_TO_LOG,
/// <summary>
/// Print blob data to std out.
/// [CV_BLOB_RENDER_TO_STD]
/// </summary>
ToStd = CvBlobConst.CV_BLOB_RENDER_TO_STD,
}
}
| 24.854545 | 62 | 0.549378 | [
"BSD-3-Clause"
] | CollegiumXR/OpenCvSharp-Xamarin.Droid | src/OpenCvSharp.Blob/RenderBlobsMode.cs | 1,369 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Este código fue generado por una herramienta.
// Versión de runtime:4.0.30319.42000
//
// Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si
// se vuelve a generar el código.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("NetTools.Tests")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("NetTools.Tests")]
[assembly: System.Reflection.AssemblyTitleAttribute("NetTools.Tests")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generado por la clase WriteCodeFragment de MSBuild.
| 43.041667 | 95 | 0.657309 | [
"MIT"
] | Daraciel/NetTools | NetTools/NetTools.Tests/obj/Debug/netcoreapp3.1/NetTools.Tests.AssemblyInfo.cs | 1,038 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace StoreApp.Library
{
public interface IProduct
{
int ProductId { get; }
string ProductName { get; }
decimal Price { get; }
void UpdatePrice(int newPrice);
}
}
| 15.722222 | 39 | 0.628975 | [
"MIT"
] | 2011-nov02-net/alex-project0 | StoreApp/StoreApp.Library/IProduct.cs | 285 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Mps.V20190612.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class MediaContentReviewOcrTextSegmentItem : AbstractModel
{
/// <summary>
/// 嫌疑片段起始的偏移时间,单位:秒。
/// </summary>
[JsonProperty("StartTimeOffset")]
public float? StartTimeOffset{ get; set; }
/// <summary>
/// 嫌疑片段结束的偏移时间,单位:秒。
/// </summary>
[JsonProperty("EndTimeOffset")]
public float? EndTimeOffset{ get; set; }
/// <summary>
/// 嫌疑片段置信度。
/// </summary>
[JsonProperty("Confidence")]
public float? Confidence{ get; set; }
/// <summary>
/// 嫌疑片段审核结果建议,取值范围:
/// <li>pass。</li>
/// <li>review。</li>
/// <li>block。</li>
/// </summary>
[JsonProperty("Suggestion")]
public string Suggestion{ get; set; }
/// <summary>
/// 嫌疑关键词列表。
/// </summary>
[JsonProperty("KeywordSet")]
public string[] KeywordSet{ get; set; }
/// <summary>
/// 嫌疑文字出现的区域坐标 (像素级),[x1, y1, x2, y2],即左上角坐标、右下角坐标。
/// </summary>
[JsonProperty("AreaCoordSet")]
public long?[] AreaCoordSet{ get; set; }
/// <summary>
/// 嫌疑图片 URL (图片不会永久存储,到达
/// PicUrlExpireTime 时间点后图片将被删除)。
/// </summary>
[JsonProperty("Url")]
public string Url{ get; set; }
/// <summary>
/// 嫌疑图片 URL 失效时间,使用 [ISO 日期格式](https://cloud.tencent.com/document/product/266/11732#iso-.E6.97.A5.E6.9C.9F.E6.A0.BC.E5.BC.8F)。
/// </summary>
[JsonProperty("PicUrlExpireTime")]
public string PicUrlExpireTime{ get; set; }
/// <summary>
/// 内部实现,用户禁止调用
/// </summary>
internal override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "StartTimeOffset", this.StartTimeOffset);
this.SetParamSimple(map, prefix + "EndTimeOffset", this.EndTimeOffset);
this.SetParamSimple(map, prefix + "Confidence", this.Confidence);
this.SetParamSimple(map, prefix + "Suggestion", this.Suggestion);
this.SetParamArraySimple(map, prefix + "KeywordSet.", this.KeywordSet);
this.SetParamArraySimple(map, prefix + "AreaCoordSet.", this.AreaCoordSet);
this.SetParamSimple(map, prefix + "Url", this.Url);
this.SetParamSimple(map, prefix + "PicUrlExpireTime", this.PicUrlExpireTime);
}
}
}
| 33.556701 | 135 | 0.596313 | [
"Apache-2.0"
] | Darkfaker/tencentcloud-sdk-dotnet | TencentCloud/Mps/V20190612/Models/MediaContentReviewOcrTextSegmentItem.cs | 3,561 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.TestPlatform.ObjectModel.UnitTests
{
using System;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class TestCaseTests
{
private TestCase testCase;
[TestInitialize]
public void TestInit()
{
testCase = new TestCase("sampleTestClass.sampleTestCase", new Uri("executor://sampleTestExecutor"), "sampleTest.dll");
}
[TestMethod]
public void TestCaseIdIfNotSetExplicitlyShouldReturnGuidBasedOnSourceAndName()
{
Assert.AreEqual("28e7a7ed-8fb9-05b7-5e90-4a8c52f32b5b", testCase.Id.ToString());
}
[TestMethod]
public void TestCaseIdIfNotSetExplicitlyShouldReturnGuidBasedOnSourceAndNameIfNameIsChanged()
{
testCase.FullyQualifiedName = "sampleTestClass1.sampleTestCase1";
Assert.AreEqual("6f86dd1c-7130-a1ae-8e7f-02e7de898a43", testCase.Id.ToString());
}
[TestMethod]
public void TestCaseIdIfNotSetExplicitlyShouldReturnGuidBasedOnSourceAndNameIfSourceIsChanged()
{
testCase.Source = "sampleTest1.dll";
Assert.AreEqual("22843fee-70ea-4cf4-37cd-5061b4c47a8a", testCase.Id.ToString());
}
[TestMethod]
public void TestCaseIdShouldReturnIdSetExplicitlyEvenIfNameOrSourceInfoChanges()
{
var testGuid = new Guid("{8167845C-9CDB-476F-9F2B-1B1C1FE01B7D}");
testCase.Id = testGuid;
testCase.FullyQualifiedName = "sampleTestClass1.sampleTestCase1";
testCase.Source = "sampleTest1.dll";
Assert.AreEqual(testGuid, testCase.Id);
}
[TestMethod]
public void TestCaseLocalExtensionDataIsPubliclySettableGettableProperty()
{
var dummyData = "foo";
this.testCase.LocalExtensionData = dummyData;
Assert.AreEqual("foo", this.testCase.LocalExtensionData);
}
#region GetSetPropertyValue Tests
[TestMethod]
public void TestCaseGetPropertyValueForCodeFilePathShouldReturnCorrectValue()
{
var testCodeFilePath = "C:\\temp\foo.cs";
this.testCase.CodeFilePath = testCodeFilePath;
Assert.AreEqual(testCodeFilePath, this.testCase.GetPropertyValue(TestCaseProperties.CodeFilePath));
}
[TestMethod]
public void TestCaseGetPropertyValueForDisplayNameShouldReturnCorrectValue()
{
var testDisplayName = "testCaseDisplayName";
this.testCase.DisplayName = testDisplayName;
Assert.AreEqual(testDisplayName, this.testCase.GetPropertyValue(TestCaseProperties.DisplayName));
}
[TestMethod]
public void TestCaseGetPropertyValueForExecutorUriShouldReturnCorrectValue()
{
var testExecutorUri = new Uri("http://foo");
this.testCase.ExecutorUri = testExecutorUri;
Assert.AreEqual(testExecutorUri, this.testCase.GetPropertyValue(TestCaseProperties.ExecutorUri));
}
[TestMethod]
public void TestCaseGetPropertyValueForFullyQualifiedNameShouldReturnCorrectValue()
{
var testFullyQualifiedName = "fullyQualifiedName.Test1";
this.testCase.FullyQualifiedName = testFullyQualifiedName;
Assert.AreEqual(testFullyQualifiedName, this.testCase.GetPropertyValue(TestCaseProperties.FullyQualifiedName));
}
[TestMethod]
public void TestCaseGetPropertyValueForIdShouldReturnCorrectValue()
{
var testId = new Guid("{7845816C-9CDB-37DA-9ADF-1B1C1FE01B7D}");
this.testCase.Id = testId;
Assert.AreEqual(testId, this.testCase.GetPropertyValue(TestCaseProperties.Id));
}
[TestMethod]
public void TestCaseGetPropertyValueForLineNumberShouldReturnCorrectValue()
{
var testLineNumber = 34;
this.testCase.LineNumber = testLineNumber;
Assert.AreEqual(testLineNumber, this.testCase.GetPropertyValue(TestCaseProperties.LineNumber));
}
[TestMethod]
public void TestCaseGetPropertyValueForSourceShouldReturnCorrectValue()
{
var testSource = "C://temp/foobar.dll";
this.testCase.Source = testSource;
Assert.AreEqual(testSource, this.testCase.GetPropertyValue(TestCaseProperties.Source));
}
[TestMethod]
public void TestCaseSetPropertyValueForCodeFilePathShouldSetValue()
{
var testCodeFilePath = "C:\\temp\foo.cs";
this.testCase.SetPropertyValue(TestCaseProperties.CodeFilePath, testCodeFilePath);
Assert.AreEqual(testCodeFilePath, this.testCase.CodeFilePath);
}
[TestMethod]
public void TestCaseSetPropertyValueForDisplayNameShouldSetValue()
{
var testDisplayName = "testCaseDisplayName";
this.testCase.SetPropertyValue(TestCaseProperties.DisplayName, testDisplayName);
Assert.AreEqual(testDisplayName, this.testCase.DisplayName);
}
[TestMethod]
public void TestCaseSetPropertyValueForExecutorUriShouldSetValue()
{
var testExecutorUri = new Uri("http://foo");
this.testCase.SetPropertyValue(TestCaseProperties.ExecutorUri, testExecutorUri);
Assert.AreEqual(testExecutorUri, this.testCase.ExecutorUri);
}
[TestMethod]
public void TestCaseSetPropertyValueForFullyQualifiedNameShouldSetValue()
{
var testFullyQualifiedName = "fullyQualifiedName.Test1";
this.testCase.SetPropertyValue(TestCaseProperties.FullyQualifiedName, testFullyQualifiedName);
Assert.AreEqual(testFullyQualifiedName, this.testCase.FullyQualifiedName);
}
[TestMethod]
public void TestCaseSetPropertyValueForIdShouldSetValue()
{
var testId = new Guid("{7845816C-9CDB-37DA-9ADF-1B1C1FE01B7D}");
this.testCase.SetPropertyValue(TestCaseProperties.Id, testId);
Assert.AreEqual(testId, this.testCase.Id);
}
[TestMethod]
public void TestCaseSetPropertyValueForLineNumberShouldSetValue()
{
var testLineNumber = 34;
this.testCase.SetPropertyValue(TestCaseProperties.LineNumber, testLineNumber);
Assert.AreEqual(testLineNumber, this.testCase.LineNumber);
}
[TestMethod]
public void TestCaseSetPropertyValueForSourceShouldSetValue()
{
var testSource = "C://temp/foobar.dll";
this.testCase.SetPropertyValue(TestCaseProperties.Source, testSource);
Assert.AreEqual(testSource, this.testCase.Source);
}
#endregion
}
}
| 36.302564 | 130 | 0.669445 | [
"MIT"
] | Cosifne/vstest | test/Microsoft.TestPlatform.ObjectModel.UnitTests/TestCaseTests.cs | 7,081 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.OperationalInsights.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Entity Resource
/// </summary>
/// <remarks>
/// The resource model definition for an Azure Resource Manager resource
/// with an etag.
/// </remarks>
public partial class AzureEntityResource : Resource
{
/// <summary>
/// Initializes a new instance of the AzureEntityResource class.
/// </summary>
public AzureEntityResource()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the AzureEntityResource class.
/// </summary>
/// <param name="id">Fully qualified resource ID for the resource. Ex -
/// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}</param>
/// <param name="name">The name of the resource</param>
/// <param name="type">The type of the resource. E.g.
/// "Microsoft.Compute/virtualMachines" or
/// "Microsoft.Storage/storageAccounts"</param>
/// <param name="etag">Resource Etag.</param>
public AzureEntityResource(string id = default(string), string name = default(string), string type = default(string), string etag = default(string))
: base(id, name, type)
{
Etag = etag;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets resource Etag.
/// </summary>
[JsonProperty(PropertyName = "etag")]
public string Etag { get; private set; }
}
}
| 34.730159 | 156 | 0.621115 | [
"MIT"
] | 93mishra/azure-sdk-for-net | sdk/operationalinsights/Microsoft.Azure.Management.OperationalInsights/src/Generated/Models/AzureEntityResource.cs | 2,188 | C# |
using System;
using SQLite;
using System.Linq;
using System.Collections.Generic;
using PasswordsStashMobile.Model;
namespace PasswordsStashMobile.Controller
{
public class PasswordController
{
private SQLiteConnection sqliteConn;
public string Status = "";
public PasswordController(string ConnectionPath)
{
sqliteConn = new SQLiteConnection(ConnectionPath);
sqliteConn.CreateTable<PasswordModel>(); // Creates table if does not exist.
}
// -------------------------------------------------------------------
// Funciones CRUD.
public IEnumerable<PasswordModel> GetAllPasswords()
{
try
{
return sqliteConn.Table<PasswordModel>();
}
catch (Exception e)
{
Status = e.Message;
}
return Enumerable.Empty<PasswordModel>();
}
public PasswordModel GetPassword(int id)
{
try
{
return sqliteConn.Table<PasswordModel>()
.Where(i => i.PasswordId == id).FirstOrDefault();
}
catch (Exception e)
{
Status = e.Message;
}
return null;
}
public int InsertPassword(PasswordModel password)
{
int AffectedRows = 0;
try
{
AffectedRows = sqliteConn.Insert(password);
Status = string.Format("Affected rows: {0}", AffectedRows);
}
catch (Exception e)
{
Status = e.Message;
}
return AffectedRows;
}
public int UpdatePassword(PasswordModel password)
{
int AffectedRows = 0;
try
{
AffectedRows = sqliteConn.Update(password);
Status = string.Format("Affected rows: {0}", AffectedRows);
}
catch (Exception e)
{
Status = e.Message;
}
return AffectedRows;
}
public int DeletePassword(PasswordModel password)
{
int AffectedRows = 0;
try
{
AffectedRows = sqliteConn.Delete<PasswordModel>(password);
Status = string.Format("Affected rows: {0}", AffectedRows);
}
catch (Exception e)
{
Status = e.Message;
}
return AffectedRows;
}
}
}
| 27.083333 | 88 | 0.478462 | [
"MIT"
] | JustVice/Passwords-Stash-Mobile | PasswordsStashMobile/PasswordsStashMobile/Controller/PasswordController.cs | 2,602 | C# |
using BEDA.CIB.Contracts.Responses;
using BEDA.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace BEDA.CIB.Contracts.Requests
{
/// <summary>
/// 3.17.5虚拟资金池主账户支付额度查询请求主体
/// </summary>
public class V1_MAINACCTPAYLIMITTRNRQ : IRequest<V1_MAINACCTPAYLIMITTRNRS>
{
/// <summary>
/// 3.17.5虚拟资金池主账户支付额度查询请求主体
/// </summary>
public MAINACCTPAYLIMITTRNRQ MAINACCTPAYLIMITTRNRQ { get; set; }
}
/// <summary>
/// 3.17.5虚拟资金池主账户支付额度查询请求主体
/// </summary>
public class MAINACCTPAYLIMITTRNRQ : BIZRQBASE
{
/// <summary>
/// 3.17.5虚拟资金池主账户支付额度查询请求内容
/// </summary>
[XmlElement(Order = 2)]
public MAINACCTPAYLIMITTRN_RQBODY RQBODY { get; set; }
}
/// <summary>
/// 3.17.5虚拟资金池主账户支付额度查询请求内容
/// </summary>
public class MAINACCTPAYLIMITTRN_RQBODY
{
/// <summary>
/// 主账户 必输
/// </summary>
[XmlElement(Order = 0)]
public string ACCTID { get; set; }
/// <summary>
/// 拟支付金额 非必输
/// </summary>
[XmlIgnore]
public decimal? PLANMONEY { get; set; }
/// <summary>
/// 拟支付金额 对应<see cref="PLANMONEY"/> 非必输
/// </summary>
[XmlElement("PLANMONEY", Order = 1)]
public string PLANMONEYStr
{
get
{
return this.PLANMONEY?.ToString();
}
set
{
this.PLANMONEY = value.TryConvert<decimal>();
}
}
}
}
| 25.630769 | 78 | 0.548019 | [
"MIT"
] | fdstar/BankEnterpriseDirectAttach | src/BEDA.CIB/Contracts/Requests/3.17/V1_MAINACCTPAYLIMITTRNRQ.cs | 1,894 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Linq;
using BuildXL.Scheduler.Distribution;
using BuildXL.Utilities.Configuration;
using BuildXL.Utilities.Instrumentation.Common;
using static BuildXL.Utilities.FormattableStringEx;
namespace BuildXL.Scheduler.Tracing
{
/// <summary>
/// Execution log events that need to be intercepted only on non-worker machines.
/// </summary>
public sealed class OchestratorSpecificExecutionLogTarget : ExecutionLogTargetBase
{
private readonly LoggingContext m_loggingContext;
private readonly Scheduler m_scheduler;
private readonly int m_workerId;
private readonly bool m_tracerEnabled;
/// <summary>
/// Handle the events from workers
/// </summary>
public override bool CanHandleWorkerEvents => true;
/// <summary>
/// Tracks time when the tracer was last updated
/// </summary>
private DateTime m_tracerLastUpdated;
/// <inheritdoc/>
public override IExecutionLogTarget CreateWorkerTarget(uint workerId)
{
return new OchestratorSpecificExecutionLogTarget(m_loggingContext, m_scheduler, (int)workerId);
}
/// <summary>
/// Constructor.
/// </summary>
public OchestratorSpecificExecutionLogTarget(
LoggingContext loggingContext,
Scheduler scheduler,
int workerId = 0)
{
m_loggingContext = loggingContext;
m_scheduler = scheduler;
m_workerId = workerId;
m_tracerEnabled = ((IPipExecutionEnvironment)m_scheduler).Configuration.Logging.LogTracer;
}
/// <inheritdoc/>
public override void CacheMaterializationError(CacheMaterializationErrorEventData data)
{
var pathTable = m_scheduler.Context.PathTable;
var pip = m_scheduler.PipGraph.PipTable.HydratePip(data.PipId, Pips.PipQueryContext.CacheMaterializationError);
string descriptionFailure = string.Join(
Environment.NewLine,
new[] { I($"Failed files to materialize:") }
.Concat(data.FailedFiles.Select(f => I($"{f.Item1.Path.ToString(pathTable)} | Hash={f.Item2.ToString()} | ProducedBy={m_scheduler.GetProducerInfoForFailedMaterializeFile(f.Item1)}"))));
Logger.Log.DetailedPipMaterializeDependenciesFromCacheFailure(
m_loggingContext,
pip.GetDescription(m_scheduler.Context),
descriptionFailure);
}
/// <inheritdoc/>
public override void StatusReported(StatusEventData data)
{
var worker = m_scheduler.Workers[m_workerId];
worker.ActualFreeMemoryMb = data.RamFreeMb;
worker.ActualFreeCommitMb = data.CommitFreeMb;
if (worker.IsRemote)
{
worker.TotalCommitMb = data.CommitUsedMb + data.CommitFreeMb;
}
if (m_tracerEnabled && DateTime.UtcNow > m_tracerLastUpdated.AddSeconds(EngineEnvironmentSettings.MinStepDurationSecForTracer))
{
LogPercentageCounter(worker, "CPU", data.CpuPercent, data.Time.Ticks);
LogPercentageCounter(worker, "RAM", data.RamPercent, data.Time.Ticks);
m_tracerLastUpdated = DateTime.UtcNow;
}
}
private void LogPercentageCounter(Worker worker, string name, int percentValue, long ticks)
{
if (worker.InitializedTracerCounters.TryAdd(name, 0))
{
// To show the counters nicely in the UI, we set percentage counters to 100 for very short time
// so that UI aligns the rest based on 100% instead of the maximum observed value
BuildXL.Tracing.Logger.Log.TracerCounterEvent(m_loggingContext, name, worker.Name, ticks, 100);
}
BuildXL.Tracing.Logger.Log.TracerCounterEvent(m_loggingContext, name, worker.Name, ticks, percentValue);
}
}
}
| 39.792453 | 202 | 0.630868 | [
"MIT"
] | BearerPipelineTest/BuildXL | Public/Src/Engine/Scheduler/Tracing/OchestratorSpecificExecutionLogTarget.cs | 4,218 | C# |
using Gov.Jag.PillPressRegistry.Interfaces;
using Gov.Jag.PillPressRegistry.Interfaces.Models;
using Gov.Jag.PillPressRegistry.Public.Authentication;
using Gov.Jag.PillPressRegistry.Public.Models;
using Gov.Jag.PillPressRegistry.Public.Utils;
using Gov.Jag.PillPressRegistry.Public.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace Gov.Jag.PillPressRegistry.Public.Controllers
{
[Route("api/[controller]")]
[Authorize(Policy = "Business-User")]
public class AccountController : Controller
{
private readonly BCeIDBusinessQuery _bceid;
private readonly IConfiguration Configuration;
private readonly IDynamicsClient _dynamicsClient;
private readonly SharePointFileManager _sharePointFileManager;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly ILogger _logger;
public AccountController(SharePointFileManager sharePointFileManager, IConfiguration configuration, IHttpContextAccessor httpContextAccessor, BCeIDBusinessQuery bceid, ILoggerFactory loggerFactory, IDynamicsClient dynamicsClient)
{
Configuration = configuration;
_bceid = bceid;
_dynamicsClient = dynamicsClient;
_httpContextAccessor = httpContextAccessor;
//_sharePointFileManager = sharePointFileManager;
_logger = loggerFactory.CreateLogger(typeof(AccountController));
_sharePointFileManager = sharePointFileManager;
}
/// GET account in Dynamics for the current user
[HttpGet("current")]
public async Task<IActionResult> GetCurrentAccount()
{
_logger.LogInformation(LoggingEvents.HttpGet, "Begin method " + this.GetType().Name + "." + MethodBase.GetCurrentMethod().ReflectedType.Name);
ViewModels.Account result = null;
// get the current user.
string sessionSettings = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
UserSettings userSettings = JsonConvert.DeserializeObject<UserSettings>(sessionSettings);
_logger.LogDebug(LoggingEvents.HttpGet, "UserSettings: " + JsonConvert.SerializeObject(userSettings));
// query the Dynamics system to get the account record.
if (userSettings.AccountId != null && userSettings.AccountId.Length > 0)
{
var accountId = GuidUtility.SanitizeGuidString(userSettings.AccountId);
MicrosoftDynamicsCRMaccount account = _dynamicsClient.GetAccountByIdWithChildren(new Guid(accountId));
_logger.LogDebug(LoggingEvents.HttpGet, "Dynamics Account: " + JsonConvert.SerializeObject(account));
if (account == null)
{
// Sometimes we receive the siteminderbusinessguid instead of the account id.
account = await _dynamicsClient.GetAccountBySiteminderBusinessGuid(accountId);
if (account == null)
{
_logger.LogWarning(LoggingEvents.NotFound, "No Account Found.");
return new NotFoundResult();
}
}
result = account.ToViewModel();
}
else
{
_logger.LogWarning(LoggingEvents.NotFound, "No Account Found.");
return new NotFoundResult();
}
_logger.LogDebug(LoggingEvents.HttpGet, "Current Account Result: " +
JsonConvert.SerializeObject(result, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }));
return Json(result);
}
/// GET account in Dynamics for the current user
[HttpGet("bceid")]
public async Task<IActionResult> GetCurrentBCeIDBusiness()
{
_logger.LogInformation(LoggingEvents.HttpGet, "Begin method " + this.GetType().Name + "." + MethodBase.GetCurrentMethod().ReflectedType.Name);
// get the current user.
string temp = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
UserSettings userSettings = JsonConvert.DeserializeObject<UserSettings>(temp);
_logger.LogDebug(LoggingEvents.HttpGet, "UserSettings: " + JsonConvert.SerializeObject(userSettings));
// query the BCeID API to get the business record.
var business = await _bceid.ProcessBusinessQuery(userSettings.SiteMinderGuid);
var cleanNumber = BusinessNumberSanitizer.SanitizeNumber(business?.businessNumber);
if (cleanNumber != null)
{
business.businessNumber = cleanNumber;
}
if (business == null)
{
_logger.LogWarning(LoggingEvents.NotFound, "No Business Found.");
return new NotFoundResult();
}
_logger.LogDebug(LoggingEvents.HttpGet, "BCeID business record: " +
JsonConvert.SerializeObject(business, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }));
return Json(business);
}
/// <summary>
/// Get a specific legal entity
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet("{id}")]
public IActionResult GetAccount(string id)
{
_logger.LogInformation(LoggingEvents.HttpGet, "Begin method " + this.GetType().Name + "." + MethodBase.GetCurrentMethod().ReflectedType.Name);
_logger.LogDebug(LoggingEvents.HttpGet, "id: " + id);
Boolean userAccessToAccount = false;
ViewModels.Account result = null;
// query the Dynamics system to get the account record.
if (!string.IsNullOrEmpty(id) && Guid.TryParse(id, out Guid accountId))
{
// verify the currently logged in user has access to this account
try
{
userAccessToAccount = UserDynamicsExtensions.CurrentUserHasAccessToAccount(accountId, _httpContextAccessor, _dynamicsClient);
}
catch (OdataerrorException odee)
{
_logger.LogError(LoggingEvents.Error, "Error while checking if current user has access to account.");
_logger.LogError("Request:");
_logger.LogError(odee.Request.Content);
_logger.LogError("Response:");
_logger.LogError(odee.Response.Content);
}
if (!userAccessToAccount)
{
_logger.LogWarning(LoggingEvents.NotFound, "Current user has NO access to account.");
return new NotFoundResult();
}
List<string> expand = new List<string> { "bcgov_CurrentBusinessPhysicalAddress",
"bcgov_CurrentBusinessMailingAddress", "bcgov_AdditionalContact", "primarycontactid" };
try
{
MicrosoftDynamicsCRMaccount account = _dynamicsClient.Accounts.GetByKey(accountId.ToString(), expand: expand);
result = account.ToViewModel();
}
catch (OdataerrorException)
{
return new NotFoundResult();
}
}
else
{
_logger.LogWarning(LoggingEvents.BadRequest, "Bad Request.");
return BadRequest();
}
_logger.LogDebug(LoggingEvents.HttpGet, "Account result: " +
JsonConvert.SerializeObject(result, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }));
return Json(result);
}
/// <summary>
/// Get the locations associated to an account
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet("{id}/locations")]
public IActionResult GetAccountLocations(string id)
{
_logger.LogInformation(LoggingEvents.HttpGet, "Begin method " + this.GetType().Name + "." + MethodBase.GetCurrentMethod().ReflectedType.Name);
_logger.LogDebug(LoggingEvents.HttpGet, "id: " + id);
Boolean userAccessToAccount = false;
List<ViewModels.Location> result = new List<ViewModels.Location>();
// query the Dynamics system to get the account record.
if (!string.IsNullOrEmpty(id) && Guid.TryParse(id, out Guid accountId))
{
// verify the currently logged in user has access to this account
try
{
userAccessToAccount = UserDynamicsExtensions.CurrentUserHasAccessToAccount(accountId, _httpContextAccessor, _dynamicsClient);
}
catch (OdataerrorException odee)
{
_logger.LogError(LoggingEvents.Error, "Error while checking if current user has access to account.");
_logger.LogError("Request:");
_logger.LogError(odee.Request.Content);
_logger.LogError("Response:");
_logger.LogError(odee.Response.Content);
}
if (!userAccessToAccount)
{
_logger.LogWarning(LoggingEvents.NotFound, "Current user has NO access to account.");
return new NotFoundResult();
}
List<string> expand = new List<string> { "bcgov_LocationAddress" };
try
{
string filter = $"_bcgov_businessprofile_value eq {id}";
var query = _dynamicsClient.Locations.Get(filter: filter, expand: expand);
foreach (var item in query.Value)
{
result.Add(item.ToViewModel());
}
}
catch (OdataerrorException)
{
_logger.LogDebug("Error occured obtaining incident locations.");
return new NotFoundResult();
}
}
else
{
_logger.LogWarning(LoggingEvents.BadRequest, "Bad Request.");
return BadRequest();
}
_logger.LogDebug(LoggingEvents.HttpGet, "Account result: " +
JsonConvert.SerializeObject(result, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }));
return Json(result);
}
/// <summary>
/// Get the business contacts associated to an account
/// </summary>
/// <param name="id"></param>
/// <param name="ownermanagercode"></param>
/// <returns></returns>
[HttpGet("{id}/businesscontacts/{ownermanagercode}")]
public IActionResult GetAccountBusinessContacts(string id, int ownermanagercode = 0)
{
_logger.LogInformation(LoggingEvents.HttpGet, "Begin method " + this.GetType().Name + "." + MethodBase.GetCurrentMethod().ReflectedType.Name);
_logger.LogDebug(LoggingEvents.HttpGet, "id: " + id);
Boolean userAccessToAccount = false;
List<ViewModels.BusinessContact> result = new List<BusinessContact>();
// query the Dynamics system to get the account record.
if (!string.IsNullOrEmpty(id) && Guid.TryParse(id, out Guid accountId))
{
// verify the currently logged in user has access to this account
try
{
userAccessToAccount = UserDynamicsExtensions.CurrentUserHasAccessToAccount(accountId, _httpContextAccessor, _dynamicsClient);
}
catch (OdataerrorException odee)
{
_logger.LogError(LoggingEvents.Error, "Error while checking if current user has access to account.");
_logger.LogError("Request:");
_logger.LogError(odee.Request.Content);
_logger.LogError("Response:");
_logger.LogError(odee.Response.Content);
}
if (!userAccessToAccount)
{
_logger.LogWarning(LoggingEvents.NotFound, "Current user has NO access to account.");
return new NotFoundResult();
}
List<string> expand = new List<string> { "bcgov_Contact" };
try
{
string filter = $"_bcgov_businessprofile_value eq {id}";
if (ownermanagercode > 0)
{
filter = filter + $" and bcgov_registeredsellerownermanager eq {ownermanagercode}";
}
var query = _dynamicsClient.Businesscontacts.Get(filter: filter, expand: expand); //, expand: expand
foreach (var item in query.Value)
{
result.Add(item.ToViewModel());
}
}
catch (OdataerrorException odee)
{
_logger.LogDebug("Error occured obtaining account business contacts.");
_logger.LogError("Request:");
_logger.LogError(odee.Request.Content);
_logger.LogError("Response:");
_logger.LogError(odee.Response.Content);
return new NotFoundResult();
}
}
else
{
_logger.LogWarning(LoggingEvents.BadRequest, "Bad Request.");
return BadRequest();
}
_logger.LogDebug(LoggingEvents.HttpGet, "Account Business Contacts result: " +
JsonConvert.SerializeObject(result, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }));
return Json(result);
}
/// <summary>
/// Update contacts
/// </summary>
/// <param name="item"></param>
private void UpdateContacts (ViewModels.Account item)
{
// Primary Contact
if (item.primaryContact.HasValue())
{
var primaryContact = item.primaryContact.ToModel();
if (string.IsNullOrEmpty(item.primaryContact.id))
{
// create an account.
try
{
primaryContact = _dynamicsClient.Contacts.Create(primaryContact);
item.primaryContact.id = primaryContact.Contactid;
}
catch (OdataerrorException odee)
{
_logger.LogError(LoggingEvents.Error, "Error creating primary contact");
_logger.LogError("Request:");
_logger.LogError(odee.Request.Content);
_logger.LogError("Response:");
_logger.LogError(odee.Response.Content);
throw new OdataerrorException("Error updating the account.");
}
}
else
{
// update
try
{
_dynamicsClient.Contacts.Update(item.primaryContact.id, primaryContact);
}
catch (OdataerrorException odee)
{
_logger.LogError(LoggingEvents.Error, "Error updating primary contact");
_logger.LogError("Request:");
_logger.LogError(odee.Request.Content);
_logger.LogError("Response:");
_logger.LogError(odee.Response.Content);
throw new OdataerrorException("Error updating the account.");
}
}
}
// Additional Contact
if (item.additionalContact.HasValue())
{
var additionalContact = item.additionalContact.ToModel();
if (string.IsNullOrEmpty(item.additionalContact.id))
{
// create an account.
try
{
additionalContact = _dynamicsClient.Contacts.Create(additionalContact);
item.additionalContact.id = additionalContact.Contactid;
}
catch (OdataerrorException odee)
{
_logger.LogError(LoggingEvents.Error, "Error creating additional contact");
_logger.LogError("Request:");
_logger.LogError(odee.Request.Content);
_logger.LogError("Response:");
_logger.LogError(odee.Response.Content);
throw new OdataerrorException("Error updating the account.");
}
}
else
{
// update
try
{
_dynamicsClient.Contacts.Update(item.additionalContact.id, additionalContact);
}
catch (OdataerrorException odee)
{
_logger.LogError(LoggingEvents.Error, "Error updating additional contact");
_logger.LogError("Request:");
_logger.LogError(odee.Request.Content);
_logger.LogError("Response:");
_logger.LogError(odee.Response.Content);
throw new OdataerrorException("Error updating the account.");
}
}
}
}
/// <summary>
/// Update an account
/// </summary>
/// <param name="item"></param>
/// <param name="id"></param>
/// <returns></returns>
[HttpPut("{id}")]
public async Task<IActionResult> UpdateAccount([FromBody] ViewModels.Account item, string id)
{
bool isAdditionalContactDeleted = false;
string additionalContactDeletedId = null;
if (!string.IsNullOrEmpty(id) && Guid.TryParse(id, out Guid accountId))
{
_logger.LogInformation(LoggingEvents.HttpPut, "Begin method " + this.GetType().Name + "." + MethodBase.GetCurrentMethod().ReflectedType.Name);
_logger.LogDebug(LoggingEvents.HttpPut, "Account parameter: " + JsonConvert.SerializeObject(item));
_logger.LogDebug(LoggingEvents.HttpPut, "id parameter: " + id);
if (!UserDynamicsExtensions.CurrentUserHasAccessToAccount(accountId, _httpContextAccessor, _dynamicsClient))
{
_logger.LogWarning(LoggingEvents.NotFound, "Current user has NO access to the account.");
return NotFound();
}
MicrosoftDynamicsCRMaccount account = _dynamicsClient.GetAccountByIdWithChildren(accountId);
if (account == null)
{
_logger.LogWarning(LoggingEvents.NotFound, "Account NOT found.");
return new NotFoundResult();
}
// handle the contacts.
if ( !string.IsNullOrEmpty(account._bcgovAdditionalcontactValue) && string.IsNullOrEmpty(item.additionalContact.id) )
{
isAdditionalContactDeleted = true;
additionalContactDeletedId = account._bcgovAdditionalcontactValue;
}
UpdateContacts(item);
// we are doing a patch, so wipe out the record.
MicrosoftDynamicsCRMaccount patchAccount = new MicrosoftDynamicsCRMaccount();
// copy values over from the data provided
patchAccount.CopyValues(item);
if (item.primaryContact != null && item.primaryContact.id != null &&
(account._primarycontactidValue == null || account._primarycontactidValue != item.primaryContact.id))
{
patchAccount.PrimaryContactidODataBind = _dynamicsClient.GetEntityURI("contacts", item.primaryContact.id);
}
else
{
if (account._primarycontactidValue != null && ! item.primaryContact.HasValue())
{
// remove the reference.
try
{
// pass null as recordId to remove the single value navigation property
_dynamicsClient.Accounts.RemoveReference(accountId.ToString(), "primarycontactid", null);
}
catch (OdataerrorException odee)
{
_logger.LogError(LoggingEvents.Error, "Error updating the account.");
_logger.LogError("Request:");
_logger.LogError(odee.Request.Content);
_logger.LogError("Response:");
_logger.LogError(odee.Response.Content);
throw new OdataerrorException("Error updating the account.");
}
// delete the contact.
try
{
_dynamicsClient.Contacts.Delete(account._primarycontactidValue);
}
catch (OdataerrorException odee)
{
_logger.LogError(LoggingEvents.Error, "Error removing primary contact");
_logger.LogError("Request:");
_logger.LogError(odee.Request.Content);
_logger.LogError("Response:");
_logger.LogError(odee.Response.Content);
throw new OdataerrorException("Error updating the account.");
}
}
}
if (item.additionalContact != null && item.additionalContact.id != null &&
(account._bcgovAdditionalcontactValue == null || account._bcgovAdditionalcontactValue != item.additionalContact.id))
{
patchAccount.AdditionalContactODataBind = _dynamicsClient.GetEntityURI("contacts", item.additionalContact.id);
}
else
{
if (account._bcgovAdditionalcontactValue != null && ! item.additionalContact.HasValue())
{
// remove the reference.
try
{
// pass null as recordId to remove the single value navigation property
_dynamicsClient.Accounts.RemoveReference(accountId.ToString(), "bcgov_AdditionalContact", null);
}
catch (OdataerrorException odee)
{
_logger.LogError(LoggingEvents.Error, "Error updating the account.");
_logger.LogError("Request:");
_logger.LogError(odee.Request.Content);
_logger.LogError("Response:");
_logger.LogError(odee.Response.Content);
throw new OdataerrorException("Error updating the account.");
}
// delete the contact.
try
{
// do not delete the contact. Should remain linked as business contact
//_dynamicsClient.Contacts.Delete(account._bcgovAdditionalcontactValue);
}
catch (OdataerrorException odee)
{
_logger.LogError(LoggingEvents.Error, "Error removing additional contact");
_logger.LogError("Request:");
_logger.LogError(odee.Request.Content);
_logger.LogError("Response:");
_logger.LogError(odee.Response.Content);
throw new OdataerrorException("Error updating the account.");
}
}
}
try
{
await _dynamicsClient.Accounts.UpdateAsync(accountId.ToString(), patchAccount);
}
catch (OdataerrorException odee)
{
_logger.LogError(LoggingEvents.Error, "Error updating the account.");
_logger.LogError("Request:");
_logger.LogError(odee.Request.Content);
_logger.LogError("Response:");
_logger.LogError(odee.Response.Content);
throw new OdataerrorException("Error updating the account.");
}
// commenting out the purge of any existing non bceid accounts. They should remain as part of business contacts history
//_dynamicsClient.DeleteNonBceidBusinessContactLinkForAccount(_logger, accountId.ToString());
// set the business contact links.
if (item.primaryContact != null)
{
_dynamicsClient.CreateBusinessContactLink(_logger, item.primaryContact.id, accountId.ToString(), null, (int?)ContactTypeCodes.Primary, item.primaryContact.title);
}
if (item.additionalContact != null && item.additionalContact.HasValue())
{
_dynamicsClient.CreateBusinessContactLink(_logger, item.additionalContact.id, accountId.ToString(), null, (int?)ContactTypeCodes.Additional, item.additionalContact.title);
}
else
{
if (isAdditionalContactDeleted) {
// find business contact record
MicrosoftDynamicsCRMbcgovBusinesscontact businessContactLinked = _dynamicsClient.GetBusinessContactLink(_logger, additionalContactDeletedId, accountId.ToString());
// set business contact record, enddate field with current date/time
try
{
MicrosoftDynamicsCRMbcgovBusinesscontact businessContact = new MicrosoftDynamicsCRMbcgovBusinesscontact()
{
BcgovEnddate = DateTimeOffset.Now
};
_dynamicsClient.Businesscontacts.Update(businessContactLinked.BcgovBusinesscontactid, businessContact);
}
catch (OdataerrorException odee)
{
if (_logger != null)
{
_logger.LogError(LoggingEvents.Error, "Error updating business contact id: " + businessContactLinked.BcgovBusinesscontactid);
_logger.LogError("Request:");
_logger.LogError(odee.Request.Content);
_logger.LogError("Response:");
_logger.LogError(odee.Response.Content);
}
}
}
}
// populate child items in the account.
patchAccount = _dynamicsClient.GetAccountByIdWithChildren(accountId);
var updatedAccount = patchAccount.ToViewModel();
_logger.LogDebug(LoggingEvents.HttpPut, "updatedAccount: " +
JsonConvert.SerializeObject(updatedAccount, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }));
return Json(updatedAccount);
}
else
{
return new BadRequestResult();
}
}
[HttpPost()]
public async Task<IActionResult> CreateAccount([FromBody] ViewModels.Account item)
{
_logger.LogInformation(LoggingEvents.HttpPost, "Begin method " + this.GetType().Name + "." + MethodBase.GetCurrentMethod().ReflectedType.Name);
_logger.LogDebug(LoggingEvents.HttpPost, "Account parameters: " + JsonConvert.SerializeObject(item));
ViewModels.Account result = null;
// get UserSettings from the session
string temp = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
UserSettings userSettings = JsonConvert.DeserializeObject<UserSettings>(temp);
_logger.LogDebug(LoggingEvents.HttpPost, "UserSettings: " + JsonConvert.SerializeObject(userSettings));
// get account Siteminder GUID
string accountSiteminderGuid = userSettings.SiteMinderBusinessGuid;
if (accountSiteminderGuid == null || accountSiteminderGuid.Length == 0)
{
_logger.LogError(LoggingEvents.Error, "No account Siteminder Guid exernal id");
throw new Exception("Error. No accountSiteminderGuid exernal id");
}
// validate contact Siteminder GUID
string contactSiteminderGuid = userSettings.SiteMinderGuid;
if (contactSiteminderGuid == null || contactSiteminderGuid.Length == 0)
{
_logger.LogError(LoggingEvents.Error, "No Contact Siteminder Guid exernal id");
throw new Exception("Error. No ContactSiteminderGuid exernal id");
}
// get BCeID record for the current user
Gov.Jag.PillPressRegistry.Interfaces.BCeIDBusiness bceidBusiness = await _bceid.ProcessBusinessQuery(userSettings.SiteMinderGuid);
var cleanNumber = BusinessNumberSanitizer.SanitizeNumber(bceidBusiness?.businessNumber);
if (cleanNumber != null)
{
bceidBusiness.businessNumber = cleanNumber;
}
_logger.LogDebug(LoggingEvents.HttpGet, "BCeId business: " + JsonConvert.SerializeObject(bceidBusiness));
MicrosoftDynamicsCRMcontact userContact = null;
// see if the contact exists.
try
{
userContact = _dynamicsClient.GetContactByExternalId(contactSiteminderGuid);
}
catch (OdataerrorException odee)
{
_logger.LogError(LoggingEvents.Error, "Error getting contact by Siteminder Guid.");
_logger.LogError("Request:");
_logger.LogError(odee.Request.Content);
_logger.LogError("Response:");
_logger.LogError(odee.Response.Content);
throw new OdataerrorException("Error getting contact by Siteminder Guid");
}
if (userContact == null)
{
// create the user contact record.
userContact = new MicrosoftDynamicsCRMcontact();
// Adoxio_externalid is where we will store the guid from siteminder.
string sanitizedContactSiteminderId = GuidUtility.SanitizeGuidString(contactSiteminderGuid);
userContact.Externaluseridentifier = sanitizedContactSiteminderId;
userContact.BcgovBceiduserguid = sanitizedContactSiteminderId;
userContact.Fullname = userSettings.UserDisplayName;
userContact.Nickname = userSettings.UserDisplayName;
// ENABLE FOR BC SERVICE CARD SUPPORT
/*
if (! Guid.TryParse(userSettings.UserId, out tryParseOutGuid))
{
userContact.Externaluseridentifier = userSettings.UserId;
}
*/
if (bceidBusiness != null)
{
// set contact according to item
userContact.Firstname = bceidBusiness.individualFirstname;
userContact.Middlename = bceidBusiness.individualMiddlename;
userContact.Lastname = bceidBusiness.individualSurname;
userContact.Emailaddress1 = bceidBusiness.contactEmail;
userContact.Telephone1 = bceidBusiness.contactPhone;
userContact.BcgovBceid = bceidBusiness.userId;
userContact.BcgovBceidemail = bceidBusiness.contactEmail;
}
else
{
userContact.Firstname = userSettings.UserDisplayName.GetFirstName();
userContact.Lastname = userSettings.UserDisplayName.GetLastName();
}
userContact.Statuscode = 1;
_logger.LogDebug(LoggingEvents.HttpGet, "Account is NOT null. Only a new user.");
try
{
userContact = await _dynamicsClient.Contacts.CreateAsync(userContact);
}
catch (OdataerrorException odee)
{
_logger.LogError(LoggingEvents.Error, "Error creating user contact.");
_logger.LogError("Request:");
_logger.LogError(odee.Request.Content);
_logger.LogError("Response:");
_logger.LogError(odee.Response.Content);
throw new OdataerrorException("Error creating user contact.");
}
}
// this may be an existing account, as this service is used during the account confirmation process.
MicrosoftDynamicsCRMaccount account = await _dynamicsClient.GetAccountBySiteminderBusinessGuid(accountSiteminderGuid);
_logger.LogDebug(LoggingEvents.HttpGet, "Account by siteminder business guid: " + JsonConvert.SerializeObject(account));
if (account == null)
{
_logger.LogDebug(LoggingEvents.HttpGet, "Creating account");
// create a new account
account = new MicrosoftDynamicsCRMaccount();
account.CopyValues(item);
// business type must be set only during creation, not in update (removed from copyValues() )
// by convention we strip out any dashes present in the guid, and force it to uppercase.
string sanitizedAccountSiteminderId = GuidUtility.SanitizeGuidString(accountSiteminderGuid);
account.BcgovBceid = sanitizedAccountSiteminderId;
UpdateContacts(item);
// For Pill Press the Primary Contact is not set to default to the first user.
if (item.primaryContact != null && !(string.IsNullOrEmpty(item.primaryContact.id)))
{
// add as a reference.
account.PrimaryContactidODataBind = _dynamicsClient.GetEntityURI("contacts", item.primaryContact.id);
}
// Additional Contact
if (item.additionalContact != null && !(string.IsNullOrEmpty(item.additionalContact.id)))
{
// add as a reference.
account.AdditionalContactODataBind = _dynamicsClient.GetEntityURI("contacts", item.additionalContact.id);
}
if (bceidBusiness != null)
{
account.Name = bceidBusiness.legalName;
account.BcgovDoingbusinessasname = bceidBusiness.legalName;
account.Emailaddress1 = bceidBusiness.contactEmail;
account.Telephone1 = bceidBusiness.contactPhone;
// do not set the address from BCeID for Pill Press.
/*
account.Address1City = bceidBusiness.addressCity;
account.Address1Postalcode = bceidBusiness.addressPostal;
account.Address1Line1 = bceidBusiness.addressLine1;
account.Address1Line2 = bceidBusiness.addressLine2;
account.Address1Postalcode = bceidBusiness.addressPostal;
*/
}
else // likely a dev login.
{
account.Name = userSettings.BusinessLegalName;
account.BcgovDoingbusinessasname = userSettings.BusinessLegalName;
}
// set the Province and Country if they are not set.
if (string.IsNullOrEmpty(account.Address1Stateorprovince))
{
account.Address1Stateorprovince = "British Columbia";
}
if (string.IsNullOrEmpty(account.Address1Country))
{
account.Address1Country = "Canada";
}
string accountString = JsonConvert.SerializeObject(account);
_logger.LogDebug("Account before creation in dynamics --> " + accountString);
try
{
account = await _dynamicsClient.Accounts.CreateAsync(account);
}
catch (OdataerrorException odee)
{
_logger.LogError(LoggingEvents.Error, "Error creating Account.");
_logger.LogError("Request:");
_logger.LogError(odee.Request.Content);
_logger.LogError("Response:");
_logger.LogError(odee.Response.Content);
throw new OdataerrorException("Error creating Account");
}
// create a document location
await CreateAccountDocumentLocation(account);
// populate child elements.
account = _dynamicsClient.GetAccountByIdWithChildren(Guid.Parse(account.Accountid));
accountString = JsonConvert.SerializeObject(accountString);
_logger.LogDebug("Account Entity after creation in dynamics --> " + accountString);
}
// always patch the userContact so it relates to the account.
_logger.LogDebug(LoggingEvents.Save, "Patching the userContact so it relates to the account.");
// parent customer id relationship will be created using the method here:
//https://msdn.microsoft.com/en-us/library/mt607875.aspx
MicrosoftDynamicsCRMcontact patchUserContact = new MicrosoftDynamicsCRMcontact();
patchUserContact.ParentCustomerIdAccountODataBind = _dynamicsClient.GetEntityURI("accounts", account.Accountid);
try
{
await _dynamicsClient.Contacts.UpdateAsync(userContact.Contactid, patchUserContact);
}
catch (OdataerrorException odee)
{
_logger.LogError(LoggingEvents.Error, "Error binding contact to account");
_logger.LogError("Request:");
_logger.LogError(odee.Request.Content);
_logger.LogError("Response:");
_logger.LogError(odee.Response.Content);
throw new OdataerrorException("Error binding contact to account");
}
// if we have not yet authenticated, then this is the new record for the user.
if (userSettings.IsNewUserRegistration)
{
userSettings.AccountId = account.Accountid.ToString();
userSettings.ContactId = userContact.Contactid.ToString();
// we can now authenticate.
if (userSettings.AuthenticatedUser == null)
{
Models.User user = new Models.User();
user.Active = true;
user.AccountId = Guid.Parse(userSettings.AccountId);
user.ContactId = Guid.Parse(userSettings.ContactId);
user.UserType = userSettings.UserType;
user.SmUserId = userSettings.UserId;
userSettings.AuthenticatedUser = user;
}
// create the bridge entity for the BCeID user
_dynamicsClient.CreateBusinessContactLink(_logger, userSettings.ContactId, userSettings.AccountId, null, (int?)ContactTypeCodes.BCeID, "BCeID");
userSettings.IsNewUserRegistration = false;
string userSettingsString = JsonConvert.SerializeObject(userSettings);
_logger.LogDebug("userSettingsString --> " + userSettingsString);
// add the user to the session.
_httpContextAccessor.HttpContext.Session.SetString("UserSettings", userSettingsString);
_logger.LogDebug("user added to session. ");
}
else
{
_logger.LogError(LoggingEvents.Error, "Invalid user registration.");
throw new Exception("Invalid user registration.");
}
// create the business contact links.
if (item.primaryContact != null)
{
_dynamicsClient.CreateBusinessContactLink(_logger, item.primaryContact.id, account.Accountid, null, (int?)ContactTypeCodes.Primary, item.primaryContact.title);
}
if (item.additionalContact != null)
{
_dynamicsClient.CreateBusinessContactLink(_logger, item.additionalContact.id, account.Accountid, null, (int?)ContactTypeCodes.Additional, item.additionalContact.title);
}
//account.Accountid = id;
result = account.ToViewModel();
_logger.LogDebug(LoggingEvents.HttpPost, "result: " +
JsonConvert.SerializeObject(result, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }));
return Json(result);
}
private async Task CreateAccountDocumentLocation(MicrosoftDynamicsCRMaccount account)
{
string serverRelativeUrl = account.GetServerUrl(_sharePointFileManager);
string name = "";
if (string.IsNullOrEmpty(account.BcgovDoingbusinessasname))
{
name = account.Accountid;
}
else
{
name = account.BcgovDoingbusinessasname;
}
name += " Account Files";
// create a SharePointDocumentLocation link
string folderName = "_" + account.Accountid;
// Create the folder
bool folderExists = await _sharePointFileManager.FolderExists(SharePointFileManager.AccountDocumentListTitle, folderName);
if (!folderExists)
{
try
{
var folder = await _sharePointFileManager.CreateFolder(SharePointFileManager.AccountDocumentListTitle, folderName);
}
catch (Exception e)
{
_logger.LogError("Error creating Sharepoint Folder");
_logger.LogError($"List is: {SharePointFileManager.AccountDocumentListTitle}");
_logger.LogError($"FolderName is: {folderName}");
throw e;
}
}
// now create a document location to link them.
// Create the SharePointDocumentLocation entity
MicrosoftDynamicsCRMsharepointdocumentlocation mdcsdl = new MicrosoftDynamicsCRMsharepointdocumentlocation()
{
Relativeurl = folderName,
Description = "Account Files",
Name = name
};
try
{
mdcsdl = _dynamicsClient.Sharepointdocumentlocations.Create(mdcsdl);
}
catch (OdataerrorException odee)
{
_logger.LogError("Error creating SharepointDocumentLocation");
_logger.LogError("Request:");
_logger.LogError(odee.Request.Content);
_logger.LogError("Response:");
_logger.LogError(odee.Response.Content);
mdcsdl = null;
}
if (mdcsdl != null)
{
// set the parent document library.
string parentDocumentLibraryReference = GetDocumentLocationReferenceByRelativeURL("account");
string accountUri = _dynamicsClient.GetEntityURI("accounts", account.Accountid);
// add a regardingobjectid.
var patchSharePointDocumentLocationIncident = new MicrosoftDynamicsCRMsharepointdocumentlocation()
{
RegardingobjectIdAccountODataBind = accountUri,
ParentsiteorlocationSharepointdocumentlocationODataBind = _dynamicsClient.GetEntityURI("sharepointdocumentlocations", parentDocumentLibraryReference),
Relativeurl = folderName,
Description = "Account Files",
};
try
{
_dynamicsClient.Sharepointdocumentlocations.Update(mdcsdl.Sharepointdocumentlocationid, patchSharePointDocumentLocationIncident);
}
catch (OdataerrorException odee)
{
_logger.LogError("Error adding reference SharepointDocumentLocation to account");
_logger.LogError("Request:");
_logger.LogError(odee.Request.Content);
_logger.LogError("Response:");
_logger.LogError(odee.Response.Content);
}
string sharePointLocationData = _dynamicsClient.GetEntityURI("sharepointdocumentlocations", mdcsdl.Sharepointdocumentlocationid);
OdataId oDataId = new OdataId()
{
OdataIdProperty = sharePointLocationData
};
try
{
_dynamicsClient.Accounts.AddReference(account.Accountid, "Account_SharepointDocumentLocation", oDataId);
}
catch (OdataerrorException odee)
{
_logger.LogError("Error adding reference to SharepointDocumentLocation");
_logger.LogError("Request:");
_logger.LogError(odee.Request.Content);
_logger.LogError("Response:");
_logger.LogError(odee.Response.Content);
}
}
}
/// <summary>
/// Delete a legal entity. Using a HTTP Post to avoid Siteminder issues with DELETE
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpPost("{id}/delete")]
public async Task<IActionResult> DeleteDynamicsAccount(string id)
{
_logger.LogInformation(LoggingEvents.HttpPost, "Begin method " + this.GetType().Name + "." + MethodBase.GetCurrentMethod().ReflectedType.Name);
// verify the currently logged in user has access to this account
Guid accountId = new Guid(id);
if (!UserDynamicsExtensions.CurrentUserHasAccessToAccount(accountId, _httpContextAccessor, _dynamicsClient))
{
_logger.LogWarning(LoggingEvents.NotFound, "Current user has NO access to the account.");
return new NotFoundResult();
}
// get the account
MicrosoftDynamicsCRMaccount account = _dynamicsClient.GetAccountByIdWithChildren(accountId);
if (account == null)
{
_logger.LogWarning(LoggingEvents.NotFound, "Account NOT found.");
return new NotFoundResult();
}
try
{
await _dynamicsClient.Accounts.DeleteAsync(accountId.ToString());
_logger.LogDebug(LoggingEvents.HttpDelete, "Account deleted: " + accountId.ToString());
}
catch (OdataerrorException odee)
{
_logger.LogError(LoggingEvents.Error, "Error deleting the account: " + accountId.ToString());
_logger.LogError("Request:");
_logger.LogError(odee.Request.Content);
_logger.LogError("Response:");
_logger.LogError(odee.Response.Content);
throw new OdataerrorException("Error deleting the account: " + accountId.ToString());
}
_logger.LogDebug(LoggingEvents.HttpDelete, "No content returned.");
return NoContent(); // 204
}
/// <summary>
/// Get a document location by reference
/// </summary>
/// <param name="relativeUrl"></param>
/// <returns></returns>
private string GetDocumentLocationReferenceByRelativeURL(string relativeUrl)
{
string result = null;
string sanitized = relativeUrl.Replace("'", "''");
// first see if one exists.
var locations = _dynamicsClient.Sharepointdocumentlocations.Get(filter: "relativeurl eq '" + sanitized + "'");
var location = locations.Value.FirstOrDefault();
if (location == null)
{
var parentSite = _dynamicsClient.Sharepointsites.Get().Value.FirstOrDefault();
var parentSiteRef = _dynamicsClient.GetEntityURI("sharepointsites", parentSite.Sharepointsiteid);
MicrosoftDynamicsCRMsharepointdocumentlocation newRecord = new MicrosoftDynamicsCRMsharepointdocumentlocation()
{
Relativeurl = relativeUrl,
Name = "Account",
ParentsiteorlocationSharepointdocumentlocationODataBind = parentSiteRef
};
// create a new document location.
try
{
location = _dynamicsClient.Sharepointdocumentlocations.Create(newRecord);
}
catch (OdataerrorException odee)
{
_logger.LogError("Error creating document location");
_logger.LogError("Request:");
_logger.LogError(odee.Request.Content);
_logger.LogError("Response:");
_logger.LogError(odee.Response.Content);
}
}
if (location != null)
{
result = location.Sharepointdocumentlocationid;
}
return result;
}
}
}
| 46.905797 | 237 | 0.557759 | [
"Apache-2.0"
] | GeorgeWalker/jag-pill-press-registry | pill-press-app/Controllers/AccountController.cs | 51,786 | C# |
namespace Lego.Ev3.BrickManager
{
partial class ExplorerWindow
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.splitter = new System.Windows.Forms.Splitter();
this.directoryContentPane = new Lego.Ev3.BrickManager.DirectoryContentPane();
this.previewPane = new Lego.Ev3.BrickManager.PreviewPane();
this.folderTree = new Lego.Ev3.BrickManager.FolderTree();
this.statusBar = new Lego.Ev3.BrickManager.StatusBar();
this.navigationBar = new Lego.Ev3.BrickManager.NavigationBar();
this.folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.SuspendLayout();
//
// splitter
//
this.splitter.Location = new System.Drawing.Point(187, 45);
this.splitter.Name = "splitter";
this.splitter.Size = new System.Drawing.Size(2, 506);
this.splitter.TabIndex = 1;
this.splitter.TabStop = false;
//
// directoryContentPane
//
this.directoryContentPane.Dock = System.Windows.Forms.DockStyle.Fill;
this.directoryContentPane.Location = new System.Drawing.Point(189, 45);
this.directoryContentPane.Name = "directoryContentPane";
this.directoryContentPane.Size = new System.Drawing.Size(697, 506);
this.directoryContentPane.TabIndex = 2;
//
// previewPane
//
this.previewPane.BackColor = System.Drawing.SystemColors.Window;
this.previewPane.Dock = System.Windows.Forms.DockStyle.Right;
this.previewPane.Location = new System.Drawing.Point(886, 45);
this.previewPane.Name = "previewPane";
this.previewPane.Size = new System.Drawing.Size(174, 506);
this.previewPane.TabIndex = 4;
//
// folderTree
//
this.folderTree.Dock = System.Windows.Forms.DockStyle.Left;
this.folderTree.Location = new System.Drawing.Point(0, 45);
this.folderTree.Name = "folderTree";
this.folderTree.Size = new System.Drawing.Size(187, 506);
this.folderTree.TabIndex = 0;
//
// statusBar
//
this.statusBar.Dock = System.Windows.Forms.DockStyle.Bottom;
this.statusBar.Location = new System.Drawing.Point(0, 551);
this.statusBar.Name = "statusBar";
this.statusBar.Size = new System.Drawing.Size(1060, 25);
this.statusBar.TabIndex = 3;
//
// navigationBar
//
this.navigationBar.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(252)))), ((int)(((byte)(252)))), ((int)(((byte)(252)))));
this.navigationBar.Dock = System.Windows.Forms.DockStyle.Top;
this.navigationBar.Location = new System.Drawing.Point(0, 0);
this.navigationBar.Name = "navigationBar";
this.navigationBar.Size = new System.Drawing.Size(1060, 45);
this.navigationBar.TabIndex = 5;
//
// openFileDialog
//
this.openFileDialog.FileName = "openFileDialog1";
//
// ExplorerWindow
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.directoryContentPane);
this.Controls.Add(this.previewPane);
this.Controls.Add(this.splitter);
this.Controls.Add(this.folderTree);
this.Controls.Add(this.statusBar);
this.Controls.Add(this.navigationBar);
this.Name = "ExplorerWindow";
this.Size = new System.Drawing.Size(1060, 576);
this.ResumeLayout(false);
}
#endregion
private FolderTree folderTree;
private System.Windows.Forms.Splitter splitter;
private DirectoryContentPane directoryContentPane;
private PreviewPane previewPane;
private StatusBar statusBar;
private NavigationBar navigationBar;
private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog;
private System.Windows.Forms.SaveFileDialog saveFileDialog;
private System.Windows.Forms.OpenFileDialog openFileDialog;
}
}
| 43.328 | 145 | 0.59435 | [
"MIT"
] | mvanderelsen/Lego.Ev3.BrickManager | Lego.Ev3.BrickManager/ExplorerWindow.Designer.cs | 5,418 | C# |
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace MonoGame.Extended.TextureAtlases
{
public class TextureRegion2D
{
public TextureRegion2D(Texture2D texture, int x, int y, int width, int height)
: this(null, texture, x, y, width, height)
{
}
public TextureRegion2D(Texture2D texture, Rectangle region)
: this(null, texture, region.X, region.Y, region.Width, region.Height)
{
}
public TextureRegion2D(string name, Texture2D texture, Rectangle region)
: this(name, texture, region.X, region.Y, region.Width, region.Height)
{
}
public TextureRegion2D(Texture2D texture)
: this(texture.Name, texture, 0, 0, texture.Width, texture.Height)
{
}
public TextureRegion2D(string name, Texture2D texture, int x, int y, int width, int height)
{
if (texture == null) throw new ArgumentNullException(nameof(texture));
Name = name;
Texture = texture;
X = x;
Y = y;
Width = width;
Height = height;
}
public string Name { get; }
public Texture2D Texture { get; protected set; }
public int X { get; }
public int Y { get; }
public int Width { get; }
public int Height { get; }
public Size2 Size => new Size2(Width, Height);
public object Tag { get; set; }
public Rectangle Bounds => new Rectangle(X, Y, Width, Height);
public override string ToString()
{
return $"{Name ?? string.Empty} {Bounds}";
}
}
} | 30.660714 | 99 | 0.569598 | [
"MIT"
] | Jaden-Giordano/MonoGame.Extended | Source/MonoGame.Extended/TextureAtlases/TextureRegion2D.cs | 1,719 | C# |
namespace TinyTools.Events
{
public class IntEventListener : GameEventListener<int> { }
}
| 18.8 | 62 | 0.755319 | [
"MIT"
] | 1ukeb/GameEvents | Events/Runtime/Listeners/IntEventListener.cs | 94 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace DaedalusCompiler.Compilation
{
public class OutputUnitsBuilder
{
private readonly Dictionary<string, string> _wavFileNameToSpokenSentence;
private List<KeyValuePair<string, string>> _wavFileNameAndSpokenSentencePairs;
private string _generationDateTimeText;
private string _userName;
private const string InstanceBody = "instanceBody";
private const string StringLiteral = "stringLiteral";
private const string Comment = "comment";
private bool _verbose;
public OutputUnitsBuilder(bool verbose)
{
_wavFileNameToSpokenSentence = new Dictionary<string, string>();
_wavFileNameAndSpokenSentencePairs = null;
_generationDateTimeText = DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss", CultureInfo.InvariantCulture);
_userName = Environment.UserName;
_verbose = verbose;
}
public void SetGenerationDateTimeText(string generationDateTimeText)
{
_generationDateTimeText = generationDateTimeText;
}
public void SetGenerationUserName(string userName)
{
_userName = userName;
}
private void AddSpokenSentencesFromMatches(MatchCollection matches)
{
foreach (Match match in matches)
{
string wavFileName = match.Groups[StringLiteral].Value;
string dialogue = match.Groups[Comment].Value.Trim();
if (_wavFileNameToSpokenSentence.ContainsKey(wavFileName))
{
if (_verbose) Console.WriteLine($"Duplicated Wav: '{wavFileName}'");
}
_wavFileNameToSpokenSentence[wavFileName] = dialogue;
}
}
public void ParseText(string fileContent)
{
string multilineComment = @"(?:/\*.*?\*/)";
fileContent = Regex.Replace(fileContent, multilineComment, "", RegexOptions.Singleline);
fileContent = Regex.Replace(fileContent, "^.*//.*(?:ai_output|=).*$", "", RegexOptions.Multiline);
string ws = @"(?:[ \t])*";
string newline = @"\r\n?|\n";
string skip = $@"(?:{newline}|{ws})*";
string identifier = @"[^\W0-9]\w*";
string stringLiteral = $@"\""(?<{StringLiteral}>[^\""\r\n]*)\""";
string inlineComment = $@"//(?<{Comment}>[^\r\n]*)";
RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Multiline;
string cSvmInstancePattern = $@"\binstance{skip}{identifier}{skip}\({skip}C_SVM{skip}\){skip}{{(?<{InstanceBody}>[^}}]+)}}";
MatchCollection instanceMatches = Regex.Matches(fileContent, cSvmInstancePattern, options);
foreach (Match instanceMatch in instanceMatches)
{
string cSvmInstanceBody = instanceMatch.Groups[InstanceBody].Value;
string assignmentPattern = $@"{identifier}{ws}={ws}{stringLiteral}{ws};{ws}{inlineComment}";
MatchCollection assignmentMatches = Regex.Matches(cSvmInstanceBody, assignmentPattern, options);
AddSpokenSentencesFromMatches(assignmentMatches);
}
string aiOutputCallPattern = $@"\bai_output{ws}\({ws}{identifier}{ws},{ws}{identifier}{ws},{ws}{stringLiteral}{ws}\){ws};{ws}{inlineComment}";
MatchCollection aiOutputCallMatches = Regex.Matches(fileContent, aiOutputCallPattern, options);
AddSpokenSentencesFromMatches(aiOutputCallMatches);
}
public void SaveOutputUnits(string dirPath)
{
_wavFileNameAndSpokenSentencePairs = _wavFileNameToSpokenSentence.ToList();
_wavFileNameAndSpokenSentencePairs.Sort((a, b) => string.Compare(a.Key, b.Key, StringComparison.Ordinal));
SaveToCsl(dirPath);
SaveToBin(dirPath);
}
private void SaveToCsl(string dirPath)
{
string cslPath = Path.Combine(dirPath, "ou.csl");
int index = 1;
using (FileStream fileStream = new FileStream(cslPath, FileMode.Create, FileAccess.Write))
using (StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.GetEncoding(1250)))
{
int count = _wavFileNameAndSpokenSentencePairs.Count;
string csl = "ZenGin Archive\n";
csl += "ver 1\n";
csl += "zCArchiverGeneric\n";
csl += "ASCII\n";
csl += "saveGame 0\n";
csl += $"date {_generationDateTimeText}\n";
csl += $"user {_userName}\n";
csl += "END\n";
csl += $"objects {count*3+1} \n";
csl += "END\n\n";
csl += "[% zCCSLib 0 0]\n";
csl += $" NumOfItems=int:{count}\n";
streamWriter.Write(csl);
foreach (KeyValuePair<string, string> pair in _wavFileNameAndSpokenSentencePairs)
{
string item = "";
item += $" [% zCCSBlock 0 {index++}]\n";
item += $" blockName=string:{pair.Key}\n";
item += $" numOfBlocks=int:1\n";
item += $" subBlock0=float:0\n";
item += $" [% zCCSAtomicBlock 0 {index++}]\n";
item += $" [% oCMsgConversation:oCNpcMessage:zCEventMessage 0 {index++}]\n";
item += $" subType=enum:0\n";
item += $" text=string:{pair.Value}\n";
item += $" name=string:{pair.Key.ToUpper()}.WAV\n";
item += $" []\n";
item += $" []\n";
item += $" []\n";
streamWriter.Write(item);
if (_verbose) Console.Write($"\r{(index - 1) / 3}/{count} csl elements written");
}
if (_verbose) Console.WriteLine("");
streamWriter.Write("[]\n");
}
}
private void SaveToBin(string dirPath)
{
string binPath = Path.Combine(dirPath, "ou.bin");
int index = 1;
int address = 0;
using (FileStream fileStream = new FileStream(binPath, FileMode.Create, FileAccess.Write))
using (BinaryWriter binaryWriter = new BinaryWriter(fileStream, Encoding.GetEncoding(1250)))
{
int count = _wavFileNameAndSpokenSentencePairs.Count;
string binHeader = "ZenGin Archive\n";
binHeader += "ver 1\n";
binHeader += "zCArchiverBinSafe\n";
binHeader += "BIN_SAFE\n";
binHeader += "saveGame 0\n";
binHeader += $"date {_generationDateTimeText}\n";
binHeader += $"user {_userName}\n";
binHeader += "END\n";
// objects {count*3+1}
binaryWriter.Write(binHeader.ToCharArray());
binaryWriter.Write(2);
binaryWriter.Write(count*3+1);
address += binHeader.Length + 4 + 4;
int addressOfLastSignificantByteAddress = address;
binaryWriter.Write(0xFFFFFFFF); // to be replaced later
address += 4;
// [% zCCSLib 0 0]
char[] zCSSLib = "[% zCCSLib 0 0]".ToCharArray();
binaryWriter.Write((Byte)1);
binaryWriter.Write((Int16)zCSSLib.Length);
binaryWriter.Write(zCSSLib);
address += 1 + 2 + zCSSLib.Length;
// NumOfItems=int:{count}
binaryWriter.Write((Byte)18);
binaryWriter.Write(0);
binaryWriter.Write((Byte)2);
binaryWriter.Write(count);
address += 1 + 4 + 1 + 4;
foreach (KeyValuePair<string, string> pair in _wavFileNameAndSpokenSentencePairs)
{
// [% zCCSBlock 0 {index++}]
char[] zCCSBlockHeader = $"[% zCCSBlock 0 {index++}]".ToCharArray();
binaryWriter.Write((Byte)1);
binaryWriter.Write((Int16)zCCSBlockHeader.Length);
binaryWriter.Write(zCCSBlockHeader);
address += 1 + 2 + zCCSBlockHeader.Length;
// blockName=string:{pair.Key}
binaryWriter.Write((Byte)18);
binaryWriter.Write(1);
binaryWriter.Write((Byte)1);
binaryWriter.Write((Int16)pair.Key.Length);
binaryWriter.Write(pair.Key.ToCharArray());
address += 1 + 4 + 1 + 2 + pair.Key.Length;
// numOfBlocks=int:1
binaryWriter.Write((Byte)18);
binaryWriter.Write(2);
binaryWriter.Write((Byte)2);
binaryWriter.Write(1);
address += 1 + 4 + 1 + 4;
// subBlock0=float:0
binaryWriter.Write((Byte)18);
binaryWriter.Write(3);
binaryWriter.Write((Byte)3);
binaryWriter.Write(0);
address += 1 + 4 + 1 + 4;
// [% zCCSAtomicBlock 0 {index++}]
char[] zCCSAtomicBlock = $"[% zCCSAtomicBlock 0 {index++}]".ToCharArray();
binaryWriter.Write((Byte)1);
binaryWriter.Write((Int16)zCCSAtomicBlock.Length);
binaryWriter.Write(zCCSAtomicBlock);
address += 1 + 2 + zCCSAtomicBlock.Length;
// [% oCMsgConversation:oCNpcMessage:zCEventMessage 0 {index++}]
char[] zCEventMessage = $"[% oCMsgConversation:oCNpcMessage:zCEventMessage 0 {index++}]".ToCharArray();
binaryWriter.Write((Byte)1);
binaryWriter.Write((Int16)zCEventMessage.Length);
binaryWriter.Write(zCEventMessage);
address += 1 + 2 + zCEventMessage.Length;
// subType=enum:0
binaryWriter.Write((Byte)18);
binaryWriter.Write(4);
binaryWriter.Write((Byte)17);
binaryWriter.Write(0);
address += 1 + 4 + 1 + 4;
// text=string:{pair.Value}
binaryWriter.Write((Byte)18);
binaryWriter.Write(5);
binaryWriter.Write((Byte)1);
binaryWriter.Write((Int16)pair.Value.Length);
binaryWriter.Write(pair.Value.ToCharArray());
address += 1 + 4 + 1 + 2 + pair.Value.Length;
// name=string:{pair.Key.ToUpper()}.WAV
char[] wavFileName = $"{pair.Key.ToUpper()}.WAV".ToCharArray();
binaryWriter.Write((Byte)18);
binaryWriter.Write(6);
binaryWriter.Write((Byte)1);
binaryWriter.Write((Int16)wavFileName.Length);
binaryWriter.Write(wavFileName);
address += 1 + 4 + 1 + 2 + wavFileName.Length;
// []
binaryWriter.Write((Byte)1);
binaryWriter.Write((Int16)2);
binaryWriter.Write("[]".ToCharArray());
address += 1 + 2 + 2;
// []
binaryWriter.Write((Byte)1);
binaryWriter.Write((Int16)2);
binaryWriter.Write("[]".ToCharArray());
address += 1 + 2 + 2;
// []
binaryWriter.Write((Byte)1);
binaryWriter.Write((Int16)2);
binaryWriter.Write("[]".ToCharArray());
address += 1 + 2 + 2;
if (_verbose) Console.Write($"\r{(index - 1) / 3}/{count} bin elements written");
}
if (_verbose) Console.WriteLine("");
// []
binaryWriter.Write((Byte)1);
binaryWriter.Write((Int16)2);
binaryWriter.Write("[]".ToCharArray());
address += 1 + 2 + 2;
byte[] binFooter = new[]
{
0x07, 0x00, 0x00, 0x00,
0x04, 0x00,
0x05, 0x00,
0x0D, 0x00, 0x00, 0x00,
0x74, 0x65, 0x78, 0x74,
0x0B, 0x00,
0x02, 0x00,
0x27, 0x00, 0x00, 0x00,
0x6E, 0x75, 0x6D, 0x4F, 0x66, 0x42, 0x6C, 0x6F, 0x63, 0x6B, 0x73,
0x04, 0x00,
0x06, 0x00,
0x29, 0x00, 0x00, 0x00,
0x6E, 0x61, 0x6D, 0x65,
0x09, 0x00,
0x03, 0x00,
0x32, 0x00, 0x00, 0x00,
0x73, 0x75, 0x62, 0x42, 0x6C, 0x6F, 0x63, 0x6B, 0x30,
0x09, 0x00,
0x01, 0x00,
0x44, 0x00, 0x00, 0x00,
0x62, 0x6C, 0x6F, 0x63, 0x6B, 0x4E, 0x61, 0x6D, 0x65,
0x07, 0x00,
0x04, 0x00,
0x4A, 0x00, 0x00, 0x00,
0x73, 0x75, 0x62, 0x54, 0x79, 0x70, 0x65,
0x0A, 0x00,
0x00, 0x00,
0x5D, 0x00, 0x00, 0x00,
0x4E, 0x75, 0x6D, 0x4F, 0x66, 0x49, 0x74, 0x65, 0x6D, 0x73,
}.Select(x => (byte)x).ToArray();
binaryWriter.Write(binFooter);
// update addressOfLastSignificantByteAddress
binaryWriter.Seek(addressOfLastSignificantByteAddress, SeekOrigin.Begin);
binaryWriter.Write(address);
}
}
}
} | 43.877976 | 154 | 0.48423 | [
"MIT"
] | Kirides/DaedalusCompiler | src/DaedalusCompiler/Compilation/OutputUnitsBuilder.cs | 14,745 | C# |
/*
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one at
http://mozilla.org/MPL/2.0/.
*/
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FSO.Client.Rendering.City
{
public struct Blend
{
public int Binary;
public Vector2 AtlasPosition;
public int MaxEdge;
}
}
| 22.181818 | 84 | 0.709016 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | Blayer98/FreeSO | TSOClient/tso.client/Rendering/City/Blend.cs | 490 | C# |
using System;
using System.Reflection;
using Ash.UI;
#if DEBUG
namespace Ash
{
public class MethodInspector : Inspector
{
// the TextField for our parameter if we have one
TextField _textField;
Type _parameterType;
public static bool AreParametersValid(ParameterInfo[] parameters)
{
if (parameters.Length == 0)
return true;
if (parameters.Length > 1)
{
Debug.Warn(
$"method {parameters[0].Member.Name} has InspectorCallableAttribute but it has more than 1 parameter");
return false;
}
var paramType = parameters[0].ParameterType;
if (paramType == typeof(int) || paramType == typeof(float) || paramType == typeof(string) ||
paramType == typeof(bool))
return true;
Debug.Warn(
$"method {parameters[0].Member.Name} has InspectorCallableAttribute but it has an invalid paraemter type {paramType}");
return false;
}
public override void Initialize(Table table, Skin skin, float leftCellWidth)
{
var button = new TextButton(_name, skin);
button.OnClicked += OnButtonClicked;
// we could have zero or 1 param
var parameters = (_memberInfo as MethodInfo).GetParameters();
if (parameters.Length == 0)
{
table.Add(button);
return;
}
var parameter = parameters[0];
_parameterType = parameter.ParameterType;
_textField =
new TextField(
_parameterType.GetTypeInfo().IsValueType ? Activator.CreateInstance(_parameterType).ToString() : "",
skin);
_textField.ShouldIgnoreTextUpdatesWhileFocused = false;
// add a filter for float/int
if (_parameterType == typeof(float))
_textField.SetTextFieldFilter(new FloatFilter());
if (_parameterType == typeof(int))
_textField.SetTextFieldFilter(new DigitsOnlyFilter());
if (_parameterType == typeof(bool))
_textField.SetTextFieldFilter(new BoolFilter());
table.Add(button);
table.Add(_textField).SetMaxWidth(70);
}
public override void Update()
{
}
void OnButtonClicked(Button button)
{
if (_parameterType == null)
{
(_memberInfo as MethodInfo).Invoke(_target, new object[] { });
}
else
{
// extract the param and properly cast it
var parameters = new object[1];
try
{
if (_parameterType == typeof(float))
parameters[0] = float.Parse(_textField.GetText());
else if (_parameterType == typeof(int))
parameters[0] = int.Parse(_textField.GetText());
else if (_parameterType == typeof(bool))
parameters[0] = bool.Parse(_textField.GetText());
else
parameters[0] = _textField.GetText();
(_memberInfo as MethodInfo).Invoke(_target, parameters);
}
catch (Exception e)
{
Debug.Error(e.ToString());
}
}
}
}
}
#endif | 24.401786 | 123 | 0.673619 | [
"MIT"
] | JonSnowbd/Ash | Ash.DefaultEC/Debug/Inspector/Inspectors/MethodInspector.cs | 2,735 | 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 Microsoft.AspNetCore.Mvc.Rendering;
namespace Microsoft.AspNetCore.Identity.UI.V4.Pages.Account.Manage.Internal
{
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public static class ManageNavPages
{
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public static string Index => "Index";
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public static string Email => "Email";
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public static string ChangePassword => "ChangePassword";
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public static string DownloadPersonalData => "DownloadPersonalData";
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public static string DeletePersonalData => "DeletePersonalData";
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public static string ExternalLogins => "ExternalLogins";
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public static string PersonalData => "PersonalData";
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public static string TwoFactorAuthentication => "TwoFactorAuthentication";
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public static string IndexNavClass(ViewContext viewContext) => PageNavClass(viewContext, Index);
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public static string EmailNavClass(ViewContext viewContext) => PageNavClass(viewContext, Email);
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public static string ChangePasswordNavClass(ViewContext viewContext) => PageNavClass(viewContext, ChangePassword);
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public static string DownloadPersonalDataNavClass(ViewContext viewContext) => PageNavClass(viewContext, DownloadPersonalData);
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public static string DeletePersonalDataNavClass(ViewContext viewContext) => PageNavClass(viewContext, DeletePersonalData);
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public static string ExternalLoginsNavClass(ViewContext viewContext) => PageNavClass(viewContext, ExternalLogins);
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public static string PersonalDataNavClass(ViewContext viewContext) => PageNavClass(viewContext, PersonalData);
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public static string TwoFactorAuthenticationNavClass(ViewContext viewContext) => PageNavClass(viewContext, TwoFactorAuthentication);
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public static string PageNavClass(ViewContext viewContext, string page)
{
var activePage = viewContext.ViewData["ActivePage"] as string
?? System.IO.Path.GetFileNameWithoutExtension(viewContext.ActionDescriptor.DisplayName);
return string.Equals(activePage, page, StringComparison.OrdinalIgnoreCase) ? "active" : null;
}
}
}
| 55.829268 | 140 | 0.665793 | [
"Apache-2.0"
] | 06b/AspNetCore | src/Identity/UI/src/Areas/Identity/Pages/V4/Account/Manage/ManageNavPages.cs | 6,867 | C# |
using System;
using System.Threading.Tasks;
using Android.Content;
using Xamarin.Forms;
// Need application's MainActivity
using VideoPlayerDemos.Droid;
[assembly: Dependency(typeof(FormsVideoLibrary.Droid.VideoPicker))]
namespace FormsVideoLibrary.Droid
{
public class VideoPicker : IVideoPicker
{
public Task<string> GetVideoFileAsync()
{
// Define the Intent for getting images
Intent intent = new Intent();
intent.SetType("video/*");
intent.SetAction(Intent.ActionGetContent);
// Get the MainActivity instance
MainActivity activity = MainActivity.Current;
// Start the picture-picker activity (resumes in MainActivity.cs)
activity.StartActivityForResult(
Intent.CreateChooser(intent, "Select Video"),
MainActivity.PickImageId);
// Save the TaskCompletionSource object as a MainActivity property
activity.PickImageTaskCompletionSource = new TaskCompletionSource<string>();
// Return Task object
return activity.PickImageTaskCompletionSource.Task;
}
}
} | 31.756757 | 88 | 0.662979 | [
"Apache-2.0"
] | 15217711253/xamarin-forms-samples | CustomRenderers/VideoPlayerDemos/VideoPlayerDemos/VideoPlayerDemos.Android/FormsVideoLibrary/VideoPicker.cs | 1,177 | C# |
/************************************************************************************
Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.2
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
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 UnityEngine;
public class OVRWaitCursor : MonoBehaviour
{
public Vector3 rotateSpeeds = new Vector3(0.0f, 0.0f, -60.0f);
private Transform thisTransform = null;
/// <summary>
/// Initialization.
/// </summary>
void Awake()
{
thisTransform = transform;
}
/// <summary>
/// Auto rotates the attached cursor.
/// </summary>
void Update()
{
thisTransform.Rotate(rotateSpeeds * Time.smoothDeltaTime);
}
}
| 31.488889 | 87 | 0.637968 | [
"MIT"
] | AlexBoyd/OculusMobileVRJam2015 | Unity/speakVR/Assets/OVR/Moonlight/Scripts/Utils/OVRWaitCursor.cs | 1,419 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using YouGe.Core.Interface.IRepositorys.Sys;
using YouGe.Core.DBEntitys.Sys;
using YouGe.Core.Interface.IDbContexts;
using YouGe.Core.Models.DTModel.Sys;
using YouGe.Core.Common.YouGeException;
using YouGe.Core.Commons.Helper;
using YouGe.Core.Common.SystemConst;
using YouGe.Core.Models.System;
using YouGe.Core.Common.Helper;
using System.Threading.Tasks;
using YouGe.Core.DbContexts;
using MySql.Data.MySqlClient;
using System.Linq;
namespace YouGe.Core.Repositorys.Sys
{
public class SysMenuRepository : BaseRepository<SysMenu, int>, ISysMenuRepository
{
private YouGeDbContextOption option { get; set; }
public IYouGeDbContext _dataContext;
public SysMenuRepository(IYouGeDbContext dbContext) : base(dbContext)
{
_dataContext = dbContext;
option = (YouGeDbContextOption)DbContext.Option;
}
public List<string> selectMenuPermsByUserId(long userId)
{
StringBuilder sql = new StringBuilder();
sql.Append(@" select distinct m.perms
from sys_menu m
left join sys_role_menu rm on m.menu_id = rm.menu_id
left join sys_user_role ur on rm.role_id = ur.role_id
left join sys_role r on r.role_id = ur.role_id
where m.status = '0' and r.status = '0' and ur.user_id = @userId");
MySqlParameter[] parametera = new MySqlParameter[1]{
new MySqlParameter("userId", MySqlDbType.Int64)
};
parametera[0].Value = userId;
var models = _dataContext.GetDatabase().SqlQuery<SysMenuPerms>(sql.ToString(), parametera);
List<string> permsSet = new List<string>();
foreach (SysMenuPerms perm in models)
{
if (null != perm)
{
permsSet.AddRange(perm.perms.Trim().Split(",").ToList());
}
}
return permsSet;
}
public List<SysMenu> selectMenuTreeAll()
{
StringBuilder sql = new StringBuilder();
sql.Append(@" select distinct m.menu_id, m.parent_id, m.menu_name, m.path, m.component, m.visible, m.status, ifnull(m.perms, '') as perms, m.is_frame, m.menu_type, m.icon, m.order_num, m.create_time
from sys_menu m where m.menu_type in ('M', 'C') and m.status = 0 order by m.parent_id, m.order_num ");
return this.GetBySql(sql.ToString());
}
public List<SysMenu> selectMenuTreeByUserId(long userId)
{
StringBuilder sql = new StringBuilder();
sql.Append(@" select distinct m.menu_id, m.parent_id, m.menu_name, m.path, m.component, m.visible, m.status, ifnull(m.perms, '') as perms, m.is_frame, m.menu_type, m.icon, m.order_num, m.create_time
from sys_menu m
left join sys_role_menu rm on m.menu_id = rm.menu_id
left join sys_user_role ur on rm.role_id = ur.role_id
left join sys_role ro on ur.role_id = ro.role_id
left join sys_user u on ur.user_id = u.user_id
where u.user_id = @userId and m.menu_type in ('M', 'C') and m.status = 0 AND ro.status = 0
order by m.parent_id, m.order_num");
MySqlParameter[] parametera = new MySqlParameter[1]{
new MySqlParameter("userId", MySqlDbType.Int64)
};
parametera[0].Value = userId;
var models = _dataContext.GetDatabase().SqlQuery<SysMenu>(sql.ToString(), parametera);
return models;
}
}
}
| 38.892473 | 211 | 0.63008 | [
"MIT"
] | chenqiangdage/YouGe.Core | YouGe.Core.Repositorys/Sys/SysMenuRepository.cs | 3,619 | C# |
/*
* Copyright (c) 2021 ETH Zürich, Educational Development and Technology (LET)
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
namespace SafeExamBrowser.Applications.Contracts.Events
{
/// <summary>
/// Event handler used to indicate that a title has changed to a new value.
/// </summary>
public delegate void TitleChangedEventHandler(string title);
}
| 32.75 | 78 | 0.727099 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | Bien-Technologies/seb-win-refactoring | SafeExamBrowser.Applications.Contracts/Events/TitleChangedEventHandler.cs | 527 | C# |
namespace GoogleCloud.Functions.Subscriber.Tests.Logic
{
using System;
using System.IO;
using System.Threading.Tasks;
using GoogleCloud.Functions.Subscriber.Contracts;
using GoogleCloud.Functions.Subscriber.Logic;
using GoogleCloud.Functions.Subscriber.Model;
using Newtonsoft.Json;
using Xunit;
/// <summary>
/// Tests for <see cref="FunctionProvider" />
/// </summary>
public class FunctionProviderTests
{
/// <summary>
/// Throw <see cref="ArgumentNullException" /> if the input is null.
/// </summary>
[Fact]
public async void HandleAsync_Null_ArgumentNullException()
{
var provider = await InitAsync();
await Assert.ThrowsAsync<ArgumentNullException>(() => provider.HandleAsync(null));
}
/// <summary>
/// Initialize the provider and its dependencies.
/// </summary>
/// <returns>A <see cref="Task" /> whose result is an <see cref="IFunctionProvider" />.</returns>
private static async Task<IFunctionProvider> InitAsync()
{
var configuration =
JsonConvert.DeserializeObject<FunctionConfiguration>(await File.ReadAllTextAsync("appsettings.json"));
var provider = new FunctionProvider(configuration);
return provider;
}
}
}
| 35.625 | 119 | 0.608421 | [
"MIT"
] | MichaelDiers/Templates | .net/GoogleCloud.Functions.Subscriber/GoogleCloud.Functions.Subscriber.Tests/Logic/FunctionProviderTests.cs | 1,427 | C# |
using PiRhoSoft.Utilities;
using UnityEngine;
namespace PiRhoSoft.Variables
{
internal class QuaternionVariableHandler : VariableHandler
{
protected internal override string ToString(Variable variable)
{
return variable.AsQuaternion.ToString();
}
protected internal override void Save(Variable variable, SerializedDataWriter writer)
{
var quaternion = variable.AsQuaternion;
writer.Writer.Write(quaternion.x);
writer.Writer.Write(quaternion.y);
writer.Writer.Write(quaternion.z);
writer.Writer.Write(quaternion.w);
}
protected internal override Variable Load(SerializedDataReader reader)
{
var x = reader.Reader.ReadSingle();
var y = reader.Reader.ReadSingle();
var z = reader.Reader.ReadSingle();
var w = reader.Reader.ReadSingle();
return Variable.Quaternion(new Quaternion(x, y, z, w));
}
protected internal override Variable Multiply(Variable left, Variable right)
{
if (right.TryGetQuaternion(out var q))
return Variable.Quaternion(left.AsQuaternion * q);
else
return Variable.Empty;
}
protected internal override Variable Lookup(Variable owner, Variable lookup)
{
if (lookup.TryGetString(out var s))
{
var quaternion = owner.AsQuaternion;
switch (s)
{
case "x": return Variable.Float(quaternion.x);
case "y": return Variable.Float(quaternion.y);
case "z": return Variable.Float(quaternion.z);
case "w": return Variable.Float(quaternion.w);
}
}
return Variable.Empty;
}
protected internal override SetVariableResult Assign(ref Variable owner, Variable lookup, Variable value)
{
if (value.TryGetFloat(out var f))
{
if (lookup.TryGetString(out var s))
{
var quaternion = owner.AsQuaternion;
switch (s)
{
case "x":
{
owner = Variable.Quaternion(new Quaternion(f, quaternion.y, quaternion.z, quaternion.w));
return SetVariableResult.Success;
}
case "y":
{
owner = Variable.Quaternion(new Quaternion(quaternion.x, f, quaternion.z, quaternion.w));
return SetVariableResult.Success;
}
case "z":
{
owner = Variable.Quaternion(new Quaternion(quaternion.x, quaternion.y, f, quaternion.w));
return SetVariableResult.Success;
}
case "w":
{
owner = Variable.Quaternion(new Quaternion(quaternion.x, quaternion.y, quaternion.z, f));
return SetVariableResult.Success;
}
}
}
return SetVariableResult.NotFound;
}
else
{
return SetVariableResult.TypeMismatch;
}
}
protected internal override bool? IsEqual(Variable left, Variable right)
{
if (right.TryGetQuaternion(out var q))
return left.AsQuaternion == q;
else
return null;
}
protected internal override float Distance(Variable from, Variable to)
{
if (to.TryGetQuaternion(out var t))
return Quaternion.Angle(from.AsQuaternion, t);
else
return 0.0f;
}
protected internal override Variable Interpolate(Variable from, Variable to, float time)
{
if (to.TryGetQuaternion(out var t))
{
var value = Quaternion.Slerp(from.AsQuaternion, t, time);
return Variable.Quaternion(value);
}
else
{
return Variable.Empty;
}
}
}
}
| 25.161538 | 107 | 0.678386 | [
"MIT"
] | pirhosoft/PiRhoVariables | Assets/PiRhoVariables/Runtime/Handlers/QuaternionVariableHandler.cs | 3,273 | C# |
#if UNITY_EDITOR
using System.Collections;
using System.Collections.Generic;
using CombatDesigner;
using UnityEditor;
using UnityEngine;
namespace CombatDesigner.EditorTool
{
public class View_BehaviorInfo
{
int timeLineTab;
Vector2 actionScrollPos = new Vector2();
private int maxLength = 100;
float attackEndFrame;
public void Init()
{
if (BehaviorEditorWindow.win == null) return;
}
public void DrawBehaviorInfoToolBar()
{
// tool bar for the behavior action and attackinfos
timeLineTab = GUILayout.Toolbar(timeLineTab, new string[] { "BehaviorAction", "AttackInfo" });
switch (timeLineTab)
{
case 0:
BehaviorActionFrameDetail();
break;
case 1:
AttackInfoFrameDetail();
break;
}
}
/// <summary>
/// The BehaviorAction Frame Range List which will be shown under the timeline
/// </summary>
void BehaviorActionFrameDetail()
{
if (BehaviorEditorWindow.win.selectedBehavior == null || BehaviorEditorWindow.win.selectedBehavior.behaviorActions == null)
{
return;
}
actionScrollPos = GUILayout.BeginScrollView(actionScrollPos);
if (BehaviorEditorWindow.win.selectedBehavior.behaviorActions.Count > 0)
{
foreach (IBehaviorAction action in BehaviorEditorWindow.win.selectedBehavior.behaviorActions)
{
GUILayout.BeginVertical(GUI.skin.box);
GUILayout.BeginHorizontal();
GUILayout.Label(action.ToString().Replace("CombatDesigner.", ""));
GUILayout.FlexibleSpace();
GUILayout.Label("FrameRange");
action.startFrame = EditorGUILayout.IntField((int)action.startFrame, GUILayout.Width(30));
action.startFrame = Mathf.Max(action.startFrame, 0);
GUILayout.Label(" ~ ");
action.endFrame = EditorGUILayout.IntField((int)action.endFrame, GUILayout.Width(30));
action.endFrame = Mathf.Clamp(action.endFrame, 0, BehaviorEditorWindow.win.timeline.totalStateFrames);
GUILayout.EndHorizontal();
EditorGUILayout.MinMaxSlider(ref action.startFrame, ref action.endFrame, 0, BehaviorEditorWindow.win.timeline.totalStateFrames);
action.startFrame = Mathf.Floor(action.startFrame);
action.endFrame = Mathf.Floor(action.endFrame);
EditorGUILayout.EndVertical();
EditorGUILayout.Space();
}
}
GUILayout.EndScrollView();
}
void AttackInfoFrameDetail()
{
if (BehaviorEditorWindow.win.selectedBehavior == null || BehaviorEditorWindow.win.selectedBehavior.attackInfos == null)
{
return;
}
actionScrollPos = GUILayout.BeginScrollView(actionScrollPos);
int index = 0;
foreach (BehaviorAttack atkInfo in BehaviorEditorWindow.win.selectedBehavior.attackInfos)
{
GUILayout.BeginVertical(GUI.skin.box);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label("Atk Index " + (index++).ToString(), "Box");
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
maxLength = (int)Mathf.Max(atkInfo.frameInfo.startFrame, maxLength);
attackEndFrame = atkInfo.frameInfo.startFrame + atkInfo.frameInfo.length;
EditorGUILayout.MinMaxSlider(ref atkInfo.frameInfo.startFrame, ref attackEndFrame, 0, maxLength);
atkInfo.frameInfo.startFrame = Mathf.Floor(atkInfo.frameInfo.startFrame);
atkInfo.frameInfo.length = Mathf.Floor(attackEndFrame) - atkInfo.frameInfo.startFrame;
GUILayout.Label("Atk Start Frame: " + atkInfo.frameInfo.startFrame.ToString());
GUILayout.BeginHorizontal();
GUILayout.Label("Current Atk Length: " + atkInfo.frameInfo.length.ToString());
GUILayout.FlexibleSpace();
GUILayout.Label("Atk Max Length: ");
maxLength = EditorGUILayout.IntField(maxLength, GUILayout.Width(30));
GUILayout.EndHorizontal();
GUILayout.EndVertical();
EditorGUILayout.Space();
}
GUILayout.EndScrollView();
}
}
}
#endif | 42.123894 | 148 | 0.583824 | [
"MIT"
] | DreamerLin96/CombatDesigner | CombatDesigner/Assets/CombatDesigner/Core/Scripts/_EditorTools/BehaviorEditor/Editor/View_BehaviorInfo.cs | 4,762 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace ParserLib.Json.Serialization
{
public static class JsonSerializer
{
#region Nested Types
private sealed class ClassAttributes
{
public JsonSerializableAttribute SerializationAttributes { get; }
public bool IsAnonymous { get; }
public SerializationMode SerializationMode { get; }
public bool IsOptInOnly { get; }
public bool IsSerializable { get; }
public BindingFlags Binding { get; }
public ClassAttributes(JsonSerializableAttribute serializationAttributes, bool isAnonymous)
{
SerializationAttributes = serializationAttributes;
IsAnonymous = isAnonymous;
SerializationMode = IsAnonymous ? SerializationMode.All : (SerializationAttributes?.Mode ?? SerializationMode.All);
IsOptInOnly = !IsAnonymous && SerializationMode == SerializationMode.OptIn;
IsSerializable = IsAnonymous || SerializationAttributes != null;
if (IsSerializable)
{
Binding = SerializationMode == SerializationMode.Public ? BindingPublic : BindingAll;
}
}
}
private interface ISerializableMember
{
string Name { get; }
Type Type { get; }
object GetValue(object source);
void SetValue(object source, object value);
}
private abstract class SerializableMember<T> : ISerializableMember where T : MemberInfo
{
protected T BackingMemberInfo { get; set; }
public string Name { get; protected set; }
public abstract Type Type { get; }
protected SerializableMember(T backingMemberInfo)
: this(backingMemberInfo, GetMemberName(backingMemberInfo)) { }
protected SerializableMember(T backingMemberInfo, string name)
{
BackingMemberInfo = backingMemberInfo;
Name = name;
}
public abstract object GetValue(object source);
public abstract void SetValue(object source, object value);
}
private sealed class FieldMember : SerializableMember<FieldInfo>
{
public override Type Type { get => BackingMemberInfo.FieldType; }
public FieldMember(FieldInfo backingMemberInfo)
: base(backingMemberInfo) { }
public FieldMember(FieldInfo backingMemberInfo, string name)
: base(backingMemberInfo, name) { }
public override object GetValue(object source)
=> BackingMemberInfo.GetValue(source);
public override void SetValue(object source, object value)
=> BackingMemberInfo.SetValue(source, value);
}
private sealed class PropertyMember : SerializableMember<PropertyInfo>
{
public override Type Type { get => BackingMemberInfo.PropertyType; }
public PropertyMember(PropertyInfo backingMemberInfo)
: base(backingMemberInfo) { }
public PropertyMember(PropertyInfo backingMemberInfo, string name)
: base(backingMemberInfo, name) { }
public override object GetValue(object source)
=> BackingMemberInfo.GetValue(source);
public override void SetValue(object source, object value)
=> BackingMemberInfo.SetValue(source, value);
}
#endregion
#region Constants
private const BindingFlags BindingAll = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
private const BindingFlags BindingPublic = BindingFlags.Instance | BindingFlags.Public;
#endregion
#region Properties
private static IDictionary<Type, Func<object, JsonElement>> JsonCastLookup { get; }
#endregion
#region Constructors
static JsonSerializer()
{
JsonCastLookup = new Dictionary<Type, Func<object, JsonElement>> {
{ typeof(string), obj => (JsonString)(string)obj },
{ typeof(short), obj => (JsonNumber)(short)obj },
{ typeof(int), obj => (JsonNumber)(int)obj },
{ typeof(long), obj => (JsonNumber)(long)obj },
{ typeof(float), obj => (JsonNumber)(float)obj },
{ typeof(double), obj => (JsonNumber)(double)obj },
{ typeof(bool), obj => (JsonBool)(bool)obj }
};
}
#endregion
#region Public API
public static string Serialize(object source)
=> Serialize(source, false);
public static string Serialize(object source, bool prettyPrint)
=> Serialize(source, new JsonWriterOptions { PrettyPrint = prettyPrint });
public static string Serialize(object source, JsonWriterOptions options)
{
JsonElement root = null;
if (typeof(IList).IsInstanceOfType(source))
{
root = SerializeArray(source);
}
else
{
root = SerializeObject(source);
}
return JsonWriter.WriteToString(root, options);
}
public static T DeserializeFromString<T>(string rawJson)
=> (T)DeserializeFromString(typeof(T), rawJson);
public static object DeserializeFromString(Type targetType, string rawJson)
=> DeserializeFromJsonElement(targetType, JsonParser.ParseFromString(rawJson));
public static T DeserializeFromFile<T>(string filePath)
=> (T)DeserializeFromFile(typeof(T), filePath);
public static object DeserializeFromFile(Type targetType, string filePath)
=> DeserializeFromJsonElement(targetType, JsonParser.ParseFromFile(filePath));
public static T DeserializeFromJsonElement<T>(JsonElement json)
=> (T)DeserializeFromJsonElement(typeof(T), json);
[Obsolete("Deserialization is not yet production-ready and for now quite error prone.")]
public static object DeserializeFromJsonElement(Type target, JsonElement json)
=> Deserialize(target, json);
#endregion
#region Helper Functions - General
static string GetMemberName(MemberInfo member)
=> member.GetCustomAttribute<JsonPropertyAttribute>()?.Name ?? member.Name;
static bool IsAnonymous(Type objType)
=> objType.IsGenericType && objType.IsClass && objType.IsSealed
&& objType.Attributes.HasFlag(TypeAttributes.NotPublic) && objType.GetCustomAttribute<CompilerGeneratedAttribute>() != null;
static bool IsAutoProperty(PropertyInfo property)
=> property.CanRead && property.CanWrite && property.GetGetMethod(true).IsDefined(typeof(CompilerGeneratedAttribute), true);
#endregion
#region Helper Functions - Serialization
static bool IsSerializable(PropertyInfo property, ClassAttributes classAttributes)
{
bool result = false;
if (classAttributes.IsAnonymous)
{
result = true;
}
else if (classAttributes.IsOptInOnly)
{
result = property.IsDefined(typeof(JsonPropertyAttribute), true);
}
else
{
result = !property.IsDefined(typeof(CompilerGeneratedAttribute)) && property.CanRead;
}
return result;
}
static bool IsSerializable(FieldInfo field, ClassAttributes classAttributes)
{
bool result = false;
if (!classAttributes.IsAnonymous)
{
result = !field.IsDefined(typeof(CompilerGeneratedAttribute));
if (classAttributes.IsOptInOnly)
{
result = result && field.IsDefined(typeof(JsonPropertyAttribute), true);
}
}
return result;
}
static IEnumerable<ISerializableMember> GetSerializableMembers(Type objType)
{
var classAttributes = new ClassAttributes(objType.GetCustomAttribute<JsonSerializableAttribute>(), IsAnonymous(objType));
var members = new List<ISerializableMember>();
if (!classAttributes.IsSerializable)
{
return members;
}
foreach (PropertyInfo property in objType.GetProperties(classAttributes.Binding))
{
if (IsSerializable(property, classAttributes))
{
members.Add(new PropertyMember(property));
}
}
foreach (FieldInfo field in objType.GetFields(classAttributes.Binding))
{
if (IsSerializable(field, classAttributes))
{
members.Add(new FieldMember(field));
}
}
return members;
}
static JsonElement SerializeField(Type fieldType, object source)
{
JsonElement result = null;
if (source == null)
{
result = JsonNull.Value;
}
else if (fieldType.IsSubclassOf(typeof(JsonElement)))
{
result = (JsonElement)source;
}
else if (fieldType.IsEnum)
{
result = (JsonNumber)(int)source;
}
else if (JsonCastLookup.TryGetValue(fieldType, out Func<object, JsonElement> castToJson))
{
result = castToJson(source);
}
else if (typeof(IList).IsInstanceOfType(source))
{
result = SerializeArray(source);
}
else
{
result = SerializeObject(source);
}
return result;
}
static JsonObject SerializeObject(object source)
{
var jsonObject = new JsonObject();
foreach (ISerializableMember member in GetSerializableMembers(source.GetType()))
{
JsonElement json = SerializeField(member.Type, member.GetValue(source));
if (json != null && !(json is JsonObject obj && obj.Count == 0))
{
jsonObject.Add(member.Name, json);
}
}
return jsonObject;
}
static JsonArray SerializeArray(object source)
{
var jsonArray = new JsonArray();
foreach (object element in (IList)source)
{
JsonElement json = SerializeField(element?.GetType(), element);
if (json != null && !(json is JsonObject obj && obj.Count == 0))
{
jsonArray.Add(json);
}
}
return jsonArray;
}
#endregion
#region Helper Functions - Deserialization
static object Deserialize(Type target, JsonElement json)
{
return DeserializeField(target, json);
}
static object DeserializeField(Type target, JsonElement json)
{
object result;
// TODO Target type needs to be used better. And add provisioning for enums.
if (target.IsSubclassOf(typeof(JsonElement)))
{
result = json;
}
else
{
switch (json)
{
case JsonBool jsonBool:
result = jsonBool.Value;
break;
case JsonNumber jsonNumber:
result = target == typeof(double) ? jsonNumber.Value : Convert.ChangeType(jsonNumber.Value, target);
break;
case JsonString jsonString:
result = jsonString.Value;
break;
case JsonArray jsonArray:
result = DeserializeArray(target, jsonArray);
break;
case JsonObject jsonObject:
result = DeserializeObject(target, jsonObject);
break;
default:
result = null;
break;
}
}
return result;
}
static object DeserializeObject(Type target, JsonObject jsonObject)
{
// TODO Get all deserializable members. Not the same as serializable members since a serializable property might not have a setter and we need to rely on a constructor to set this state.
IEnumerable<ISerializableMember> deserializableMembers = new List<ISerializableMember>();
// TODO Figure out which constructor to use and add the values to the constructor parameters. Will later add a JsonConstructor attribute to indicate this.
IDictionary<string, object> constructorParameters = new Dictionary<string, object>();
object result = Activator.CreateInstance(target, constructorParameters.Values.ToArray());
foreach (ISerializableMember member in deserializableMembers)
{
if (!constructorParameters.ContainsKey(member.Name) && jsonObject.ContainsKey(member.Name))
{
member.SetValue(result, DeserializeField(member.Type, jsonObject[member.Name]));
}
}
return result;
}
static object DeserializeArray(Type target, JsonArray jsonArray)
{
// TODO Finish this implementation. There are a few curveballs with using reflection and figuring out what
// the actual type of the IList's elements are, further exasperated by conrecte implementations which might only be implementing IList.
return null;
}
#endregion
}
}
| 28.299505 | 189 | 0.718796 | [
"MIT"
] | ceNobiteElf/parserlib | ParserLib/Json/Serialization/JsonSerializer.cs | 11,435 | C# |
//
// SqlClientPermissionAttributeTest.cs -
// NUnit Test Cases for SqlClientPermissionAttribute
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using NUnit.Framework;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Security;
using System.Security.Permissions;
namespace MonoTests.System.Data.SqlClient {
[TestFixture]
public class SqlClientPermissionAttributeTest {
[Test]
public void Default ()
{
SqlClientPermissionAttribute a = new SqlClientPermissionAttribute (SecurityAction.Assert);
Assert.AreEqual (a.ToString (), a.TypeId.ToString (), "TypeId");
Assert.IsFalse (a.Unrestricted, "Unrestricted");
Assert.IsFalse (a.AllowBlankPassword, "AllowBlankPassword");
Assert.AreEqual (String.Empty, a.ConnectionString, "ConnectionString");
Assert.AreEqual (KeyRestrictionBehavior.AllowOnly, a.KeyRestrictionBehavior, "KeyRestrictionBehavior");
Assert.AreEqual (String.Empty, a.KeyRestrictions, "KeyRestrictions");
#if NET_2_0
Assert.IsFalse (a.ShouldSerializeConnectionString (), "ShouldSerializeConnectionString");
Assert.IsFalse (a.ShouldSerializeKeyRestrictions (), "ShouldSerializeConnectionString");
#endif
SqlClientPermission sp = (SqlClientPermission)a.CreatePermission ();
Assert.IsFalse (sp.IsUnrestricted (), "IsUnrestricted");
}
[Test]
public void Action ()
{
SqlClientPermissionAttribute a = new SqlClientPermissionAttribute (SecurityAction.Assert);
Assert.AreEqual (SecurityAction.Assert, a.Action, "Action=Assert");
a.Action = SecurityAction.Demand;
Assert.AreEqual (SecurityAction.Demand, a.Action, "Action=Demand");
a.Action = SecurityAction.Deny;
Assert.AreEqual (SecurityAction.Deny, a.Action, "Action=Deny");
a.Action = SecurityAction.InheritanceDemand;
Assert.AreEqual (SecurityAction.InheritanceDemand, a.Action, "Action=InheritanceDemand");
a.Action = SecurityAction.LinkDemand;
Assert.AreEqual (SecurityAction.LinkDemand, a.Action, "Action=LinkDemand");
a.Action = SecurityAction.PermitOnly;
Assert.AreEqual (SecurityAction.PermitOnly, a.Action, "Action=PermitOnly");
a.Action = SecurityAction.RequestMinimum;
Assert.AreEqual (SecurityAction.RequestMinimum, a.Action, "Action=RequestMinimum");
a.Action = SecurityAction.RequestOptional;
Assert.AreEqual (SecurityAction.RequestOptional, a.Action, "Action=RequestOptional");
a.Action = SecurityAction.RequestRefuse;
Assert.AreEqual (SecurityAction.RequestRefuse, a.Action, "Action=RequestRefuse");
}
[Test]
public void Action_Invalid ()
{
SqlClientPermissionAttribute a = new SqlClientPermissionAttribute ((SecurityAction)Int32.MinValue);
// no validation in attribute
}
[Test]
public void Unrestricted ()
{
SqlClientPermissionAttribute a = new SqlClientPermissionAttribute (SecurityAction.Assert);
a.Unrestricted = true;
SqlClientPermission scp = (SqlClientPermission)a.CreatePermission ();
Assert.IsTrue (scp.IsUnrestricted (), "IsUnrestricted");
Assert.IsFalse (a.AllowBlankPassword, "AllowBlankPassword");
Assert.AreEqual (String.Empty, a.ConnectionString, "ConnectionString");
Assert.AreEqual (KeyRestrictionBehavior.AllowOnly, a.KeyRestrictionBehavior, "KeyRestrictionBehavior");
Assert.AreEqual (String.Empty, a.KeyRestrictions, "KeyRestrictions");
a.Unrestricted = false;
scp = (SqlClientPermission)a.CreatePermission ();
Assert.IsFalse (scp.IsUnrestricted (), "!IsUnrestricted");
}
[Test]
public void AllowBlankPassword ()
{
SqlClientPermissionAttribute a = new SqlClientPermissionAttribute (SecurityAction.Assert);
Assert.IsFalse (a.AllowBlankPassword, "Default");
a.AllowBlankPassword = true;
Assert.IsTrue (a.AllowBlankPassword, "True");
a.AllowBlankPassword = false;
Assert.IsFalse (a.AllowBlankPassword, "False");
}
[Test]
public void ConnectionString ()
{
SqlClientPermissionAttribute a = new SqlClientPermissionAttribute (SecurityAction.Assert);
a.ConnectionString = String.Empty;
Assert.AreEqual (String.Empty, a.ConnectionString, "Empty");
a.ConnectionString = "Mono";
Assert.AreEqual ("Mono", a.ConnectionString, "Mono");
a.ConnectionString = null;
Assert.AreEqual (String.Empty, a.ConnectionString, "Empty(null)");
}
[Test]
public void KeyRestrictionBehavior_All ()
{
SqlClientPermissionAttribute a = new SqlClientPermissionAttribute (SecurityAction.Assert);
a.KeyRestrictionBehavior = KeyRestrictionBehavior.AllowOnly;
Assert.AreEqual (KeyRestrictionBehavior.AllowOnly, a.KeyRestrictionBehavior, "AllowOnly");
a.KeyRestrictionBehavior = KeyRestrictionBehavior.PreventUsage;
Assert.AreEqual (KeyRestrictionBehavior.PreventUsage, a.KeyRestrictionBehavior, "PreventUsage");
}
[Test]
#if NET_2_0
[ExpectedException (typeof (ArgumentOutOfRangeException))]
#else
[ExpectedException (typeof (ArgumentException))]
#endif
public void KeyRestrictionBehavior_Invalid ()
{
SqlClientPermissionAttribute a = new SqlClientPermissionAttribute (SecurityAction.Assert);
a.KeyRestrictionBehavior = (KeyRestrictionBehavior)Int32.MinValue;
}
[Test]
public void KeyRestriction ()
{
SqlClientPermissionAttribute a = new SqlClientPermissionAttribute (SecurityAction.Assert);
a.KeyRestrictions = String.Empty;
Assert.AreEqual (String.Empty, a.KeyRestrictions, "Empty");
a.KeyRestrictions = "Mono";
Assert.AreEqual ("Mono", a.KeyRestrictions, "Mono");
a.KeyRestrictions = null;
Assert.AreEqual (String.Empty, a.KeyRestrictions, "Empty(null)");
}
[Test]
public void Attributes ()
{
Type t = typeof (SqlClientPermissionAttribute);
Assert.IsTrue (t.IsSerializable, "IsSerializable");
object [] attrs = t.GetCustomAttributes (typeof (AttributeUsageAttribute), false);
Assert.AreEqual (1, attrs.Length, "AttributeUsage");
AttributeUsageAttribute aua = (AttributeUsageAttribute)attrs [0];
Assert.IsTrue (aua.AllowMultiple, "AllowMultiple");
Assert.IsFalse (aua.Inherited, "Inherited");
AttributeTargets at = AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method;
Assert.AreEqual (at, aua.ValidOn, "ValidOn");
}
}
}
| 41.938889 | 160 | 0.743277 | [
"Apache-2.0"
] | CRivlaldo/mono | mcs/class/System.Data/Test/System.Data.SqlClient/SqlClientPermissionAttributeTest.cs | 7,549 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.22000.0\um\mfplay.h(1212,9)
using System;
using System.Runtime.InteropServices;
namespace DirectN
{
[StructLayout(LayoutKind.Sequential)]
public partial struct MFP_ACQUIRE_USER_CREDENTIAL_EVENT
{
public MFP_EVENT_HEADER header;
public IntPtr dwUserData;
public bool fProceedWithAuthentication;
public HRESULT hrAuthenticationStatus;
[MarshalAs(UnmanagedType.LPWStr)]
public string pwszURL;
[MarshalAs(UnmanagedType.LPWStr)]
public string pwszSite;
[MarshalAs(UnmanagedType.LPWStr)]
public string pwszRealm;
[MarshalAs(UnmanagedType.LPWStr)]
public string pwszPackage;
public int nRetries;
public uint flags;
public IntPtr pCredential;
}
}
| 31.925926 | 84 | 0.665893 | [
"MIT"
] | Steph55/DirectN | DirectN/DirectN/Generated/MFP_ACQUIRE_USER_CREDENTIAL_EVENT.cs | 864 | C# |
namespace GildedRose.Policies
{
public interface IPolicy
{
void UpdateQuality();
}
} | 14.857143 | 29 | 0.634615 | [
"MIT"
] | scmallorca/gilded-rose-dojo | jrogalan_csharp/src/GildedRose/Policies/IPolicy.cs | 104 | C# |
// <copyright file="SendFunction.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.Apps.CompanyCommunicator.Send.Func
{
using System;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Schema;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Teams.Apps.CompanyCommunicator.Common.Extensions;
using Microsoft.Teams.Apps.CompanyCommunicator.Common.Repositories.NotificationData;
using Microsoft.Teams.Apps.CompanyCommunicator.Common.Repositories.SentNotificationData;
using Microsoft.Teams.Apps.CompanyCommunicator.Common.Resources;
using Microsoft.Teams.Apps.CompanyCommunicator.Common.Services.MessageQueues.SendQueue;
using Microsoft.Teams.Apps.CompanyCommunicator.Common.Services.Teams;
using Microsoft.Teams.Apps.CompanyCommunicator.Send.Func.Services;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
/// <summary>
/// Azure Function App triggered by messages from a Service Bus queue
/// Used for sending messages from the bot.
/// </summary>
public class SendFunction
{
/// <summary>
/// This is set to 10 because the default maximum delivery count from the service bus
/// message queue before the service bus will automatically put the message in the Dead Letter
/// Queue is 10.
/// </summary>
private static readonly int MaxDeliveryCountForDeadLetter = 10;
private static readonly string AdaptiveCardContentType = "application/vnd.microsoft.card.adaptive";
private readonly int maxNumberOfAttempts;
private readonly double sendRetryDelayNumberOfSeconds;
private readonly INotificationService notificationService;
private readonly ISendingNotificationDataRepository notificationRepo;
private readonly IMessageService messageService;
private readonly ISendQueue sendQueue;
private readonly IStringLocalizer<Strings> localizer;
/// <summary>
/// Initializes a new instance of the <see cref="SendFunction"/> class.
/// </summary>
/// <param name="options">Send function options.</param>
/// <param name="notificationService">The service to precheck and determine if the queue message should be processed.</param>
/// <param name="messageService">Message service.</param>
/// <param name="notificationRepo">Notification repository.</param>
/// <param name="sendQueue">The send queue.</param>
/// <param name="localizer">Localization service.</param>
public SendFunction(
IOptions<SendFunctionOptions> options,
INotificationService notificationService,
IMessageService messageService,
ISendingNotificationDataRepository notificationRepo,
ISendQueue sendQueue,
IStringLocalizer<Strings> localizer)
{
if (options is null)
{
throw new ArgumentNullException(nameof(options));
}
this.maxNumberOfAttempts = options.Value.MaxNumberOfAttempts;
this.sendRetryDelayNumberOfSeconds = options.Value.SendRetryDelayNumberOfSeconds;
this.notificationService = notificationService ?? throw new ArgumentNullException(nameof(notificationService));
this.messageService = messageService ?? throw new ArgumentNullException(nameof(messageService));
this.notificationRepo = notificationRepo ?? throw new ArgumentNullException(nameof(notificationRepo));
this.sendQueue = sendQueue ?? throw new ArgumentNullException(nameof(sendQueue));
this.localizer = localizer ?? throw new ArgumentNullException(nameof(localizer));
}
/// <summary>
/// Azure Function App triggered by messages from a Service Bus queue
/// Used for sending messages from the bot.
/// </summary>
/// <param name="myQueueItem">The Service Bus queue item.</param>
/// <param name="deliveryCount">The deliver count.</param>
/// <param name="enqueuedTimeUtc">The enqueued time.</param>
/// <param name="messageId">The message ID.</param>
/// <param name="log">The logger.</param>
/// <param name="context">The execution context.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
[FunctionName("SendMessageFunction")]
public async Task Run(
[ServiceBusTrigger(
SendQueue.QueueName,
Connection = SendQueue.ServiceBusConnectionConfigurationKey)]
string myQueueItem,
int deliveryCount,
DateTime enqueuedTimeUtc,
string messageId,
ILogger log,
ExecutionContext context)
{
log.LogInformation($"C# ServiceBus queue trigger function processed message: {myQueueItem}");
var messageContent = JsonConvert.DeserializeObject<SendQueueMessageContent>(myQueueItem);
try
{
// Check if notification is pending.
var isPending = await this.notificationService.IsPendingNotification(messageContent);
if (!isPending)
{
// Notification is either already sent or failed and shouldn't be retried.
return;
}
// Check if conversationId is set to send message.
if (string.IsNullOrWhiteSpace(messageContent.GetConversationId()))
{
await this.notificationService.UpdateSentNotification(
notificationId: messageContent.NotificationId,
recipientId: messageContent.RecipientData.RecipientId,
totalNumberOfSendThrottles: 0,
statusCode: SentNotificationDataEntity.FinalFaultedStatusCode,
allSendStatusCodes: $"{SentNotificationDataEntity.FinalFaultedStatusCode},",
errorMessage: this.localizer.GetString("AppNotInstalled"));
return;
}
// Check if the system is throttled.
var isThrottled = await this.notificationService.IsSendNotificationThrottled();
if (isThrottled)
{
// Re-Queue with delay.
await this.sendQueue.SendDelayedAsync(messageContent, this.sendRetryDelayNumberOfSeconds);
return;
}
// Send message.
var messageActivity = await this.GetMessageActivity(messageContent);
var response = await this.messageService.SendMessageAsync(
message: messageActivity,
serviceUrl: messageContent.GetServiceUrl(),
conversationId: messageContent.GetConversationId(),
maxAttempts: this.maxNumberOfAttempts,
logger: log);
// Process response.
await this.ProcessResponseAsync(messageContent, response, log);
}
catch (InvalidOperationException exception)
{
// Bad message shouldn't be requeued.
log.LogError(exception, $"InvalidOperationException thrown. Error message: {exception.Message}");
}
catch (Exception e)
{
var errorMessage = $"{e.GetType()}: {e.Message}";
log.LogError(e, $"Failed to send message. ErrorMessage: {errorMessage}");
// Update status code depending on delivery count.
var statusCode = SentNotificationDataEntity.FaultedAndRetryingStatusCode;
if (deliveryCount >= SendFunction.MaxDeliveryCountForDeadLetter)
{
// Max deliveries attempted. No further retries.
statusCode = SentNotificationDataEntity.FinalFaultedStatusCode;
}
// Update sent notification table.
await this.notificationService.UpdateSentNotification(
notificationId: messageContent.NotificationId,
recipientId: messageContent.RecipientData.RecipientId,
totalNumberOfSendThrottles: 0,
statusCode: statusCode,
allSendStatusCodes: $"{statusCode},",
errorMessage: errorMessage);
throw;
}
}
/// <summary>
/// Process send notification response.
/// </summary>
/// <param name="messageContent">Message content.</param>
/// <param name="sendMessageResponse">Send notification response.</param>
/// <param name="log">Logger.</param>
private async Task ProcessResponseAsync(
SendQueueMessageContent messageContent,
SendMessageResponse sendMessageResponse,
ILogger log)
{
if (sendMessageResponse.ResultType == SendMessageResult.Succeeded)
{
log.LogInformation($"Successfully sent the message." +
$"\nRecipient Id: {messageContent.RecipientData.RecipientId}");
}
else
{
log.LogError($"Failed to send message." +
$"\nRecipient Id: {messageContent.RecipientData.RecipientId}" +
$"\nResult: {sendMessageResponse.ResultType}." +
$"\nErrorMessage: {sendMessageResponse.ErrorMessage}.");
}
await this.notificationService.UpdateSentNotification(
notificationId: messageContent.NotificationId,
recipientId: messageContent.RecipientData.RecipientId,
totalNumberOfSendThrottles: sendMessageResponse.TotalNumberOfSendThrottles,
statusCode: sendMessageResponse.StatusCode,
allSendStatusCodes: sendMessageResponse.AllSendStatusCodes,
errorMessage: sendMessageResponse.ErrorMessage);
// Throttled
if (sendMessageResponse.ResultType == SendMessageResult.Throttled)
{
// Set send function throttled.
await this.notificationService.SetSendNotificationThrottled(this.sendRetryDelayNumberOfSeconds);
// Requeue.
await this.sendQueue.SendDelayedAsync(messageContent, this.sendRetryDelayNumberOfSeconds);
return;
}
}
private async Task<IMessageActivity> GetMessageActivity(SendQueueMessageContent message)
{
var notification = await this.notificationRepo.GetAsync(
NotificationDataTableNames.SendingNotificationsPartition,
message.NotificationId);
dynamic counterJson = JObject.Parse(notification.Content);
counterJson.actions[0].Replace(
JObject.FromObject(
new
{
type = counterJson.actions[0].type,
url = counterJson.actions[0].url + "¬ificationid=" + message.NotificationId + "&recipientid=" + message.RecipientData.RecipientId,
title = counterJson.actions[0].title,
}));
var adaptiveCardAttachment = new Attachment()
{
ContentType = AdaptiveCardContentType,
Content = counterJson,
};
return MessageFactory.Attachment(adaptiveCardAttachment);
}
}
}
| 47.621514 | 169 | 0.616247 | [
"MIT"
] | ccampora/microsoft-teams-apps-company-communicator | Source/Microsoft.Teams.Apps.CompanyCommunicator.Send.Func/SendFunction.cs | 11,953 | C# |
using JetBrains.Annotations;
using JetBrains.ReSharper.Feature.Services.CodeStructure;
using JetBrains.ReSharper.Feature.Services.CSharp.CodeStructure;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.Util;
namespace GammaJul.ForTea.Core.Services.CodeStructure {
internal sealed class T4CSharpCodeStructureRegionEnd : CodeStructurePreprocessorElement, ICodeStructureBlockEnd {
[CanBeNull] private readonly CSharpCodeStructureRegion _parentRegion;
public override ICodeStructureBlockStart ParentBlock
=> _parentRegion;
public T4CSharpCodeStructureRegionEnd(
[NotNull] CodeStructureElement parentElement,
[NotNull] ITreeNode preprocessorDirective,
[NotNull] CSharpCodeStructureProcessingState state
)
: base(parentElement, preprocessorDirective) {
_parentRegion = state.Regions.TryPeek();
}
}
} | 30.888889 | 114 | 0.821343 | [
"Apache-2.0"
] | JetBrains/ForTea | Backend/Core/ForTea.Core/Services/CodeStructure/T4CSharpCodeStructureRegionEnd.cs | 834 | C# |
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PTSchool.Services.Contracts;
using PTSchool.Web.Models.Subject;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace PTSchool.Web.Controllers
{
[Authorize(Roles = "Admin, Teacher, Parent, Student")]
public class SubjectsController : Controller
{
private readonly ISubjectService subjectService;
private readonly IMapper mapper;
public SubjectsController(ISubjectService subjectService, IMapper mapper)
{
this.subjectService = subjectService;
this.mapper = mapper;
}
public async Task<IActionResult> AllSubjects(int page = 1)
{
var subjects = await this.subjectService.GetAllSubjectsLightByPageAsync(page);
var model = new CollectionSubjectsFullViewModels
{
Subjects = this.mapper.Map<IEnumerable<SubjectLightViewModel>>(subjects),
Url = "/Subjects/AllSubjects",
PageSize = subjectService.GetPageSize(),
TotalCount = subjectService.GetTotalCount(),
CurrentPage = page
};
return this.View(model);
}
public async Task<IActionResult> Subject(Guid id)
{
var subject = await this.subjectService.GetSubjectFullByIdAsync(id);
var model = this.mapper.Map<SubjectFullViewModel>(subject);
return this.View(model);
}
}
}
| 31.1 | 90 | 0.648875 | [
"MIT"
] | petartotev/PT_WebApp_PTSchool | Solution/Web/PTSchool.Web/Controllers/SubjectsController.cs | 1,557 | C# |
using Machine.Specifications;
using PlainElastic.Net.IndexSettings;
using PlainElastic.Net.Utils;
namespace PlainElastic.Net.Tests.Builders.IndexSettings
{
[Subject(typeof(IndexSettingsBuilder))]
public class When_IndexSettingsBuilder_builder_has_shards_and_a_replica
{
private static string result;
Because of = () =>
result = new IndexSettingsBuilder()
.NumberOfReplicas(3)
.NumberOfShards(2)
.Build();
It should_contain_the_number_of_replicas = () =>
result.ShouldContain("'number_of_replicas': 3,'number_of_shards': 2".AltQuote());
}
} | 32.428571 | 93 | 0.643172 | [
"MIT"
] | AAATechGuy/PlainElastic.Net | src/PlainElastic.Net.Tests/Builders/IndexSettings/When_IndexSettingsBuilder_builder_has_shards_and_a_replica.cs | 683 | C# |
using Perpetuum.Groups.Gangs;
using Perpetuum.Services.Sessions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Perpetuum.Zones
{
public class StrongHoldZone : Zone
{
public StrongHoldZone(ISessionManager sessionManager, IGangManager gangManager) : base(sessionManager, gangManager)
{
}
}
}
| 22.666667 | 123 | 0.742647 | [
"MIT"
] | LoyalServant/PerpetuumServerCore | Perpetuum/Zones/StrongHoldZone.cs | 410 | 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.Kusto.V20190907
{
/// <summary>
/// Class representing an Event Grid data connection.
/// </summary>
[AzureNativeResourceType("azure-native:kusto/v20190907:EventGridDataConnection")]
public partial class EventGridDataConnection : Pulumi.CustomResource
{
/// <summary>
/// The event hub consumer group.
/// </summary>
[Output("consumerGroup")]
public Output<string> ConsumerGroup { get; private set; } = null!;
/// <summary>
/// The data format of the message. Optionally the data format can be added to each message.
/// </summary>
[Output("dataFormat")]
public Output<string> DataFormat { get; private set; } = null!;
/// <summary>
/// The resource ID where the event grid is configured to send events.
/// </summary>
[Output("eventHubResourceId")]
public Output<string> EventHubResourceId { get; private set; } = null!;
/// <summary>
/// Kind of the endpoint for the data connection
/// Expected value is 'EventGrid'.
/// </summary>
[Output("kind")]
public Output<string> Kind { get; private set; } = null!;
/// <summary>
/// Resource location.
/// </summary>
[Output("location")]
public Output<string?> Location { get; private set; } = null!;
/// <summary>
/// The mapping rule to be used to ingest the data. Optionally the mapping information can be added to each message.
/// </summary>
[Output("mappingRuleName")]
public Output<string?> MappingRuleName { get; private set; } = null!;
/// <summary>
/// The name of the resource
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// The resource ID of the storage account where the data resides.
/// </summary>
[Output("storageAccountResourceId")]
public Output<string> StorageAccountResourceId { get; private set; } = null!;
/// <summary>
/// The table where the data should be ingested. Optionally the table information can be added to each message.
/// </summary>
[Output("tableName")]
public Output<string> TableName { get; private set; } = null!;
/// <summary>
/// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts"
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a EventGridDataConnection resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public EventGridDataConnection(string name, EventGridDataConnectionArgs args, CustomResourceOptions? options = null)
: base("azure-native:kusto/v20190907:EventGridDataConnection", name, MakeArgs(args), MakeResourceOptions(options, ""))
{
}
private EventGridDataConnection(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:kusto/v20190907:EventGridDataConnection", name, null, MakeResourceOptions(options, id))
{
}
private static EventGridDataConnectionArgs MakeArgs(EventGridDataConnectionArgs args)
{
args ??= new EventGridDataConnectionArgs();
args.Kind = "EventGrid";
return args;
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:kusto/v20190907:EventGridDataConnection"},
new Pulumi.Alias { Type = "azure-native:kusto:EventGridDataConnection"},
new Pulumi.Alias { Type = "azure-nextgen:kusto:EventGridDataConnection"},
new Pulumi.Alias { Type = "azure-native:kusto/v20190121:EventGridDataConnection"},
new Pulumi.Alias { Type = "azure-nextgen:kusto/v20190121:EventGridDataConnection"},
new Pulumi.Alias { Type = "azure-native:kusto/v20190515:EventGridDataConnection"},
new Pulumi.Alias { Type = "azure-nextgen:kusto/v20190515:EventGridDataConnection"},
new Pulumi.Alias { Type = "azure-native:kusto/v20191109:EventGridDataConnection"},
new Pulumi.Alias { Type = "azure-nextgen:kusto/v20191109:EventGridDataConnection"},
new Pulumi.Alias { Type = "azure-native:kusto/v20200215:EventGridDataConnection"},
new Pulumi.Alias { Type = "azure-nextgen:kusto/v20200215:EventGridDataConnection"},
new Pulumi.Alias { Type = "azure-native:kusto/v20200614:EventGridDataConnection"},
new Pulumi.Alias { Type = "azure-nextgen:kusto/v20200614:EventGridDataConnection"},
new Pulumi.Alias { Type = "azure-native:kusto/v20200918:EventGridDataConnection"},
new Pulumi.Alias { Type = "azure-nextgen:kusto/v20200918:EventGridDataConnection"},
new Pulumi.Alias { Type = "azure-native:kusto/v20210101:EventGridDataConnection"},
new Pulumi.Alias { Type = "azure-nextgen:kusto/v20210101:EventGridDataConnection"},
new Pulumi.Alias { Type = "azure-native:kusto/v20210827:EventGridDataConnection"},
new Pulumi.Alias { Type = "azure-nextgen:kusto/v20210827:EventGridDataConnection"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing EventGridDataConnection resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static EventGridDataConnection Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new EventGridDataConnection(name, id, options);
}
}
public sealed class EventGridDataConnectionArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The name of the Kusto cluster.
/// </summary>
[Input("clusterName", required: true)]
public Input<string> ClusterName { get; set; } = null!;
/// <summary>
/// The event hub consumer group.
/// </summary>
[Input("consumerGroup", required: true)]
public Input<string> ConsumerGroup { get; set; } = null!;
/// <summary>
/// The name of the data connection.
/// </summary>
[Input("dataConnectionName")]
public Input<string>? DataConnectionName { get; set; }
/// <summary>
/// The data format of the message. Optionally the data format can be added to each message.
/// </summary>
[Input("dataFormat", required: true)]
public InputUnion<string, Pulumi.AzureNative.Kusto.V20190907.DataFormat> DataFormat { get; set; } = null!;
/// <summary>
/// The name of the database in the Kusto cluster.
/// </summary>
[Input("databaseName", required: true)]
public Input<string> DatabaseName { get; set; } = null!;
/// <summary>
/// The resource ID where the event grid is configured to send events.
/// </summary>
[Input("eventHubResourceId", required: true)]
public Input<string> EventHubResourceId { get; set; } = null!;
/// <summary>
/// Kind of the endpoint for the data connection
/// Expected value is 'EventGrid'.
/// </summary>
[Input("kind", required: true)]
public Input<string> Kind { get; set; } = null!;
/// <summary>
/// Resource location.
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
/// <summary>
/// The mapping rule to be used to ingest the data. Optionally the mapping information can be added to each message.
/// </summary>
[Input("mappingRuleName")]
public Input<string>? MappingRuleName { get; set; }
/// <summary>
/// The name of the resource group containing the Kusto cluster.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
/// <summary>
/// The resource ID of the storage account where the data resides.
/// </summary>
[Input("storageAccountResourceId", required: true)]
public Input<string> StorageAccountResourceId { get; set; } = null!;
/// <summary>
/// The table where the data should be ingested. Optionally the table information can be added to each message.
/// </summary>
[Input("tableName", required: true)]
public Input<string> TableName { get; set; } = null!;
public EventGridDataConnectionArgs()
{
}
}
}
| 44.675325 | 130 | 0.607267 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Kusto/V20190907/EventGridDataConnection.cs | 10,320 | C# |
using MediatR;
using MyBankManager.Api.Requests.Transaction;
using MyBankManager.Api.Responses;
using MyBankManager.Domain.Interfaces;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace MyBankManager.Api.Handlers.Query
{
public class TransactionRequestHandler : IRequestHandler<TransactionRequest, Response>
{
private readonly ITransactionRepository _TransactionRepository;
public TransactionRequestHandler(ITransactionRepository TransactionRepository) => _TransactionRepository = TransactionRepository;
public async Task<Response> Handle(TransactionRequest request, CancellationToken cancellationToken)
{
if (request.Id == Guid.Empty)
return new Response(await _TransactionRepository.Get());
return new Response(await _TransactionRepository.GetById(request.Id));
}
}
}
| 37.166667 | 137 | 0.76009 | [
"MIT"
] | erick-adl/my-bank-manager | src/MyBankManager.Api/Handlers/Query/TransactionRequestHandler.cs | 894 | 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.DataFactory.Outputs
{
/// <summary>
/// The TarGZip compression read settings.
/// </summary>
[OutputType]
public sealed class TarGZipReadSettingsResponse
{
/// <summary>
/// Preserve the compression file name as folder path. Type: boolean (or Expression with resultType boolean).
/// </summary>
public readonly object? PreserveCompressionFileNameAsFolder;
/// <summary>
/// The Compression setting type.
/// Expected value is 'TarGZipReadSettings'.
/// </summary>
public readonly string Type;
[OutputConstructor]
private TarGZipReadSettingsResponse(
object? preserveCompressionFileNameAsFolder,
string type)
{
PreserveCompressionFileNameAsFolder = preserveCompressionFileNameAsFolder;
Type = type;
}
}
}
| 30.4 | 117 | 0.659539 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/DataFactory/Outputs/TarGZipReadSettingsResponse.cs | 1,216 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.Cdn.Models
{
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Describes resource usage.
/// </summary>
public partial class Usage
{
/// <summary>
/// Initializes a new instance of the Usage class.
/// </summary>
public Usage()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the Usage class.
/// </summary>
/// <param name="currentValue">The current value of the usage.</param>
/// <param name="limit">The limit of usage.</param>
/// <param name="name">The name of the type of usage.</param>
/// <param name="id">Resource identifier.</param>
public Usage(long currentValue, long limit, UsageName name, string id = default(string))
{
Id = id;
CurrentValue = currentValue;
Limit = limit;
Name = name;
CustomInit();
}
/// <summary>
/// Static constructor for Usage class.
/// </summary>
static Usage()
{
Unit = "Count";
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets resource identifier.
/// </summary>
[JsonProperty(PropertyName = "id")]
public string Id { get; private set; }
/// <summary>
/// Gets or sets the current value of the usage.
/// </summary>
[JsonProperty(PropertyName = "currentValue")]
public long CurrentValue { get; set; }
/// <summary>
/// Gets or sets the limit of usage.
/// </summary>
[JsonProperty(PropertyName = "limit")]
public long Limit { get; set; }
/// <summary>
/// Gets or sets the name of the type of usage.
/// </summary>
[JsonProperty(PropertyName = "name")]
public UsageName Name { get; set; }
/// <summary>
/// An enum describing the unit of measurement.
/// </summary>
[JsonProperty(PropertyName = "unit")]
public static string Unit { get; private set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Name");
}
}
}
}
| 29.932039 | 96 | 0.54687 | [
"MIT"
] | 93mishra/azure-sdk-for-net | sdk/cdn/Microsoft.Azure.Management.Cdn/src/Generated/Models/Usage.cs | 3,083 | C# |
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Ordering.Application.Features.Orders.Commands.CheckoutOrder;
using Ordering.Application.Features.Orders.Commands.DeleteCommand;
using Ordering.Application.Features.Orders.Commands.UpdateOrder;
using Ordering.Application.Features.Orders.Queries.GetOrdersList;
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
namespace Ordering.API.Controllers;
[Route("api/v1/[controller]")]
[ApiController]
public class OrderController : ControllerBase
{
private readonly IMediator _mediator;
public OrderController(IMediator mediator)
{
_mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
}
[HttpGet("{userName}", Name = "GetOrder")]
[ProducesResponseType(typeof(IEnumerable<OrdersVm>), (int)HttpStatusCode.OK)]
public async Task<ActionResult<IEnumerable<OrdersVm>>> GetOrdersByUserName(string userName)
{
var query = new GetOrdersListQuery(userName);
var orders = await _mediator.Send(query);
return Ok(orders);
}
// testing purpose
[HttpPost(Name = "CheckoutOrder")]
[ProducesResponseType(typeof(int), StatusCodes.Status200OK)]
public async Task<ActionResult<int>> CheckoutOrder([FromBody] CheckoutOrderCommand command)
{
var result = await _mediator.Send(command);
return Ok(result);
}
[HttpPut(Name = "UpdateOrder")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesDefaultResponseType]
public async Task<ActionResult> UpdateOrder([FromBody] UpdateOrderCommand command)
{
await _mediator.Send(command);
return NoContent();
}
[HttpDelete("{id}", Name = "DeleteOrder")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesDefaultResponseType]
public async Task<ActionResult> DeleteOrder(int id)
{
var command = new DeleteOrderCommand() { Id = id };
await _mediator.Send(command);
return NoContent();
}
} | 34.265625 | 95 | 0.733698 | [
"MIT"
] | sanjyotagureddy/aspnetrun-Microservices | src/Services/Ordering/Ordering.API/Controllers/OrderController.cs | 2,195 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Common.Authentication.Utilities;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Microsoft.Azure.Commands.Common.Authentication.Models
{
public partial class AzureAccount
{
public AzureAccount()
{
Properties = new Dictionary<Property,string>();
}
public string GetProperty(Property property)
{
return Properties.GetProperty(property);
}
public string[] GetPropertyAsArray(Property property)
{
return Properties.GetPropertyAsArray(property);
}
public void SetProperty(Property property, params string[] values)
{
Properties.SetProperty(property, values);
}
public void SetOrAppendProperty(Property property, params string[] values)
{
Properties.SetOrAppendProperty(property, values);
}
public bool IsPropertySet(Property property)
{
return Properties.IsPropertySet(property);
}
public List<AzureSubscription> GetSubscriptions(AzureSMProfile profile)
{
string subscriptions = string.Empty;
List<AzureSubscription> subscriptionsList = new List<AzureSubscription>();
if (Properties.ContainsKey(Property.Subscriptions))
{
subscriptions = Properties[Property.Subscriptions];
}
foreach (var subscription in subscriptions.Split(new [] {','}, StringSplitOptions.RemoveEmptyEntries))
{
try
{
Guid subscriptionId = new Guid(subscription);
Debug.Assert(profile.Subscriptions.ContainsKey(subscriptionId));
subscriptionsList.Add(profile.Subscriptions[subscriptionId]);
}
catch
{
// Skip
}
}
return subscriptionsList;
}
public bool HasSubscription(Guid subscriptionId)
{
bool exists = false;
string subscriptions = GetProperty(Property.Subscriptions);
if (!string.IsNullOrEmpty(subscriptions))
{
exists = subscriptions.Contains(subscriptionId.ToString());
}
return exists;
}
public void SetSubscriptions(List<AzureSubscription> subscriptions)
{
if (subscriptions == null || subscriptions.Count == 0)
{
if (Properties.ContainsKey(Property.Subscriptions))
{
Properties.Remove(Property.Subscriptions);
}
}
else
{
string value = string.Join(",", subscriptions.Select(s => s.Id.ToString()));
Properties[Property.Subscriptions] = value;
}
}
public void RemoveSubscription(Guid id)
{
if (HasSubscription(id))
{
var remainingSubscriptions = GetPropertyAsArray(Property.Subscriptions).Where(s => s != id.ToString()).ToArray();
if (remainingSubscriptions.Any())
{
Properties[Property.Subscriptions] = string.Join(",", remainingSubscriptions);
}
else
{
Properties.Remove(Property.Subscriptions);
}
}
}
public override bool Equals(object obj)
{
var anotherAccount = obj as AzureAccount;
if (anotherAccount == null)
{
return false;
}
else
{
return string.Equals(anotherAccount.Id, Id, StringComparison.InvariantCultureIgnoreCase);
}
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
}
}
| 33.746575 | 130 | 0.534808 | [
"MIT"
] | Peter-Schneider/azure-powershell | src/Common/Commands.Common.Authentication/Models/AzureAccount.Methods.cs | 4,784 | C# |
using UnityEngine;
public class GeneralBasic : MonoBehaviour {
public GameObject prefabAvatar;
void Start() {
// Setup
var avatarRotate = GameObject.Find("AvatarRotate");
var avatarScale = GameObject.Find("AvatarScale");
var avatarMove = GameObject.Find("AvatarMove");
// Rotate Example
LeanTween.rotateAround(avatarRotate, Vector3.forward, 360f, 5f);
// Scale Example
LeanTween.scale(avatarScale, new Vector3(1.7f, 1.7f, 1.7f), 5f).setEase(LeanTweenType.easeOutBounce);
LeanTween.moveX(avatarScale, avatarScale.transform.position.x + 5f, 5f).setEase(LeanTweenType.easeOutBounce); // Simultaneously target many different tweens on the same object
// Move Example
LeanTween.move(avatarMove, avatarMove.transform.position + new Vector3(-9f, 0f, 1f), 2f).setEase(LeanTweenType.easeInQuad);
// Delay
LeanTween.move(avatarMove, avatarMove.transform.position + new Vector3(-6f, 0f, 1f), 2f).setDelay(3f);
// Chain properties (delay, easing with a set repeating of type ping pong)
LeanTween.scale(avatarScale, new Vector3(0.2f, 0.2f, 0.2f), 1f).setDelay(7f).setEase(LeanTweenType.easeInOutCirc).setLoopPingPong(3);
// Call methods after a certain time period
LeanTween.delayedCall(gameObject, 0.2f, advancedExamples);
}
// Advanced Examples
// It might be best to master the basics first, but this is included to tease the many possibilies LeanTween provides.
void advancedExamples() {
LeanTween.delayedCall(gameObject, 14f, () => {
for (int i = 0; i < 10; i++) {
// Instantiate Container
var rotator = new GameObject("rotator" + i);
rotator.transform.position = new Vector3(10.2f, 2.85f, 0f);
// Instantiate Avatar
var dude = GameObject.Instantiate(prefabAvatar, Vector3.zero, prefabAvatar.transform.rotation);
dude.transform.parent = rotator.transform;
dude.transform.localPosition = new Vector3(0f, 1.5f, 2.5f * i);
// Scale, pop-in
dude.transform.localScale = new Vector3(0f, 0f, 0f);
LeanTween.scale(dude, new Vector3(0.65f, 0.65f, 0.65f), 1f).setDelay(i * 0.2f).setEase(LeanTweenType.easeOutBack);
// Color like the rainbow
float period = LeanTween.tau / 10 * i;
float red = Mathf.Sin(period + LeanTween.tau * 0f / 3f) * 0.5f + 0.5f;
float green = Mathf.Sin(period + LeanTween.tau * 1f / 3f) * 0.5f + 0.5f;
float blue = Mathf.Sin(period + LeanTween.tau * 2f / 3f) * 0.5f + 0.5f;
var rainbowColor = new Color(red, green, blue);
LeanTween.color(dude, rainbowColor, 0.3f).setDelay(1.2f + i * 0.4f);
// Push into the wheel
LeanTween.moveZ(dude, 0f, 0.3f).setDelay(1.2f + i * 0.4f).setEase(LeanTweenType.easeSpring).setOnComplete(
() => {
LeanTween.rotateAround(rotator, Vector3.forward, -1080f, 12f);
}
);
// Jump Up and back down
LeanTween.moveLocalY(dude, 4f, 1.2f).setDelay(5f + i * 0.2f).setLoopPingPong(1).setEase(LeanTweenType.easeInOutQuad);
// Alpha Out, and destroy
LeanTween.alpha(dude, 0f, 0.6f).setDelay(9.2f + i * 0.4f).setDestroyOnComplete(true).setOnComplete(
() => {
Destroy(rotator); // destroying parent as well
}
);
}
}).setOnCompleteOnStart(true).setRepeat(-1); // Have the OnComplete play in the beginning and have the whole group repeat endlessly
}
}
| 46.585366 | 184 | 0.597382 | [
"CC0-1.0"
] | Faulo/AGGamesEngineering | Assets/Plugins/LeanTween/Examples/Scripts/GeneralBasic.cs | 3,820 | C# |
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Expressions;
using WalkingTec.Mvvm.Core.Extensions;
namespace WalkingTec.Mvvm.Core
{
public class ExcelPropety
{
#region 属性
private string _columnName;
/// <summary>
/// 列名
/// </summary>
public string ColumnName
{
get
{
string col = _columnName;
return col;
}
set
{
_columnName = value;
}
}
public string FieldName { get; set; }
//private string _backgroudColor;
///// <summary>
///// 背景色
///// </summary>
//public string BackgroudColor
//{
// get { return _backgroudColor; }
// set { _backgroudColor = value; }
//}
/// <summary>
/// 背景色
/// </summary>
public BackgroudColorEnum BackgroudColor { get; set; }
private Type _resourceType;
/// <summary>
/// 多语言
/// </summary>
public Type ResourceType
{
get { return _resourceType; }
set { _resourceType = value; }
}
private ColumnDataType _dataType;
/// <summary>
/// 数据类型
/// </summary>
public ColumnDataType DataType
{
get { return _dataType; }
set { _dataType = value; }
}
private Type _enumType;
public Type EnumType
{
get { return _enumType; }
set
{
_enumType = value;
this.ListItems = _enumType.ToListItems();
}
}
private string _minValueOrLength;
/// <summary>
/// 最小长度
/// </summary>
public string MinValueOrLength
{
get { return _minValueOrLength; }
set { _minValueOrLength = value; }
}
private string _maxValuseOrLength;
/// <summary>
/// 最大长度
/// </summary>
public string MaxValuseOrLength
{
get { return _maxValuseOrLength; }
set { _maxValuseOrLength = value; }
}
private bool _isNullAble;
/// <summary>
/// 是否可以为空
/// </summary>
public bool IsNullAble
{
get { return _isNullAble; }
set { _isNullAble = value; }
}
private IEnumerable<ComboSelectListItem> _listItems;
/// <summary>
/// 类表中数据
/// </summary>
public IEnumerable<ComboSelectListItem> ListItems
{
get { return _listItems; }
set { _listItems = value; }
}
private object _value;
/// <summary>
/// Value
/// </summary>
public object Value
{
get { return _value; }
set { _value = value; }
}
private List<ExcelPropety> _dynamicColumns;
/// <summary>
/// 动态列
/// </summary>
public List<ExcelPropety> DynamicColumns
{
get { return _dynamicColumns == null ? new List<ExcelPropety>() : _dynamicColumns; }
set { _dynamicColumns = value; }
}
public Type SubTableType { get; set; }
public bool ReadOnly { get; set; }
/// <summary>
/// 字符数量
/// </summary>
public int CharCount { get; set; }
#endregion
#region 设定Excel数据验证
/// <summary>
/// 设置Excel单元格样式(标题),数据格式
/// </summary>
/// <param name="dateType">数据类型</param>
/// <param name="porpetyIndex">单元格索引</param>
/// <param name="sheet">Sheet页</param>
/// <param name="dataSheet">数据Sheet页</param>
/// <param name="dataStyle">样式</param>
/// <param name="dataFormat">格式</param>
public void SetColumnFormat(ColumnDataType dateType, int porpetyIndex, HSSFSheet sheet, HSSFSheet dataSheet, ICellStyle dataStyle, IDataFormat dataFormat)
{
HSSFDataValidation dataValidation = null;
switch (dateType)
{
case ColumnDataType.Date:
this.MinValueOrLength = DateTime.Parse("1950/01/01").ToString("yyyy/MM/dd");
this.MaxValuseOrLength = string.IsNullOrEmpty(this.MaxValuseOrLength) ? DateTime.MaxValue.ToString("yyyy/MM/dd") : this.MaxValuseOrLength;
dataValidation = new HSSFDataValidation(new CellRangeAddressList(1, 65535, porpetyIndex, porpetyIndex),
DVConstraint.CreateDateConstraint(OperatorType.BETWEEN, this.MinValueOrLength, this.MaxValuseOrLength, "yyyy/MM/dd"));
dataValidation.CreateErrorBox("错误", "请输入日期");
dataValidation.CreatePromptBox("请输入日期格式 yyyy/mm/dd", "在" + MinValueOrLength + " 到 " + MaxValuseOrLength + "之间");
//dataStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("yyyy/MM/dd");
dataStyle.DataFormat = dataFormat.GetFormat("yyyy/mm/dd");
break;
case ColumnDataType.DateTime:
this.MinValueOrLength = DateTime.Parse("1950/01/01").ToString("yyyy/MM/dd HH:mm:ss");
this.MaxValuseOrLength = string.IsNullOrEmpty(this.MaxValuseOrLength) ? DateTime.MaxValue.ToString("yyyy/MM/dd HH:mm:ss") : this.MaxValuseOrLength;
dataValidation = new HSSFDataValidation(new CellRangeAddressList(1, 65535, porpetyIndex, porpetyIndex),
DVConstraint.CreateDateConstraint(OperatorType.BETWEEN, this.MinValueOrLength, this.MaxValuseOrLength, "yyyy/MM/dd HH:mm:ss"));
dataValidation.CreateErrorBox("错误", "请输入日期");
dataValidation.CreatePromptBox("请输入日期格式 yyyy/mm/dd HH:mm:ss", "在" + MinValueOrLength + " 到 " + MaxValuseOrLength + "之间");
//dataStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("yyyy/MM/dd");
dataStyle.DataFormat = dataFormat.GetFormat("yyyy/mm/dd HH:mm:ss");
break;
case ColumnDataType.Number:
this.MinValueOrLength = string.IsNullOrEmpty(this.MinValueOrLength) ? long.MinValue.ToString() : this.MinValueOrLength;
this.MaxValuseOrLength = string.IsNullOrEmpty(this.MaxValuseOrLength) ? long.MaxValue.ToString() : this.MaxValuseOrLength;
dataValidation = new HSSFDataValidation(new CellRangeAddressList(1, 65535, porpetyIndex, porpetyIndex),
DVConstraint.CreateNumericConstraint(ValidationType.INTEGER, OperatorType.BETWEEN, this.MinValueOrLength, this.MaxValuseOrLength));
dataValidation.CreateErrorBox("错误", "请输入数字");
dataStyle.DataFormat = dataFormat.GetFormat("0");
dataValidation.CreatePromptBox("请输入数字格式", "在" + MinValueOrLength + " 到 " + MaxValuseOrLength + "之间");
break;
case ColumnDataType.Float:
this.MinValueOrLength = string.IsNullOrEmpty(this.MinValueOrLength) ? decimal.MinValue.ToString() : this.MinValueOrLength;
this.MaxValuseOrLength = string.IsNullOrEmpty(this.MaxValuseOrLength) ? decimal.MaxValue.ToString() : this.MaxValuseOrLength;
dataValidation = new HSSFDataValidation(new CellRangeAddressList(1, 65535, porpetyIndex, porpetyIndex),
DVConstraint.CreateNumericConstraint(ValidationType.DECIMAL, OperatorType.BETWEEN, this.MinValueOrLength, this.MaxValuseOrLength));
dataValidation.CreateErrorBox("错误", "请输入小数");
dataStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00");
dataValidation.CreatePromptBox("请输入小数", "在" + MinValueOrLength + " 到 " + MaxValuseOrLength + "之间");
break;
case ColumnDataType.Bool:
dataValidation = new HSSFDataValidation(new CellRangeAddressList(1, 65535, porpetyIndex, porpetyIndex),
DVConstraint.CreateFormulaListConstraint("Sheet1!$A$1:$B$1"));
dataValidation.CreateErrorBox("错误", "请输入下拉菜单中存在的数据");
sheet.AddValidationData(dataValidation);
dataValidation.CreatePromptBox("下拉菜单", "请输入下拉菜单中存在的数据");
break;
case ColumnDataType.Text:
this.MinValueOrLength = string.IsNullOrEmpty(this.MinValueOrLength) ? "0" : this.MinValueOrLength;
this.MaxValuseOrLength = string.IsNullOrEmpty(this.MaxValuseOrLength) ? "2000" : this.MaxValuseOrLength;
dataValidation = new HSSFDataValidation(new CellRangeAddressList(1, 65535, porpetyIndex, porpetyIndex),
DVConstraint.CreateNumericConstraint(ValidationType.TEXT_LENGTH, OperatorType.BETWEEN, MinValueOrLength, MaxValuseOrLength));
dataValidation.CreateErrorBox("错误", "文本长度不符合要求");
dataStyle.DataFormat = dataFormat.GetFormat("@");
dataValidation.CreatePromptBox("请输入文本", "在" + MinValueOrLength + " 到 " + MaxValuseOrLength + "之间");
break;
case ColumnDataType.ComboBox:
case ColumnDataType.Enum:
int count = this.ListItems.Count() == 0 ? 1 : this.ListItems.Count();
string cloIndex = "";
if(porpetyIndex > 25)
{
cloIndex += Convert.ToChar((int)(Math.Floor(porpetyIndex / 26d)) -1 + 65);
}
cloIndex += Convert.ToChar(65 + porpetyIndex % 26).ToString();
//定义名称
IName range = sheet.Workbook.CreateName();
range.RefersToFormula = "Sheet2!$" + cloIndex + "$1:$" + cloIndex + "$" + count;
range.NameName = "dicRange" + porpetyIndex;
//dataValidation = new HSSFDataValidation(new CellRangeAddressList(1, 65535, porpetyIndex, porpetyIndex),
// DVConstraint.CreateFormulaListConstraint("Sheet2!$" + cloIndex + "$1:$" + cloIndex + "$" + count));
dataValidation = new HSSFDataValidation(new CellRangeAddressList(1, 65535, porpetyIndex, porpetyIndex),
DVConstraint.CreateFormulaListConstraint("dicRange" + porpetyIndex));
dataValidation.CreateErrorBox("错误", "请输入下拉菜单中存在的数据");
var listItemsTemp = this.ListItems.ToList();
for (int rowIndex = 0; rowIndex < this.ListItems.Count(); rowIndex++)
{
//HSSFRow dataSheetRow = (HSSFRow)dataSheet.CreateRow(rowIndex);
HSSFRow dataSheetRow = (HSSFRow)dataSheet.GetRow(rowIndex);
if (dataSheetRow == null)
{
dataSheetRow = (HSSFRow)dataSheet.CreateRow(rowIndex);
}
//dataSheetRow.CreateCell(porpetyIndex).SetCellValue(this.ListItems.ToList()[rowIndex].Text);
dataSheetRow.CreateCell(porpetyIndex).SetCellValue(listItemsTemp[rowIndex].Text);
dataStyle.DataFormat = dataFormat.GetFormat("@");
dataSheetRow.Cells.Where(x => x.ColumnIndex == porpetyIndex).FirstOrDefault().CellStyle = dataStyle;
}
sheet.AddValidationData(dataValidation);
dataValidation.CreatePromptBox("下拉菜单", "请输入下拉菜单中存在的数据");
break;
default:
dataValidation = new HSSFDataValidation(new CellRangeAddressList(1, 65535, porpetyIndex, porpetyIndex),
DVConstraint.CreateNumericConstraint(ValidationType.TEXT_LENGTH, OperatorType.BETWEEN, this.MinValueOrLength, this.MaxValuseOrLength));
dataValidation.CreateErrorBox("错误", "文本长度不符合要求");
dataStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
break;
}
if (!this.IsNullAble)
{
dataValidation.EmptyCellAllowed = false;
}
sheet.SetDefaultColumnStyle(porpetyIndex, dataStyle);
sheet.AddValidationData(dataValidation);
}
#endregion
#region 验证Excel数据
/// <summary>
/// 验证Value 并生成错误信息(edit by dufei 2014-06-12,修改了当列设置为不验证时候,下拉列表获取不到值的问题)
/// </summary>
/// <param name="value"></param>
/// <param name="errorMessage"></param>
/// <param name="rowIndex"></param>
public void ValueValidity(string value, List<ErrorMessage> errorMessage, int rowIndex)
{
if (this.IsNullAble && string.IsNullOrEmpty(value))
{
this.Value = value;
}
else
{
ErrorMessage err = null;
switch (this.DataType)
{
case ColumnDataType.Date:
case ColumnDataType.DateTime:
DateTime tryDateTimeResult;
if (!DateTime.TryParse(value, out tryDateTimeResult))
{
err = new ErrorMessage { Index = rowIndex, Message = string.Format("列:{0},日期格式错误", this.ColumnName) };
//errorMessage.Add(new ErrorMessage { ColumnName = this.ColumnName, Index = rowIndex, Message = "日期格式错误" });
}
this.Value = tryDateTimeResult;
break;
case ColumnDataType.Number:
int tryIntResult;
if (!int.TryParse(value, out tryIntResult))
{
err = new ErrorMessage { Index = rowIndex, Message = string.Format("列:{0},数字格式错误", this.ColumnName) };
//errorMessage.Add(new ErrorMessage { ColumnName = this.ColumnName, Index = rowIndex, Message = "日期格式错误" });
}
this.Value = tryIntResult;
break;
case ColumnDataType.Float:
decimal tryDecimalResult;
if (!decimal.TryParse(value, out tryDecimalResult))
{
err = new ErrorMessage { Index = rowIndex, Message = string.Format("列:{0},小数格式错误", this.ColumnName) };
//errorMessage.Add(new ErrorMessage { ColumnName = this.ColumnName, Index = rowIndex, Message = "日期格式错误" });
}
this.Value = tryDecimalResult;
break;
case ColumnDataType.Bool:
if (value == "是")
{
this.Value = true;
}
else if (value == "否")
{
this.Value = false;
}
else
{
err = new ErrorMessage { Index = rowIndex, Message = string.Format("列:{0},应该输入【是】或者【否】", this.ColumnName) };
}
break;
case ColumnDataType.Text:
this.Value = value;
break;
case ColumnDataType.ComboBox:
case ColumnDataType.Enum:
if (!this.ListItems.Any(x => x.Text == value))
{
err = new ErrorMessage { Index = rowIndex, Message = string.Format("列:{0},输入的值在数据库中不存在", this.ColumnName) };
}
else
{
this.Value = this.ListItems.Where(x => x.Text == value).FirstOrDefault().Value;
}
break;
default:
err = new ErrorMessage { Index = rowIndex, Message = string.Format("列:{0},输入的值不在允许的数据类型范围内", this.ColumnName) };
break;
}
if(err != null && this.SubTableType == null)
{
errorMessage.Add(err);
}
}
}
#endregion
#region 自定义委托处理excel数据
/// <summary>
/// 处理为多列数据
/// </summary>
public CopyData FormatData;
/// <summary>
/// 处理为单列数据
/// </summary>
public CopySingleData FormatSingleData;
#endregion
public static ExcelPropety CreateProperty<T>(Expression<Func<T, object>> field, bool isDateTime = false)
{
ExcelPropety cp = new ExcelPropety();
cp.ColumnName = field.GetPropertyDisplayName();
var fname = field.GetPropertyName();
Type t = field.GetPropertyInfo().PropertyType;
if (fname.Contains('.'))
{
int index = fname.LastIndexOf('.');
cp.FieldName = fname.Substring(index + 1);
cp.SubTableType = field.GetPropertyInfo().DeclaringType;
}
else
{
cp.FieldName = fname;
}
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
{
var req = field.GetPropertyInfo().GetCustomAttributes(typeof(RequiredAttribute), false).Cast<RequiredAttribute>().FirstOrDefault();
if (req == null)
{
cp.IsNullAble = true;
}
t = t.GenericTypeArguments[0];
}
if(t == typeof(int) || t == typeof(long) || t == typeof(short))
{
var sl = t.GetCustomAttributes(typeof(RangeAttribute), false).Cast<RangeAttribute>().FirstOrDefault();
cp.DataType = ColumnDataType.Number;
if(sl != null)
{
if (sl.Maximum != null)
{
cp.MaxValuseOrLength = sl.Maximum.ToString();
}
if(sl.Minimum != null)
{
cp.MinValueOrLength = sl.Minimum.ToString();
}
}
}
else if( t== typeof(float) || t == typeof(double) || t == typeof(decimal))
{
cp.DataType = ColumnDataType.Float;
}
else if( t == typeof(bool))
{
cp.DataType = ColumnDataType.Bool;
}
else if (t.IsEnum)
{
cp.DataType = ColumnDataType.Enum;
cp.EnumType = t;
}
else if(t == typeof(DateTime))
{
cp.DataType = ColumnDataType.Date;
if (isDateTime)
cp.DataType = ColumnDataType.DateTime;
}
else
{
var sl = field.GetPropertyInfo().GetCustomAttributes(typeof(StringLengthAttribute),false).Cast<StringLengthAttribute>().FirstOrDefault();
var req = field.GetPropertyInfo().GetCustomAttributes(typeof(RequiredAttribute), false).Cast<RequiredAttribute>().FirstOrDefault();
cp.DataType = ColumnDataType.Text;
if(req == null)
{
cp.IsNullAble = true;
}
if (sl != null)
{
if (sl.MaximumLength != 0)
{
cp.MaxValuseOrLength = sl.MaximumLength + "";
}
if (sl.MinimumLength != 0)
{
cp.MinValueOrLength = sl.MinimumLength + "";
}
}
}
cp.CharCount = 20;
return cp;
}
}
#region 辅助类型
/// <summary>
/// 定义处理excel为单个字段的委托
/// </summary>
/// <param name="excelValue">excel中的值</param>
/// <param name="excelTemplate">excel中的值</param>
/// <param name="entityValue">实体的值</param>
/// <param name="errorMsg">错误消息,没有错误为空</param>
public delegate void CopySingleData(object excelValue, BaseTemplateVM excelTemplate, out string entityValue, out string errorMsg);
/// <summary>
/// 定义处理excel为多个字段的委托
/// </summary>
/// <param name="excelValue">excel中的值</param>
/// <param name="excelTemplate">excel中的值</param>
/// <returns>返回的处理结果</returns>
public delegate ProcessResult CopyData(object excelValue, BaseTemplateVM excelTemplate);
/// <summary>
/// 处理结果
/// </summary>
public class ProcessResult
{
public List<EntityValue> EntityValues { get; set; }
public ProcessResult()
{
EntityValues = new List<EntityValue>();
}
}
/// <summary>
/// 单字段类
/// </summary>
public class EntityValue
{
/// <summary>
/// 字段名称
/// </summary>
public string FieldName { get; set; }
/// <summary>
/// 字段值
/// </summary>
public string FieldValue { get; set; }
/// <summary>
/// 错误消息
/// </summary>
public string ErrorMsg { get; set; }
}
public enum ColumnDataType { Text, Number, Date, Float, Bool, ComboBox, Enum, Dynamic, DateTime }
#endregion
}
| 42.829746 | 167 | 0.519099 | [
"MIT"
] | 18363098520/WTM | src/WalkingTec.Mvvm.Core/Support/ExcelPropety.cs | 22,842 | 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.Network.V20200701.Inputs
{
/// <summary>
/// Frontend IP address of the load balancer.
/// </summary>
public sealed class FrontendIPConfigurationArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Resource ID.
/// </summary>
[Input("id")]
public Input<string>? Id { get; set; }
/// <summary>
/// The name of the resource that is unique within the set of frontend IP configurations used by the load balancer. This name can be used to access the resource.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// The private IP address of the IP configuration.
/// </summary>
[Input("privateIPAddress")]
public Input<string>? PrivateIPAddress { get; set; }
/// <summary>
/// Whether the specific ipconfiguration is IPv4 or IPv6. Default is taken as IPv4.
/// </summary>
[Input("privateIPAddressVersion")]
public InputUnion<string, Pulumi.AzureNative.Network.V20200701.IPVersion>? PrivateIPAddressVersion { get; set; }
/// <summary>
/// The Private IP allocation method.
/// </summary>
[Input("privateIPAllocationMethod")]
public InputUnion<string, Pulumi.AzureNative.Network.V20200701.IPAllocationMethod>? PrivateIPAllocationMethod { get; set; }
/// <summary>
/// The reference to the Public IP resource.
/// </summary>
[Input("publicIPAddress")]
public Input<Inputs.PublicIPAddressArgs>? PublicIPAddress { get; set; }
/// <summary>
/// The reference to the Public IP Prefix resource.
/// </summary>
[Input("publicIPPrefix")]
public Input<Inputs.SubResourceArgs>? PublicIPPrefix { get; set; }
/// <summary>
/// The reference to the subnet resource.
/// </summary>
[Input("subnet")]
public Input<Inputs.SubnetArgs>? Subnet { get; set; }
[Input("zones")]
private InputList<string>? _zones;
/// <summary>
/// A list of availability zones denoting the IP allocated for the resource needs to come from.
/// </summary>
public InputList<string> Zones
{
get => _zones ?? (_zones = new InputList<string>());
set => _zones = value;
}
public FrontendIPConfigurationArgs()
{
}
}
}
| 33.614458 | 169 | 0.602509 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Network/V20200701/Inputs/FrontendIPConfigurationArgs.cs | 2,790 | C# |
using System.ComponentModel.DataAnnotations;
namespace SFA.DAS.Validation.NetCoreSample.ViewModels.Accounts
{
public class CreateAccountViewModel
{
[Required(ErrorMessage = "The 'Username' field is required")]
public string Username { get; set; }
}
} | 27.9 | 69 | 0.72043 | [
"MIT"
] | SkillsFundingAgency/das-shared-packages | SFA.DAS.Validation/SFA.DAS.Validation.NetCoreSample/ViewModels/Accounts/CreateAccountViewModel.cs | 279 | C# |
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Xml.Serialization;
namespace Workday.RevenueManagement
{
[GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")]
[Serializable]
public class Award_Year_DataType : INotifyPropertyChanged
{
private string award_Period_Reference_IDField;
private string award_Period_NameField;
private decimal award_Period_NumberField;
private Award_Period_DataType[] award_Interval_DataField;
private bool is_Award_Contract_Start_DateField;
private bool is_Award_Contract_Start_DateFieldSpecified;
private bool is_Award_Contract_End_DateField;
private bool is_Award_Contract_End_DateFieldSpecified;
[method: CompilerGenerated]
[CompilerGenerated]
public event PropertyChangedEventHandler PropertyChanged;
[XmlElement(Order = 0)]
public string Award_Period_Reference_ID
{
get
{
return this.award_Period_Reference_IDField;
}
set
{
this.award_Period_Reference_IDField = value;
this.RaisePropertyChanged("Award_Period_Reference_ID");
}
}
[XmlElement(Order = 1)]
public string Award_Period_Name
{
get
{
return this.award_Period_NameField;
}
set
{
this.award_Period_NameField = value;
this.RaisePropertyChanged("Award_Period_Name");
}
}
[XmlElement(Order = 2)]
public decimal Award_Period_Number
{
get
{
return this.award_Period_NumberField;
}
set
{
this.award_Period_NumberField = value;
this.RaisePropertyChanged("Award_Period_Number");
}
}
[XmlElement("Award_Interval_Data", Order = 3)]
public Award_Period_DataType[] Award_Interval_Data
{
get
{
return this.award_Interval_DataField;
}
set
{
this.award_Interval_DataField = value;
this.RaisePropertyChanged("Award_Interval_Data");
}
}
[XmlElement(Order = 4)]
public bool Is_Award_Contract_Start_Date
{
get
{
return this.is_Award_Contract_Start_DateField;
}
set
{
this.is_Award_Contract_Start_DateField = value;
this.RaisePropertyChanged("Is_Award_Contract_Start_Date");
}
}
[XmlIgnore]
public bool Is_Award_Contract_Start_DateSpecified
{
get
{
return this.is_Award_Contract_Start_DateFieldSpecified;
}
set
{
this.is_Award_Contract_Start_DateFieldSpecified = value;
this.RaisePropertyChanged("Is_Award_Contract_Start_DateSpecified");
}
}
[XmlElement(Order = 5)]
public bool Is_Award_Contract_End_Date
{
get
{
return this.is_Award_Contract_End_DateField;
}
set
{
this.is_Award_Contract_End_DateField = value;
this.RaisePropertyChanged("Is_Award_Contract_End_Date");
}
}
[XmlIgnore]
public bool Is_Award_Contract_End_DateSpecified
{
get
{
return this.is_Award_Contract_End_DateFieldSpecified;
}
set
{
this.is_Award_Contract_End_DateFieldSpecified = value;
this.RaisePropertyChanged("Is_Award_Contract_End_DateSpecified");
}
}
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
| 21.711538 | 136 | 0.743431 | [
"MIT"
] | matteofabbri/Workday.WebServices | Workday.RevenueManagement/Award_Year_DataType.cs | 3,387 | 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.GoogleNative.Eventarc.V1Beta1.Inputs
{
/// <summary>
/// Represents a Cloud Run service destination.
/// </summary>
public sealed class CloudRunServiceArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Optional. The relative path on the Cloud Run service the events should be sent to. The value must conform to the definition of URI path segment (section 3.3 of RFC2396). Examples: "/route", "route", "route/subroute".
/// </summary>
[Input("path")]
public Input<string>? Path { get; set; }
/// <summary>
/// The region the Cloud Run service is deployed in.
/// </summary>
[Input("region", required: true)]
public Input<string> Region { get; set; } = null!;
/// <summary>
/// The name of the Cloud run service being addressed (see https://cloud.google.com/run/docs/reference/rest/v1/namespaces.services). Only services located in the same project of the trigger object can be addressed.
/// </summary>
[Input("service", required: true)]
public Input<string> Service { get; set; } = null!;
public CloudRunServiceArgs()
{
}
}
}
| 36.829268 | 228 | 0.641722 | [
"Apache-2.0"
] | AaronFriel/pulumi-google-native | sdk/dotnet/Eventarc/V1Beta1/Inputs/CloudRunServiceArgs.cs | 1,510 | C# |
using Sitecore.ContentSearch;
using Sitecore.ContentSearch.SearchTypes;
using System;
using System.Collections.Generic;
namespace SitecoreForms.Foundation.Search.Models
{
public class BaseSearchResultItem : SearchResultItem
{
[IndexField("alltemplates")]
public IList<Guid> Templates { get; set; }
}
}
| 23.642857 | 56 | 0.743202 | [
"MIT"
] | jaffal83/Sitecore-Forms-Examples | src/Foundation/Search/website/Models/BaseSearchResultItem.cs | 331 | C# |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditorInternal;
[CustomEditor(typeof(EnviroWeatherPreset))]
public class EnviroWeatherPresetEditor : Editor {
GUIStyle boxStyle;
GUIStyle boxStyle2;
GUIStyle wrapStyle;
GUIStyle clearStyle;
EnviroWeatherPreset myTarget;
public bool showAudio = false;
public bool showFog = false;
public bool showSeason = false;
public bool showClouds = false;
public bool showGeneral = false;
SerializedObject serializedObj;
SerializedProperty fogMod;
SerializedProperty skyMod;
SerializedProperty lightMod;
void OnEnable()
{
myTarget = (EnviroWeatherPreset)target;
serializedObj = new SerializedObject (myTarget);
fogMod = serializedObj.FindProperty ("weatherFogMod");
skyMod = serializedObj.FindProperty ("weatherSkyMod");
lightMod = serializedObj.FindProperty ("weatherLightMod");
}
public override void OnInspectorGUI ()
{
myTarget = (EnviroWeatherPreset)target;
#if UNITY_5_6_OR_NEWER
serializedObj.UpdateIfRequiredOrScript ();
#else
serializedObj.UpdateIfDirtyOrScript ();
#endif
//Set up the box style
if (boxStyle == null)
{
boxStyle = new GUIStyle(GUI.skin.box);
boxStyle.normal.textColor = GUI.skin.label.normal.textColor;
boxStyle.fontStyle = FontStyle.Bold;
boxStyle.alignment = TextAnchor.UpperLeft;
}
if (boxStyle2 == null)
{
boxStyle2 = new GUIStyle(GUI.skin.label);
boxStyle2.normal.textColor = GUI.skin.label.normal.textColor;
boxStyle2.fontStyle = FontStyle.Bold;
boxStyle2.alignment = TextAnchor.UpperLeft;
}
//Setup the wrap style
if (wrapStyle == null)
{
wrapStyle = new GUIStyle(GUI.skin.label);
wrapStyle.fontStyle = FontStyle.Bold;
wrapStyle.wordWrap = true;
}
if (clearStyle == null) {
clearStyle = new GUIStyle(GUI.skin.label);
clearStyle.normal.textColor = GUI.skin.label.normal.textColor;
clearStyle.fontStyle = FontStyle.Bold;
clearStyle.alignment = TextAnchor.UpperRight;
}
// Begin
GUILayout.BeginVertical("", boxStyle);
GUILayout.Space(10);
myTarget.Name = EditorGUILayout.TextField ("Name", myTarget.Name);
GUILayout.Space(10);
// General Setup
GUILayout.BeginVertical("", boxStyle);
showGeneral = EditorGUILayout.BeginToggleGroup ("General Configs", showGeneral);
if (showGeneral) {
GUILayout.BeginVertical("Sky and Light Color", boxStyle);
GUILayout.Space(15);
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(skyMod, true, null);
EditorGUILayout.PropertyField(lightMod, true, null);
myTarget.volumeLightIntensity = EditorGUILayout.Slider("Volume Light Intensity", myTarget.volumeLightIntensity, 0, 2);
if (EditorGUI.EndChangeCheck())
{
serializedObj.ApplyModifiedProperties();
}
EditorGUILayout.EndVertical ();
GUILayout.BeginVertical("Weather Condition", boxStyle);
GUILayout.Space(15);
myTarget.WindStrenght = EditorGUILayout.Slider("Wind Intensity",myTarget.WindStrenght,0f,1f);
myTarget.wetnessLevel = EditorGUILayout.Slider("Maximum Wetness",myTarget.wetnessLevel,0f,1f);
myTarget.snowLevel = EditorGUILayout.Slider("Maximum Snow",myTarget.snowLevel,0f,1f);
myTarget.isLightningStorm = EditorGUILayout.Toggle ("Lightning Storm", myTarget.isLightningStorm);
myTarget.lightningInterval = EditorGUILayout.Slider("Lightning Interval",myTarget.lightningInterval,2f,60f);
EditorGUILayout.EndVertical ();
GUILayout.BeginVertical("Particle Effects", boxStyle);
GUILayout.Space(15);
if (!Application.isPlaying) {
if (GUILayout.Button ("Add")) {
myTarget.effectSystems.Add (new EnviroWeatherEffects ());
}
} else
EditorGUILayout.LabelField ("Can't add effects in runtime!");
for (int i = 0; i < myTarget.effectSystems.Count; i++) {
GUILayout.BeginVertical ("Effect " + (i+1), boxStyle);
GUILayout.Space(15);
myTarget.effectSystems[i].prefab = (GameObject)EditorGUILayout.ObjectField ("Effect Prefab", myTarget.effectSystems[i].prefab, typeof(GameObject), true);
myTarget.effectSystems [i].localPositionOffset = EditorGUILayout.Vector3Field ("Position Offset", myTarget.effectSystems [i].localPositionOffset);
myTarget.effectSystems [i].localRotationOffset = EditorGUILayout.Vector3Field ("Rotation Offset", myTarget.effectSystems [i].localRotationOffset);
if (GUILayout.Button ("Remove")) {
myTarget.effectSystems.Remove (myTarget.effectSystems[i]);
}
GUILayout.EndVertical ();
}
EditorGUILayout.EndVertical ();
}
EditorGUILayout.EndToggleGroup ();
EditorGUILayout.EndVertical ();
// Season Setup
GUILayout.BeginVertical("", boxStyle);
showSeason = EditorGUILayout.BeginToggleGroup ("Season Configs", showSeason);
if (showSeason) {
myTarget.Spring = EditorGUILayout.Toggle ("Spring",myTarget.Spring);
if (myTarget.Spring)
myTarget.possibiltyInSpring = EditorGUILayout.Slider ("Spring Possibility",myTarget.possibiltyInSpring, 0, 100);
myTarget.Summer = EditorGUILayout.Toggle ("Summer",myTarget.Summer);
if (myTarget.Summer)
myTarget.possibiltyInSummer = EditorGUILayout.Slider ("Summer Possibility",myTarget.possibiltyInSummer, 0, 100);
myTarget.Autumn = EditorGUILayout.Toggle ("Autumn",myTarget.Autumn);
if (myTarget.Autumn)
myTarget.possibiltyInAutumn = EditorGUILayout.Slider ("Autumn Possibility",myTarget.possibiltyInAutumn, 0, 100);
myTarget.winter = EditorGUILayout.Toggle ("Winter",myTarget.winter);
if (myTarget.winter)
myTarget.possibiltyInWinter = EditorGUILayout.Slider ("Winter Possibility",myTarget.possibiltyInWinter, 0, 100);
//Add Content
}
EditorGUILayout.EndToggleGroup ();
EditorGUILayout.EndVertical ();
// Clouds Setup
GUILayout.BeginVertical("", boxStyle);
showClouds = EditorGUILayout.BeginToggleGroup ("Clouds Configs", showClouds);
if (showClouds) {
//Add Cloud Stuff
GUILayout.BeginVertical("Volume Clouds", boxStyle);
GUILayout.Space(20);
myTarget.cloudsConfig.topColor = EditorGUILayout.ColorField ("Top Color", myTarget.cloudsConfig.topColor);
myTarget.cloudsConfig.bottomColor = EditorGUILayout.ColorField ("Bottom Color", myTarget.cloudsConfig.bottomColor);
GUILayout.Space(10);
myTarget.cloudsConfig.alphaCoef = EditorGUILayout.Slider ("Alpha Factor", myTarget.cloudsConfig.alphaCoef,1f,4f);
myTarget.cloudsConfig.scatteringCoef = EditorGUILayout.Slider ("Light Scattering Factor", myTarget.cloudsConfig.scatteringCoef,0f,2f);
myTarget.cloudsConfig.skyBlending = EditorGUILayout.Slider("Sky Blending Factor", myTarget.cloudsConfig.skyBlending, 0.25f, 1f);
GUILayout.Space(10);
myTarget.cloudsConfig.coverage = EditorGUILayout.Slider ("Coverage", myTarget.cloudsConfig.coverage,-1f,2f);
myTarget.cloudsConfig.coverageHeight = EditorGUILayout.Slider ("Coverage Height", myTarget.cloudsConfig.coverageHeight,0f,2f);
myTarget.cloudsConfig.raymarchingScale = EditorGUILayout.Slider ("Raymarch Step Modifier", myTarget.cloudsConfig.raymarchingScale, 0.25f,1f);
myTarget.cloudsConfig.density = EditorGUILayout.Slider ("Density", myTarget.cloudsConfig.density,1f,2f);
myTarget.cloudsConfig.cloudType = EditorGUILayout.Slider ("Cloud Type", myTarget.cloudsConfig.cloudType,0f,1f);
EditorGUILayout.EndVertical ();
GUILayout.BeginVertical("Flat Clouds", boxStyle);
GUILayout.Space(20);
myTarget.cloudsConfig.flatAlpha = EditorGUILayout.Slider ("Flat Clouds Alpha", myTarget.cloudsConfig.flatAlpha,1f,2f);
myTarget.cloudsConfig.flatCoverage = EditorGUILayout.Slider ("Flat Clouds Coverage", myTarget.cloudsConfig.flatCoverage, 0f,1f);
myTarget.cloudsConfig.flatSoftness = EditorGUILayout.Slider("Flat Clouds Softness", myTarget.cloudsConfig.flatSoftness, 0f, 1f);
myTarget.cloudsConfig.flatBrightness = EditorGUILayout.Slider("Flat Clouds Brighness", myTarget.cloudsConfig.flatBrightness, 0f, 1f);
myTarget.cloudsConfig.flatColorPow = EditorGUILayout.Slider ("Flat Clouds Color Power", myTarget.cloudsConfig.flatColorPow,0.1f,5f);
EditorGUILayout.EndVertical ();
GUILayout.BeginVertical("Cirrus Clouds", boxStyle);
GUILayout.Space(20);
myTarget.cloudsConfig.cirrusAlpha = EditorGUILayout.Slider ("Cirrus Clouds Alpha", myTarget.cloudsConfig.cirrusAlpha,0f,1f);
myTarget.cloudsConfig.cirrusCoverage = EditorGUILayout.Slider ("Cirrus Clouds Coverage", myTarget.cloudsConfig.cirrusCoverage,0f,1f);
myTarget.cloudsConfig.cirrusColorPow = EditorGUILayout.Slider ("Cirrus Clouds Color Power", myTarget.cloudsConfig.cirrusColorPow,0.1f,5f);
EditorGUILayout.EndVertical ();
}
EditorGUILayout.EndToggleGroup ();
EditorGUILayout.EndVertical ();
// Fog Setup
GUILayout.BeginVertical("", boxStyle);
showFog = EditorGUILayout.BeginToggleGroup ("Fog Configs", showFog);
if (showFog) {
GUILayout.BeginVertical ("Fog Intensity", boxStyle);
GUILayout.Space(15);
GUILayout.BeginVertical ("Linear",boxStyle2);
GUILayout.Space(15);
myTarget.fogStartDistance = EditorGUILayout.FloatField ("Start Distance", myTarget.fogStartDistance);
myTarget.fogDistance = EditorGUILayout.FloatField ("End Distance", myTarget.fogDistance);
EditorGUILayout.EndVertical ();
GUILayout.BeginVertical ("EXP",boxStyle2);
GUILayout.Space(15);
myTarget.fogDensity = EditorGUILayout.FloatField ("Density", myTarget.fogDensity);
EditorGUILayout.EndVertical ();
GUILayout.BeginVertical ("Height",boxStyle2);
GUILayout.Space(15);
myTarget.heightFogDensity = EditorGUILayout.Slider ("Height Fog Density", myTarget.heightFogDensity,0f,10f);
EditorGUILayout.EndVertical ();
EditorGUILayout.EndVertical ();
GUILayout.BeginVertical ("Advanced", boxStyle);
GUILayout.Space(15);
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(fogMod, true, null);
if(EditorGUI.EndChangeCheck())
{
serializedObj.ApplyModifiedProperties();
}
myTarget.FogScatteringIntensity = EditorGUILayout.Slider ("Scattering Intensity", myTarget.FogScatteringIntensity,1f,10f);
myTarget.fogSunBlocking = EditorGUILayout.Slider ("Sundisk Intensity", myTarget.fogSunBlocking,0f,1f);
GUILayout.BeginVertical ("Sky Fog",boxStyle2);
GUILayout.Space(15);
myTarget.SkyFogHeight = EditorGUILayout.Slider ("Sky Fog Height", myTarget.SkyFogHeight,0f,2f);
myTarget.SkyFogIntensity = EditorGUILayout.Slider ("Sky Fog Intensity", myTarget.SkyFogIntensity,0.25f,2f);
EditorGUILayout.EndVertical ();
EditorGUILayout.EndVertical ();
//Add Content
}
EditorGUILayout.EndToggleGroup ();
EditorGUILayout.EndVertical ();
// Audio Setup
GUILayout.BeginVertical("", boxStyle);
showAudio = EditorGUILayout.BeginToggleGroup ("Audio Configs", showAudio);
if (showAudio) {
myTarget.weatherSFX = (AudioClip)EditorGUILayout.ObjectField ("Weather Soundeffect",myTarget.weatherSFX, typeof(AudioClip), true);
GUILayout.Space(10);
myTarget.SpringDayAmbient = (AudioClip)EditorGUILayout.ObjectField ("Spring Day Ambient",myTarget.SpringDayAmbient, typeof(AudioClip), true);
myTarget.SpringNightAmbient = (AudioClip)EditorGUILayout.ObjectField ("Spring Night Ambient",myTarget.SpringNightAmbient, typeof(AudioClip), true);
GUILayout.Space(10);
myTarget.SummerDayAmbient = (AudioClip)EditorGUILayout.ObjectField ("Summer Day Ambient",myTarget.SummerDayAmbient, typeof(AudioClip), true);
myTarget.SummerNightAmbient = (AudioClip)EditorGUILayout.ObjectField ("Summer Night Ambient",myTarget.SummerNightAmbient, typeof(AudioClip), true);
GUILayout.Space(10);
myTarget.AutumnDayAmbient = (AudioClip)EditorGUILayout.ObjectField ("Autumn Day Ambient",myTarget.AutumnDayAmbient, typeof(AudioClip), true);
myTarget.AutumnNightAmbient = (AudioClip)EditorGUILayout.ObjectField ("Autumn Night Ambient",myTarget.AutumnNightAmbient, typeof(AudioClip), true);
GUILayout.Space(10);
myTarget.WinterDayAmbient = (AudioClip)EditorGUILayout.ObjectField ("Winter Day Ambient",myTarget.WinterDayAmbient, typeof(AudioClip), true);
myTarget.WinterNightAmbient = (AudioClip)EditorGUILayout.ObjectField ("Winter Night Ambient",myTarget.WinterNightAmbient, typeof(AudioClip), true);
//Add Content
}
EditorGUILayout.EndToggleGroup ();
EditorGUILayout.EndVertical ();
// END
EditorGUILayout.EndVertical ();
EditorUtility.SetDirty (target);
}
}
| 45.8 | 157 | 0.762979 | [
"MIT"
] | jsl-bim/- | Assets/Plugins/Enviro - Dynamic Enviroment/Scripts/Editor/EnviroWeatherPresetEditor.cs | 12,368 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Nest;
using PatentSpoiler.App.Domain.Patents;
using PatentSpoiler.Models;
namespace PatentSpoiler.App.Data.ElasticSearch
{
public interface IPatentSchemeSearchIndexBuilder
{
Task IndexCategoriesAsync(PatentHierrachyNode root);
}
public class PatentSchemeSearchIndexBuilder : IPatentSchemeSearchIndexBuilder
{
private readonly IElasticClient elasticClient;
private int count = 0;
private BulkDescriptor bulkDescriptor;
public PatentSchemeSearchIndexBuilder(IElasticClient elasticClient)
{
this.elasticClient = elasticClient;
}
public async Task IndexCategoriesAsync(PatentHierrachyNode root)
{
Check(root, new HashSet<string>(), new List<PatentHierrachyNode>());
bulkDescriptor = new BulkDescriptor();
await BuildIndexOperation(root);
var result = await elasticClient.BulkAsync(bulkDescriptor);
}
private async Task BuildIndexOperation(PatentHierrachyNode node, int level = 0)
{
//var classification = new PatentClassification{Id=node.ClassificationSymbol, Title = node.Title};
var classification = new PatentClassificationIndexItem { Id=node.ClassificationSymbol, Title = GetTotalDescriptionFor(node)};
if (level > 3)
{
count++;
bulkDescriptor.Index<PatentClassificationIndexItem>(x => x.Document(classification).Index("patent-classifications"));
if (count == 2500)
{
var result = await elasticClient.BulkAsync(bulkDescriptor);
count = 0;
bulkDescriptor = new BulkDescriptor();
}
}
foreach (var child in node.Children)
{
await BuildIndexOperation(child, level+1);
}
}
private string GetTotalDescriptionFor(PatentHierrachyNode node)
{
var keywords = new StringBuilder();
do
{
keywords.Append(' ').Append(node.Title);
node = node.Parent;
} while (node != null);
var distinctKeywords = keywords.ToString()
.Split(',',';', ' ')
.Distinct(StringComparer.InvariantCultureIgnoreCase)
.Where(x=>x.Length>2);
return string.Join(" ", distinctKeywords);
}
private void Check(PatentHierrachyNode node, HashSet<string> prev, List<PatentHierrachyNode> nodes)
{
if (!prev.Add(node.ClassificationSymbol))
{
}
nodes.Add(node);
foreach (var child in node.Children)
{
Check(child, prev, nodes);
}
}
}
} | 32.680851 | 137 | 0.570638 | [
"Apache-2.0"
] | spadger/patent-spoiler | src/PatentSpoiler/App/Data/ElasticSearch/PatentSchemeSearchIndexBuilder.cs | 3,074 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System.Threading.Tasks;
using Elastic.Elasticsearch.Xunit.XunitPlumbing;
using Nest;
using Tests.Domain;
using Tests.Framework.EndpointTests;
using static Tests.Framework.EndpointTests.UrlTester;
namespace Tests.Document.Multiple.DeleteByQuery
{
public class DeleteByQueryUrlTests : UrlTestsBase
{
[U] public override async Task Urls() =>
await POST("/project/_delete_by_query")
.Fluent(c => c.DeleteByQuery<Project>(d => d))
.Request(c => c.DeleteByQuery(new DeleteByQueryRequest<Project>("project")))
.FluentAsync(c => c.DeleteByQueryAsync<Project>(d => d))
.RequestAsync(c => c.DeleteByQueryAsync(new DeleteByQueryRequest<Project>("project")));
}
}
| 37.041667 | 91 | 0.760405 | [
"Apache-2.0"
] | Atharvpatel21/elasticsearch-net | tests/Tests/Document/Multiple/DeleteByQuery/DeleteByQueryUrlTests.cs | 889 | C# |
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TestHouse.Application.Infastructure.Repositories;
using TestHouse.Application.Services;
using TestHouse.Domain.Enums;
using TestHouse.Domain.Models;
using TestHouse.Infrastructure.Repositories;
using Xunit;
namespace TestHouse.Application.Tests
{
public class ProjectServiceTests
{
[Fact]
public async Task AddProjectTest()
{
// In-memory database only exists while the connection is open
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
try
{
var options = new DbContextOptionsBuilder<ProjectRespository>()
.UseSqlite(connection)
.Options;
// Create the schema in the database
using (var context = new ProjectRespository(options))
{
context.Database.EnsureCreated();
}
// Run the test against one instance of the context
using (var repository = new ProjectRespository(options))
{
var projectService = new ProjectService(repository);
var project = await projectService.AddProjectAsync("test name", "test description");
Assert.NotEqual(0, project.Id);
}
// Use a separate instance of the context to verify correct data was saved to database
using (var context = new ProjectRespository(options))
{
var project = await context.GetAsync(1);
Assert.Equal(1, context.Projects.Count());
Assert.Equal("test name", project.Name);
Assert.Equal("test description", project.Description);
Assert.NotEqual(0, project.Id);
Assert.NotNull(project.Suits);
Assert.NotNull(project.RootSuit);
Assert.NotNull(project.TestRuns);
}
}
finally
{
connection.Close();
}
}
[Fact]
public async Task GetAllTest()
{
// In-memory database only exists while the connection is open
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
try
{
var options = new DbContextOptionsBuilder<ProjectRespository>()
.UseSqlite(connection)
.Options;
// Create the schema in the database
using (var context = new ProjectRespository(options))
{
context.Database.EnsureCreated();
}
// Run the test against one instance of the context
using (var repository = new ProjectRespository(options))
{
var projectService = new ProjectService(repository);
await projectService.AddProjectAsync("test name 1", "test description 1");
await projectService.AddProjectAsync("test name 2", "test description 2");
}
// Use a separate instance of the context to verify correct data was saved to database
using (var context = new ProjectRespository(options))
{
var projectService = new ProjectService(context);
var projects = await projectService.GetAllAsync();
Assert.Collection(projects, project =>
{
Assert.Equal(1, project.Id);
Assert.Equal("test name 1", project.Name);
Assert.Equal("test description 1", project.Description);
},
project =>
{
Assert.Equal(2, project.Id);
Assert.Equal("test name 2", project.Name);
Assert.Equal("test description 2", project.Description);
});
}
}
finally
{
connection.Close();
}
}
[Fact]
public async Task GetTest()
{
// In-memory database only exists while the connection is open
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
try
{
var options = new DbContextOptionsBuilder<ProjectRespository>()
.UseSqlite(connection)
.Options;
// Create the schema in the database
using (var context = new ProjectRespository(options))
{
context.Database.EnsureCreated();
}
// Run the test against one instance of the context
using (var repository = new ProjectRespository(options))
{
var projectService = new ProjectService(repository);
await projectService.AddProjectAsync("test name 1", "test description 1");
var suitService = new SuitService(repository);
await suitService.AddSuitAsync("suit level 1", "suit description 1", 1, 1);
await suitService.AddSuitAsync("suit level 2", "suit description 2", 1, 2);
await suitService.AddSuitAsync("suit level 1.1", "suit description 1.1", 1, 1);
await suitService.AddSuitAsync("suit level 3", "suit description 3", 1, 3);
var testCaseService = new TestCaseService(repository);
await testCaseService.AddTestCaseAsync("test case 1", "descr 1", "expected 1", 1, 1,
new List<Step> {
new Step(0,"step descr 1", "expected 1"),
new Step(1, "step descr 2", "expected 2")
});
await testCaseService.AddTestCaseAsync("test case 2", "descr 2", "expected 2", 1, 5,
new List<Step> {
new Step(0,"step descr 3", "expected 3"),
new Step(1, "step descr 4", "expected 4")
});
await testCaseService.AddTestCaseAsync("test case 3", "descr 3", "expected 3", 1, 5, null);
}
// Use a separate instance of the context to verify correct data was saved to database
using (var context = new ProjectRespository(options))
{
var projectService = new ProjectService(context);
var project = await projectService.GetAsync(1);
Assert.Equal(1, project.RootSuit.Id);
Assert.Equal("root", project.RootSuit.Name);
Assert.Equal("root", project.RootSuit.Description);
Assert.Collection(project.RootSuit.TestCases, testCase =>
{
Assert.Equal("test case 1", testCase.Name);
Assert.Equal("descr 1", testCase.Description);
Assert.Equal("expected 1", testCase.ExpectedResult);
Assert.Collection(testCase.Steps, step =>
{
Assert.Equal("step descr 1", step.Description);
Assert.Equal("expected 1", step.ExpectedResult);
Assert.Equal(0, step.Order);
},
step=>
{
Assert.Equal("step descr 2", step.Description);
Assert.Equal("expected 2", step.ExpectedResult);
Assert.Equal(1, step.Order);
});
});
Assert.Collection(project.RootSuit.Suits, suit =>
{
Assert.Equal(2, suit.Id);
Assert.Equal("suit level 1", suit.Name);
Assert.Equal("suit description 1", suit.Description);
Assert.Collection(suit.Suits, suit1 =>
{
Assert.Equal(3, suit1.Id);
Assert.Equal("suit level 2", suit1.Name);
Assert.Equal("suit description 2", suit1.Description);
Assert.Collection(suit1.Suits, suit2 =>
{
Assert.Equal(5, suit2.Id);
Assert.Equal("suit level 3", suit2.Name);
Assert.Equal("suit description 3", suit2.Description);
Assert.Null(suit2.Suits);
Assert.Collection(suit2.TestCases, testCase =>
{
Assert.Equal("test case 2", testCase.Name);
Assert.Equal("descr 2", testCase.Description);
Assert.Equal("expected 2", testCase.ExpectedResult);
Assert.Collection(testCase.Steps, step =>
{
Assert.Equal("step descr 3", step.Description);
Assert.Equal("expected 3", step.ExpectedResult);
Assert.Equal(0, step.Order);
},
step =>
{
Assert.Equal("step descr 4", step.Description);
Assert.Equal("expected 4", step.ExpectedResult);
Assert.Equal(1, step.Order);
});
},
testCase =>
{
Assert.Equal("test case 3", testCase.Name);
Assert.Equal("descr 3", testCase.Description);
Assert.Equal("expected 3", testCase.ExpectedResult);
});
});
});
},
suit =>
{
Assert.Equal(4, suit.Id);
Assert.Equal("suit level 1.1", suit.Name);
Assert.Equal("suit description 1.1", suit.Description);
Assert.Null(suit.Suits);
});
}
}
finally
{
connection.Close();
}
}
[Fact]
public async Task RemoveTest()
{
// In-memory database only exists while the connection is open
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
try
{
var options = new DbContextOptionsBuilder<ProjectRespository>()
.UseSqlite(connection)
.Options;
// Create the schema in the database
using (var context = new ProjectRespository(options))
{
context.Database.EnsureCreated();
}
// Run the test against one instance of the context
using (var repository = new ProjectRespository(options))
{
var projectService = new ProjectService(repository);
await projectService.AddProjectAsync("test name 1", "test description 1");
var suitService = new SuitService(repository);
await suitService.AddSuitAsync("suit level 1", "suit description 1", 1, 1);
await suitService.AddSuitAsync("suit level 2", "suit description 2", 1, 2);
await suitService.AddSuitAsync("suit level 1.1", "suit description 1.1", 1, 1);
await suitService.AddSuitAsync("suit level 3", "suit description 3", 1, 3);
var testCaseService = new TestCaseService(repository);
await testCaseService.AddTestCaseAsync("test case 1", "descr 1", "expected 1", 1, 1,
new List<Step> {
new Step(0,"step descr 1", "expected 1"),
new Step(1, "step descr 2", "expected 2")
});
await testCaseService.AddTestCaseAsync("test case 2", "descr 2", "expected 2", 1, 5,
new List<Step> {
new Step(0,"step descr 3", "expected 3"),
new Step(1, "step descr 4", "expected 4")
});
await testCaseService.AddTestCaseAsync("test case 3", "descr 3", "expected 3", 1, 5, null);
}
// Use a separate instance of the context to verify correct data was saved to database
using (var context = new ProjectRespository(options))
{
var projectService = new ProjectService(context);
await projectService.RemoveAsync(1);
var project = projectService.GetAsync(1).Result;
Assert.NotNull(project);
Assert.True(project.State == ProjectAggregateState.Deleted);
}
}
finally
{
connection.Close();
}
}
[Theory]
[InlineData("new name 1", "new description")]
[InlineData("new name 2", "")]
[InlineData("new name 3", " ")]
[InlineData("new name 4", null)]
public async Task UpdateInfoTest(string newName, string newDescription)
{
//ARRANGE
var project = new ProjectAggregate("name", "description");
var repo = new Mock<IProjectRepository>();
repo.Setup(x => x.GetAsync(It.IsAny<long>())).ReturnsAsync(project).Verifiable();
var projectService = new ProjectService(repo.Object);
//ACT
await projectService.UpdateProject(1, newName, newDescription);
//ASSERT
repo.Verify(x => x.SaveAsync());
repo.Verify();
Assert.Equal(newName, project.Name);
Assert.Equal(newDescription, project.Description);
}
}
}
| 43.124294 | 124 | 0.468034 | [
"Apache-2.0"
] | nightBaker/TestHouse | TestHouse.Application.Tests/ProjectServiceTests.cs | 15,266 | C# |
using CulverinEditor;
using CulverinEditor.SceneManagement;
class TestScript : CulverinBehaviour
{
} | 13 | 37 | 0.817308 | [
"MIT"
] | TempName0/TempMotor3D_P3 | Engine/Game/Assets/TestScript.cs | 106 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Compute.Outputs
{
[OutputType]
public sealed class VirtualMachineScaleSetVMProtectionPolicyResponse
{
/// <summary>
/// Indicates that the virtual machine scale set VM shouldn't be considered for deletion during a scale-in operation.
/// </summary>
public readonly bool? ProtectFromScaleIn;
/// <summary>
/// Indicates that model updates or actions (including scale-in) initiated on the virtual machine scale set should not be applied to the virtual machine scale set VM.
/// </summary>
public readonly bool? ProtectFromScaleSetActions;
[OutputConstructor]
private VirtualMachineScaleSetVMProtectionPolicyResponse(
bool? protectFromScaleIn,
bool? protectFromScaleSetActions)
{
ProtectFromScaleIn = protectFromScaleIn;
ProtectFromScaleSetActions = protectFromScaleSetActions;
}
}
}
| 35.361111 | 174 | 0.697565 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Compute/Outputs/VirtualMachineScaleSetVMProtectionPolicyResponse.cs | 1,273 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TAlex.MathCore.ExpressionEvaluation.Tokenize
{
public class Token
{
public readonly string Value;
public readonly TokenType TokenType;
public Token(string value, TokenType type)
{
Value = value;
TokenType = type;
}
public override bool Equals(object obj)
{
if (obj is Token)
return Equals((Token)obj);
else
return false;
}
public virtual bool Equals(Token token)
{
return (String.Equals(Value, token.Value) && TokenType == token.TokenType);
}
public override int GetHashCode()
{
return ToString().GetHashCode();
}
public override string ToString()
{
return String.Format("(Value: {0}, Type: {1})", Value, TokenType);
}
}
}
| 22.044444 | 87 | 0.548387 | [
"MIT"
] | T-Alex/MathCore | src/TAlex.MathCore.ExpressionsBase/Tokenize/Token.cs | 994 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WeatherGrabber.Domain.Models
{
public class City
{
public City(string name, string weatherUrl)
{
Name = name ?? throw new ArgumentNullException(nameof(name));
WeatherUrl = weatherUrl ?? throw new ArgumentNullException(nameof(weatherUrl));
}
public string Name { get; }
public string WeatherUrl { get; }
public override string ToString()
{
var sb = new StringBuilder();
sb.Append($"{nameof(City)}: ");
sb.Append($"{nameof(Name)} = {Name}, ");
sb.Append($"{nameof(WeatherUrl)} = {WeatherUrl}");
return sb.ToString();
}
}
}
| 27.033333 | 91 | 0.58693 | [
"MIT"
] | bildeyko/WeatherGrab | WeatherGrabber.Domain/Models/City.cs | 813 | 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 iot-2015-05-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.IoT.Model
{
/// <summary>
/// Container for the parameters to the ListProvisioningTemplates operation.
/// Lists the fleet provisioning templates in your AWS account.
/// </summary>
public partial class ListProvisioningTemplatesRequest : AmazonIoTRequest
{
private int? _maxResults;
private string _nextToken;
/// <summary>
/// Gets and sets the property MaxResults.
/// <para>
/// The maximum number of results to return at one time.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=250)]
public int MaxResults
{
get { return this._maxResults.GetValueOrDefault(); }
set { this._maxResults = value; }
}
// Check to see if MaxResults property is set
internal bool IsSetMaxResults()
{
return this._maxResults.HasValue;
}
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// A token to retrieve the next set of results.
/// </para>
/// </summary>
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
}
} | 30.551282 | 102 | 0.60512 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/IoT/Generated/Model/ListProvisioningTemplatesRequest.cs | 2,383 | C# |
using System;
namespace NorthwindTraders.Common.Dates
{
public interface IDateTime
{
DateTime Now { get; }
}
}
| 13.3 | 39 | 0.639098 | [
"MIT"
] | jernejk/NorthwindTraders | Common/Dates/IDateTime.cs | 135 | C# |
using System;
using Chartreuse.Today.Core.Shared.Model.Recurrence;
using Chartreuse.Today.ToodleDo;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Chartreuse.Today.Core.Shared.Tests.ToodleDo
{
[TestClass]
public class ToodleDoRecurrencyTest
{
[TestMethod]
public void ToodleDoNoneFrequencyTest()
{
ICustomFrequency frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency(null);
Assert.IsTrue(frequency is OnceOnlyFrequency);
frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency(String.Empty);
Assert.IsTrue(frequency is OnceOnlyFrequency);
frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency("none");
Assert.IsTrue(frequency is OnceOnlyFrequency);
frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency("None");
Assert.IsTrue(frequency is OnceOnlyFrequency);
}
[TestMethod]
public void ToodleDoDailyFrequencyTest()
{
ICustomFrequency frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency("daily");
Assert.IsTrue(frequency is DailyFrequency);
frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency("Daily");
Assert.IsTrue(frequency is DailyFrequency);
frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency("every 1 DAY");
Assert.IsTrue(frequency is DailyFrequency);
}
[TestMethod]
public void ToodleDoWeeklyFrequencyTest()
{
ICustomFrequency frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency("weekly");
Assert.IsTrue(frequency is WeeklyFrequency);
frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency("WeeKLy");
Assert.IsTrue(frequency is WeeklyFrequency);
frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency("eVERY 1 Week");
Assert.IsTrue(frequency is WeeklyFrequency);
}
[TestMethod]
public void ToodleDoMonthlyFrequencyTest()
{
ICustomFrequency frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency("monthly");
Assert.IsTrue(frequency is MonthlyFrequency);
frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency("MonthlY");
Assert.IsTrue(frequency is MonthlyFrequency);
frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency("every 1 monTH");
Assert.IsTrue(frequency is MonthlyFrequency);
}
[TestMethod]
public void ToodleDoYearlyFrequencyTest()
{
ICustomFrequency frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency("yearly");
Assert.IsTrue(frequency is YearlyFrequency);
frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency("yeARly");
Assert.IsTrue(frequency is YearlyFrequency);
frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency("Every 1 Year");
Assert.IsTrue(frequency is YearlyFrequency);
}
[TestMethod]
public void ToodleDoDaysOfWeekFrequencyTest1()
{
ICustomFrequency frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency("every mon");
DaysOfWeekFrequency freq = frequency as DaysOfWeekFrequency;
Assert.IsNotNull(freq);
Assert.IsTrue(freq.IsMonday);
Assert.IsFalse(freq.IsTuesday);
Assert.IsFalse(freq.IsWednesday);
Assert.IsFalse(freq.IsThursday);
Assert.IsFalse(freq.IsFriday);
Assert.IsFalse(freq.IsSaturday);
Assert.IsFalse(freq.IsSunday);
}
[TestMethod]
public void ToodleDoDaysOfWeekFrequencyTest2()
{
ICustomFrequency frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency("every tue, WED");
DaysOfWeekFrequency freq = frequency as DaysOfWeekFrequency;
Assert.IsNotNull(freq);
Assert.IsFalse(freq.IsMonday);
Assert.IsTrue(freq.IsTuesday);
Assert.IsTrue(freq.IsWednesday);
Assert.IsFalse(freq.IsThursday);
Assert.IsFalse(freq.IsFriday);
Assert.IsFalse(freq.IsSaturday);
Assert.IsFalse(freq.IsSunday);
}
[TestMethod]
public void ToodleDoDaysOfWeekFrequencyTest3()
{
ICustomFrequency frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency("every fri, sat and sun");
DaysOfWeekFrequency freq = frequency as DaysOfWeekFrequency;
Assert.IsNotNull(freq);
Assert.IsFalse(freq.IsMonday);
Assert.IsFalse(freq.IsTuesday);
Assert.IsFalse(freq.IsWednesday);
Assert.IsFalse(freq.IsThursday);
Assert.IsTrue(freq.IsFriday);
Assert.IsTrue(freq.IsSaturday);
Assert.IsTrue(freq.IsSunday);
}
[TestMethod]
public void ToodleDoDaysOfWeekFrequencyTest4()
{
ICustomFrequency frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency("every weekday");
DaysOfWeekFrequency freq = frequency as DaysOfWeekFrequency;
Assert.IsNotNull(freq);
Assert.IsTrue(freq.IsMonday);
Assert.IsTrue(freq.IsTuesday);
Assert.IsTrue(freq.IsWednesday);
Assert.IsTrue(freq.IsThursday);
Assert.IsTrue(freq.IsFriday);
Assert.IsFalse(freq.IsSaturday);
Assert.IsFalse(freq.IsSunday);
}
[TestMethod]
public void ToodleDoDaysOfWeekFrequencyTest5()
{
ICustomFrequency frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency("every weekEND");
DaysOfWeekFrequency freq = frequency as DaysOfWeekFrequency;
Assert.IsNotNull(freq);
Assert.IsFalse(freq.IsMonday);
Assert.IsFalse(freq.IsTuesday);
Assert.IsFalse(freq.IsWednesday);
Assert.IsFalse(freq.IsThursday);
Assert.IsFalse(freq.IsFriday);
Assert.IsTrue(freq.IsSaturday);
Assert.IsTrue(freq.IsSunday);
}
[TestMethod]
public void ToodleDoEveryPeriodFrequencyTest1()
{
ICustomFrequency frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency("every 2 days");
EveryXPeriodFrequency freq = frequency as EveryXPeriodFrequency;
Assert.IsNotNull(freq);
Assert.AreEqual(2,freq.Rate);
Assert.AreEqual(CustomFrequencyScale.Day,freq.Scale);
}
[TestMethod]
public void ToodleDoEveryPeriodFrequencyTest2()
{
ICustomFrequency frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency("every 4 months");
EveryXPeriodFrequency freq = frequency as EveryXPeriodFrequency;
Assert.IsNotNull(freq);
Assert.AreEqual(4, freq.Rate);
Assert.AreEqual(CustomFrequencyScale.Month, freq.Scale);
}
[TestMethod]
public void ToodleDoEveryPeriodFrequencyTest3()
{
ICustomFrequency frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency("EveRy 160 WeeKs");
EveryXPeriodFrequency freq = frequency as EveryXPeriodFrequency;
Assert.IsNotNull(freq);
Assert.AreEqual(160, freq.Rate);
Assert.AreEqual(CustomFrequencyScale.Week, freq.Scale);
}
[TestMethod]
public void ToodleDoEveryPeriodFrequencyTest4()
{
ICustomFrequency frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency("EveRy 3 Years");
EveryXPeriodFrequency freq = frequency as EveryXPeriodFrequency;
Assert.IsNotNull(freq);
Assert.AreEqual(3, freq.Rate);
Assert.AreEqual(CustomFrequencyScale.Year, freq.Scale);
}
[TestMethod]
public void ToodleDoOnXDayFrequencyTest1()
{
ICustomFrequency frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency("The 1st mon of each month");
OnXDayFrequency freq = frequency as OnXDayFrequency;
Assert.IsNotNull(freq);
Assert.AreEqual(DayOfWeek.Monday, freq.DayOfWeek);
Assert.AreEqual(RankingPosition.First, freq.RankingPosition);
}
[TestMethod]
public void ToodleDoOnXDayFrequencyTest2()
{
ICustomFrequency frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency("The 2ND THU of each month");
OnXDayFrequency freq = frequency as OnXDayFrequency;
Assert.IsNotNull(freq);
Assert.AreEqual(DayOfWeek.Thursday, freq.DayOfWeek);
Assert.AreEqual(RankingPosition.Second, freq.RankingPosition);
}
[TestMethod]
public void ToodleDoOnXDayFrequencyTest3()
{
ICustomFrequency frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency("The 3rd SaT of each month");
OnXDayFrequency freq = frequency as OnXDayFrequency;
Assert.IsNotNull(freq);
Assert.AreEqual(DayOfWeek.Saturday, freq.DayOfWeek);
Assert.AreEqual(RankingPosition.Third, freq.RankingPosition);
}
[TestMethod]
public void ToodleDoOnXDayFrequencyTest4()
{
ICustomFrequency frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency("The 4th sun of each month");
OnXDayFrequency freq = frequency as OnXDayFrequency;
Assert.IsNotNull(freq);
Assert.AreEqual(DayOfWeek.Sunday, freq.DayOfWeek);
Assert.AreEqual(RankingPosition.Fourth, freq.RankingPosition);
}
[TestMethod]
public void ToodleDoOnXDayFrequencyTest5()
{
ICustomFrequency frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency("The 5th tue of each month");
OnXDayFrequency freq = frequency as OnXDayFrequency;
Assert.IsNotNull(freq);
Assert.AreEqual(DayOfWeek.Tuesday, freq.DayOfWeek);
Assert.AreEqual(RankingPosition.Last, freq.RankingPosition);
}
[TestMethod]
public void ToodleDoOnXDayFrequencyTest6()
{
ICustomFrequency frequency = ToodleDoRecurrencyHelpers.Get2DayRecurrency("The LasT WeD of each month");
OnXDayFrequency freq = frequency as OnXDayFrequency;
Assert.IsNotNull(freq);
Assert.AreEqual(DayOfWeek.Wednesday, freq.DayOfWeek);
Assert.AreEqual(RankingPosition.Last, freq.RankingPosition);
}
}
}
| 42.682927 | 115 | 0.654952 | [
"MIT"
] | 2DayApp/2day | src/2Day.Core.Shared.Tests/ToodleDo/ToodleDoRecurrencyTest.cs | 10,502 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Generated by the MSBuild WriteCodeFragment class.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("SelectionStatements")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("SelectionStatements")]
[assembly: System.Reflection.AssemblyTitleAttribute("SelectionStatements")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
| 48 | 80 | 0.650735 | [
"MIT"
] | MikeAlexMartinez/LearningCSharp | code/chapter03-FlowAndConversion/SelectionStatements/obj/Debug/netcoreapp2.0/SelectionStatements.AssemblyInfo.cs | 816 | C# |
using System.Collections.Generic;
using JetBrains.Annotations;
using JetBrains.ReSharper.Plugins.FSharp.Psi.Impl.DeclaredElement;
using JetBrains.ReSharper.Plugins.FSharp.Psi.Impl.DeclaredElement.CompilerGenerated;
using JetBrains.ReSharper.Plugins.FSharp.Psi.Impl.Tree;
using JetBrains.ReSharper.Plugins.FSharp.Psi.Tree;
using JetBrains.ReSharper.Plugins.FSharp.Util;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.ExtensionsAPI.Caches2;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.FSharp.Psi.Impl.Cache2.Parts
{
internal class ExceptionPart : FSharpTypeMembersOwnerTypePart, IExceptionPart, IGeneratedConstructorOwner
{
private static readonly string[] ourExtendsListShortNames = {"Exception", "IStructuralEquatable"};
public bool HasFields { get; }
public ExceptionPart([NotNull] IExceptionDeclaration declaration, [NotNull] ICacheBuilder cacheBuilder)
: base(declaration, cacheBuilder) =>
HasFields = !declaration.Fields.IsEmpty;
public ExceptionPart(IReader reader) : base(reader) =>
HasFields = reader.ReadBool();
protected override void Write(IWriter writer)
{
base.Write(writer);
writer.WriteBool(HasFields);
}
public override TypeElement CreateTypeElement() =>
new FSharpClass(this);
protected override byte SerializationTag =>
(byte) FSharpPartKind.Exception;
public override string[] ExtendsListShortNames =>
ourExtendsListShortNames;
public override IDeclaredType GetBaseClassType() =>
GetPsiModule().GetPredefinedType().Exception;
public override IEnumerable<IDeclaredType> GetSuperTypes() =>
new[]
{
GetPsiModule().GetPredefinedType().Exception,
TypeFactory.CreateTypeByCLRName(FSharpPredefinedType.StructuralEquatableTypeName, GetPsiModule())
};
public override IEnumerable<ITypeMember> GetTypeMembers() =>
this.GetGeneratedMembers().Prepend(base.GetTypeMembers());
public IList<ITypeOwner> Fields
{
get
{
// todo: add field list tree node
var fields = new LocalList<ITypeOwner>();
foreach (var typeMember in base.GetTypeMembers())
if (typeMember is FSharpUnionCaseField<ExceptionFieldDeclaration> fieldProperty)
fields.Add(fieldProperty);
return fields.ResultingList();
}
}
public bool OverridesToString => false;
public bool HasCompareTo => false;
public IParametersOwner GetConstructor() =>
new FSharpGeneratedConstructorFromFields(this);
}
public interface IExceptionPart : Class.IClassPart, IFieldsOwnerPart
{
bool HasFields { get; }
}
}
| 33.35 | 107 | 0.735757 | [
"Apache-2.0"
] | En3Tho/fsharp-support | ReSharper.FSharp/src/FSharp.Psi/src/Impl/Cache2/Parts/ExceptionPart.cs | 2,670 | C# |
// Copyright 2005 University of Wisconsin
// Authors:
// Robert M. Scheller
// James B. Domingo
// BDA originally programmed by Wei (Vera) Li at University of Missouri-Columbia in 2004.
// Version 1.0
// License: Available at
// http://landis.forest.wisc.edu/developers/LANDIS-IISourceCodeLicenseAgreement.pdf
using Landis.AgeCohort;
using Landis.Ecoregions;
using Landis.Landscape;
using Landis.Species;
using Landis.Util;
using System.Collections.Generic;
namespace Landis.BDA
{
public class SiteResources
{
//---------------------------------------------------------------------
///<summary>
///Calculate the Site Resource Dominance (SRD) for all active sites.
///The SRD averages the resources for each species as defined in the
///BDA species table.
///SRD ranges from 0 - 1.
///</summary>
//---------------------------------------------------------------------
public static void SiteResourceDominance(IAgent agent, int ROS)
//ILandscapeCohorts cohorts)
{
UI.WriteLine(" Calculating BDA Site Resource Dominance.");
foreach (ActiveSite site in Model.Core.Landscape) {
double sumValue = 0.0;
double maxValue = 0.0;
int ageOldestCohort= 0;
int numValidSpp = 0;
double speciesHostValue = 0;
foreach (ISpecies species in Model.Core.Species)
{
ageOldestCohort = AgeCohort.Util.GetMaxAge(PlugIn.Cohorts[site][species]);
ISppParameters sppParms = agent.SppParameters[species.Index];
if (sppParms == null)
continue;
bool negList = false;
foreach (ISpecies negSpp in agent.NegSppList)
{
if (species == negSpp)
negList = true;
}
if ((ageOldestCohort > 0) && (! negList))
{
numValidSpp++;
speciesHostValue = 0.0;
if (ageOldestCohort >= sppParms.MinorHostAge)
speciesHostValue = 0.33;
if (ageOldestCohort >= sppParms.SecondaryHostAge)
speciesHostValue = 0.66;
if (ageOldestCohort >= sppParms.PrimaryHostAge)
speciesHostValue = 1.0;
sumValue += speciesHostValue;
maxValue = System.Math.Max(maxValue, speciesHostValue);
}
}
if (agent.SRDmode == SRDmode.mean)
SiteVars.SiteResourceDom[site] = sumValue / (double) numValidSpp;
if (agent.SRDmode == SRDmode.max)
SiteVars.SiteResourceDom[site] = maxValue;
}
} //end siteResourceDom
//---------------------------------------------------------------------
///<summary>
///Calculate the Site Resource Dominance MODIFIER for all active sites.
///Site Resource Dominance Modifier takes into account other disturbances and
///any ecoregion modifiers defined.
///SRDMods range from 0 - 1.
///</summary>
//---------------------------------------------------------------------
public static void SiteResourceDominanceModifier(IAgent agent)
{
UI.WriteLine(" Calculating BDA Modified Site Resource Dominance.");
foreach (ActiveSite site in Model.Core.Landscape) {
if (SiteVars.SiteResourceDom[site] > 0.0)
{
int lastDisturb = 0;
int duration = 0;
double disturbMod = 0;
double sumDisturbMods = 0.0;
double SRDM = 0.0;
//---- FIRE -------------------------
if(SiteVars.TimeOfLastFire != null &&
agent.DistParameters[(int) DisturbanceType.Fire].Duration > 0)
{
UI.WriteLine(" Calculating effect of Fire.");
lastDisturb = SiteVars.TimeOfLastFire[site];
duration = agent.DistParameters[(int) DisturbanceType.Fire].Duration;
if (lastDisturb < duration)
{
disturbMod = agent.DistParameters[(int) DisturbanceType.Fire].DistModifier *
(double)(duration - lastDisturb) / duration;
sumDisturbMods += disturbMod;
}
}
//---- WIND -------------------------
if(SiteVars.TimeOfLastWind != null &&
agent.DistParameters[(int) DisturbanceType.Wind].Duration > 0)
{
UI.WriteLine(" Calculating effect of Wind.");
lastDisturb = SiteVars.TimeOfLastWind[site];
duration = agent.DistParameters[(int) DisturbanceType.Wind].Duration;
if (lastDisturb < duration)
{
disturbMod = agent.DistParameters[(int) DisturbanceType.Wind].DistModifier *
(double)(duration - lastDisturb) / duration;
sumDisturbMods += disturbMod;
}
}
//---- HARVEST -------------------------
if(SiteVars.TimeOfLastHarvest != null &&
agent.DistParameters[(int) DisturbanceType.Harvest].Duration > 0)
{
UI.WriteLine(" Calculating effect of Harvesting.");
lastDisturb = SiteVars.TimeOfLastHarvest[site];
duration = agent.DistParameters[(int) DisturbanceType.Harvest].Duration;
if (lastDisturb < duration)
{
disturbMod = agent.DistParameters[(int) DisturbanceType.Harvest].DistModifier *
(double)(duration - lastDisturb) / duration;
sumDisturbMods += disturbMod;
}
}
//UI.WriteLine(" Summation of Disturbance Modifiers = {0}.", sumMods);
//---- APPLY ECOREGION MODIFIERS --------
IEcoregion ecoregion = Model.Core.Ecoregion[site];
SRDM = SiteVars.SiteResourceDom[site] +
sumDisturbMods +
agent.EcoParameters[ecoregion.Index].EcoModifier;
SRDM = System.Math.Max(0.0, SRDM);
SRDM = System.Math.Min(1.0, SRDM);
SiteVars.SiteResourceDomMod[site] = SRDM;
}//end of one site
else SiteVars.SiteResourceDomMod[site] = 0.0;
} //end Active sites
} //end Function
//---------------------------------------------------------------------
///<summary>
///Calculate SITE VULNERABILITY
///Following equations found in Sturtevant et al. 2004.
///Ecological Modeling 180: 153-174.
///</summary>
//---------------------------------------------------------------------
public static void SiteVulnerability(IAgent agent,
int ROS,
bool considerNeighbor)
{
double SRD, SRDMod, NRD;
double CaliROS3 = ((double) ROS / 3) * agent.BDPCalibrator;
UI.WriteLine(" Calculating BDA SiteVulnerability.");
if (considerNeighbor) //take neigborhood into consideration
{
foreach (ActiveSite site in Model.Core.Landscape)
{
SRD = SiteVars.SiteResourceDom[site];
//If a site has been chosen for an outbreak and there are
//resources available for an outbreak:
if (SRD > 0)
{
SRDMod = SiteVars.SiteResourceDomMod[site];
NRD = SiteVars.NeighborResourceDom[site];
double tempSV = 0.0;
//Equation (8) in Sturtevant et al. 2004.
tempSV = SRDMod + (NRD * agent.NeighborWeight);
tempSV = tempSV / (1 + agent.NeighborWeight);
double vulnerable = (double)(CaliROS3 * tempSV);
SiteVars.Vulnerability[site] = System.Math.Max(0.0, vulnerable);
//UI.WriteLine("Site Vulnerability = {0}.", SiteVars.Vulnerability[site]);
}
else
SiteVars.Vulnerability[site] = 0;
}
}
else //Do NOT take neigborhood into consideration
{
foreach (ActiveSite site in Model.Core.Landscape)
{
SRDMod = SiteVars.SiteResourceDomMod[site];
double vulnerable = (double)(CaliROS3 * SRDMod);
SiteVars.Vulnerability[site] = System.Math.Max(0, vulnerable);
}
}
}
//---------------------------------------------------------------------
///<summary>
/// Calculate the The Resource Dominance of all active NEIGHBORS
/// within the User defined NeighborRadius.
///
/// The weight of neighbors is dependent upon distance and a
/// weighting algorithm: uniform, linear, or gaussian.
///
/// Subsampling determined by User defined NeighborSpeedUp.
/// Gaussian equation: http://www.anc.ed.ac.uk/~mjo/intro/node7.html
///</summary>
//---------------------------------------------------------------------
public static void NeighborResourceDominance(IAgent agent)
{
UI.WriteLine(" Calculating BDA Neighborhood Resource Dominance.");
double totalNeighborWeight = 0.0;
double maxNeighborWeight = 0.0;
int neighborCnt = 0;
int speedUpFraction = (int) agent.NeighborSpeedUp + 1;
foreach (ActiveSite site in Model.Core.Landscape) {
if (agent.OutbreakZone[site] == Zone.Newzone)
{
//neighborWeight = 0.0;
totalNeighborWeight = 0.0;
maxNeighborWeight = 0.0;
neighborCnt = 0;
if (SiteVars.SiteResourceDom[site] > 0 )
{
List<RelativeLocationWeighted> neighborhood = new List<RelativeLocationWeighted>();
foreach (RelativeLocationWeighted relativeLoc in agent.ResourceNeighbors)
{
Site neighbor = site.GetNeighbor(relativeLoc.Location);
if (neighbor != null
&& neighbor.IsActive)
{
neighborhood.Add(relativeLoc);
}
}
Random.Shuffle(neighborhood);
foreach(RelativeLocationWeighted neighbor in neighborhood)
{
//Do NOT subsample if there are too few neighbors
//i.e., <= subsample size.
if(neighborhood.Count <= speedUpFraction ||
neighborCnt%speedUpFraction == 0)
{
Site activeSite = site.GetNeighbor(neighbor.Location);
//Note: SiteResourceDomMod ranges from 0 - 1.
if (SiteVars.SiteResourceDomMod[activeSite] > 0)
{
totalNeighborWeight += SiteVars.SiteResourceDomMod[activeSite] * neighbor.Weight;
maxNeighborWeight += neighbor.Weight;
}
}
neighborCnt++;
}
SiteVars.NeighborResourceDom[site] = totalNeighborWeight / maxNeighborWeight;
} else
SiteVars.NeighborResourceDom[site] = 0;
}
}
}
//End of SiteResources
}
}
| 43.219355 | 117 | 0.438722 | [
"Apache-2.0"
] | IvanPizhenko/Extension-Base-BDA-fork | testings/version-tests/release-2.0/src/SiteResources.cs | 13,398 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Gov.Lclb.Cllb.Interfaces
{
using Microsoft.Rest;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Specialeventinvoices operations.
/// </summary>
public partial interface ISpecialeventinvoices
{
/// <summary>
/// Get adoxio_specialevent_invoices from adoxio_specialevents
/// </summary>
/// <param name='adoxioSpecialeventid'>
/// key: adoxio_specialeventid of adoxio_specialevent
/// </param>
/// <param name='top'>
/// </param>
/// <param name='skip'>
/// </param>
/// <param name='search'>
/// </param>
/// <param name='filter'>
/// </param>
/// <param name='count'>
/// </param>
/// <param name='orderby'>
/// Order items by property values
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<MicrosoftDynamicsCRMinvoiceCollection>> GetWithHttpMessagesAsync(string adoxioSpecialeventid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get adoxio_specialevent_invoices from adoxio_specialevents
/// </summary>
/// <param name='adoxioSpecialeventid'>
/// key: adoxio_specialeventid of adoxio_specialevent
/// </param>
/// <param name='invoiceid'>
/// key: invoiceid of invoice
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<MicrosoftDynamicsCRMinvoice>> InvoicesByKeyWithHttpMessagesAsync(string adoxioSpecialeventid, string invoiceid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| 43.684211 | 541 | 0.618313 | [
"Apache-2.0"
] | BrendanBeachBC/jag-lcrb-carla-public | cllc-interfaces/Dynamics-Autorest/ISpecialeventinvoices.cs | 4,150 | C# |
/*************************************************************************************************************************************
* Developed by Mamadou Cisse *
* Mail => mciissee@gmail.com *
* Twitter => http://www.twitter.com/IncMce *
* Infinity Interactive Unity Asset Store catalog: http://u3d.as/riS *
*************************************************************************************************************************************/
namespace InfinityEditor
{
using UnityEngine;
using UnityEditor;
using System;
using InfinityEngine.Utils;
using UnityEditor.AnimatedValues;
/// <summary>
/// Represents a simple collapsible area
/// </summary>
[Serializable]
public class SimpleAccordion
{
#region Fields
private Color backgroundColor;
private float backgroundAlpha;
private GUIStyle headerStyle;
private Rect headerRect;
private AnimBool animation;
/// <summary>
/// Callback action invoked when the expand state of the accordion changes
/// </summary>
public Action<SimpleAccordion> expandStateChangeCallback;
/// <summary>
/// Invoked when the accordion is opened
/// </summary>
public Action onOpenedCallback;
/// <summary>
/// Invoked when the accordion is closed
/// </summary>
public Action onClosedCallback;
/// <summary>
/// Use this field to overrides the draw function of the header (the function must return the position of the header)
/// </summary>
public Func<Rect> drawHeaderCallback;
/// <summary>
/// The draw function of the contents.
/// </summary>
public Action drawCallback;
private bool isFirstExpand;
#endregion Fields
#region Properties
/// <summary>
/// Gets or sets the speed of the animation
/// </summary>
public float Speed { get { return animation.speed; } set { animation.speed = value; } }
/// <summary>
/// The title of the accordion
/// </summary>
public string Title { get; set; }
/// <summary>
/// Gets or sets the expand state of the accordion
/// </summary>
public bool IsExpanded
{
get { return animation.target; }
set { animation.target = value; }
}
/// <summary>
/// Returns the float value of the fade animation in the range [0,1]
/// </summary>
public float Faded
{
get { return animation.faded; }
}
#endregion Properties
#region Constructors
public SimpleAccordion() : this(string.Empty, null, null) { }
public SimpleAccordion(string title) : this(title, null, null) { }
public SimpleAccordion(Action drawCallback) : this(string.Empty, null, drawCallback) { }
public SimpleAccordion(string title, Action drawCallback) : this(title, null, drawCallback) { }
public SimpleAccordion(Func<Rect> drawHeaderCallback, Action drawCallback) : this(string.Empty, drawHeaderCallback, drawCallback){}
public SimpleAccordion(string title, Func<Rect> drawHeaderCallback, Action drawCallback)
{
this.Title = title;
this.drawHeaderCallback = drawHeaderCallback;
this.drawCallback = drawCallback;
animation = new AnimBool();
animation.target = false;
isFirstExpand = true;
}
#endregion Constructors
/// <summary>
/// Draws the body of the accordion with <see cref="EditorStyles.helpBox"/> style
/// </summary>
public void OnGUI()
{
OnGUI(EditorStyles.helpBox);
}
/// <summary>
/// Draws the body of the accordion with the given style
/// </summary>
/// <param name="style">The style to use</param>
public void OnGUI(GUIStyle style)
{
backgroundColor = GUI.backgroundColor;
backgroundAlpha = backgroundColor.a;
backgroundColor.a = 1f;
GUI.backgroundColor = backgroundColor;
EditorGUILayout.BeginVertical(style);
if(drawHeaderCallback != null)
{
headerRect = drawHeaderCallback.Invoke();
}
else
{
headerRect = DrawDefaultAccordionHeader(this);
}
ProcessEvents(Event.current);
if(IsExpanded && isFirstExpand)
{
if(Faded >= 1)
{
isFirstExpand = false;
}
if (drawCallback != null)
{
drawCallback.Invoke();
}
}
else
{
if (EditorGUILayout.BeginFadeGroup(animation.faded))
{
if (drawCallback != null)
{
drawCallback.Invoke();
}
}
EditorGUILayout.EndFadeGroup();
}
EditorGUILayout.EndVertical();
backgroundColor.a = backgroundAlpha;
GUI.backgroundColor = backgroundColor;
}
private void ProcessEvents(Event evt)
{
if (evt.type == EventType.MouseDown && headerRect.Contains(evt.mousePosition))
{
IsExpanded = !IsExpanded;
if(IsExpanded && onOpenedCallback != null)
{
onOpenedCallback.Invoke();
}
if (!IsExpanded && onClosedCallback != null)
{
onClosedCallback.Invoke();
}
if (expandStateChangeCallback != null)
{
expandStateChangeCallback.Invoke(this);
}
evt.Use();
}
}
public Rect DrawDefaultAccordionHeader(int height = 20, int fontSize = 14)
{
return DrawDefaultAccordionHeader(this, height, fontSize);
}
public Rect DrawDefaultAccordionHeader(string icon, int height = 20, int fontSize = 14)
{
return DrawDefaultAccordionHeader(this, height, fontSize);
}
public static Rect DrawDefaultAccordionHeader(SimpleAccordion accordion, int height = 20, int fontSize = 14)
{
var icon = accordion.IsExpanded ? FA.angle_double_down : FA.angle_double_right;
return DrawDefaultAccordionHeader(accordion, icon, height, fontSize);
}
public static Rect DrawDefaultAccordionHeader(SimpleAccordion accordion, string icon, int height = 20, int fontSize = 14)
{
if(accordion.headerStyle == null)
{
accordion.headerStyle = new GUIStyle(AssetReferences.AccordionHeader);
}
accordion.headerStyle.fontSize = fontSize;
GUILayout.Box(accordion.Title, accordion.headerStyle, GUILayout.ExpandWidth(true), GUILayout.Height(height));
var rect = GUILayoutUtility.GetLastRect();
DrawerHelper.FAIcon(rect, icon, FAOption.TextAnchor(TextAnchor.MiddleLeft),
//FAOption.FontSize(fontSize),
FAOption.Padding(new RectOffset(5, 0, 0, 0))
);
return rect;
}
}
}
| 33.908714 | 141 | 0.491557 | [
"MIT"
] | mciissee/CutTheWood | Assets/InfinityEngine/Editor/Utils/SimpleAccordion.cs | 8,174 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.