content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using System;
using System.Collections;
using System.Collections.Generic;
namespace Microsoft.Azure.PowerShell.Cmdlets.EdgeOrder.Runtime.Json
{
internal sealed class XList<T> : JsonArray, IEnumerable<JsonNode>
{
private readonly IList<T> values;
private readonly JsonType elementType;
private readonly TypeCode elementCode;
internal XList(IList<T> values)
{
this.values = values ?? throw new ArgumentNullException(nameof(values));
this.elementCode = System.Type.GetTypeCode(typeof(T));
this.elementType = XHelper.GetElementType(this.elementCode);
}
public override JsonNode this[int index] =>
XHelper.Create(elementType, elementCode, values[index]);
internal override JsonType? ElementType => elementType;
public override int Count => values.Count;
public bool IsReadOnly => values.IsReadOnly;
#region IList
public void Add(T value)
{
values.Add(value);
}
public bool Contains(T value) => values.Contains(value);
#endregion
#region IEnumerable Members
IEnumerator<JsonNode> IEnumerable<JsonNode>.GetEnumerator()
{
foreach (var value in values)
{
yield return XHelper.Create(elementType, elementCode, value);
}
}
IEnumerator IEnumerable.GetEnumerator()
{
foreach (var value in values)
{
yield return XHelper.Create(elementType, elementCode, value);
}
}
#endregion
}
} | 32.25 | 97 | 0.546027 | [
"MIT"
] | Agazoth/azure-powershell | src/EdgeOrder/generated/runtime/Nodes/Collections/XList.cs | 2,003 | C# |
using UI_Context.Classes.Templates.Dialogs;
namespace UI_Context.Classes.Context.Dialogs
{
public class GradeInfoDialogContext
{
//--------------------------------------------------------Attributes:-----------------------------------------------------------------\\
#region --Attributes--
public readonly GradeInfoDialogDataTemplate MODEL = new GradeInfoDialogDataTemplate();
#endregion
//--------------------------------------------------------Constructor:----------------------------------------------------------------\\
#region --Constructors--
#endregion
//--------------------------------------------------------Set-, Get- Methods:---------------------------------------------------------\\
#region --Set-, Get- Methods--
#endregion
//--------------------------------------------------------Misc Methods:---------------------------------------------------------------\\
#region --Misc Methods (Public)--
#endregion
#region --Misc Methods (Private)--
#endregion
#region --Misc Methods (Protected)--
#endregion
//--------------------------------------------------------Events:---------------------------------------------------------------------\\
#region --Events--
#endregion
}
}
| 31.25 | 144 | 0.319273 | [
"MIT"
] | COM8/TUM_Campus_App_UWP | UI_Context/Classes/Context/Dialogs/GradeInfoDialogContext.cs | 1,377 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#if !SILVERLIGHT // ComObject
namespace System.Management.Automation.ComInterop
{
internal class ComTypeLibMemberDesc
{
internal ComTypeLibMemberDesc(ComType kind)
{
Kind = kind;
}
public ComType Kind { get; }
}
}
#endif
| 17 | 51 | 0.638655 | [
"MIT"
] | 202006233011/PowerShell | src/System.Management.Automation/engine/ComInterop/ComTypeLibMemberDesc.cs | 357 | C# |
using System;
using System.IO;
using System.Text;
namespace ICSharpCode.SharpZipLib.Tar
{
/// <summary>
/// Used to advise clients of 'events' while processing archives
/// </summary>
public delegate void ProgressMessageHandler(TarArchive archive, TarEntry entry, string message);
/// <summary>
/// The TarArchive class implements the concept of a
/// 'Tape Archive'. A tar archive is a series of entries, each of
/// which represents a file system object. Each entry in
/// the archive consists of a header block followed by 0 or more data blocks.
/// Directory entries consist only of the header block, and are followed by entries
/// for the directory's contents. File entries consist of a
/// header followed by the number of blocks needed to
/// contain the file's contents. All entries are written on
/// block boundaries. Blocks are 512 bytes long.
///
/// TarArchives are instantiated in either read or write mode,
/// based upon whether they are instantiated with an InputStream
/// or an OutputStream. Once instantiated TarArchives read/write
/// mode can not be changed.
///
/// There is currently no support for random access to tar archives.
/// However, it seems that subclassing TarArchive, and using the
/// TarBuffer.CurrentRecord and TarBuffer.CurrentBlock
/// properties, this would be rather trivial.
/// </summary>
public class TarArchive : IDisposable
{
/// <summary>
/// Client hook allowing detailed information to be reported during processing
/// </summary>
public event ProgressMessageHandler ProgressMessageEvent;
/// <summary>
/// Raises the ProgressMessage event
/// </summary>
/// <param name="entry">The <see cref="TarEntry">TarEntry</see> for this event</param>
/// <param name="message">message for this event. Null is no message</param>
protected virtual void OnProgressMessageEvent(TarEntry entry, string message)
{
ProgressMessageHandler handler = ProgressMessageEvent;
if (handler != null) {
handler(this, entry, message);
}
}
#region Constructors
/// <summary>
/// Constructor for a default <see cref="TarArchive"/>.
/// </summary>
protected TarArchive()
{
}
/// <summary>
/// Initalise a TarArchive for input.
/// </summary>
/// <param name="stream">The <see cref="TarInputStream"/> to use for input.</param>
protected TarArchive(TarInputStream stream)
{
if (stream == null) {
throw new ArgumentNullException(nameof(stream));
}
tarIn = stream;
}
/// <summary>
/// Initialise a TarArchive for output.
/// </summary>
/// <param name="stream">The <see cref="TarOutputStream"/> to use for output.</param>
protected TarArchive(TarOutputStream stream)
{
if (stream == null) {
throw new ArgumentNullException(nameof(stream));
}
tarOut = stream;
}
#endregion
#region Static factory methods
/// <summary>
/// The InputStream based constructors create a TarArchive for the
/// purposes of extracting or listing a tar archive. Thus, use
/// these constructors when you wish to extract files from or list
/// the contents of an existing tar archive.
/// </summary>
/// <param name="inputStream">The stream to retrieve archive data from.</param>
/// <returns>Returns a new <see cref="TarArchive"/> suitable for reading from.</returns>
public static TarArchive CreateInputTarArchive(Stream inputStream)
{
if (inputStream == null) {
throw new ArgumentNullException(nameof(inputStream));
}
var tarStream = inputStream as TarInputStream;
TarArchive result;
if (tarStream != null) {
result = new TarArchive(tarStream);
} else {
result = CreateInputTarArchive(inputStream, TarBuffer.DefaultBlockFactor);
}
return result;
}
/// <summary>
/// Create TarArchive for reading setting block factor
/// </summary>
/// <param name="inputStream">A stream containing the tar archive contents</param>
/// <param name="blockFactor">The blocking factor to apply</param>
/// <returns>Returns a <see cref="TarArchive"/> suitable for reading.</returns>
public static TarArchive CreateInputTarArchive(Stream inputStream, int blockFactor)
{
if (inputStream == null) {
throw new ArgumentNullException(nameof(inputStream));
}
if (inputStream is TarInputStream) {
throw new ArgumentException("TarInputStream not valid");
}
return new TarArchive(new TarInputStream(inputStream, blockFactor));
}
/// <summary>
/// Create a TarArchive for writing to, using the default blocking factor
/// </summary>
/// <param name="outputStream">The <see cref="Stream"/> to write to</param>
/// <returns>Returns a <see cref="TarArchive"/> suitable for writing.</returns>
public static TarArchive CreateOutputTarArchive(Stream outputStream)
{
if (outputStream == null) {
throw new ArgumentNullException(nameof(outputStream));
}
var tarStream = outputStream as TarOutputStream;
TarArchive result;
if (tarStream != null) {
result = new TarArchive(tarStream);
} else {
result = CreateOutputTarArchive(outputStream, TarBuffer.DefaultBlockFactor);
}
return result;
}
/// <summary>
/// Create a <see cref="TarArchive">tar archive</see> for writing.
/// </summary>
/// <param name="outputStream">The stream to write to</param>
/// <param name="blockFactor">The blocking factor to use for buffering.</param>
/// <returns>Returns a <see cref="TarArchive"/> suitable for writing.</returns>
public static TarArchive CreateOutputTarArchive(Stream outputStream, int blockFactor)
{
if (outputStream == null) {
throw new ArgumentNullException(nameof(outputStream));
}
if (outputStream is TarOutputStream) {
throw new ArgumentException("TarOutputStream is not valid");
}
return new TarArchive(new TarOutputStream(outputStream, blockFactor));
}
#endregion
/// <summary>
/// Set the flag that determines whether existing files are
/// kept, or overwritten during extraction.
/// </summary>
/// <param name="keepExistingFiles">
/// If true, do not overwrite existing files.
/// </param>
public void SetKeepOldFiles(bool keepExistingFiles)
{
if (isDisposed) {
throw new ObjectDisposedException("TarArchive");
}
keepOldFiles = keepExistingFiles;
}
/// <summary>
/// Get/set the ascii file translation flag. If ascii file translation
/// is true, then the file is checked to see if it a binary file or not.
/// If the flag is true and the test indicates it is ascii text
/// file, it will be translated. The translation converts the local
/// operating system's concept of line ends into the UNIX line end,
/// '\n', which is the defacto standard for a TAR archive. This makes
/// text files compatible with UNIX.
/// </summary>
public bool AsciiTranslate {
get {
if (isDisposed) {
throw new ObjectDisposedException("TarArchive");
}
return asciiTranslate;
}
set {
if (isDisposed) {
throw new ObjectDisposedException("TarArchive");
}
asciiTranslate = value;
}
}
/// <summary>
/// Set the ascii file translation flag.
/// </summary>
/// <param name= "translateAsciiFiles">
/// If true, translate ascii text files.
/// </param>
[Obsolete("Use the AsciiTranslate property")]
public void SetAsciiTranslation(bool translateAsciiFiles)
{
if (isDisposed) {
throw new ObjectDisposedException("TarArchive");
}
asciiTranslate = translateAsciiFiles;
}
/// <summary>
/// PathPrefix is added to entry names as they are written if the value is not null.
/// A slash character is appended after PathPrefix
/// </summary>
public string PathPrefix {
get {
if (isDisposed) {
throw new ObjectDisposedException("TarArchive");
}
return pathPrefix;
}
set {
if (isDisposed) {
throw new ObjectDisposedException("TarArchive");
}
pathPrefix = value;
}
}
/// <summary>
/// RootPath is removed from entry names if it is found at the
/// beginning of the name.
/// </summary>
public string RootPath {
get {
if (isDisposed) {
throw new ObjectDisposedException("TarArchive");
}
return rootPath;
}
set {
if (isDisposed) {
throw new ObjectDisposedException("TarArchive");
}
// Convert to forward slashes for matching. Trim trailing / for correct final path
rootPath = value.Replace('\\', '/').TrimEnd('/');
}
}
/// <summary>
/// Set user and group information that will be used to fill in the
/// tar archive's entry headers. This information is based on that available
/// for the linux operating system, which is not always available on other
/// operating systems. TarArchive allows the programmer to specify values
/// to be used in their place.
/// <see cref="ApplyUserInfoOverrides"/> is set to true by this call.
/// </summary>
/// <param name="userId">
/// The user id to use in the headers.
/// </param>
/// <param name="userName">
/// The user name to use in the headers.
/// </param>
/// <param name="groupId">
/// The group id to use in the headers.
/// </param>
/// <param name="groupName">
/// The group name to use in the headers.
/// </param>
public void SetUserInfo(int userId, string userName, int groupId, string groupName)
{
if (isDisposed) {
throw new ObjectDisposedException("TarArchive");
}
this.userId = userId;
this.userName = userName;
this.groupId = groupId;
this.groupName = groupName;
applyUserInfoOverrides = true;
}
/// <summary>
/// Get or set a value indicating if overrides defined by <see cref="SetUserInfo">SetUserInfo</see> should be applied.
/// </summary>
/// <remarks>If overrides are not applied then the values as set in each header will be used.</remarks>
public bool ApplyUserInfoOverrides {
get {
if (isDisposed) {
throw new ObjectDisposedException("TarArchive");
}
return applyUserInfoOverrides;
}
set {
if (isDisposed) {
throw new ObjectDisposedException("TarArchive");
}
applyUserInfoOverrides = value;
}
}
/// <summary>
/// Get the archive user id.
/// See <see cref="ApplyUserInfoOverrides">ApplyUserInfoOverrides</see> for detail
/// on how to allow setting values on a per entry basis.
/// </summary>
/// <returns>
/// The current user id.
/// </returns>
public int UserId {
get {
if (isDisposed) {
throw new ObjectDisposedException("TarArchive");
}
return userId;
}
}
/// <summary>
/// Get the archive user name.
/// See <see cref="ApplyUserInfoOverrides">ApplyUserInfoOverrides</see> for detail
/// on how to allow setting values on a per entry basis.
/// </summary>
/// <returns>
/// The current user name.
/// </returns>
public string UserName {
get {
if (isDisposed) {
throw new ObjectDisposedException("TarArchive");
}
return userName;
}
}
/// <summary>
/// Get the archive group id.
/// See <see cref="ApplyUserInfoOverrides">ApplyUserInfoOverrides</see> for detail
/// on how to allow setting values on a per entry basis.
/// </summary>
/// <returns>
/// The current group id.
/// </returns>
public int GroupId {
get {
if (isDisposed) {
throw new ObjectDisposedException("TarArchive");
}
return groupId;
}
}
/// <summary>
/// Get the archive group name.
/// See <see cref="ApplyUserInfoOverrides">ApplyUserInfoOverrides</see> for detail
/// on how to allow setting values on a per entry basis.
/// </summary>
/// <returns>
/// The current group name.
/// </returns>
public string GroupName {
get {
if (isDisposed) {
throw new ObjectDisposedException("TarArchive");
}
return groupName;
}
}
/// <summary>
/// Get the archive's record size. Tar archives are composed of
/// a series of RECORDS each containing a number of BLOCKS.
/// This allowed tar archives to match the IO characteristics of
/// the physical device being used. Archives are expected
/// to be properly "blocked".
/// </summary>
/// <returns>
/// The record size this archive is using.
/// </returns>
public int RecordSize {
get {
if (isDisposed) {
throw new ObjectDisposedException("TarArchive");
}
if (tarIn != null) {
return tarIn.RecordSize;
} else if (tarOut != null) {
return tarOut.RecordSize;
}
return TarBuffer.DefaultRecordSize;
}
}
/// <summary>
/// Sets the IsStreamOwner property on the underlying stream.
/// Set this to false to prevent the Close of the TarArchive from closing the stream.
/// </summary>
public bool IsStreamOwner {
set {
if (tarIn != null) {
tarIn.IsStreamOwner = value;
} else {
tarOut.IsStreamOwner = value;
}
}
}
/// <summary>
/// Close the archive.
/// </summary>
[Obsolete("Use Close instead")]
public void CloseArchive()
{
Close();
}
/// <summary>
/// Perform the "list" command for the archive contents.
///
/// NOTE That this method uses the <see cref="ProgressMessageEvent"> progress event</see> to actually list
/// the contents. If the progress display event is not set, nothing will be listed!
/// </summary>
public void ListContents()
{
if (isDisposed) {
throw new ObjectDisposedException("TarArchive");
}
while (true) {
TarEntry entry = tarIn.GetNextEntry();
if (entry == null) {
break;
}
OnProgressMessageEvent(entry, null);
}
}
/// <summary>
/// Perform the "extract" command and extract the contents of the archive.
/// </summary>
/// <param name="destinationDirectory">
/// The destination directory into which to extract.
/// </param>
public void ExtractContents(string destinationDirectory)
{
if (isDisposed) {
throw new ObjectDisposedException("TarArchive");
}
while (true) {
TarEntry entry = tarIn.GetNextEntry();
if (entry == null) {
break;
}
if (entry.TarHeader.TypeFlag == TarHeader.LF_LINK || entry.TarHeader.TypeFlag == TarHeader.LF_SYMLINK)
continue;
ExtractEntry(destinationDirectory, entry);
}
}
/// <summary>
/// Extract an entry from the archive. This method assumes that the
/// tarIn stream has been properly set with a call to GetNextEntry().
/// </summary>
/// <param name="destDir">
/// The destination directory into which to extract.
/// </param>
/// <param name="entry">
/// The TarEntry returned by tarIn.GetNextEntry().
/// </param>
void ExtractEntry(string destDir, TarEntry entry)
{
OnProgressMessageEvent(entry, null);
string name = entry.Name;
if (Path.IsPathRooted(name)) {
// NOTE:
// for UNC names... \\machine\share\zoom\beet.txt gives \zoom\beet.txt
name = name.Substring(Path.GetPathRoot(name).Length);
}
name = name.Replace('/', Path.DirectorySeparatorChar);
string destFile = Path.Combine(destDir, name);
if (entry.IsDirectory) {
EnsureDirectoryExists(destFile);
} else {
string parentDirectory = Path.GetDirectoryName(destFile);
EnsureDirectoryExists(parentDirectory);
bool process = true;
var fileInfo = new FileInfo(destFile);
if (fileInfo.Exists) {
if (keepOldFiles) {
OnProgressMessageEvent(entry, "Destination file already exists");
process = false;
} else if ((fileInfo.Attributes & FileAttributes.ReadOnly) != 0) {
OnProgressMessageEvent(entry, "Destination file already exists, and is read-only");
process = false;
}
}
if (process) {
bool asciiTrans = false;
Stream outputStream = File.Create(destFile);
if (this.asciiTranslate) {
asciiTrans = !IsBinary(destFile);
}
StreamWriter outw = null;
if (asciiTrans) {
outw = new StreamWriter(outputStream);
}
byte[] rdbuf = new byte[32 * 1024];
while (true) {
int numRead = tarIn.Read(rdbuf, 0, rdbuf.Length);
if (numRead <= 0) {
break;
}
if (asciiTrans) {
for (int off = 0, b = 0; b < numRead; ++b) {
if (rdbuf[b] == 10) {
string s = Encoding.ASCII.GetString(rdbuf, off, (b - off));
outw.WriteLine(s);
off = b + 1;
}
}
} else {
outputStream.Write(rdbuf, 0, numRead);
}
}
if (asciiTrans) {
outw.Dispose();
} else {
outputStream.Dispose();
}
}
}
}
/// <summary>
/// Write an entry to the archive. This method will call the putNextEntry
/// and then write the contents of the entry, and finally call closeEntry()
/// for entries that are files. For directories, it will call putNextEntry(),
/// and then, if the recurse flag is true, process each entry that is a
/// child of the directory.
/// </summary>
/// <param name="sourceEntry">
/// The TarEntry representing the entry to write to the archive.
/// </param>
/// <param name="recurse">
/// If true, process the children of directory entries.
/// </param>
public void WriteEntry(TarEntry sourceEntry, bool recurse)
{
if (sourceEntry == null) {
throw new ArgumentNullException(nameof(sourceEntry));
}
if (isDisposed) {
throw new ObjectDisposedException("TarArchive");
}
try {
if (recurse) {
TarHeader.SetValueDefaults(sourceEntry.UserId, sourceEntry.UserName,
sourceEntry.GroupId, sourceEntry.GroupName);
}
WriteEntryCore(sourceEntry, recurse);
} finally {
if (recurse) {
TarHeader.RestoreSetValues();
}
}
}
/// <summary>
/// Write an entry to the archive. This method will call the putNextEntry
/// and then write the contents of the entry, and finally call closeEntry()
/// for entries that are files. For directories, it will call putNextEntry(),
/// and then, if the recurse flag is true, process each entry that is a
/// child of the directory.
/// </summary>
/// <param name="sourceEntry">
/// The TarEntry representing the entry to write to the archive.
/// </param>
/// <param name="recurse">
/// If true, process the children of directory entries.
/// </param>
void WriteEntryCore(TarEntry sourceEntry, bool recurse)
{
string tempFileName = null;
string entryFilename = sourceEntry.File;
var entry = (TarEntry)sourceEntry.Clone();
if (applyUserInfoOverrides) {
entry.GroupId = groupId;
entry.GroupName = groupName;
entry.UserId = userId;
entry.UserName = userName;
}
OnProgressMessageEvent(entry, null);
if (asciiTranslate && !entry.IsDirectory) {
if (!IsBinary(entryFilename)) {
tempFileName = Path.GetTempFileName();
using (StreamReader inStream = File.OpenText(entryFilename)) {
using (Stream outStream = File.Create(tempFileName)) {
while (true) {
string line = inStream.ReadLine();
if (line == null) {
break;
}
byte[] data = Encoding.ASCII.GetBytes(line);
outStream.Write(data, 0, data.Length);
outStream.WriteByte((byte)'\n');
}
outStream.Flush();
}
}
entry.Size = new FileInfo(tempFileName).Length;
entryFilename = tempFileName;
}
}
string newName = null;
if (rootPath != null) {
if (entry.Name.StartsWith(rootPath, StringComparison.OrdinalIgnoreCase)) {
newName = entry.Name.Substring(rootPath.Length + 1);
}
}
if (pathPrefix != null) {
newName = (newName == null) ? pathPrefix + "/" + entry.Name : pathPrefix + "/" + newName;
}
if (newName != null) {
entry.Name = newName;
}
tarOut.PutNextEntry(entry);
if (entry.IsDirectory) {
if (recurse) {
TarEntry[] list = entry.GetDirectoryEntries();
for (int i = 0; i < list.Length; ++i) {
WriteEntryCore(list[i], recurse);
}
}
} else {
using (Stream inputStream = File.OpenRead(entryFilename)) {
byte[] localBuffer = new byte[32 * 1024];
while (true) {
int numRead = inputStream.Read(localBuffer, 0, localBuffer.Length);
if (numRead <= 0) {
break;
}
tarOut.Write(localBuffer, 0, numRead);
}
}
if (!string.IsNullOrEmpty(tempFileName)) {
File.Delete(tempFileName);
}
tarOut.CloseEntry();
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases the unmanaged resources used by the FileStream and optionally releases the managed resources.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources;
/// false to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (!isDisposed) {
isDisposed = true;
if (disposing) {
if (tarOut != null) {
tarOut.Flush();
tarOut.Dispose();
}
if (tarIn != null) {
tarIn.Dispose();
}
}
}
}
/// <summary>
/// Closes the archive and releases any associated resources.
/// </summary>
public virtual void Close()
{
Dispose(true);
}
/// <summary>
/// Ensures that resources are freed and other cleanup operations are performed
/// when the garbage collector reclaims the <see cref="TarArchive"/>.
/// </summary>
~TarArchive()
{
Dispose(false);
}
static void EnsureDirectoryExists(string directoryName)
{
if (!Directory.Exists(directoryName)) {
try {
Directory.CreateDirectory(directoryName);
} catch (Exception e) {
throw new TarException("Exception creating directory '" + directoryName + "', " + e.Message, e);
}
}
}
// TODO: TarArchive - Is there a better way to test for a text file?
// It no longer reads entire files into memory but is still a weak test!
// This assumes that byte values 0-7, 14-31 or 255 are binary
// and that all non text files contain one of these values
static bool IsBinary(string filename)
{
using (FileStream fs = File.OpenRead(filename)) {
int sampleSize = Math.Min(4096, (int)fs.Length);
byte[] content = new byte[sampleSize];
int bytesRead = fs.Read(content, 0, sampleSize);
for (int i = 0; i < bytesRead; ++i) {
byte b = content[i];
if ((b < 8) || ((b > 13) && (b < 32)) || (b == 255)) {
return true;
}
}
}
return false;
}
#region Instance Fields
bool keepOldFiles;
bool asciiTranslate;
int userId;
string userName = string.Empty;
int groupId;
string groupName = string.Empty;
string rootPath;
string pathPrefix;
bool applyUserInfoOverrides;
TarInputStream tarIn;
TarOutputStream tarOut;
bool isDisposed;
#endregion
}
}
| 27.476534 | 120 | 0.653966 | [
"MIT"
] | Acidburn0zzz/SharpZipLib | src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs | 22,833 | C# |
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
namespace Plotly.Models.Layouts.Scenes.XAxes
{
/// <summary>
/// Specifies the ordering logic for the case of categorical variables. By default,
/// plotly uses <c>trace</c>, which specifies the order that is present in the
/// data supplied. Set <c>categoryorder</c> to 'category ascending'
/// or 'category descending' if order should be determined by the alphanumerical
/// order of the category names. Set <c>categoryorder</c> to <c>array</c> to
/// derive the ordering from the attribute <c>categoryarray</c>. If a category
/// is not found in the <c>categoryarray</c> array, the sorting behavior for
/// that attribute will be identical to the <c>trace</c> mode. The unspecified
/// categories will follow the categories in <c>categoryarray</c>. Set <c>categoryorder</c>
/// to 'total ascending' or 'total descending' if order should
/// be determined by the numerical order of the values. Similarly, the order
/// can be determined by the min, max, sum, mean or median of all the values.
/// </summary>
[JsonConverter(typeof(EnumConverter))]
public enum CategoryOrderEnum
{
[EnumMember(Value = @"trace")]
Trace = 0,
[EnumMember(Value = @"category ascending")]
CategoryAscending,
[EnumMember(Value = @"category descending")]
CategoryDescending,
[EnumMember(Value = @"array")]
Array,
[EnumMember(Value = @"total ascending")]
TotalAscending,
[EnumMember(Value = @"total descending")]
TotalDescending,
[EnumMember(Value = @"min ascending")]
MinAscending,
[EnumMember(Value = @"min descending")]
MinDescending,
[EnumMember(Value = @"max ascending")]
MaxAscending,
[EnumMember(Value = @"max descending")]
MaxDescending,
[EnumMember(Value = @"sum ascending")]
SumAscending,
[EnumMember(Value = @"sum descending")]
SumDescending,
[EnumMember(Value = @"mean ascending")]
MeanAscending,
[EnumMember(Value = @"mean descending")]
MeanDescending,
[EnumMember(Value = @"median ascending")]
MedianAscending,
[EnumMember(Value = @"median descending")]
MedianDescending
}
}
| 34.194444 | 99 | 0.623477 | [
"MIT"
] | trmcnealy/Plotly.WPF | Plotly/Models/Layouts/Scenes/XAxes/CategoryOrderEnum.cs | 2,462 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//Declare two string variables and assign them with Hello and World.
//Declare an object variable and assign it with the concatenation of the first two variables (mind adding an interval between).
//Declare a third string variable and initialize it with the value of the object variable (you should perform type casting).
namespace _6.Strings_and_Objects
{
class Program
{
static void Main(string[] args)
{
string hello = "Hello!";
string world = "World";
object all = hello + " " + world;
Console.WriteLine(all);
}
}
}
| 30.125 | 127 | 0.676349 | [
"MIT"
] | Das8Beste/Primitive-Data-Types-and-Variables | 6. Strings and Objects/Program.cs | 725 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Exoscale
{
/// <summary>
/// Provides an Exoscale [DNS][dns-doc] domain record resource. This can be used to create, modify, and delete DNS domain records.
///
/// ## Usage example
///
/// ```csharp
/// using Pulumi;
/// using Exoscale = Pulumi.Exoscale;
///
/// class MyStack : Stack
/// {
/// public MyStack()
/// {
/// var example = new Exoscale.Domain("example", new Exoscale.DomainArgs
/// {
/// });
/// var myserver = new Exoscale.DomainRecord("myserver", new Exoscale.DomainRecordArgs
/// {
/// Domain = example.Id,
/// RecordType = "A",
/// Content = "1.2.3.4",
/// });
/// var myserverAlias = new Exoscale.DomainRecord("myserverAlias", new Exoscale.DomainRecordArgs
/// {
/// Domain = example.Id,
/// RecordType = "CNAME",
/// Content = myserver.Hostname,
/// });
/// }
///
/// }
/// ```
///
/// ## Import
///
/// An existing DNS domain record can be imported as a resource by IDconsole
///
/// ```sh
/// $ pulumi import exoscale:index/domainRecord:DomainRecord www 12480484
/// ```
///
/// [dns-doc]https://community.exoscale.com/documentation/dns/ [r-domain]domain.html [ttl]https://en.wikipedia.org/wiki/Time_to_live
/// </summary>
[ExoscaleResourceType("exoscale:index/domainRecord:DomainRecord")]
public partial class DomainRecord : Pulumi.CustomResource
{
/// <summary>
/// The value of the domain record.
/// </summary>
[Output("content")]
public Output<string> Content { get; private set; } = null!;
/// <summary>
/// The name of the [`exoscale.Domain`][r-domain] to create the record into.
/// </summary>
[Output("domain")]
public Output<string> Domain { get; private set; } = null!;
/// <summary>
/// The DNS domain record's *Fully Qualified Domain Name* (FQDN), useful for linking `A` records into `CNAME`.
/// </summary>
[Output("hostname")]
public Output<string> Hostname { get; private set; } = null!;
/// <summary>
/// The name of the domain record; leave blank (`""`) to create a root record (similar to using `@` in a DNS zone file).
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// The priority of the DNS domain record (for types that support it).
/// </summary>
[Output("prio")]
public Output<int> Prio { get; private set; } = null!;
/// <summary>
/// The type of the domain record. Supported values are: `A`, `AAAA`, `ALIAS`, `CAA`, `CNAME`, `HINFO`, `MX`, `NAPTR`, `NS`, `POOL`, `SPF`, `SRV`, `SSHFP`, `TXT`, `URL`.
/// </summary>
[Output("recordType")]
public Output<string> RecordType { get; private set; } = null!;
/// <summary>
/// The [Time To Live][ttl] of the domain record.
/// </summary>
[Output("ttl")]
public Output<int> Ttl { get; private set; } = null!;
/// <summary>
/// Create a DomainRecord 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 DomainRecord(string name, DomainRecordArgs args, CustomResourceOptions? options = null)
: base("exoscale:index/domainRecord:DomainRecord", name, args ?? new DomainRecordArgs(), MakeResourceOptions(options, ""))
{
}
private DomainRecord(string name, Input<string> id, DomainRecordState? state = null, CustomResourceOptions? options = null)
: base("exoscale:index/domainRecord:DomainRecord", name, state, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing DomainRecord resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="state">Any extra arguments used during the lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static DomainRecord Get(string name, Input<string> id, DomainRecordState? state = null, CustomResourceOptions? options = null)
{
return new DomainRecord(name, id, state, options);
}
}
public sealed class DomainRecordArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The value of the domain record.
/// </summary>
[Input("content", required: true)]
public Input<string> Content { get; set; } = null!;
/// <summary>
/// The name of the [`exoscale.Domain`][r-domain] to create the record into.
/// </summary>
[Input("domain", required: true)]
public Input<string> Domain { get; set; } = null!;
/// <summary>
/// The name of the domain record; leave blank (`""`) to create a root record (similar to using `@` in a DNS zone file).
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// The priority of the DNS domain record (for types that support it).
/// </summary>
[Input("prio")]
public Input<int>? Prio { get; set; }
/// <summary>
/// The type of the domain record. Supported values are: `A`, `AAAA`, `ALIAS`, `CAA`, `CNAME`, `HINFO`, `MX`, `NAPTR`, `NS`, `POOL`, `SPF`, `SRV`, `SSHFP`, `TXT`, `URL`.
/// </summary>
[Input("recordType", required: true)]
public Input<string> RecordType { get; set; } = null!;
/// <summary>
/// The [Time To Live][ttl] of the domain record.
/// </summary>
[Input("ttl")]
public Input<int>? Ttl { get; set; }
public DomainRecordArgs()
{
}
}
public sealed class DomainRecordState : Pulumi.ResourceArgs
{
/// <summary>
/// The value of the domain record.
/// </summary>
[Input("content")]
public Input<string>? Content { get; set; }
/// <summary>
/// The name of the [`exoscale.Domain`][r-domain] to create the record into.
/// </summary>
[Input("domain")]
public Input<string>? Domain { get; set; }
/// <summary>
/// The DNS domain record's *Fully Qualified Domain Name* (FQDN), useful for linking `A` records into `CNAME`.
/// </summary>
[Input("hostname")]
public Input<string>? Hostname { get; set; }
/// <summary>
/// The name of the domain record; leave blank (`""`) to create a root record (similar to using `@` in a DNS zone file).
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// The priority of the DNS domain record (for types that support it).
/// </summary>
[Input("prio")]
public Input<int>? Prio { get; set; }
/// <summary>
/// The type of the domain record. Supported values are: `A`, `AAAA`, `ALIAS`, `CAA`, `CNAME`, `HINFO`, `MX`, `NAPTR`, `NS`, `POOL`, `SPF`, `SRV`, `SSHFP`, `TXT`, `URL`.
/// </summary>
[Input("recordType")]
public Input<string>? RecordType { get; set; }
/// <summary>
/// The [Time To Live][ttl] of the domain record.
/// </summary>
[Input("ttl")]
public Input<int>? Ttl { get; set; }
public DomainRecordState()
{
}
}
}
| 38.351695 | 177 | 0.55574 | [
"ECL-2.0",
"Apache-2.0"
] | secustor/pulumi-exoscale | sdk/dotnet/DomainRecord.cs | 9,051 | C# |
using System;
using System.Diagnostics.Contracts;
using System.Drawing;
using System.Linq;
using ReClassNET.UI;
namespace ReClassNET.Nodes
{
public delegate void ClassCreatedEventHandler(ClassNode node);
public class ClassNode : BaseContainerNode
{
public static event ClassCreatedEventHandler ClassCreated;
#if RECLASSNET64
public static IntPtr DefaultAddress { get; } = (IntPtr)0x140000000;
public static string DefaultAddressFormula { get; } = "140000000";
#else
public static IntPtr DefaultAddress { get; } = (IntPtr)0x400000;
public static string DefaultAddressFormula { get; } = "400000";
#endif
public override int MemorySize => Nodes.Sum(n => n.MemorySize);
protected override bool ShouldCompensateSizeChanges => true;
private NodeUuid uuid;
public NodeUuid Uuid
{
get => uuid;
set
{
Contract.Requires(value != null);
uuid = value;
}
}
public string AddressFormula { get; set; } = DefaultAddressFormula;
public event NodeEventHandler NodesChanged;
internal ClassNode(bool notifyClassCreated)
{
Contract.Ensures(AddressFormula != null);
LevelsOpen.DefaultValue = true;
Uuid = new NodeUuid(true);
if (notifyClassCreated)
{
ClassCreated?.Invoke(this);
}
}
public static ClassNode Create()
{
Contract.Ensures(Contract.Result<ClassNode>() != null);
return new ClassNode(true);
}
public override void GetUserInterfaceInfo(out string name, out Image icon)
{
throw new InvalidOperationException($"The '{nameof(ClassNode)}' node should not be accessible from the ui.");
}
public override bool CanHandleChildNode(BaseNode node)
{
switch (node)
{
case null:
case ClassNode _:
case VirtualMethodNode _:
return false;
}
return true;
}
public override void Initialize()
{
AddBytes(IntPtr.Size);
}
public override Size Draw(ViewInfo view, int x, int y)
{
AddSelection(view, 0, y, view.Font.Height);
var origX = x;
var origY = y;
x = AddOpenCloseIcon(view, x, y);
var tx = x;
x = AddIcon(view, x, y, Icons.Class, HotSpot.NoneId, HotSpotType.None);
x = AddText(view, x, y, view.Settings.OffsetColor, 0, AddressFormula) + view.Font.Width;
x = AddText(view, x, y, view.Settings.TypeColor, HotSpot.NoneId, "Class") + view.Font.Width;
x = AddText(view, x, y, view.Settings.NameColor, HotSpot.NameId, Name) + view.Font.Width;
x = AddText(view, x, y, view.Settings.ValueColor, HotSpot.NoneId, $"[{MemorySize}]") + view.Font.Width;
x = AddComment(view, x, y);
y += view.Font.Height;
var size = new Size(x - origX, y - origY);
if (LevelsOpen[view.Level])
{
var childOffset = tx - origX;
var nv = view.Clone();
nv.Level++;
foreach (var node in Nodes)
{
Size AggregateNodeSizes(Size baseSize, Size newSize)
{
return new Size(Math.Max(baseSize.Width, newSize.Width), baseSize.Height + newSize.Height);
}
Size ExtendWidth(Size baseSize, int width)
{
return new Size(baseSize.Width + width, baseSize.Height);
}
// Draw the node if it is in the visible area.
if (view.ClientArea.Contains(tx, y))
{
var innerSize = node.Draw(nv, tx, y);
size = AggregateNodeSizes(size, ExtendWidth(innerSize, childOffset));
y += innerSize.Height;
}
else
{
// Otherwise calculate the height...
var calculatedHeight = node.CalculateDrawnHeight(nv);
// and check if the node area overlaps with the visible area...
if (new Rectangle(tx, y, 9999999, calculatedHeight).IntersectsWith(view.ClientArea))
{
// then draw the node...
var innerSize = node.Draw(nv, tx, y);
size = AggregateNodeSizes(size, ExtendWidth(innerSize, childOffset));
y += innerSize.Height;
}
else
{
// or skip drawing and just use the calculated height.
size = AggregateNodeSizes(size, new Size(0, calculatedHeight));
y += calculatedHeight;
}
}
}
}
return size;
}
public override int CalculateDrawnHeight(ViewInfo view)
{
if (IsHidden)
{
return HiddenHeight;
}
var height = view.Font.Height;
if (LevelsOpen[view.Level])
{
var nv = view.Clone();
nv.Level++;
height += Nodes.Sum(n => n.CalculateDrawnHeight(nv));
}
return height;
}
public override void Update(HotSpot spot)
{
base.Update(spot);
if (spot.Id == 0)
{
AddressFormula = spot.Text;
}
}
protected internal override void ChildHasChanged(BaseNode child)
{
NodesChanged?.Invoke(this);
}
}
}
| 23.175879 | 112 | 0.658933 | [
"MIT"
] | EliteOutlaws/ReClass.NET | ReClass.NET/Nodes/ClassNode.cs | 4,614 | C# |
//-----------------------------------------------------------------------
// <copyright company="CoApp Project">
// Copyright (c) 2010-2013 Garrett Serack and CoApp Contributors.
// Contributors can be discovered using the 'git log' command.
// All rights reserved.
// </copyright>
// <license>
// The software is licensed under the Apache 2.0 License (the "License")
// You may not use the software except in compliance with the License.
// </license>
//-----------------------------------------------------------------------
namespace ClrPlus.Core.Linq.Serialization.Xml {
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
using System.Xml.Linq;
public sealed class TypeResolver {
private Dictionary<AnonTypeId, Type> anonymousTypes = new Dictionary<AnonTypeId, Type>();
private ModuleBuilder moduleBuilder;
private int anonymousTypeIndex;
/// <summary>
/// KnownTypes for DataContractSerializer. Only needs to hold the element type, not the collection or array type.
/// </summary>
public ReadOnlyCollection<Type> knownTypes {get; private set;}
private HashSet<Assembly> assemblies = new HashSet<Assembly> {
typeof (ExpressionType).Assembly,
typeof (string).Assembly,
typeof (List<>).Assembly,
typeof (XElement).Assembly,
Assembly.GetExecutingAssembly(),
Assembly.GetEntryAssembly(),
};
/// <summary>
/// Relying on the constructor only, to load all possible (including IEnumerable, IQueryable, Nullable, Array) Types into memory, may not scale well.
/// </summary>
/// <param name="assemblies"> </param>
/// <param name="knownTypes"> </param>
public TypeResolver(IEnumerable<Assembly> @assemblies = null, IEnumerable<Type> @knownTypes = null) {
var asmname = new AssemblyName();
asmname.Name = "AnonymousTypes";
var assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(asmname, AssemblyBuilderAccess.Run);
moduleBuilder = assemblyBuilder.DefineDynamicModule("AnonymousTypes");
if (@assemblies != null) {
foreach (var a in @assemblies) {
this.assemblies.Add(a);
}
}
foreach (var n in AppDomain.CurrentDomain.GetAssemblies()) {
this.assemblies.Add(n);
}
var simpleTypes = from t in typeof (String).Assembly.GetTypes()
where
(t.IsPrimitive || t == typeof (String) || t.IsEnum)
&& !(t == typeof (IntPtr) || t == typeof (UIntPtr))
select t;
this.knownTypes = new ReadOnlyCollection<Type>(new List<Type>(simpleTypes.Union(@knownTypes ?? Type.EmptyTypes)));
}
public bool HasMappedKnownType(Type input) {
Type knownType;
return HasMappedKnownType(input, out knownType);
}
/// <summary>
/// Checks if the input Type is "mapped" or otherwise somehow related (e.g. Array) to a KnownType found in this.KnownTypes.
/// </summary>
/// <param name="input"> </param>
/// <param name="knownType"> </param>
/// <returns> </returns>
public bool HasMappedKnownType(Type input, out Type knownType) //out suggestedType?
{
var copy = new HashSet<Type>(knownTypes); //to prevent duplicates.
knownType = null;
//suggestedType = null;
//generic , array , IEnumerable types, IQueryable, Nullable Types...
foreach (var existing in knownTypes) {
if (input == existing) {
knownType = existing;
//suggestedType = knownType;
return true;
} else if (input == existing.MakeArrayType()
|| input == typeof (IEnumerable<>).MakeGenericType(existing)
|| IsIEnumerableOf(input, existing)) {
copy.Add(input);
knownTypes = new ReadOnlyCollection<Type>(new List<Type>(copy));
knownType = existing;
//suggestedType = existing.MakeArrayType();
return true;
} else if (existing.IsValueType && input == typeof (Nullable<>).MakeGenericType(existing)) {
copy.Add(input);
knownTypes = new ReadOnlyCollection<Type>(new List<Type>(copy));
knownType = existing;
//suggestedType = existing;//Nullable.Value instead
return true;
}
}
return false; // knownType != null;
}
//public static bool IsTypeRelated(Type existing, Type input)
//{
// return existing == input
// || (input == existing.MakeArrayType())// || input.IsArray && input.GetElementType() == existing)// |
// || (input == typeof(IEnumerable<>).MakeGenericType(existing))
// || IsIEnumerableOf(input, existing)
// || (existing.IsValueType && input == typeof(Nullable<>).MakeGenericType(existing));
//}
//protected virtual Type ResolveTypeFromString(string typeString) { return null; }
//protected virtual string ResolveStringFromType(Type type) { return null; }
public Type GetType(string typeName, IEnumerable<Type> genericArgumentTypes) {
return GetType(typeName).MakeGenericType(genericArgumentTypes.ToArray());
}
public Type GetType(string typeName) {
Type type;
if (string.IsNullOrEmpty(typeName)) {
throw new ArgumentNullException("typeName");
}
#region// First - try all replacers
//type = ResolveTypeFromString(typeName);
//type = typeReplacers.Select(f => f(typeName)).FirstOrDefault();
//if (type != null)
// return type;
#endregion
// If it's an array name - get the element type and wrap in the array type.
if (typeName.EndsWith("[]")) {
return GetType(typeName.Substring(0, typeName.Length - 2)).MakeArrayType();
}
if (knownTypes.Any(k => k.FullName == typeName)) {
return knownTypes.First(k => k.FullName == typeName);
}
// try all loaded types
foreach (var assembly in assemblies) {
type = assembly.GetType(typeName);
if (type != null) {
return type;
}
}
// Second - try just plain old Type.GetType()
type = Type.GetType(typeName, false, true);
if (type != null) {
return type;
}
throw new ArgumentException("Could not find a matching type", typeName);
}
internal static string GetNameOfExpression(Expression e) {
string name;
if (e is LambdaExpression) {
name = typeof (LambdaExpression).Name;
} else if (e is ParameterExpression) {
name = typeof (ParameterExpression).Name; //PrimitiveParameterExpression?
} else if (e is BinaryExpression) {
name = typeof (BinaryExpression).Name; //SimpleBinaryExpression?
} else if (e is MethodCallExpression) {
name = typeof (MethodCallExpression).Name; //MethodCallExpressionN?
} else {
name = e.GetType().Name;
}
return name;
}
public MethodInfo GetMethod(Type declaringType, string name, Type[] parameterTypes, Type[] genArgTypes) {
var methods = from mi in declaringType.GetMethods()
where mi.Name == name
select mi;
foreach (var method in methods) {
// Would be nice to remvoe the try/catch
try {
var realMethod = method;
if (method.IsGenericMethod) {
realMethod = method.MakeGenericMethod(genArgTypes);
}
var methodParameterTypes = realMethod.GetParameters().Select(p => p.ParameterType);
if (MatchPiecewise(parameterTypes, methodParameterTypes)) {
return realMethod;
}
} catch (ArgumentException) {
continue;
}
}
return null;
}
private bool MatchPiecewise<T>(IEnumerable<T> first, IEnumerable<T> second) {
var firstArray = first.ToArray();
var secondArray = second.ToArray();
if (firstArray.Length != secondArray.Length) {
return false;
}
for (var i = 0; i < firstArray.Length; i++) {
if (!firstArray[i].Equals(secondArray[i])) {
return false;
}
}
return true;
}
//vsadov: need to take ctor parameters too as they do not
//necessarily match properties order as returned by GetProperties
public Type GetOrCreateAnonymousTypeFor(string name, NameTypePair[] properties, NameTypePair[] ctr_params) {
var id = new AnonTypeId(name, properties.Concat(ctr_params));
if (anonymousTypes.ContainsKey(id)) {
return anonymousTypes[id];
}
//vsadov: VB anon type. not necessary, just looks better
var anon_prefix = "<>f__AnonymousType";
var anonTypeBuilder = moduleBuilder.DefineType(anon_prefix + anonymousTypeIndex++, TypeAttributes.Public | TypeAttributes.Class);
var fieldBuilders = new FieldBuilder[properties.Length];
var propertyBuilders = new PropertyBuilder[properties.Length];
for (var i = 0; i < properties.Length; i++) {
fieldBuilders[i] = anonTypeBuilder.DefineField("_generatedfield_" + properties[i].Name, properties[i].Type, FieldAttributes.Private);
propertyBuilders[i] = anonTypeBuilder.DefineProperty(properties[i].Name, PropertyAttributes.None, properties[i].Type, new Type[0]);
var propertyGetterBuilder = anonTypeBuilder.DefineMethod("get_" + properties[i].Name, MethodAttributes.Public, properties[i].Type, new Type[0]);
var getterILGenerator = propertyGetterBuilder.GetILGenerator();
getterILGenerator.Emit(OpCodes.Ldarg_0);
getterILGenerator.Emit(OpCodes.Ldfld, fieldBuilders[i]);
getterILGenerator.Emit(OpCodes.Ret);
propertyBuilders[i].SetGetMethod(propertyGetterBuilder);
}
var constructorBuilder = anonTypeBuilder.DefineConstructor(MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.Public, CallingConventions.Standard, ctr_params.Select(prop => prop.Type).ToArray());
var constructorILGenerator = constructorBuilder.GetILGenerator();
for (var i = 0; i < ctr_params.Length; i++) {
constructorILGenerator.Emit(OpCodes.Ldarg_0);
constructorILGenerator.Emit(OpCodes.Ldarg, i + 1);
constructorILGenerator.Emit(OpCodes.Stfld, fieldBuilders[i]);
constructorBuilder.DefineParameter(i + 1, ParameterAttributes.None, ctr_params[i].Name);
}
constructorILGenerator.Emit(OpCodes.Ret);
//TODO - Define ToString() and GetHashCode implementations for our generated Anonymous Types
//MethodBuilder toStringBuilder = anonTypeBuilder.DefineMethod();
//MethodBuilder getHashCodeBuilder = anonTypeBuilder.DefineMethod();
var anonType = anonTypeBuilder.CreateType();
anonymousTypes.Add(id, anonType);
return anonType;
}
#region static methods
public static Type GetElementType(Type collectionType) {
var ienum = FindIEnumerable(collectionType);
if (ienum == null) {
return collectionType;
}
return ienum.GetGenericArguments()[0];
}
private static Type FindIEnumerable(Type collectionType) {
if (collectionType == null || collectionType == typeof (string)) {
return null;
}
if (collectionType.IsArray) {
return typeof (IEnumerable<>).MakeGenericType(collectionType.GetElementType());
}
if (collectionType.IsGenericType) {
foreach (var arg in collectionType.GetGenericArguments()) {
var ienum = typeof (IEnumerable<>).MakeGenericType(arg);
if (ienum.IsAssignableFrom(collectionType)) {
return ienum;
}
}
}
var ifaces = collectionType.GetInterfaces();
if (ifaces != null && ifaces.Length > 0) {
foreach (var iface in ifaces) {
var ienum = FindIEnumerable(iface);
if (ienum != null) {
return ienum;
}
}
}
if (collectionType.BaseType != null && collectionType.BaseType != typeof (object)) {
return FindIEnumerable(collectionType.BaseType);
}
return null;
}
/// <summary>
/// </summary>
/// <param name="enumerableType"> the candidate enumerable Type in question </param>
/// <param name="elementType"> is the candidate type a IEnumerable of elementType </param>
/// <returns> </returns>
public static bool IsIEnumerableOf(Type enumerableType, Type elementType) {
if (elementType.MakeArrayType() == enumerableType) {
return true;
}
if (!enumerableType.IsGenericType) {
return false;
}
var typeArgs = enumerableType.GetGenericArguments();
if (typeArgs.Length != 1) {
return false;
}
if (!elementType.IsAssignableFrom(typeArgs[0])) {
return false;
}
if (!typeof (IEnumerable<>).MakeGenericType(typeArgs).IsAssignableFrom(enumerableType)) {
return false;
}
return true;
}
public static bool HasBaseType(Type thisType, Type baseType) {
while (thisType.BaseType != null && thisType.BaseType != typeof (Object)) {
if (thisType.BaseType == baseType) {
return true;
}
thisType = thisType.BaseType;
}
return false;
}
public static IEnumerable<Type> GetBaseTypes(Type expectedType) {
var list = new List<Type>();
list.Add(expectedType);
if (expectedType.IsArray) {
expectedType = expectedType.GetElementType();
list.Add(expectedType);
} else {
list.Add(expectedType.MakeArrayType());
}
while (expectedType.BaseType != null && expectedType.BaseType != typeof (Object)) {
expectedType = expectedType.BaseType;
list.Add(expectedType);
}
return list;
}
/// <summary>
/// For determining KnownType(s) to declare on a DataContract
/// </summary>
/// <param name="baseType"> </param>
/// <returns> </returns>
public static List<Type> GetDerivedTypes(Type baseType) {
var a = baseType.Assembly;
var derived = from anyType in a.GetTypes()
where HasBaseType(anyType, baseType)
select anyType;
var list = derived.ToList();
return list;
}
public static bool IsNullableType(Type t) {
return t.IsValueType && t.Name == "Nullable`1";
}
public static bool HasInheritedProperty(Type declaringType, PropertyInfo pInfo) {
if (pInfo.DeclaringType != declaringType) {
return true;
}
while (declaringType.BaseType != null && declaringType.BaseType != typeof (Object)) {
foreach (var baseP in declaringType.BaseType.GetProperties()) {
if (baseP.Name == pInfo.Name && baseP.PropertyType == pInfo.PropertyType) {
return true;
}
}
declaringType = declaringType.BaseType;
}
return false;
}
public static string ToGenericTypeFullNameString(Type t) {
if (t.FullName == null && t.IsGenericParameter) {
return t.GenericParameterPosition == 0 ? "T" : "T" + t.GenericParameterPosition;
}
if (!t.IsGenericType) {
return t.FullName;
}
var value = t.FullName.Substring(0, t.FullName.IndexOf('`')) + "<";
var genericArgs = t.GetGenericArguments();
var list = new List<string>();
for (var i = 0; i < genericArgs.Length; i++) {
value += "{" + i + "},";
var s = ToGenericTypeFullNameString(genericArgs[i]);
list.Add(s);
}
value = value.TrimEnd(',');
value += ">";
value = string.Format(value, list.ToArray<string>());
return value;
}
public static string ToGenericTypeNameString(Type t) {
var fullname = ToGenericTypeFullNameString(t);
fullname = fullname.Substring(fullname.LastIndexOf('.') + 1).TrimEnd('>');
return fullname;
}
#endregion
#region nested classes
public class NameTypePair {
public string Name {get; set;}
public Type Type {get; set;}
public override int GetHashCode() {
return Name.GetHashCode() + Type.GetHashCode();
}
public override bool Equals(object obj) {
if (!(obj is NameTypePair)) {
return false;
}
var other = obj as NameTypePair;
return Name.Equals(other.Name) && Type.Equals(other.Type);
}
}
private class AnonTypeId {
public string Name {get; private set;}
public IEnumerable<NameTypePair> Properties {get; private set;}
public AnonTypeId(string name, IEnumerable<NameTypePair> properties) {
Name = name;
Properties = properties;
}
public override int GetHashCode() {
var result = Name.GetHashCode();
foreach (var ntpair in Properties) {
result += ntpair.GetHashCode();
}
return result;
}
public override bool Equals(object obj) {
if (!(obj is AnonTypeId)) {
return false;
}
var other = obj as AnonTypeId;
return (Name.Equals(other.Name)
&& Properties.SequenceEqual(other.Properties));
}
}
#endregion
}
} | 42.711579 | 229 | 0.53401 | [
"Apache-2.0"
] | Jaykul/clrplus | Core/Linq/Serialization/Xml/TypeResolver.cs | 20,288 | C# |
using SolastaModApi.Infrastructure;
using static RuleDefinitions;
namespace SolastaModApi.Extensions
{
/// <summary>
/// This helper extensions class was automatically generated.
/// If you find a problem please report at https://github.com/SolastaMods/SolastaModApi/issues.
/// </summary>
[TargetType(typeof(ArmorDescription))]
public static class ArmorDescriptionExtensions
{
public static T SetArmorClassValue<T>(this T entity, int value)
where T : ArmorDescription
{
entity.SetField("armorClassValue", value);
return entity;
}
public static T SetArmorType<T>(this T entity, string value)
where T : ArmorDescription
{
entity.SetField("armorType", value);
return entity;
}
public static T SetIsBaseArmorClass<T>(this T entity, bool value)
where T : ArmorDescription
{
entity.SetField("isBaseArmorClass", value);
return entity;
}
public static T SetMaxDexterityBonus<T>(this T entity, int value)
where T : ArmorDescription
{
entity.SetField("maxDexterityBonus", value);
return entity;
}
public static T SetMinimalStrength<T>(this T entity, int value)
where T : ArmorDescription
{
entity.SetField("minimalStrength", value);
return entity;
}
public static T SetRequiresMinimalStrength<T>(this T entity, bool value)
where T : ArmorDescription
{
entity.SetField("requiresMinimalStrength", value);
return entity;
}
}
} | 31.127273 | 99 | 0.603388 | [
"MIT"
] | ChrisPJohn/SolastaModApi | SolastaModApi/Extensions/ArmorDescriptionExtensions.cs | 1,712 | 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.AppPlatform.Latest.Inputs
{
/// <summary>
/// Source information for a deployment
/// </summary>
public sealed class UserSourceInfoArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Selector for the artifact to be used for the deployment for multi-module projects. This should be
/// the relative path to the target module/project.
/// </summary>
[Input("artifactSelector")]
public Input<string>? ArtifactSelector { get; set; }
/// <summary>
/// Relative path of the storage which stores the source
/// </summary>
[Input("relativePath")]
public Input<string>? RelativePath { get; set; }
/// <summary>
/// Type of the source uploaded
/// </summary>
[Input("type")]
public Input<string>? Type { get; set; }
/// <summary>
/// Version of the source
/// </summary>
[Input("version")]
public Input<string>? Version { get; set; }
public UserSourceInfoArgs()
{
}
}
}
| 29.291667 | 110 | 0.602418 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/AppPlatform/Latest/Inputs/UserSourceInfoArgs.cs | 1,406 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System.Collections.Generic;
using System.Buffers;
using System.Buffers.Text;
namespace System.Text.Http.Parser.Tests
{
public class HttpParserBasicTests
{
[Theory]
[InlineData("GET /plaintext HTTP/1.1\r\nN: V\r\n\r\n")]
public void HttpParserBasicsRob(string requestText)
{
var parser = new HttpParser();
var request = new Request();
ReadOnlySequence<byte> buffer = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes(requestText));
Assert.True(parser.ParseRequestLine(ref request, buffer, out var consumed));
Assert.Equal(25, consumed);
Assert.True(parser.ParseHeaders(ref request, buffer.Slice(consumed), out consumed));
Assert.Equal(8, consumed);
// request line
Assert.Equal(Http.Method.Get, request.Method);
Assert.Equal(Http.Version.Http11, request.Version);
Assert.Equal("/plaintext", request.Path);
// headers
Assert.Equal(1, request.Headers.Count);
Assert.True(request.Headers.ContainsKey("N"));
Assert.Equal("V", request.Headers["N"]);
}
[Theory]
[InlineData("GET /plaintext HTTP/1.1\r\nN: V\r\n\r\n")]
public void HttpParserSegmentedRob(string requestText)
{
var parser = new HttpParser();
for (int pivot = 26; pivot < requestText.Length; pivot++) {
var front = requestText.Substring(0, pivot);
var back = requestText.Substring(pivot);
var frontBytes = Encoding.ASCII.GetBytes(front);
var endBytes = Encoding.ASCII.GetBytes(back);
var (first, last) = BufferList.Create(frontBytes, endBytes);
var buffer = new ReadOnlySequence<byte>(first, 0, last, last.Memory.Length);
var request = new Request();
try {
Assert.True(parser.ParseRequestLine(ref request, buffer, out var consumed));
Assert.Equal(25, consumed);
var unconsumed = buffer.Slice(consumed);
Assert.True(parser.ParseHeaders(ref request, unconsumed, out consumed));
Assert.Equal(8, consumed);
}
catch {
throw;
}
// request line
Assert.Equal(Http.Method.Get, request.Method);
Assert.Equal(Http.Version.Http11, request.Version);
Assert.Equal("/plaintext", request.Path);
// headers
Assert.Equal(1, request.Headers.Count);
Assert.True(request.Headers.ContainsKey("N"));
Assert.Equal("V", request.Headers["N"]);
}
}
[Fact]
public void TechEmpowerRob()
{
var parser = new HttpParser();
var request = new Request();
ReadOnlySequence<byte> buffer = new ReadOnlySequence<byte>(_plaintextTechEmpowerRequestBytes);
Assert.True(parser.ParseRequestLine(ref request, buffer, out var consumed));
Assert.Equal(25, consumed);
Assert.True(parser.ParseHeaders(ref request, buffer.Slice(consumed), out consumed));
Assert.Equal(139, consumed);
// request line
Assert.Equal(Http.Method.Get, request.Method);
Assert.Equal(Http.Version.Http11, request.Version);
Assert.Equal("/plaintext", request.Path);
// headers
Assert.Equal(3, request.Headers.Count);
Assert.True(request.Headers.ContainsKey("Host"));
Assert.True(request.Headers.ContainsKey("Accept"));
Assert.True(request.Headers.ContainsKey("Connection"));
Assert.Equal("localhost", request.Headers["Host"]);
Assert.Equal("text/plain,text/html;q=0.9,application/xhtml+xml;q=0.9,application/xml;q=0.8,*/*;q=0.7", request.Headers["Accept"]);
Assert.Equal("keep-alive", request.Headers["Connection"]);
}
[Fact]
public void TechEmpowerRobRb()
{
var parser = new HttpParser();
var request = new Request();
ReadOnlySequence<byte> buffer = new ReadOnlySequence<byte>(_plaintextTechEmpowerRequestBytes);
Assert.True(parser.ParseRequestLine(request, buffer, out var consumed, out var read));
Assert.True(parser.ParseHeaders(request, buffer.Slice(consumed), out consumed, out var examined, out var consumedBytes));
Assert.Equal(139, consumedBytes);
// request line
Assert.Equal(Http.Method.Get, request.Method);
Assert.Equal(Http.Version.Http11, request.Version);
Assert.Equal("/plaintext", request.Path);
// headers
Assert.Equal(3, request.Headers.Count);
Assert.True(request.Headers.ContainsKey("Host"));
Assert.True(request.Headers.ContainsKey("Accept"));
Assert.True(request.Headers.ContainsKey("Connection"));
Assert.Equal("localhost", request.Headers["Host"]);
Assert.Equal("text/plain,text/html;q=0.9,application/xhtml+xml;q=0.9,application/xml;q=0.8,*/*;q=0.7", request.Headers["Accept"]);
Assert.Equal("keep-alive", request.Headers["Connection"]);
}
private const string _plaintextTechEmpowerRequest =
"GET /plaintext HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"Accept: text/plain,text/html;q=0.9,application/xhtml+xml;q=0.9,application/xml;q=0.8,*/*;q=0.7\r\n" +
"Connection: keep-alive\r\n" +
"\r\n";
byte[] _plaintextTechEmpowerRequestBytes = Encoding.ASCII.GetBytes(_plaintextTechEmpowerRequest);
}
class Request : IHttpHeadersHandler, IHttpRequestLineHandler
{
public Http.Method Method;
public Http.Version Version;
public string Path;
public string Query;
public string Target;
public Dictionary<string, string> Headers = new Dictionary<string, string>();
public void OnHeader(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value)
{
var nameString = Encodings.Ascii.ToUtf16String(name);
var valueString = Encodings.Ascii.ToUtf16String(value);
Headers.Add(nameString, valueString);
}
public void OnStartLine(Http.Method method, Http.Version version, ReadOnlySpan<byte> target, ReadOnlySpan<byte> path, ReadOnlySpan<byte> query, ReadOnlySpan<byte> customMethod, bool pathEncoded)
{
Method = method;
Version = version;
Path = Encodings.Ascii.ToUtf16String(path);
Query = Encodings.Ascii.ToUtf16String(query);
Target = Encodings.Ascii.ToUtf16String(target);
}
}
}
| 41.288235 | 202 | 0.605784 | [
"MIT"
] | benaadams/corefxlab | tests/System.Text.Http.Tests/HttpParserBasicTests.cs | 7,019 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProtoBuf;
namespace Gear.Net.ChannelPlugins.StreamTransfer
{
[ProtoContract]
public class RequestStreamMessage : IMessage
{
[ProtoIgnore]
int IMessage.DispatchId
{
get
{
return BuiltinMessageIds.RequestStream;
}
}
[ProtoMember(1)]
public string Name { get; set; }
}
}
| 19.576923 | 55 | 0.607073 | [
"MIT"
] | cathode/gear | Gear.Net/ChannelPlugins/StreamTransfer/RequestStreamMessage.cs | 511 | C# |
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Diagnostics;
using System.IO;
using System.ComponentModel;
using System.Text;
using System.Net;
using System.Net.Cache;
using System.Timers;
namespace XmlNotepad
{
/// <summary>
/// XmlCache wraps an XmlDocument and provides the stuff necessary for an "editor" in terms
/// of watching for changes on disk, notification when the file has been reloaded, and keeping
/// track of the current file name and dirty state.
/// </summary>
public class XmlCache : IDisposable
{
private string _fileName;
private string _renamed;
private bool _dirty;
private DomLoader _loader;
private XmlDocument _doc;
private FileSystemWatcher _watcher;
private int _retries;
private SchemaCache _schemaCache;
private Dictionary<XmlNode, XmlSchemaInfo> _typeInfo;
private int _batch;
private DateTime _lastModified;
private Checker _checker;
private IServiceProvider _site;
private DelayedActions _actions;
private Settings _settings;
public event EventHandler FileChanged;
public event EventHandler<ModelChangedEventArgs> ModelChanged;
public XmlCache(IServiceProvider site, DelayedActions handler)
{
this._loader = new DomLoader(site);
this._schemaCache = new SchemaCache(site);
this._site = site;
this.Document = new XmlDocument();
this._actions = handler;
this._settings = (Settings)this._site.GetService(typeof(Settings));
}
~XmlCache()
{
Dispose(false);
}
public Uri Location => new Uri(this._fileName);
public string FileName => this._fileName;
public string NewName => this._renamed;
public bool IsFile
{
get
{
if (!string.IsNullOrEmpty(this._fileName))
{
return this.Location.IsFile;
}
return false;
}
}
/// <summary>
/// File path to (optionally user-specified) xslt file.
/// </summary>
public string XsltFileName { get; set; }
/// <summary>
/// File path to (optionally user-specified) to use for xslt output.
/// </summary>
public string XsltDefaultOutput { get; set; }
public bool Dirty => this._dirty;
public Settings Settings => this._settings;
public XmlResolver SchemaResolver => this._schemaCache.Resolver;
public XPathNavigator Navigator
{
get
{
XPathDocument xdoc = new XPathDocument(this._fileName);
XPathNavigator nav = xdoc.CreateNavigator();
return nav;
}
}
public void ValidateModel(ErrorHandler handler)
{
this._checker = new Checker(handler);
_checker.Validate(this);
}
public XmlDocument Document
{
get { return this._doc; }
set
{
if (this._doc != null)
{
this._doc.NodeChanged -= new XmlNodeChangedEventHandler(OnDocumentChanged);
this._doc.NodeInserted -= new XmlNodeChangedEventHandler(OnDocumentChanged);
this._doc.NodeRemoved -= new XmlNodeChangedEventHandler(OnDocumentChanged);
}
this._doc = value;
if (this._doc != null)
{
this._doc.NodeChanged += new XmlNodeChangedEventHandler(OnDocumentChanged);
this._doc.NodeInserted += new XmlNodeChangedEventHandler(OnDocumentChanged);
this._doc.NodeRemoved += new XmlNodeChangedEventHandler(OnDocumentChanged);
}
}
}
public Dictionary<XmlNode, XmlSchemaInfo> TypeInfoMap
{
get { return this._typeInfo; }
set { this._typeInfo = value; }
}
public XmlSchemaInfo GetTypeInfo(XmlNode node)
{
if (this._typeInfo == null) return null;
if (this._typeInfo.ContainsKey(node))
{
return this._typeInfo[node];
}
return null;
}
public XmlSchemaElement GetElementType(XmlQualifiedName xmlQualifiedName)
{
if (this._schemaCache != null)
{
return this._schemaCache.GetElementType(xmlQualifiedName);
}
return null;
}
public XmlSchemaAttribute GetAttributeType(XmlQualifiedName xmlQualifiedName)
{
if (this._schemaCache != null)
{
return this._schemaCache.GetAttributeType(xmlQualifiedName);
}
return null;
}
/// <summary>
/// Provides schemas used for validation.
/// </summary>
public SchemaCache SchemaCache
{
get { return this._schemaCache; }
set { this._schemaCache = value; }
}
/// <summary>
/// Loads an instance of xml.
/// Load updated to handle validation when instance doc refers to schema.
/// </summary>
/// <param name="file">Xml instance document</param>
/// <returns></returns>
public void Load(string file)
{
Uri uri = new Uri(file, UriKind.RelativeOrAbsolute);
if (!uri.IsAbsoluteUri)
{
Uri resolved = new Uri(new Uri(Directory.GetCurrentDirectory() + "\\"), uri);
file = resolved.LocalPath;
uri = resolved;
}
XmlReaderSettings settings = GetReaderSettings();
settings.ValidationEventHandler += new ValidationEventHandler(OnValidationEvent);
using (XmlReader reader = XmlReader.Create(file, settings))
{
this.Load(reader, file);
}
}
public void Load(XmlReader reader, string fileName)
{
this.Clear();
_loader = new DomLoader(this._site);
StopFileWatch();
Uri uri = new Uri(fileName, UriKind.RelativeOrAbsolute);
if (!uri.IsAbsoluteUri)
{
Uri resolved = new Uri(new Uri(Directory.GetCurrentDirectory() + "\\"), uri);
fileName = resolved.LocalPath;
uri = resolved;
}
this._fileName = fileName;
this._lastModified = this.LastModTime;
this._dirty = false;
StartFileWatch();
this.Document = _loader.Load(reader);
this.XsltFileName = this._loader.XsltFileName;
this.XsltDefaultOutput = this._loader.XsltDefaultOutput;
// calling this event will cause the XmlTreeView to populate
FireModelChanged(ModelChangeType.Reloaded, this._doc);
}
public XmlReaderSettings GetReaderSettings()
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = this._settings.GetBoolean("IgnoreDTD") ? DtdProcessing.Ignore : DtdProcessing.Parse;
settings.CheckCharacters = false;
settings.XmlResolver = Settings.Instance.Resolver;
return settings;
}
public void ExpandIncludes()
{
if (this.Document != null)
{
this._dirty = true;
XmlReaderSettings s = new XmlReaderSettings();
s.DtdProcessing = this._settings.GetBoolean("IgnoreDTD") ? DtdProcessing.Ignore : DtdProcessing.Parse;
s.XmlResolver = Settings.Instance.Resolver;
using (XmlReader r = XmlIncludeReader.CreateIncludeReader(this.Document, s, this.FileName))
{
this.Document = _loader.Load(r);
}
// calling this event will cause the XmlTreeView to populate
FireModelChanged(ModelChangeType.Reloaded, this._doc);
}
}
public void BeginUpdate()
{
if (_batch == 0)
FireModelChanged(ModelChangeType.BeginBatchUpdate, this._doc);
_batch++;
}
public void EndUpdate()
{
_batch--;
if (_batch == 0)
FireModelChanged(ModelChangeType.EndBatchUpdate, this._doc);
}
public LineInfo GetLineInfo(XmlNode node)
{
return _loader.GetLineInfo(node);
}
void OnValidationEvent(object sender, ValidationEventArgs e)
{
// todo: log errors in error list window.
}
public void Reload()
{
string filename = this._fileName;
Clear();
Load(filename);
}
public void Clear()
{
this._renamed = null;
this.Document = new XmlDocument();
StopFileWatch();
this._fileName = null;
FireModelChanged(ModelChangeType.Reloaded, this._doc);
}
public void Save()
{
Save(this._fileName);
}
public Encoding GetEncoding()
{
XmlDeclaration xmldecl = _doc.FirstChild as XmlDeclaration;
Encoding result = null;
if (xmldecl != null)
{
string name = "";
try
{
name = xmldecl.Encoding;
if (!string.IsNullOrEmpty(name))
{
result = Encoding.GetEncoding(name);
}
}
catch (Exception ex)
{
Debug.WriteLine(string.Format("Error getting encoding '{0}': {1}", name, ex.Message));
}
}
if (result == null)
{
// default is UTF-8.
result = Encoding.UTF8;
}
return result;
}
public void AddXmlDeclarationWithEncoding()
{
XmlDeclaration xmldecl = _doc.FirstChild as XmlDeclaration;
if (xmldecl == null)
{
_doc.InsertBefore(_doc.CreateXmlDeclaration("1.0", "utf-8", null), _doc.FirstChild);
}
else
{
string e = xmldecl.Encoding;
if (string.IsNullOrEmpty(e))
{
xmldecl.Encoding = "utf-8";
}
}
}
public void Save(string name)
{
SaveCopy(name);
this._dirty = false;
this._fileName = name;
this._lastModified = this.LastModTime;
FireModelChanged(ModelChangeType.Saved, this._doc);
}
public void SaveCopy(string filename)
{
try
{
StopFileWatch();
XmlWriterSettings s = new XmlWriterSettings();
Utilities.InitializeWriterSettings(s, this._site);
var encoding = GetEncoding();
s.Encoding = encoding;
bool noBom = false;
if (this._site != null)
{
Settings settings = (Settings)this._site.GetService(typeof(Settings));
if (settings != null)
{
noBom = (bool)settings["NoByteOrderMark"];
if (noBom)
{
// then we must have an XML declaration with an encoding attribute.
AddXmlDeclarationWithEncoding();
}
}
}
if (noBom)
{
MemoryStream ms = new MemoryStream();
using (XmlWriter w = XmlWriter.Create(ms, s))
{
_doc.Save(w);
}
ms.Seek(0, SeekOrigin.Begin);
Utilities.WriteFileWithoutBOM(ms, filename);
}
else
{
using (XmlWriter w = XmlWriter.Create(filename, s))
{
_doc.Save(w);
}
}
}
finally
{
StartFileWatch();
}
}
public bool IsReadOnly(string filename)
{
return File.Exists(filename) &&
(File.GetAttributes(filename) & FileAttributes.ReadOnly) != 0;
}
public void MakeReadWrite(string filename)
{
if (!File.Exists(filename))
return;
StopFileWatch();
try
{
FileAttributes attrsMinusReadOnly = File.GetAttributes(this._fileName) & ~FileAttributes.ReadOnly;
File.SetAttributes(filename, attrsMinusReadOnly);
}
finally
{
StartFileWatch();
}
}
void StopFileWatch()
{
if (this._watcher != null)
{
this._watcher.Dispose();
this._watcher = null;
}
}
private void StartFileWatch()
{
if (this._fileName != null && Location.IsFile && File.Exists(this._fileName))
{
string dir = Path.GetDirectoryName(this._fileName) + "\\";
this._watcher = new FileSystemWatcher(dir, "*.*");
this._watcher.Changed += new FileSystemEventHandler(watcher_Changed);
this._watcher.Renamed += new RenamedEventHandler(watcher_Renamed);
this._watcher.EnableRaisingEvents = true;
}
else
{
StopFileWatch();
}
}
class ReloadAction
{
public XmlCache Cache;
public string FileName;
public bool Renamed;
public void HandleReload()
{
if (!Renamed)
{
Cache.CheckReload(FileName);
}
}
}
ReloadAction pending;
void StartReload()
{
// Apart from retrying, the DelayedActions has the nice side effect of also
// collapsing multiple file system events into one action callback.
_retries = 3;
if (pending == null)
{
pending = new ReloadAction() { FileName = this._fileName, Cache = this };
_actions.StartDelayedAction("reload", () => pending.HandleReload(), TimeSpan.FromSeconds(1));
}
}
DateTime LastModTime
{
get
{
if (Location.IsFile) return File.GetLastWriteTime(this._fileName);
return DateTime.Now;
}
}
public void CheckReload(string fileName)
{
if (!File.Exists(fileName))
{
// file was deleted...
return;
}
pending = null;
try
{
// Only do the reload if the file on disk really is different from
// what we last loaded.
if (this._lastModified < LastModTime && this._fileName == fileName)
{
// Test if we can open the file (it might still be locked).
using (FileStream fs = new FileStream(this._fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
fs.Close();
}
FireFileChanged();
}
}
finally
{
_retries--;
if (_retries > 0)
{
_actions.StartDelayedAction("reload", Reload, TimeSpan.FromSeconds(1));
}
}
}
private void watcher_Changed(object sender, FileSystemEventArgs e)
{
try
{
if (e.ChangeType == WatcherChangeTypes.Changed &&
IsSamePath(this._fileName, e.FullPath))
{
Debug.WriteLine("### File changed " + this._fileName);
StartReload();
}
}
catch { }
}
private void watcher_Renamed(object sender, RenamedEventArgs e)
{
// Some editors rename the file to *.bak then save the new version and
// in that case we do not want XmlNotepad to switch to the .bak file.
try
{
string ext = Path.GetExtension(e.FullPath);
if (IsSamePath(this._fileName, e.OldFullPath) &&
// ignore renames that create a '.bak' file (like what UltraEdit does).
string.Compare(ext, ".bak", StringComparison.OrdinalIgnoreCase) != 0)
{
Debug.WriteLine("### File renamed to " + e.FullPath);
var p = pending;
if (p != null)
{
// we have a situation were file was modified AND renamed. Tricky!
p.Renamed = true;
}
// switch to UI thread
if (renamePending == null)
{
renamePending = new RenameAction { OldName = e.OldFullPath, NewName = e.FullPath, Cache = this };
_actions.StartDelayedAction("renamed", renamePending.HandleEvent, TimeSpan.FromMilliseconds(1));
}
}
} catch
{}
}
class RenameAction {
public string OldName;
public string NewName;
public XmlCache Cache;
public void HandleEvent()
{
Cache.OnRenamed(OldName, NewName);
}
}
RenameAction renamePending;
private void OnRenamed(string oldName, string newName)
{
this.renamePending = null;
this._dirty = true;
if (System.IO.Path.GetFullPath(this._fileName) == oldName)
{
this._renamed = newName;
FireFileChanged();
}
}
static bool IsSamePath(string a, string b)
{
return string.Compare(a, b, true) == 0;
}
void FireFileChanged()
{
if (this.FileChanged != null)
{
FileChanged(this, EventArgs.Empty);
}
}
void FireModelChanged(ModelChangeType t, XmlNode node)
{
if (this.ModelChanged != null)
this.ModelChanged(this, new ModelChangedEventArgs(t, node));
}
void OnPIChange(XmlNodeChangedEventArgs e)
{
XmlProcessingInstruction pi = (XmlProcessingInstruction)e.Node;
if (pi.Name == "xml-stylesheet")
{
if (e.Action == XmlNodeChangedAction.Remove)
{
// see if there's another!
pi = this._doc.SelectSingleNode("processing-instruction('xml-stylesheet')") as XmlProcessingInstruction;
}
if (pi != null)
{
this.XsltFileName = DomLoader.ParseXsltArgs(pi.Data);
}
else
{
this.XsltFileName = null;
}
}
else if (pi.Name == "xsl-output")
{
if (e.Action == XmlNodeChangedAction.Remove)
{
// see if there's another!
pi = this._doc.SelectSingleNode("processing-instruction('xsl-output')") as XmlProcessingInstruction;
}
if (pi != null)
{
this.XsltDefaultOutput = DomLoader.ParseXsltOutputArgs(pi.Data);
}
else
{
this.XsltDefaultOutput = null;
}
}
}
private void OnDocumentChanged(object sender, XmlNodeChangedEventArgs e)
{
// initialize t
ModelChangeType t = ModelChangeType.NodeChanged;
if (e.Node is XmlProcessingInstruction)
{
OnPIChange(e);
}
if (XmlHelpers.IsXmlnsNode(e.NewParent) || XmlHelpers.IsXmlnsNode(e.Node))
{
// we flag a namespace change whenever an xmlns attribute changes.
t = ModelChangeType.NamespaceChanged;
XmlNode node = e.Node;
if (e.Action == XmlNodeChangedAction.Remove)
{
node = e.OldParent; // since node.OwnerElement link has been severed!
}
this._dirty = true;
FireModelChanged(t, node);
}
else
{
switch (e.Action)
{
case XmlNodeChangedAction.Change:
t = ModelChangeType.NodeChanged;
break;
case XmlNodeChangedAction.Insert:
t = ModelChangeType.NodeInserted;
break;
case XmlNodeChangedAction.Remove:
t = ModelChangeType.NodeRemoved;
break;
}
this._dirty = true;
FireModelChanged(t, e.Node);
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
this._actions.CancelDelayedAction("reload");
StopFileWatch();
}
}
public enum ModelChangeType
{
Reloaded,
Saved,
NodeChanged,
NodeInserted,
NodeRemoved,
NamespaceChanged,
BeginBatchUpdate,
EndBatchUpdate
}
public class ModelChangedEventArgs : EventArgs
{
ModelChangeType type;
XmlNode node;
public ModelChangedEventArgs(ModelChangeType t, XmlNode node)
{
this.type = t;
this.node = node;
}
public XmlNode Node
{
get { return node; }
set { node = value; }
}
public ModelChangeType ModelChangeType
{
get { return this.type; }
set { this.type = value; }
}
}
public enum IndentChar
{
Space,
Tab
}
} | 31.548913 | 127 | 0.493066 | [
"MIT"
] | acidburn0zzz/XmlNotepad | src/Model/XmlCache.cs | 23,220 | 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.Compute.Models
{
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Describes a Virtual Machine Image.
/// </summary>
[Rest.Serialization.JsonTransformation]
public partial class VirtualMachineImage : VirtualMachineImageResource
{
/// <summary>
/// Initializes a new instance of the VirtualMachineImage class.
/// </summary>
public VirtualMachineImage()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the VirtualMachineImage class.
/// </summary>
/// <param name="name">The name of the resource.</param>
/// <param name="location">The supported Azure location of the
/// resource.</param>
/// <param name="id">Resource Id</param>
/// <param name="tags">Specifies the tags that are assigned to the
/// virtual machine. For more information about using tags, see [Using
/// tags to organize your Azure
/// resources](https://docs.microsoft.com/azure/azure-resource-manager/resource-group-using-tags.md).</param>
/// <param name="extendedLocation">The extended location of the Virtual
/// Machine.</param>
/// <param name="hyperVGeneration">Possible values include: 'V1',
/// 'V2'</param>
/// <param name="disallowed">Specifies disallowed configuration for the
/// VirtualMachine created from the image</param>
/// <param name="architecture">Possible values include: 'x64',
/// 'Arm64'</param>
public VirtualMachineImage(string name, string location, string id = default(string), IDictionary<string, string> tags = default(IDictionary<string, string>), ExtendedLocation extendedLocation = default(ExtendedLocation), PurchasePlan plan = default(PurchasePlan), OSDiskImage osDiskImage = default(OSDiskImage), IList<DataDiskImage> dataDiskImages = default(IList<DataDiskImage>), AutomaticOSUpgradeProperties automaticOSUpgradeProperties = default(AutomaticOSUpgradeProperties), string hyperVGeneration = default(string), DisallowedConfiguration disallowed = default(DisallowedConfiguration), IList<VirtualMachineImageFeature> features = default(IList<VirtualMachineImageFeature>), string architecture = default(string))
: base(name, location, id, tags, extendedLocation)
{
Plan = plan;
OsDiskImage = osDiskImage;
DataDiskImages = dataDiskImages;
AutomaticOSUpgradeProperties = automaticOSUpgradeProperties;
HyperVGeneration = hyperVGeneration;
Disallowed = disallowed;
Features = features;
Architecture = architecture;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "properties.plan")]
public PurchasePlan Plan { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "properties.osDiskImage")]
public OSDiskImage OsDiskImage { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "properties.dataDiskImages")]
public IList<DataDiskImage> DataDiskImages { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "properties.automaticOSUpgradeProperties")]
public AutomaticOSUpgradeProperties AutomaticOSUpgradeProperties { get; set; }
/// <summary>
/// Gets or sets possible values include: 'V1', 'V2'
/// </summary>
[JsonProperty(PropertyName = "properties.hyperVGeneration")]
public string HyperVGeneration { get; set; }
/// <summary>
/// Gets or sets specifies disallowed configuration for the
/// VirtualMachine created from the image
/// </summary>
[JsonProperty(PropertyName = "properties.disallowed")]
public DisallowedConfiguration Disallowed { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "properties.features")]
public IList<VirtualMachineImageFeature> Features { get; set; }
/// <summary>
/// Gets or sets possible values include: 'x64', 'Arm64'
/// </summary>
[JsonProperty(PropertyName = "properties.architecture")]
public string Architecture { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public override void Validate()
{
base.Validate();
if (Plan != null)
{
Plan.Validate();
}
if (OsDiskImage != null)
{
OsDiskImage.Validate();
}
if (AutomaticOSUpgradeProperties != null)
{
AutomaticOSUpgradeProperties.Validate();
}
}
}
}
| 40.7 | 730 | 0.625483 | [
"MIT"
] | AikoBB/azure-sdk-for-net | sdk/compute/Microsoft.Azure.Management.Compute/src/Generated/Models/VirtualMachineImage.cs | 5,698 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Conditions.Tests.CollectionTests
{
/// <summary>
/// Tests the ValidatorExtensions.IsNotLongerThan method.
/// </summary>
[TestClass]
public class CollectionIsNotLongerThanTests
{
[TestMethod]
[Description("Calling IsNotLongerThan(1) with a collection containing no elements should pass.")]
public void CollectionIsNotLongerThanTest01()
{
// HashSet only implements generic ICollection<T>, no ICollection.
HashSet<int> set = new HashSet<int>();
Condition.Requires(set).IsNotLongerThan(1);
}
[TestMethod]
[Description("Calling IsNotLongerThan(0) with a collection containing no elements should pass.")]
public void CollectionIsNotLongerThanTest02()
{
// HashSet only implements generic ICollection<T>, no ICollection.
HashSet<int> set = new HashSet<int>();
Condition.Requires(set).IsNotLongerThan(0);
}
[TestMethod]
[ExpectedException(typeof (ArgumentException))]
[Description("Calling IsNotLongerThan(-1) with a collection containing no elements should fail.")]
public void CollectionIsNotLongerThanTest03()
{
// HashSet only implements generic ICollection<T>, no ICollection.
HashSet<int> set = new HashSet<int>();
Condition.Requires(set).IsNotLongerThan(-1);
}
[TestMethod]
[ExpectedException(typeof (ArgumentException))]
[Description("Calling IsNotLongerThan(1) with a collection containing two element should fail.")]
public void CollectionIsNotLongerThanTest04()
{
// HashSet only implements generic ICollection<T>, no ICollection.
HashSet<int> set = new HashSet<int> {1, 2};
Condition.Requires(set).IsNotLongerThan(1);
}
[TestMethod]
[Description("Calling IsNotLongerThan(2) with a collection containing two elements should pass.")]
public void CollectionIsNotLongerThanTest05()
{
// HashSet only implements generic ICollection<T>, no ICollection.
HashSet<int> set = new HashSet<int> {1, 2};
Condition.Requires(set).IsNotLongerThan(2);
}
[TestMethod]
[Description("Calling IsNotLongerThan(1) with an ArrayList containing one element should pass.")]
public void CollectionIsNotLongerThanTest06()
{
// ArrayList implements ICollection.
ArrayList list = new ArrayList {1};
Condition.Requires(list).IsNotLongerThan(1);
}
[TestMethod]
[ExpectedException(typeof (ArgumentException))]
[Description("Calling IsNotLongerThan(0) with an ArrayList containing one element should fail.")]
public void CollectionIsNotLongerThanTest07()
{
// ArrayList implements ICollection.
ArrayList list = new ArrayList {1};
Condition.Requires(list).IsNotLongerThan(0);
}
[TestMethod]
[Description("Calling IsNotLongerThan(0) on a null reference should pass.")]
public void CollectionIsNotLongerThanTest08()
{
IEnumerable list = null;
Condition.Requires(list).IsNotLongerThan(0);
}
[TestMethod]
[ExpectedException(typeof (ArgumentNullException))]
[Description("Calling IsNotLongerThan(-1) on a null reference should fail.")]
public void CollectionIsNotLongerThanTest09()
{
IEnumerable list = null;
Condition.Requires(list).IsNotLongerThan(-1);
}
[TestMethod]
[Description("Calling IsNotLongerThan with the condtionDescription parameter should pass.")]
public void CollectionIsNotLongerThanTest10()
{
IEnumerable list = null;
Condition.Requires(list).IsNotLongerThan(1, string.Empty);
}
[TestMethod]
[Description(
"Calling a failing IsNotLongerThan should throw an Exception with an exception message that contains the given parameterized condition description argument."
)]
public void CollectionIsNotLongerThanTest11()
{
IEnumerable list = null;
try
{
Condition.Requires(list, "list").IsNotLongerThan(-1, "abc {0} def");
}
catch (ArgumentException ex)
{
Assert.IsTrue(ex.Message.Contains("abc list def"));
}
}
[TestMethod]
[Description(
"Calling IsNotLongerThan(-1) with a collection containing no elements should succeed when exceptions are suppressed."
)]
public void CollectionIsNotLongerThanTest12()
{
// HashSet only implements generic ICollection<T>, no ICollection.
HashSet<int> set = new HashSet<int>();
Condition.Requires(set).SuppressExceptionsForTest().IsNotLongerThan(-1);
}
}
} | 36.055556 | 169 | 0.627696 | [
"MIT"
] | Kleptine/conditions-unity | src/Conditions.Tests/CollectionTests/CollectionIsNotLongerThanTests.cs | 5,192 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using lmDatasets;
namespace atriumDAL
{
public partial class AddressDAL : atDAL.ObjectDAL
{
public atriumDB.AddressDataTable LoadByFileIdP(int FileId)
{
this.sqlDa.SelectCommand = sqlSelect;
this.sqlSelect.Parameters.Clear();
this.sqlSelect.CommandText = "[AddressSelectByFileIdP]";
this.sqlSelect.Parameters.Add(new System.Data.SqlClient.SqlParameter("@RETURN_VALUE", System.Data.SqlDbType.Int, 4, System.Data.ParameterDirection.ReturnValue, false, ((System.Byte)(10)), ((System.Byte)(0)), "", System.Data.DataRowVersion.Current, null));
this.sqlSelect.Parameters.Add(new System.Data.SqlClient.SqlParameter("@FileId", System.Data.SqlDbType.Int, 4, System.Data.ParameterDirection.Input, false, ((System.Byte)(10)), ((System.Byte)(0)), "", System.Data.DataRowVersion.Current, null));
this.sqlSelect.Parameters["@FileId"].Value = FileId;
atriumDB.AddressDataTable dt = new atriumDB.AddressDataTable();
Fill(dt);
return dt;
}
}
}
| 43 | 267 | 0.681309 | [
"MIT"
] | chris-weekes/atrium | atriumDAL/Address_UDAL.cs | 1,163 | C# |
using System;
using Microsoft.Extensions.Options;
using Q42.HueApi;
using Q42.HueApi.ColorConverters;
using Q42.HueApi.ColorConverters.HSB;
using Q42.HueApi.Interfaces;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace PresenceLight.Core
{
public interface IHueService
{
Task SetColor(string availability, string lightId);
Task<string> RegisterBridge();
Task<IEnumerable<Light>> CheckLights();
Task<string> FindBridge();
}
public class HueService : IHueService
{
private readonly ConfigWrapper _options;
private LocalHueClient _client;
public HueService(IOptionsMonitor<ConfigWrapper> optionsAccessor)
{
_options = optionsAccessor.CurrentValue;
}
public HueService(ConfigWrapper options)
{
_options = options;
}
public async Task SetColor(string availability, string lightId)
{
_client = new LocalHueClient(_options.HueIpAddress);
_client.Initialize(_options.HueApiKey);
var command = new LightCommand();
if (_options.Brightness == 0)
{
command.On = false;
}
else
{
command.On = true;
command.Brightness = Convert.ToByte(((_options.Brightness / 100) * 254));
}
switch (availability)
{
case "Available":
command.SetColor(new RGBColor("#009933"));
break;
case "Busy":
command.SetColor(new RGBColor("#ff3300"));
break;
case "BeRightBack":
command.SetColor(new RGBColor("#ffff00"));
break;
case "Away":
command.SetColor(new RGBColor("#ffff00"));
break;
case "DoNotDisturb":
command.SetColor(new RGBColor("#800000"));
break;
case "Offline":
command.SetColor(new RGBColor("#FFFFFF"));
break;
case "Off":
command.SetColor(new RGBColor("#FFFFFF"));
break;
default:
command.SetColor(new RGBColor(availability));
break;
}
await _client.SendCommandAsync(command, new List<string> { lightId });
}
//Need to wire up a way to do this without user intervention
public async Task<string> RegisterBridge()
{
if (string.IsNullOrEmpty(_options.HueApiKey))
{
try
{
_client = new LocalHueClient(_options.HueIpAddress);
//Make sure the user has pressed the button on the bridge before calling RegisterAsync
//It will throw an LinkButtonNotPressedException if the user did not press the button
return await _client.RegisterAsync("presence-light", "presence-light");
}
catch
{
return String.Empty;
}
}
return String.Empty;
}
public async Task<string> FindBridge()
{
try
{
IBridgeLocator locator = new HttpBridgeLocator(); //Or: LocalNetworkScanBridgeLocator, MdnsBridgeLocator, MUdpBasedBridgeLocator
var bridges = await locator.LocateBridgesAsync(TimeSpan.FromSeconds(5));
if (bridges.Count() > 0)
{
return bridges.FirstOrDefault().IpAddress;
}
}
catch
{
return String.Empty;
}
return String.Empty;
}
public async Task<IEnumerable<Light>> CheckLights()
{
if (_client == null)
{
_client = new LocalHueClient(_options.HueIpAddress);
_client.Initialize(_options.HueApiKey);
}
var lights = await _client.GetLightsAsync();
// if there are no lights, get some
if (lights.Count() == 0)
{
await _client.SearchNewLightsAsync();
Thread.Sleep(40000);
lights = await _client.GetNewLightsAsync();
}
return lights;
}
}
}
| 32.146853 | 144 | 0.514683 | [
"MIT"
] | jeffwmiles/PresenceLight | src/PresenceLight.Core/Lights/HueService.cs | 4,599 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace UdemyProject3.ScriptableObjects
{
[CreateAssetMenu(fileName = "Health Info", menuName = "Combat/Health Information/Create New", order = 51)]
public class HealthSO : ScriptableObject
{
[SerializeField] int _maxHealth;
public int MaxHealth => _maxHealth;
}
} | 27.071429 | 110 | 0.728232 | [
"Unlicense"
] | berkterek/Udemy3DProje3Repository | UdemyProje3/Assets/GameFolders/Scripts/Concretes/ScriptableObjects/HealthSO.cs | 379 | C# |
using System.Collections.Generic;
using System.Data.SqlClient;
using System;
namespace Restaurant
{
public class Restaurant
{
private int _id;
private string _name;
private string _description;
private int _cuisineId;
public Restaurant(string Name, string Description, int CuisineId, int Id = 0)
{
_id = Id;
_name = Name;
_description = Description;
_cuisineId = CuisineId;
}
public int GetId()
{
return _id;
}
public string GetName()
{
return _name;
}
public void SetName(string newName)
{
_name = newName;
}
public string GetDescription()
{
return _description;
}
public int GetCuisineId()
{
return _cuisineId;
}
public override bool Equals(System.Object otherRestaurant)
{
if (!(otherRestaurant is Restaurant))
{
return false;
}
else
{
Restaurant newRestaurant = (Restaurant) otherRestaurant;
bool idEquality = (this.GetId() == newRestaurant.GetId());
bool nameEquality = (this.GetName() == newRestaurant.GetName());
bool descriptionEquality = (this.GetDescription() == newRestaurant.GetDescription());
bool cuisineEquality = this.GetCuisineId() == newRestaurant.GetCuisineId();
return (idEquality && nameEquality && descriptionEquality && cuisineEquality);
}
}
public void Save()
{
SqlConnection conn = DB.Connection();
conn.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO restaurants (name, description, cuisine_id) OUTPUT INSERTED.id VALUES (@RestaurantName, @RestaurantDescription, @RestaurantCuisineId);", conn);
SqlParameter nameParameter = new SqlParameter();
nameParameter.ParameterName = "@RestaurantName";
nameParameter.Value = this.GetName();
SqlParameter descriptionParameter = new SqlParameter();
descriptionParameter.ParameterName = "@RestaurantDescription";
descriptionParameter.Value = this.GetDescription();
SqlParameter cuisineIdParameter = new SqlParameter();
cuisineIdParameter.ParameterName = "@RestaurantCuisineId";
cuisineIdParameter.Value = this.GetCuisineId();
cmd.Parameters.Add(nameParameter);
cmd.Parameters.Add(descriptionParameter);
cmd.Parameters.Add(cuisineIdParameter);
SqlDataReader rdr = cmd.ExecuteReader();
while(rdr.Read())
{
this._id = rdr.GetInt32(0);
}
if (rdr != null)
{
rdr.Close();
}
if (conn != null)
{
conn.Close();
}
}
public void Update(string newName, string newDescription)
{ //Update method for strings
SqlConnection conn = DB.Connection();
conn.Open();
SqlCommand cmd = new SqlCommand("UPDATE restaurants SET name = @NewName, description = @NewDescription OUTPUT INSERTED.name, INSERTED.description WHERE id = @RestaurantId;", conn);
SqlParameter newNameParameter = new SqlParameter();
newNameParameter.ParameterName = "@NewName";
newNameParameter.Value = newName;
cmd.Parameters.Add(newNameParameter);
SqlParameter newDescriptionParameter = new SqlParameter();
newDescriptionParameter.ParameterName = "@NewDescription";
newDescriptionParameter.Value = newDescription;
cmd.Parameters.Add(newDescriptionParameter);
SqlParameter restaurantIdParameter = new SqlParameter();
restaurantIdParameter.ParameterName = "@RestaurantId";
restaurantIdParameter.Value = this.GetId();
cmd.Parameters.Add(restaurantIdParameter);
SqlDataReader rdr = cmd.ExecuteReader();
while(rdr.Read())
{
this._name = rdr.GetString(0);
this._description = rdr.GetString(1);
}
if (rdr != null)
{
rdr.Close();
}
if (conn != null)
{
conn.Close();
}
} //SQL allows multiple methods with the same name as long as they work on different variable types
public static List<Restaurant> GetAll()
{
List<Restaurant> allRestaurants = new List<Restaurant> {};
SqlConnection conn = DB.Connection();
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM restaurants;", conn);
SqlDataReader rdr = cmd.ExecuteReader();
while(rdr.Read())
{
int restaurantId = rdr.GetInt32(0);
string restaurantName = rdr.GetString(1);
string restaurantDescription = rdr.GetString(2);
int restaurantCuisineId = rdr.GetInt32(3);
Restaurant newRestaurant = new Restaurant(restaurantName, restaurantDescription, restaurantCuisineId, restaurantId);
allRestaurants.Add(newRestaurant);
}
if (rdr != null)
{
rdr.Close();
}
if (conn != null)
{
conn.Close();
}
return allRestaurants;
}
public static Restaurant Find(int id)
{
SqlConnection conn = DB.Connection();
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM restaurants WHERE id = @RestaurantId;", conn);
SqlParameter restaurantIdParameter = new SqlParameter();
restaurantIdParameter.ParameterName = "@RestaurantId";
restaurantIdParameter.Value = id.ToString();
cmd.Parameters.Add(restaurantIdParameter);
SqlDataReader rdr = cmd.ExecuteReader();
int foundRestaurantId = 0;
string foundRestaurantName = null;
string foundRestaurantDescription = null;
int foundCuisineId = 0;
while(rdr.Read())
{
foundRestaurantId = rdr.GetInt32(0);
foundRestaurantName = rdr.GetString(1);
foundRestaurantDescription = rdr.GetString(2);
foundCuisineId = rdr.GetInt32(3);
}
Restaurant foundRestaurant = new Restaurant(foundRestaurantName, foundRestaurantDescription, foundCuisineId, foundRestaurantId);
if (rdr != null)
{
rdr.Close();
}
if (conn != null)
{
conn.Close();
}
return foundRestaurant;
}
public static List<Restaurant> ByCuisine()
{
List<Restaurant> AllRestaurants = new List<Restaurant>{};
SqlConnection conn = DB.Connection();
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM restaurants ORDER BY cuisine_id", conn);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
int restaurantId = rdr.GetInt32(0);
string restaurantName = rdr.GetString(1);
string restaurantDescription = rdr.GetString(2);
int cuisineId = rdr.GetInt32(3);
Restaurant newRestaurant = new Restaurant(restaurantName, restaurantDescription, cuisineId, restaurantId);
AllRestaurants.Add(newRestaurant);
}
if (rdr != null)
{
rdr.Close();
}
if (conn != null)
{
conn.Close();
}
return AllRestaurants;
}
public void Delete()
{
SqlConnection conn = DB.Connection();
conn.Open();
SqlCommand cmd = new SqlCommand("DELETE FROM restaurants WHERE id = @RestaurantId;", conn);
SqlParameter restaurantIdParameter = new SqlParameter();
restaurantIdParameter.ParameterName = "@RestaurantId";
restaurantIdParameter.Value = this.GetId();
cmd.Parameters.Add(restaurantIdParameter);
cmd.ExecuteNonQuery();
if (conn != null)
{
conn.Close();
}
}
public static void DeleteAll()
{
SqlConnection conn = DB.Connection();
conn.Open();
SqlCommand cmd = new SqlCommand("DELETE FROM restaurants;", conn);
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
| 28.902256 | 194 | 0.638137 | [
"MIT"
] | aglines-epicodus/sql-best-restaurants | Objects/Restaurant.cs | 7,688 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Resources;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
namespace Dream_AIO
{
public class Builder
{
public Logger Logger { get; set; }
public bool Build(SettingsFile settings,string file)
{
List<string> loaderResources = new List<string>();
List<string> serSettings = new List<string>();
string defines = "";
if (settings.DownloadFiles.Count > 0)
{
Logger.LogInformation("Encoding downloader options...");
defines += "DOWNLOADER;";
foreach (DownloaderSetting ds in settings.DownloadFiles)
{
serSettings.Add(SerializeDictionary(ds.Dictionarize()));
}
}
string dllSource = Properties.Resources.Worker;
if (settings.BindFiles.Count > 0)
{
Logger.LogInformation("Encoding binder options...");
Logger.LogInformation("Generating binder resources...");
string binderResourceName = GenerateBinderResources(settings, serSettings);
dllSource = dllSource.Replace("%RESNAME%", binderResourceName);
loaderResources.Add(binderResourceName);
defines += "BINDER;";
}
dllSource = dllSource.Replace("/*SERIALIZED_SETTINGS*/", WriteSettingsList(serSettings, "options"));
/*SERIALIZED_SETTINGS*/
if (settings.CompressFiles)
{
defines += "COMPRESSION;";
}
if (settings.EncryptFiles)
{
defines += "ENCRYPTION;";
}
string outPath = string.Format("{0}.dll", WordGen.GenWord(5));
Logger.LogInformation("Compiling library...");
if (!Codedom.Compile(outPath, "cs", new string[] { dllSource }, null, defines, null, null, "library", 20))
{
return false;
}
byte[] dll = File.ReadAllBytes(outPath);
File.Delete(outPath);
string dllResourceName = string.Format("{0}.resources",WordGen.GenWord(5));
string dllResourceId = string.Format("{0}.dat",WordGen.GenWord(5));
Logger.LogInformation("Encrypting library...");
byte[] key = new byte[WordGen.R.Next(16, 24)];
WordGen.R.NextBytes(key);
for(int i = 0; i < dll.Length;i++)
{
dll[i] = (byte)(dll[i] ^ key[i % key.Length]);
}
using(ResourceWriter rw = new ResourceWriter(dllResourceName))
{
rw.AddResource(dllResourceId, dll);
rw.Generate();
}
loaderResources.Add(dllResourceName);
string loaderSource = Properties.Resources.Loader;
outPath = file;
loaderSource = loaderSource.Replace("/*ASM_INFO*/", GenerateAssemblyInfoSource(settings));
loaderSource = loaderSource.Replace("%KEY%",Convert.ToBase64String(key));
loaderSource = loaderSource.Replace("%RESNAME%", dllResourceName);
loaderSource = loaderSource.Replace("%RESID%", dllResourceId);
Logger.LogInformation("Compiling loader...");
if (!Codedom.Compile(outPath, "cs", new string[] { loaderSource }, settings.IconPath, null, new string[] { "System.Drawing.dll", "System.Windows.Forms.dll" }, loaderResources.ToArray(), "winexe", 20))
{
return false;
}
Logger.LogSuccess("Done");
return true;
}
private string WriteSettingsList(List<string> s,string varName)
{
StringBuilder sb = new StringBuilder();
foreach (string x in s)
{
sb.AppendFormat("{0}.Add(\"{1}\");\r\n", varName,x);
}
return sb.ToString();
}
private string GenerateAssemblyInfoSource(SettingsFile settings)
{
StringBuilder sb = new StringBuilder();
// settings.ass
sb.AppendLine("using System.Reflection;");
sb.AppendLine("using System.Runtime.CompilerServices;");
sb.AppendLine("using System.Runtime.InteropServices;");
sb.AppendFormat("[assembly: AssemblyTitle(\"{0}\")]\r\n", settings.AssemblyDescription);
sb.AppendLine("[assembly: AssemblyDescription(\"\")]");
sb.AppendLine("[assembly: AssemblyConfiguration(\"\")]");
sb.AppendFormat("[assembly: AssemblyCompany(\"{0}\")]\r\n", settings.AssemblyCompany);
sb.AppendFormat("[assembly: AssemblyProduct(\"{0}\")]\r\n", settings.AssemblyProductName);
sb.AppendFormat("[assembly: AssemblyCopyright(\"{0}\")]\r\n", settings.AssemblyCopyright);
sb.AppendLine("[assembly: AssemblyTrademark(\"\")]");
sb.AppendLine("[assembly: AssemblyCulture(\"\")]");
sb.AppendFormat("[assembly: Guid(\"{0}\")]", Guid.NewGuid().ToString("D"));
sb.AppendFormat("[assembly: AssemblyVersion(\"{0}\")]", settings.AssemblyVersion);
sb.AppendFormat("[assembly: AssemblyFileVersion(\"{0}\")]", settings.AssemblyVersion);
return sb.ToString();
}
private string GenerateBinderResources(SettingsFile settings,List<string> serSettings)
{
string resourceName = string.Format("{0}.resources", WordGen.GenWord(5));
using (ResourceWriter rw = new ResourceWriter(resourceName))
{
foreach (BinderSetting ds in settings.BindFiles)
{
Dictionary<string, string> dic = ds.Dictionarize();
byte[] boundFile = File.ReadAllBytes(ds.FileName);
if (settings.CompressFiles)
{
boundFile = QuickLz.Compress(boundFile);
}
if (settings.EncryptFiles)
{
using (RijndaelManaged rij = new RijndaelManaged())
{
rij.GenerateKey();
rij.GenerateIV();
dic.Add("ek", Convert.ToBase64String(rij.Key)); //encryption key
dic.Add("ei", Convert.ToBase64String(rij.IV)); //encryption iv
using (ICryptoTransform ict = rij.CreateEncryptor())
{
boundFile = ict.TransformFinalBlock(boundFile, 0, boundFile.Length);
}
}
}
string resKey = string.Format("{0}.dat", WordGen.GenWord(5));
dic.Add("r_k", resKey);
rw.AddResource(resKey, boundFile);
serSettings.Add(SerializeDictionary(dic));
}
rw.Generate();
}
return resourceName;
}
//foreach binded file a res file or not no
private string SerializeDictionary(Dictionary<string, string> options)
{
using (MemoryStream ms = new MemoryStream())
{
using (BinaryWriter bw = new BinaryWriter(ms, Encoding.UTF8))
{
bw.Write(options.Count);
foreach (var k in options)
{
bw.Write(k.Key);
bw.Write(k.Value);
}
}
return Convert.ToBase64String(ms.ToArray());
}
}
}
}
| 33.352459 | 213 | 0.507373 | [
"MIT"
] | rohan-patra/File-Binder-Pro | File-Binder-Pro-master/Dream AIO/Builder.cs | 8,140 | C# |
using Meel.Commands;
using Meel.Parsing;
using Meel.Responses;
using Meel.Stations;
using NUnit.Framework;
using System.Buffers;
using System.Text;
namespace Meel.Tests.Commands
{
[TestFixture]
public class RenameCommandTest
{
[Test]
public void ShouldRename()
{
// Arrange
var station = new InMemoryStation();
var user = "Piet";
var oldName = "Existing";
var newName = "Renamed";
station.CreateMailbox(user, oldName);
var command = new RenameCommand(station);
var response = new ImapResponse();
var context = new ConnectionContext(42);
context.State = SessionState.Authenticated;
context.Username = user;
var requestId = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes("123"));
var options = $"{oldName} {newName}".AsAsciiSpan();
// Act
command.Execute(context, requestId, options, ref response);
// Assert
var txt = response.ToString();
Assert.IsNotNull(txt);
StringAssert.DoesNotContain("BAD", txt);
StringAssert.DoesNotContain("NO", txt);
StringAssert.Contains("OK", txt);
Assert.IsNotNull(station.SelectMailbox(user, newName));
Assert.IsNull(station.SelectMailbox(user, oldName));
}
[Test]
public void ShouldFailToRenameNonExistingBox()
{
// Arrange
var station = new InMemoryStation();
var user = "Piet";
var oldName = "NonExisting";
var newName = "Renamed";
var command = new RenameCommand(station);
var response = new ImapResponse();
var context = new ConnectionContext(42);
context.State = SessionState.Authenticated;
context.Username = user;
var requestId = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes("123"));
var options = $"{oldName} {newName}".AsAsciiSpan();
// Act
command.Execute(context, requestId, options, ref response);
// Assert
var txt = response.ToString();
Assert.IsNotNull(txt);
StringAssert.DoesNotContain("OK", txt);
StringAssert.DoesNotContain("BAD", txt);
StringAssert.Contains("NO", txt);
Assert.IsNull(station.SelectMailbox(user, newName));
Assert.IsNull(station.SelectMailbox(user, oldName));
}
[Test]
public void ShouldFailToRenameToExistingBox()
{
// Arrange
var station = new InMemoryStation();
var user = "Piet";
var oldName = "Existing";
var newName = "Destination";
station.CreateMailbox(user, oldName);
station.CreateMailbox(user, newName);
var command = new RenameCommand(station);
var response = new ImapResponse();
var context = new ConnectionContext(42);
context.State = SessionState.Authenticated;
context.Username = user;
var requestId = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes("123"));
var options = $"{oldName} {newName}".AsAsciiSpan();
// Act
command.Execute(context, requestId, options, ref response);
// Assert
var txt = response.ToString();
Assert.IsNotNull(txt);
StringAssert.DoesNotContain("OK", txt);
StringAssert.DoesNotContain("BAD", txt);
StringAssert.Contains("NO", txt);
}
[Test]
public void ShouldNotRenameBeforeLogin()
{
// Arrange
var station = new InMemoryStation();
var user = "Piet";
var box = "Existing";
station.CreateMailbox(user, box);
var command = new RenameCommand(station);
var response = new ImapResponse();
var context = new ConnectionContext(42);
context.Username = user;
var requestId = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes("123"));
var options = box.AsAsciiSpan();
// Act
command.Execute(context, requestId, options, ref response);
// Assert
var txt = response.ToString();
Assert.IsNotNull(txt);
StringAssert.DoesNotContain("OK", txt);
StringAssert.DoesNotContain("NO", txt);
StringAssert.Contains("BAD", txt);
}
[Test]
public void ShouldNotRenameAfterLogout()
{
// Arrange
var station = new InMemoryStation();
var user = "Piet";
var box = "Existing";
station.CreateMailbox(user, box);
var command = new RenameCommand(station);
var response = new ImapResponse();
var context = new ConnectionContext(42);
context.State = SessionState.Logout;
context.Username = user;
var requestId = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes("123"));
var options = box.AsAsciiSpan();
// Act
command.Execute(context, requestId, options, ref response);
// Assert
var txt = response.ToString();
Assert.IsNotNull(txt);
StringAssert.DoesNotContain("OK", txt);
StringAssert.DoesNotContain("NO", txt);
StringAssert.Contains("BAD", txt);
}
[Test]
public void ShouldReturnBadWithSingleArgument()
{
// Arrange
var station = new InMemoryStation();
var user = "Piet";
var box = "Existing";
station.CreateMailbox(user, box);
var command = new RenameCommand(station);
var response = new ImapResponse();
var context = new ConnectionContext(42);
context.State = SessionState.Authenticated;
context.Username = user;
var requestId = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes("123"));
var options = box.AsAsciiSpan();
// Act
command.Execute(context, requestId, options, ref response);
// Assert
var txt = response.ToString();
Assert.IsNotNull(txt);
StringAssert.DoesNotContain("OK", txt);
StringAssert.DoesNotContain("NO", txt);
StringAssert.Contains("BAD", txt);
}
[Test]
public void ShouldReturnBadWithoutArgument()
{
// Arrange
var station = new InMemoryStation();
var user = "Piet";
var command = new RenameCommand(station);
var response = new ImapResponse();
var context = new ConnectionContext(42);
context.State = SessionState.Authenticated;
context.Username = user;
var requestId = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes("123"));
var options = "".AsAsciiSpan();
// Act
command.Execute(context, requestId, options, ref response);
// Assert
var txt = response.ToString();
Assert.IsNotNull(txt);
StringAssert.DoesNotContain("OK", txt);
StringAssert.DoesNotContain("NO", txt);
StringAssert.Contains("BAD", txt);
}
}
}
| 38.680412 | 87 | 0.558236 | [
"MIT"
] | ynse01/meel | Tests/Commands/RenameCommandTest.cs | 7,506 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Shirley.Book.DataAccess;
namespace Shirley.Book.DataAccess.Migrations
{
[DbContext(typeof(BookContext))]
[Migration("20200913083246_add-concurrency-for-stock-count")]
partial class addconcurrencyforstockcount
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.8");
modelBuilder.Entity("BookApi.Model.UserInfo", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Pwd")
.HasColumnType("TEXT");
b.Property<string>("UserName")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("UserInfo");
});
modelBuilder.Entity("Shirley.Book.Model.BookOrder", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<DateTime>("CreatedTime")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("BookOrders");
});
modelBuilder.Entity("Shirley.Book.Model.BookOrderDetail", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("BookOrderId")
.HasColumnType("TEXT");
b.Property<int>("Count")
.HasColumnType("INTEGER");
b.Property<string>("OrderId")
.HasColumnType("TEXT");
b.Property<string>("Sn")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("BookOrderId");
b.ToTable("BookOrderDetials");
});
modelBuilder.Entity("Shirley.Book.Model.BookStock", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("Sn")
.HasColumnType("TEXT");
b.Property<int>("StockCount")
.IsConcurrencyToken()
.HasColumnType("INTEGER");
b.HasKey("Id");
b.ToTable("BookStocks");
});
modelBuilder.Entity("Shirley.Book.Model.OrderStock", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<int>("Count")
.HasColumnType("INTEGER");
b.Property<DateTime>("CreatedTime")
.HasColumnType("TEXT");
b.Property<string>("OrderId")
.HasColumnType("TEXT");
b.Property<string>("Sn")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("OrderStocks");
});
modelBuilder.Entity("Shirley.Book.Model.BookOrderDetail", b =>
{
b.HasOne("Shirley.Book.Model.BookOrder", null)
.WithMany("OrderDetails")
.HasForeignKey("BookOrderId");
});
#pragma warning restore 612, 618
}
}
}
| 31.625 | 75 | 0.454051 | [
"MIT"
] | YizhixiaoMoJun/BookStore | src/Shirley.Book.DataAccess/Migrations/20200913083246_add-concurrency-for-stock-count.Designer.cs | 4,050 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Writa.Models;
using BCrypt;
namespace Writa.Frontend.Controllers.api
{
public class AddUserRequest
{
public string UserFullName { get; set; }
public string EmailAddress { get; set; }
public string Password { get; set; }
}
public class UpdateUserRequest
{
public string Id { get; set; }
public string UserFullName { get; set; }
public string EmailAddress { get; set; }
public AccountType UserType { get; set; }
}
public class ChangePasswordRequest
{
public string Id { get; set; }
public string NewPassword { get; set; }
public string ConfirmNewPassword { get; set; }
}
[RoutePrefix("api")]
public class UserAdminController : ApiController
{
private IDataHelper _dbhelper;
public UserAdminController(IDataHelper dbhelper)
{
_dbhelper = dbhelper;
}
// GET api/<controller>
[Route("updateuser")]
[HttpPost]
public string UpdateUser(UpdateUserRequest a)
{
var user = _dbhelper.GetUserById(new WritaUser() { Id = a.Id });
user.EmailAddress = a.EmailAddress;
user.UserFullName = a.UserFullName;
user.UserType = a.UserType;
_dbhelper.UpdateUser(user);
return "Updated";
}
// GET api/<controller>
[Route("changepassword")]
[HttpPost]
public string UpdateUser(ChangePasswordRequest a)
{
var user = _dbhelper.GetUserById(new WritaUser() { Id = a.Id });
var newEncpassword = BCrypt.Net.BCrypt.HashPassword(a.NewPassword, 13);
_dbhelper.UpdateUser(user);
return "Updated";
}
// GET api/<controller>
[Route("adduser")]
[HttpPost]
public string AddUser(AddUserRequest a)
{
var newEncpassword = BCrypt.Net.BCrypt.HashPassword(a.Password, 13);
WritaUser newUser = new WritaUser()
{
EmailAddress = a.EmailAddress,
DateRegistered = DateTime.Now,
DateLastLogin = DateTime.Now,
UserFullName = a.UserFullName,
UserPasswordEncrypted = newEncpassword,
UserIpAddress = ""
};
WritaUser u = _dbhelper.CreateUser(newUser);
return "User "+ a.EmailAddress + " was created";
}
}
} | 28.5 | 87 | 0.576659 | [
"Apache-2.0"
] | cdc1979/Writa | Writa.Frontend/Controllers/api/UserAdminController.cs | 2,624 | C# |
using Assets.Scripts.Data.Entities;
namespace Assets.Scripts.Services
{
public interface IWeaponService : IService<WeaponModel>
{
}
}
| 16.444444 | 59 | 0.72973 | [
"MIT"
] | Jimud1/RpgProject | Test Project/Jimmy Rpg/Assets/Scripts/Services/Weapon/IWeaponService.cs | 150 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using MPT.Geometry.Shapes;
using MPT.Geometry.Tools;
using MPT.Math.Coordinates;
using NUnit.Framework;
namespace MPT.Geometry.UnitTests.Shapes
{
[TestFixture]
public static class IsoscelesRightTriangleTests
{
public static double Tolerance = 0.00001;
private static List<CartesianCoordinate> triangleCoordinates = new List<CartesianCoordinate>()
{
new CartesianCoordinate(0, 0),
new CartesianCoordinate(4, 0),
new CartesianCoordinate(0, 4),
};
#region Initialization
[Test]
public static void Initialization_with_Coordinates_Creates_Shape()
{
IsoscelesRightTriangle triangle = new IsoscelesRightTriangle(4);
Assert.AreEqual(GeometryLibrary.ZeroTolerance, triangle.Tolerance);
Assert.AreEqual(3, triangle.Points.Count);
Assert.AreEqual(triangleCoordinates[0].X, triangle.SideA.I.X);
Assert.AreEqual(triangleCoordinates[0].Y, triangle.SideA.I.Y, Tolerance);
Assert.AreEqual(triangleCoordinates[1], triangle.SideA.J);
Assert.AreEqual(triangleCoordinates[1], triangle.SideB.I);
Assert.AreEqual(triangleCoordinates[2], triangle.SideB.J);
Assert.AreEqual(triangleCoordinates[2], triangle.SideC.I);
Assert.AreEqual(triangleCoordinates[0].X, triangle.SideC.J.X);
Assert.AreEqual(triangleCoordinates[0].Y, triangle.SideC.J.Y, Tolerance);
Assert.AreEqual(3, triangle.Sides.Count);
Assert.AreEqual(4, triangle.SideA.Length(), Tolerance);
Assert.AreEqual(5.656854249, triangle.SideB.Length(), Tolerance);
Assert.AreEqual(4, triangle.SideC.Length(), Tolerance);
Assert.AreEqual(3, triangle.Angles.Count);
Assert.AreEqual(45, triangle.AngleA.Degrees, Tolerance);
Assert.AreEqual(90, triangle.AngleB.Degrees, Tolerance);
Assert.AreEqual(45, triangle.AngleC.Degrees, Tolerance);
Assert.AreEqual(2.82843, triangle.h, Tolerance);
Assert.AreEqual(1.333333, triangle.Centroid.X, Tolerance);
Assert.AreEqual(1.333333, triangle.Centroid.Y, Tolerance);
Assert.AreEqual(0, triangle.OrthoCenter.X, Tolerance);
Assert.AreEqual(0, triangle.OrthoCenter.Y, Tolerance);
Assert.AreEqual(2.828427125, triangle.CircumRadius, Tolerance);
Assert.AreEqual(2, triangle.CircumCenter.X, Tolerance);
Assert.AreEqual(2, triangle.CircumCenter.Y, Tolerance);
Assert.AreEqual(1.171572875, triangle.InRadius, Tolerance);
Assert.AreEqual(1.171572875, triangle.InCenter.X, Tolerance);
Assert.AreEqual(1.171572875, triangle.InCenter.Y, Tolerance);
}
#endregion
#region Methods
[Test]
public static void Area()
{
IsoscelesRightTriangle triangle = new IsoscelesRightTriangle(4);
double area = triangle.Area();
Assert.AreEqual(8, area, Tolerance);
}
[Test]
public static void LocalCoordinates()
{
IsoscelesRightTriangle triangle = new IsoscelesRightTriangle(4);
IList<CartesianCoordinate> coordinates = triangle.LocalCoordinates();
Assert.AreEqual(3, coordinates.Count);
Assert.AreEqual(triangleCoordinates[0].X, coordinates[0].X);
Assert.AreEqual(triangleCoordinates[0].Y, coordinates[0].Y, Tolerance);
Assert.AreEqual(triangleCoordinates[1], coordinates[1]);
Assert.AreEqual(triangleCoordinates[2], coordinates[2]);
}
#endregion
}
}
| 39.53125 | 102 | 0.652701 | [
"MIT"
] | MarkPThomas/MPT.Geometry-.netCore | MPT.Geometry.UnitTests/Shapes/IsoscelesRightTriangleTests.cs | 3,797 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Duality.Editor;
namespace create_object_with_mouseclick.Editor
{
/// <summary>
/// Defines a Duality editor plugin.
/// </summary>
public class create_object_with_mouseclickEditorPlugin : EditorPlugin
{
public override string Id
{
get { return "create_object_with_mouseclickEditorPlugin"; }
}
}
}
| 19.52381 | 73 | 0.753659 | [
"MIT"
] | GameTemplates/Duality-Examples | create-physics-object-with-mouseclick/src/Source/Code/EditorPlugin/EditorPlugin.cs | 412 | 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>
//------------------------------------------------------------------------------
[assembly: global::Xamarin.Forms.Xaml.XamlResourceIdAttribute("ProtogenControl.Views.AboutPage.xaml", "Views/AboutPage.xaml", typeof(global::ProtogenControl.Views.AboutPage))]
namespace ProtogenControl.Views {
[global::Xamarin.Forms.Xaml.XamlFilePathAttribute("Views\\AboutPage.xaml")]
public partial class AboutPage : global::Xamarin.Forms.ContentPage {
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "2.0.0.0")]
private void InitializeComponent() {
global::Xamarin.Forms.Xaml.Extensions.LoadFromXaml(this, typeof(AboutPage));
}
}
}
| 43.28 | 175 | 0.60536 | [
"CC0-1.0"
] | oscar-almaraz/ProtogenControl | ProtogenControl/ProtogenControl/obj/Debug/netstandard2.0/Views/AboutPage.xaml.g.cs | 1,087 | C# |
using System;
namespace Miris.DomainEvents.ImmediateConsistency
{
/// <summary>
/// Usado para especificar se <see cref="TransactionScopeInterceptor"/> vai criar um
/// escopo transacional para o Proxied method.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class ImplicitTransactionScopeAttribute
: Attribute
{
public ImplicitTransactionScopeAttribute(bool criar)
{
Criar = criar;
}
public readonly bool Criar;
}
}
| 22.153846 | 93 | 0.649306 | [
"MIT"
] | marcusmiris/DomainEvents | Miris.DomainEvents/ImmediateConsistency/ImplicitTransactionScopeAttribute.cs | 578 | C# |
namespace _03.BiDictionary
{
using System;
public class Startup
{
public static void Main(string[] args)
{
var dict = new BiDictionary<int, int, string>();
dict.Add(1, 1, "Pesho");
dict.Add(1, 21, "Gosho");
dict.Add(2, 1, "Stamat");
dict.Add(1, 3, "Mariika");
Console.WriteLine(dict[1, 3]);
Console.WriteLine(dict[1, 1]);
var collectionByKey2 = dict.GetByKey2(1);
Console.WriteLine(string.Join(", ", collectionByKey2));
}
}
}
| 24.208333 | 69 | 0.509466 | [
"MIT"
] | ni4ka7a/TelerikAcademyHomeworks | DataStructuresAndAlgorithms/06.DataStructureEfficiency/03.BiDictionary/Startup.cs | 583 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Extensions.Internal;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Query.Internal;
using Microsoft.EntityFrameworkCore.Utilities;
using Remotion.Linq;
using Remotion.Linq.Clauses;
using Remotion.Linq.Clauses.Expressions;
using Remotion.Linq.Parsing;
namespace Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal
{
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public class CollectionNavigationSubqueryInjector : RelinqExpressionVisitor
{
private readonly EntityQueryModelVisitor _queryModelVisitor;
private static readonly List<string> _collectionMaterializingMethodNames = new List<string>
{
nameof(Enumerable.ToArray),
nameof(Enumerable.ToDictionary),
nameof(Enumerable.ToList),
nameof(Enumerable.ToLookup)
};
private static readonly List<MethodInfo> _collectionMaterializingMethods
= typeof(Enumerable).GetRuntimeMethods().Where(m => _collectionMaterializingMethodNames.Contains(m.Name))
.Concat(typeof(AsyncEnumerable).GetRuntimeMethods().Where(m => _collectionMaterializingMethodNames.Contains(m.Name)))
.Where(m => m.GetParameters().Length == 1).ToList();
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public CollectionNavigationSubqueryInjector([NotNull] EntityQueryModelVisitor queryModelVisitor, bool shouldInject = false)
{
Check.NotNull(queryModelVisitor, nameof(queryModelVisitor));
_queryModelVisitor = queryModelVisitor;
ShouldInject = shouldInject;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual bool ShouldInject { get; set; }
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public static readonly MethodInfo MaterializeCollectionNavigationMethodInfo
= typeof(CollectionNavigationSubqueryInjector).GetTypeInfo()
.GetDeclaredMethod(nameof(MaterializeCollectionNavigation));
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitMember(MemberExpression memberExpression)
{
Check.NotNull(memberExpression, nameof(memberExpression));
var newMemberExpression = default(Expression);
if (ShouldInject)
{
newMemberExpression = _queryModelVisitor.BindNavigationPathPropertyExpression(
memberExpression,
(properties, querySource) =>
{
var collectionNavigation = properties.OfType<INavigation>().SingleOrDefault(n => n.IsCollection());
return collectionNavigation != null
? InjectSubquery(memberExpression, collectionNavigation)
: default;
});
}
return newMemberExpression ?? base.VisitMember(memberExpression);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression)
{
Check.NotNull(methodCallExpression, nameof(methodCallExpression));
if (methodCallExpression.Method.MethodIsClosedFormOf(MaterializeCollectionNavigationMethodInfo)
|| IncludeCompiler.IsIncludeMethod(methodCallExpression))
{
return methodCallExpression;
}
var shouldInject = ShouldInject;
if (!methodCallExpression.Method.IsEFPropertyMethod()
&& !_collectionMaterializingMethods.Any(m => methodCallExpression.Method.MethodIsClosedFormOf(m)))
{
ShouldInject = true;
}
var newMethodCallExpression = default(Expression);
if (ShouldInject)
{
newMethodCallExpression = _queryModelVisitor.BindNavigationPathPropertyExpression(
methodCallExpression,
(properties, querySource) =>
{
var collectionNavigation = properties.OfType<INavigation>().SingleOrDefault(n => n.IsCollection());
return collectionNavigation != null
? InjectSubquery(methodCallExpression, collectionNavigation)
: default;
});
}
try
{
return newMethodCallExpression ?? base.VisitMethodCall(methodCallExpression);
}
finally
{
ShouldInject = shouldInject;
}
}
private Expression InjectSubquery(Expression expression, INavigation collectionNavigation)
{
var targetType = collectionNavigation.GetTargetType().ClrType;
var mainFromClause = new MainFromClause(targetType.Name.Substring(0, 1).ToLowerInvariant(), targetType, expression);
var selector = new QuerySourceReferenceExpression(mainFromClause);
_queryModelVisitor.QueryCompilationContext.AddOrUpdateMapping(mainFromClause, collectionNavigation.GetTargetType());
var subqueryModel = new QueryModel(mainFromClause, new SelectClause(selector));
var subqueryExpression = new SubQueryExpression(subqueryModel);
var resultCollectionType = collectionNavigation.GetCollectionAccessor().CollectionType;
var result = Expression.Call(
MaterializeCollectionNavigationMethodInfo.MakeGenericMethod(targetType),
Expression.Constant(collectionNavigation), subqueryExpression);
return resultCollectionType.GetTypeInfo().IsGenericType && resultCollectionType.GetGenericTypeDefinition() == typeof(ICollection<>)
? (Expression)result
: Expression.Convert(result, resultCollectionType);
}
[UsedImplicitly]
private static ICollection<TEntity> MaterializeCollectionNavigation<TEntity>(
INavigation navigation,
IEnumerable<object> elements)
{
var collection = navigation.GetCollectionAccessor().Create(elements);
return (ICollection<TEntity>)collection;
}
}
}
| 49.84153 | 143 | 0.663962 | [
"Apache-2.0"
] | BionStt/EntityFrameworkCore | src/EFCore/Query/ExpressionVisitors/Internal/CollectionNavigationSubqueryInjector.cs | 9,123 | C# |
using System.IO;
using System.Runtime.Serialization;
using GameEstate.Red.Formats.Red.CR2W.Reflection;
using FastMember;
using static GameEstate.Red.Formats.Red.Records.Enums;
namespace GameEstate.Red.Formats.Red.Types
{
[DataContract(Namespace = "")]
[REDMeta]
public class CModSbUiIdlePoseList : CModUiFilteredList
{
public CModSbUiIdlePoseList(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ }
public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CModSbUiIdlePoseList(cr2w, parent, name);
public override void Read(BinaryReader file, uint size) => base.Read(file, size);
public override void Write(BinaryWriter file) => base.Write(file);
}
} | 32.434783 | 132 | 0.75067 | [
"MIT"
] | bclnet/GameEstate | src/Estates/Red/GameEstate.Red.Format/Red/W3/RTTIConvert/CModSbUiIdlePoseList.cs | 746 | C# |
using System;
public class InvalidSongException : Exception
{
public InvalidSongException(string message = "Invalid song.")
: base(message)
{
}
} | 18.666667 | 66 | 0.666667 | [
"MIT"
] | pirocorp/C-OOP-Basics- | 04. Inheritance/04. Inheritance - Exercises/P04_OnlineRadioDatabase/Exceptions/InvalidSongException.cs | 170 | C# |
namespace Datadog.Trace.ClrProfiler.Interfaces
{
internal interface IHttpSpanTagsSource
{
string GetHttpMethod();
string GetHttpHost();
string GetHttpUrl();
}
}
| 16.583333 | 46 | 0.653266 | [
"Apache-2.0"
] | alonf/dd-trace-dotnet | src/Datadog.Trace.ClrProfiler.Managed/Interfaces/IHttpSpanTagsSource.cs | 199 | C# |
using eroller.logic;
using Nancy;
using Nancy.TinyIoc;
namespace eroller.web
{
public class Bootstrapper : DefaultNancyBootstrapper
{
protected override void ConfigureApplicationContainer(TinyIoCContainer container) {
base.ConfigureApplicationContainer(container);
container.Register<Interactors>().AsSingleton();
}
}
} | 24.866667 | 91 | 0.713137 | [
"MIT"
] | slieser/eroller | eroller/eroller.web/Bootstrapper.cs | 373 | C# |
using System.Threading;
using System.Threading.Tasks;
namespace StableCube.DigitalOcean.DotNetClient
{
public interface IDropletEndpoint
{
Task<Droplet> GetAsync(
int dropletId,
CancellationToken cancellationToken = default(CancellationToken)
);
Task<Droplet> GetByTagSingleOrDefaultAsync(
string tag,
CancellationToken cancellationToken = default(CancellationToken)
);
Task<DropletList> GetAllAsync(
CancellationToken cancellationToken = default(CancellationToken)
);
Task<DropletList> GetByTagAsync(
string tag,
CancellationToken cancellationToken = default(CancellationToken)
);
Task<Droplet> CreateAsync(
DropletCreate data,
CancellationToken cancellationToken = default(CancellationToken)
);
Task DeleteAsync(
int dropletId,
CancellationToken cancellationToken = default(CancellationToken)
);
Task DeleteByTagAsync(
string tag,
CancellationToken cancellationToken = default(CancellationToken)
);
}
} | 29.333333 | 77 | 0.618506 | [
"MIT"
] | StableCube/DigitalOcean | DotNetClient/src/EndpointsV2/IDropletEndpoint.cs | 1,232 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("tSQLtTestUtilCLR")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("tSQLtTestUtilCLR")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("82c6526b-de5c-4b32-a99b-24d75acb9f4f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: System.Security.AllowPartiallyTrustedCallers] | 39.447368 | 85 | 0.733155 | [
"Apache-2.0"
] | Amith211/tSQLt | tSQLtCLR/tSQLtTestUtilCLR/Properties/AssemblyInfo.cs | 1,502 | C# |
using System;
using System.Linq;
using Ploeh.AutoFixture.Kernel;
using Xunit;
namespace Ploeh.AutoFixtureUnitTest.Kernel
{
public class FilteringSpecimenBuilderTest
{
[Fact]
public void SutIsSpecimenBuilder()
{
// Fixture setup
var dummySpecification = new DelegatingRequestSpecification();
var dummyBuilder = new DelegatingSpecimenBuilder();
// Exercise system
var sut = new FilteringSpecimenBuilder(dummyBuilder, dummySpecification);
// Verify outcome
Assert.IsAssignableFrom<ISpecimenBuilder>(sut);
// Teardown
}
[Fact]
public void InitializeWithNullBuilderWillThrows()
{
// Fixture setup
var dummySpecification = new DelegatingRequestSpecification();
// Exercise system and verify outcome
Assert.Throws<ArgumentNullException>(() => new FilteringSpecimenBuilder(null, dummySpecification));
// Teardown
}
[Fact]
public void InitializeWithNullSpecificationWillThrow()
{
// Fixture setup
var dummyBuilder = new DelegatingSpecimenBuilder();
// Exercise system and verify outcome
Assert.Throws<ArgumentNullException>(() => new FilteringSpecimenBuilder(dummyBuilder, null));
// Teardown
}
[Fact]
public void BuilderIsCorrect()
{
// Fixture setup
var expectedBuilder = new DelegatingSpecimenBuilder();
var dummySpecification = new DelegatingRequestSpecification();
var sut = new FilteringSpecimenBuilder(expectedBuilder, dummySpecification);
// Exercise system
ISpecimenBuilder result = sut.Builder;
// Verify outcome
Assert.Equal(expectedBuilder, result);
// Teardown
}
[Fact]
public void SpecificationIsCorrect()
{
// Fixture setup
var dummyBuilder = new DelegatingSpecimenBuilder();
var expectedSpecification = new DelegatingRequestSpecification();
var sut = new FilteringSpecimenBuilder(dummyBuilder, expectedSpecification);
// Exercise system
IRequestSpecification result = sut.Specification;
// Verify outcome
Assert.Equal(expectedSpecification, result);
// Teardown
}
[Fact]
public void CreateReturnsCorrectResultWhenSpecificationIsNotSatisfied()
{
// Fixture setup
var spec = new DelegatingRequestSpecification { OnIsSatisfiedBy = r => false };
var dummyBuilder = new DelegatingSpecimenBuilder();
var sut = new FilteringSpecimenBuilder(dummyBuilder, spec);
var request = new object();
// Exercise system
var dummyContainer = new DelegatingSpecimenContext();
var result = sut.Create(request, dummyContainer);
// Verify outcome
var expectedResult = new NoSpecimen(request);
Assert.Equal(expectedResult, result);
// Teardown
}
[Fact]
public void SpecificationReceivesCorrectRequest()
{
// Fixture setup
var expectedRequest = new object();
var verified = false;
var specMock = new DelegatingRequestSpecification { OnIsSatisfiedBy = r => verified = expectedRequest == r };
var dummyBuilder = new DelegatingSpecimenBuilder();
var sut = new FilteringSpecimenBuilder(dummyBuilder, specMock);
// Exercise system
var dummyContainer = new DelegatingSpecimenContext();
sut.Create(expectedRequest, dummyContainer);
// Verify outcome
Assert.True(verified, "Mock verified");
// Teardown
}
[Fact]
public void CreateReturnsCorrectResultWhenFilterAllowsRequestThrough()
{
// Fixture setup
var expectedResult = new object();
var spec = new DelegatingRequestSpecification { OnIsSatisfiedBy = r => true };
var builder = new DelegatingSpecimenBuilder { OnCreate = (r, c) => expectedResult };
var sut = new FilteringSpecimenBuilder(builder, spec);
// Exercise system
var dummyRequest = new object();
var dummyContainer = new DelegatingSpecimenContext();
var result = sut.Create(dummyRequest, dummyContainer);
// Verify outcome
Assert.Equal(expectedResult, result);
// Teardown
}
[Fact]
public void CreatePassesCorrectParametersToDecoratedBuilder()
{
// Fixture setup
var expectedRequest = new object();
var expectedContainer = new DelegatingSpecimenContext();
var verified = false;
var builderMock = new DelegatingSpecimenBuilder { OnCreate = (r, c) => verified = r == expectedRequest && c == expectedContainer };
var spec = new DelegatingRequestSpecification { OnIsSatisfiedBy = r => true };
var sut = new FilteringSpecimenBuilder(builderMock, spec);
// Exercise system
sut.Create(expectedRequest, expectedContainer);
// Verify outcome
Assert.True(verified, "Mock verified");
// Teardown
}
[Fact]
public void SutIsNode()
{
// Fixture setup
var dummyBuilder = new DelegatingSpecimenBuilder();
var dummySpecification = new DelegatingRequestSpecification();
// Exercise system
var sut = new FilteringSpecimenBuilder(dummyBuilder, dummySpecification);
// Verify outcome
Assert.IsAssignableFrom<ISpecimenBuilderNode>(sut);
// Teardown
}
[Fact]
public void SutYieldsDecoratedBuilder()
{
// Fixture setup
var expected = new DelegatingSpecimenBuilder();
var dummySpecification = new DelegatingRequestSpecification();
// Exercise system
var sut = new FilteringSpecimenBuilder(expected, dummySpecification);
// Verify outcome
Assert.True(new[] { expected }.SequenceEqual(sut));
Assert.True(new object[] { expected }.SequenceEqual(((System.Collections.IEnumerable)sut).Cast<object>()));
// Teardown
}
[Fact]
public void ComposeReturnsCorrectResult()
{
// Fixture setup
var dummyBuilder = new DelegatingSpecimenBuilder();
var dummySpecification = new DelegatingRequestSpecification();
var sut = new FilteringSpecimenBuilder(dummyBuilder, dummySpecification);
// Exercise system
var expectedBuilders = new[]
{
new DelegatingSpecimenBuilder(),
new DelegatingSpecimenBuilder(),
new DelegatingSpecimenBuilder()
};
var actual = sut.Compose(expectedBuilders);
// Verify outcome
var f = Assert.IsAssignableFrom<FilteringSpecimenBuilder>(actual);
var composite = Assert.IsAssignableFrom<CompositeSpecimenBuilder>(f.Builder);
Assert.True(expectedBuilders.SequenceEqual(composite));
// Teardown
}
[Fact]
public void ComposeSingleItemReturnsCorrectResult()
{
// Fixture setup
var dummyBuilder = new DelegatingSpecimenBuilder();
var dummySpecification = new DelegatingRequestSpecification();
var sut = new FilteringSpecimenBuilder(dummyBuilder, dummySpecification);
// Exercise system
var expected = new DelegatingSpecimenBuilder();
var actual = sut.Compose(new[] { expected });
// Verify outcome
var f = Assert.IsAssignableFrom<FilteringSpecimenBuilder>(actual);
Assert.Equal(expected, f.Builder);
// Teardown
}
[Fact]
public void ComposePreservesSpecification()
{
// Fixture setup
var dummyBuilder = new DelegatingSpecimenBuilder();
var expected = new DelegatingRequestSpecification();
var sut = new FilteringSpecimenBuilder(dummyBuilder, expected);
// Exercise system
var actual = sut.Compose(new ISpecimenBuilder[0]);
// Verify outcome
var f = Assert.IsAssignableFrom<FilteringSpecimenBuilder>(actual);
Assert.Equal(expected, f.Specification);
// Teardown
}
}
}
| 40.778281 | 144 | 0.585331 | [
"MIT"
] | jrnail23/AutoFixture | Src/AutoFixtureUnitTest/Kernel/FilteringSpecimenBuilderTest.cs | 9,014 | C# |
namespace CheckoutAuthCodeGrant.Models.PaymentsApi
{
using Newtonsoft.Json;
/// <summary>
/// Data model for a public key from Payments API.
/// </summary>
/// <remarks>
/// https://developer.sky.blackbaud.com/docs/services/payments/operations/GetPublicKey
/// </remarks>
public class PublicKeyData
{
[JsonProperty("public_key")]
public string Value { get; set; }
}
}
| 25.058824 | 90 | 0.63615 | [
"MIT"
] | blackbaud/payments-checkout-authcodegrant-sample | src/CheckoutAuthCodeGrant/Models/PaymentsApi/PublicKeyData.cs | 428 | 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 workdocs-2016-05-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.WorkDocs.Model
{
/// <summary>
/// You've reached the limit on the number of subscriptions for the WorkDocs instance.
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public partial class TooManySubscriptionsException : AmazonWorkDocsException
{
/// <summary>
/// Constructs a new TooManySubscriptionsException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public TooManySubscriptionsException(string message)
: base(message) {}
/// <summary>
/// Construct instance of TooManySubscriptionsException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public TooManySubscriptionsException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of TooManySubscriptionsException
/// </summary>
/// <param name="innerException"></param>
public TooManySubscriptionsException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of TooManySubscriptionsException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public TooManySubscriptionsException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of TooManySubscriptionsException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public TooManySubscriptionsException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the TooManySubscriptionsException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected TooManySubscriptionsException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception>
#if BCL35
[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand,
Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)]
#endif
[System.Security.SecurityCritical]
// These FxCop rules are giving false-positives for this method
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
}
#endif
}
} | 47.774194 | 178 | 0.683997 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/WorkDocs/Generated/Model/TooManySubscriptionsException.cs | 5,924 | C# |
using Jint.Native.Object;
using Jint.Runtime;
using Jint.Runtime.Descriptors;
using Jint.Runtime.Descriptors.Specialized;
using Jint.Runtime.Interop;
namespace Jint.Native.Function
{
/// <summary>
/// http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.4
/// </summary>
public sealed class FunctionPrototype : FunctionInstance
{
private FunctionPrototype(Engine engine)
: base(engine, "Function", null, null, false)
{
}
public static FunctionPrototype CreatePrototypeObject(Engine engine)
{
var obj = new FunctionPrototype(engine);
obj.Extensible = true;
// The value of the [[Prototype]] internal property of the Function prototype object is the standard built-in Object prototype object
obj.Prototype = engine.Object.PrototypeObject;
obj.SetOwnProperty("length", new PropertyDescriptor(0, PropertyFlag.AllForbidden));
return obj;
}
public void Configure()
{
SetOwnProperty("constructor", new PropertyDescriptor(Engine.Function, PropertyFlag.NonEnumerable));
FastAddProperty("toString", new ClrFunctionInstance(Engine, "toString", ToString), true, false, true);
FastAddProperty("apply", new ClrFunctionInstance(Engine, "apply", Apply, 2), true, false, true);
FastAddProperty("call", new ClrFunctionInstance(Engine, "call", CallImpl, 1), true, false, true);
FastAddProperty("bind", new ClrFunctionInstance(Engine, "bind", Bind, 1), true, false, true);
}
private JsValue Bind(JsValue thisObj, JsValue[] arguments)
{
var target = thisObj.TryCast<ICallable>(x =>
{
ExceptionHelper.ThrowTypeError(Engine);
});
var thisArg = arguments.At(0);
var f = new BindFunctionInstance(Engine) {Extensible = true};
f.TargetFunction = thisObj;
f.BoundThis = thisArg;
f.BoundArgs = arguments.Skip(1);
f.Prototype = Engine.Function.PrototypeObject;
var o = target as FunctionInstance;
if (!ReferenceEquals(o, null))
{
var l = TypeConverter.ToNumber(o.Get("length")) - (arguments.Length - 1);
f.SetOwnProperty("length", new PropertyDescriptor(System.Math.Max(l, 0), PropertyFlag.AllForbidden));
}
else
{
f.SetOwnProperty("length", new PropertyDescriptor(0, PropertyFlag.AllForbidden));
}
var thrower = Engine.Function.ThrowTypeError;
const PropertyFlag flags = PropertyFlag.EnumerableSet | PropertyFlag.ConfigurableSet;
f.DefineOwnProperty("caller", new GetSetPropertyDescriptor(thrower, thrower, flags), false);
f.DefineOwnProperty("arguments", new GetSetPropertyDescriptor(thrower, thrower, flags), false);
return f;
}
private JsValue ToString(JsValue thisObj, JsValue[] arguments)
{
var func = thisObj.TryCast<FunctionInstance>();
if (ReferenceEquals(func, null))
{
ExceptionHelper.ThrowTypeError(_engine, "Function object expected.");
}
return "function() {{ ... }}";
}
public JsValue Apply(JsValue thisObject, JsValue[] arguments)
{
var func = thisObject.TryCast<ICallable>();
var thisArg = arguments.At(0);
var argArray = arguments.At(1);
if (func == null)
{
ExceptionHelper.ThrowTypeError(Engine);
}
if (argArray.IsNull() || argArray.IsUndefined())
{
return func.Call(thisArg, Arguments.Empty);
}
var argArrayObj = argArray.TryCast<ObjectInstance>();
if (ReferenceEquals(argArrayObj, null))
{
ExceptionHelper.ThrowTypeError(Engine);
}
var len = ((JsNumber) argArrayObj.Get("length"))._value;
uint n = TypeConverter.ToUint32(len);
var argList = _engine._jsValueArrayPool.RentArray((int) n);
for (int index = 0; index < n; index++)
{
string indexName = TypeConverter.ToString(index);
var nextArg = argArrayObj.Get(indexName);
argList[index] = nextArg;
}
var result = func.Call(thisArg, argList);
_engine._jsValueArrayPool.ReturnArray(argList);
return result;
}
public JsValue CallImpl(JsValue thisObject, JsValue[] arguments)
{
var func = thisObject.TryCast<ICallable>();
if (func == null)
{
ExceptionHelper.ThrowTypeError(Engine);
}
return func.Call(arguments.At(0), arguments.Length == 0 ? arguments : arguments.Skip(1));
}
public override JsValue Call(JsValue thisObject, JsValue[] arguments)
{
return Undefined;
}
}
} | 36.211268 | 145 | 0.583042 | [
"BSD-2-Clause"
] | jfoshee/jint | Jint/Native/Function/FunctionPrototype.cs | 5,144 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
namespace paralelismoY
{
class Program
{
public static void Main()
{
//Declarar y crear un array
int[] Numeros = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Console.WriteLine("Normal foreach: ");
foreach (var numeros in Numeros)
{
//Impresion del 1 al 100
Console.WriteLine(longCalculation(numeros));
}
//Salida en desorden
Console.WriteLine("Paralelismo foreach : ");
Parallel.ForEach(Numeros, numeros => {
Console.WriteLine(longCalculation(numeros));
});
}
private static int longCalculation(int numeros)
{
Thread.Sleep(100);
return numeros * numeros;
}
}
} | 27.848485 | 73 | 0.500544 | [
"Apache-2.0"
] | yoly6/EnParalelo | paralelismo/Program.cs | 921 | 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 System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.MetadataUtilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.Test.Utilities
{
public abstract class CSharpTestBase : CSharpTestBaseBase
{
protected new CSharpCompilation GetCompilationForEmit(
IEnumerable<string> source,
MetadataReference[] additionalRefs,
CompilationOptions options)
{
return (CSharpCompilation)base.GetCompilationForEmit(source, additionalRefs, options);
}
internal new IEnumerable<ModuleSymbol> ReferencesToModuleSymbols(IEnumerable<MetadataReference> references, MetadataImportOptions importOptions = MetadataImportOptions.Public)
{
return base.ReferencesToModuleSymbols(references, importOptions).Cast<ModuleSymbol>();
}
private Action<IModuleSymbol, EmitOptions> Translate2(Action<ModuleSymbol> action)
{
if (action != null)
{
return (m, _) => action((ModuleSymbol)m);
}
else
{
return null;
}
}
private Action<IModuleSymbol> Translate(Action<ModuleSymbol> action)
{
if (action != null)
{
return m => action((ModuleSymbol)m);
}
else
{
return null;
}
}
internal CompilationVerifier CompileAndVerify(
string source,
MetadataReference[] additionalRefs = null,
IEnumerable<ModuleData> dependencies = null,
EmitOptions emitOptions = EmitOptions.All,
Action<ModuleSymbol> sourceSymbolValidator = null,
Action<PEAssembly, EmitOptions> assemblyValidator = null,
Action<ModuleSymbol> symbolValidator = null,
SignatureDescription[] expectedSignatures = null,
string expectedOutput = null,
CompilationOptions options = null,
bool collectEmittedAssembly = true,
bool verify = true)
{
return base.CompileAndVerify(
source: source,
additionalRefs: additionalRefs,
dependencies: dependencies,
emitOptions: emitOptions,
sourceSymbolValidator: Translate2(sourceSymbolValidator),
assemblyValidator: assemblyValidator,
symbolValidator: Translate2(symbolValidator),
expectedSignatures: expectedSignatures,
expectedOutput: expectedOutput,
options: options,
collectEmittedAssembly: collectEmittedAssembly,
verify: verify);
}
internal CompilationVerifier CompileAndVerifyExperimental(
string source,
string expectedOutput = null,
MetadataReference[] additionalRefs = null,
IEnumerable<ModuleData> dependencies = null,
EmitOptions emitOptions = EmitOptions.All,
Action<ModuleSymbol> sourceSymbolValidator = null,
Action<PEAssembly, EmitOptions> assemblyValidator = null,
Action<ModuleSymbol> symbolValidator = null,
SignatureDescription[] expectedSignatures = null,
bool collectEmittedAssembly = true,
bool verify = true)
{
var options = (expectedOutput != null) ? TestOptions.ReleaseExe : TestOptions.ReleaseDll;
var compilation = CreateExperimentalCompilationWithMscorlib45(source, additionalRefs, options);
return CompileAndVerify(
compilation: compilation,
dependencies: dependencies,
emitOptions: emitOptions,
sourceSymbolValidator: Translate2(sourceSymbolValidator),
assemblyValidator: assemblyValidator,
symbolValidator: Translate2(symbolValidator),
expectedSignatures: expectedSignatures,
expectedOutput: expectedOutput,
collectEmittedAssembly: collectEmittedAssembly,
verify: verify);
}
internal CompilationVerifier CompileAndVerify(
string[] sources,
MetadataReference[] additionalRefs = null,
IEnumerable<ModuleData> dependencies = null,
EmitOptions emitOptions = EmitOptions.All,
Action<ModuleSymbol> sourceSymbolValidator = null,
Action<PEAssembly, EmitOptions> validator = null,
Action<ModuleSymbol> symbolValidator = null,
SignatureDescription[] expectedSignatures = null,
string expectedOutput = null,
CompilationOptions options = null,
bool collectEmittedAssembly = true,
bool verify = true)
{
return base.CompileAndVerify(
sources,
additionalRefs,
dependencies,
emitOptions,
Translate2(sourceSymbolValidator),
validator,
Translate2(symbolValidator),
expectedSignatures,
expectedOutput,
options,
collectEmittedAssembly,
verify);
}
internal CompilationVerifier CompileAndVerify(
Compilation compilation,
IEnumerable<ResourceDescription> manifestResources = null,
IEnumerable<ModuleData> dependencies = null,
EmitOptions emitOptions = EmitOptions.All,
Action<ModuleSymbol> sourceSymbolValidator = null,
Action<PEAssembly, EmitOptions> validator = null,
Action<ModuleSymbol> symbolValidator = null,
SignatureDescription[] expectedSignatures = null,
string expectedOutput = null,
bool collectEmittedAssembly = true,
bool verify = true)
{
return base.CompileAndVerify(
compilation,
manifestResources,
dependencies,
emitOptions,
Translate2(sourceSymbolValidator),
validator,
Translate2(symbolValidator),
expectedSignatures,
expectedOutput,
collectEmittedAssembly,
verify);
}
internal CompilationVerifier CompileAndVerifyOnWin8Only(
string source,
MetadataReference[] additionalRefs = null,
IEnumerable<ModuleData> dependencies = null,
EmitOptions emitOptions = EmitOptions.All,
Action<ModuleSymbol> sourceSymbolValidator = null,
Action<PEAssembly> validator = null,
Action<ModuleSymbol> symbolValidator = null,
SignatureDescription[] expectedSignatures = null,
string expectedOutput = null,
CompilationOptions options = null,
bool collectEmittedAssembly = true)
{
return base.CompileAndVerifyOnWin8Only(
source,
additionalRefs,
dependencies,
emitOptions,
Translate(sourceSymbolValidator),
validator,
Translate(symbolValidator),
expectedSignatures,
expectedOutput,
options,
collectEmittedAssembly);
}
internal CompilationVerifier CompileAndVerifyOnWin8Only(
Compilation compilation,
IEnumerable<ModuleData> dependencies = null,
EmitOptions emitOptions = EmitOptions.All,
Action<ModuleSymbol> sourceSymbolValidator = null,
Action<PEAssembly> validator = null,
Action<ModuleSymbol> symbolValidator = null,
SignatureDescription[] expectedSignatures = null,
string expectedOutput = null,
bool collectEmittedAssembly = true)
{
return base.CompileAndVerifyOnWin8Only(
compilation,
dependencies,
emitOptions,
Translate(sourceSymbolValidator),
validator,
Translate(symbolValidator),
expectedSignatures,
expectedOutput,
collectEmittedAssembly);
}
internal CompilationVerifier CompileAndVerifyOnWin8Only(
string[] sources,
MetadataReference[] additionalRefs = null,
IEnumerable<ModuleData> dependencies = null,
EmitOptions emitOptions = EmitOptions.All,
Action<ModuleSymbol> sourceSymbolValidator = null,
Action<PEAssembly> validator = null,
Action<ModuleSymbol> symbolValidator = null,
SignatureDescription[] expectedSignatures = null,
string expectedOutput = null,
CompilationOptions options = null,
bool collectEmittedAssembly = true,
bool verify = true)
{
return base.CompileAndVerifyOnWin8Only(
sources,
additionalRefs,
dependencies,
emitOptions,
Translate(sourceSymbolValidator),
validator,
Translate(symbolValidator),
expectedSignatures,
expectedOutput,
options,
collectEmittedAssembly,
verify);
}
}
public abstract class CSharpTestBaseBase : CommonTestBase
{
public static CSharpCompilation CreateWinRtCompilation(string text)
{
return CSharpTestBase.CreateCompilationWithMscorlib(text, WinRtRefs, TestOptions.ReleaseExe);
}
internal static DiagnosticDescription Diagnostic(ErrorCode code, string squiggledText = null, object[] arguments = null,
LinePosition? startLocation = null, Func<SyntaxNode, bool> syntaxNodePredicate = null, bool argumentOrderDoesNotMatter = false)
{
return new DiagnosticDescription((int)code, false, squiggledText, arguments, startLocation, syntaxNodePredicate, argumentOrderDoesNotMatter, typeof(ErrorCode));
}
internal static DiagnosticDescription Diagnostic(string code, string squiggledText = null, object[] arguments = null,
LinePosition? startLocation = null, Func<SyntaxNode, bool> syntaxNodePredicate = null, bool argumentOrderDoesNotMatter = false)
{
return new DiagnosticDescription(
code: code, isWarningAsError: false, squiggledText: squiggledText, arguments: arguments,
startLocation: startLocation, syntaxNodePredicate: syntaxNodePredicate,
argumentOrderDoesNotMatter: argumentOrderDoesNotMatter, errorCodeType: typeof(string));
}
internal override IEnumerable<IModuleSymbol> ReferencesToModuleSymbols(IEnumerable<MetadataReference> references, MetadataImportOptions importOptions = MetadataImportOptions.Public)
{
var options = TestOptions.ReleaseDll.WithMetadataImportOptions(importOptions);
var tc1 = CSharpCompilation.Create("Dummy", new SyntaxTree[0], references, options);
return references.Select(r =>
{
if (r.Properties.Kind == MetadataImageKind.Assembly)
{
var assemblySymbol = tc1.GetReferencedAssemblySymbol(r);
return (object)assemblySymbol == null ? null : assemblySymbol.Modules[0];
}
else
{
return tc1.GetReferencedModuleSymbol(r);
}
});
}
protected override CompilationOptions CompilationOptionsReleaseDll
{
get { return TestOptions.ReleaseDll; }
}
#region SyntaxTree Factories
public static SyntaxTree Parse(string text, string filename = "", CSharpParseOptions options = null)
{
if ((object)options == null)
{
options = TestOptions.Regular;
}
var stringText = StringText.From(text, Encoding.UTF8);
return SyntaxFactory.ParseSyntaxTree(stringText, options, filename);
}
public static SyntaxTree[] Parse(IEnumerable<string> sources)
{
if (sources == null || !sources.Any())
{
return new SyntaxTree[] { };
}
return Parse(sources.ToArray());
}
public static SyntaxTree[] Parse(params string[] sources)
{
if (sources == null || (sources.Length == 1 && null == sources[0]))
{
return new SyntaxTree[] { };
}
return sources.Select(src => Parse(src)).ToArray();
}
public static SyntaxTree ParseWithRoundTripCheck(string text, CSharpParseOptions options = null)
{
var tree = Parse(text, options: options);
var parsedText = tree.GetRoot();
// we validate the text roundtrips
Assert.Equal(text, parsedText.ToFullString());
return tree;
}
#endregion
#region Compilation Factories
public static CSharpCompilation CreateCompilationWithCustomILSource(
string source,
string ilSource,
IEnumerable<MetadataReference> references = null,
CSharpCompilationOptions options = null,
bool appendDefaultHeader = true)
{
if (string.IsNullOrEmpty(ilSource))
{
return CreateCompilationWithMscorlib(source, references, options);
}
IEnumerable<MetadataReference> metadataReferences = new[] { CompileIL(ilSource, appendDefaultHeader) };
if (references != null)
{
metadataReferences = metadataReferences.Concat(references);
}
return CreateCompilationWithMscorlib(source, metadataReferences, options);
}
public static CSharpCompilation CreateCompilationWithMscorlib45(
IEnumerable<SyntaxTree> source,
IEnumerable<MetadataReference> references = null,
CSharpCompilationOptions options = null,
string assemblyName = "")
{
var refs = new List<MetadataReference>();
if (references != null)
{
refs.AddRange(references);
}
refs.Add(MscorlibRef_v4_0_30316_17626);
return CreateCompilation(source, refs, options, assemblyName);
}
public static CSharpCompilation CreateCompilationWithMscorlib45(
string source,
IEnumerable<MetadataReference> references = null,
CSharpCompilationOptions options = null,
CSharpParseOptions parseOptions = null,
string sourceFileName = "",
string assemblyName = "")
{
return CreateCompilationWithMscorlib45(
new SyntaxTree[] { Parse(source, sourceFileName, parseOptions) },
references,
options,
assemblyName);
}
public static CSharpCompilation CreateCompilationWithMscorlib(
string text,
IEnumerable<MetadataReference> references = null,
CSharpCompilationOptions options = null,
CSharpParseOptions parseOptions = null,
string assemblyName = "",
string sourceFileName = "")
{
return CreateCompilationWithMscorlib(
new[] { Parse(text, sourceFileName, parseOptions) },
references: references,
options: options,
assemblyName: assemblyName);
}
public static CSharpCompilation CreateExperimentalCompilationWithMscorlib45(
string text,
IEnumerable<MetadataReference> references = null,
CSharpCompilationOptions options = null,
string assemblyName = "",
string sourceFileName = "")
{
var refs = new List<MetadataReference>();
if (references != null)
{
refs.AddRange(references);
}
refs.Add(MscorlibRef_v4_0_30316_17626);
return CreateCompilation(new[] { Parse(text, sourceFileName, TestOptions.ExperimentalParseOptions) }, refs, options, assemblyName);
}
public static CSharpCompilation CreateCompilationWithMscorlib(
IEnumerable<string> sources,
IEnumerable<MetadataReference> references = null,
CSharpCompilationOptions options = null,
string assemblyName = "")
{
return CreateCompilationWithMscorlib(Parse(sources), references, options, assemblyName);
}
public static CSharpCompilation CreateCompilationWithMscorlib(
SyntaxTree syntaxTree,
IEnumerable<MetadataReference> references = null,
CSharpCompilationOptions options = null,
string assemblyName = "")
{
return CreateCompilationWithMscorlib(new SyntaxTree[] { syntaxTree }, references, options, assemblyName);
}
public static CSharpCompilation CreateCompilationWithMscorlib(
IEnumerable<SyntaxTree> trees,
IEnumerable<MetadataReference> references = null,
CSharpCompilationOptions options = null,
string assemblyName = "")
{
return CreateCompilation(trees, (references != null) ? new[] { MscorlibRef }.Concat(references) : new[] { MscorlibRef }, options, assemblyName);
}
public static CSharpCompilation CreateCompilationWithMscorlibAndSystemCore(
IEnumerable<SyntaxTree> trees,
IEnumerable<MetadataReference> references = null,
CSharpCompilationOptions options = null,
string assemblyName = "")
{
return CreateCompilation(trees, (references != null) ? new[] { MscorlibRef, SystemCoreRef }.Concat(references) : new[] { MscorlibRef, SystemCoreRef }, options, assemblyName);
}
public static CSharpCompilation CreateCompilationWithMscorlibAndSystemCore(
string text,
IEnumerable<MetadataReference> references = null,
CSharpCompilationOptions options = null,
CSharpParseOptions parseOptions = null,
string assemblyName = "")
{
references = (references != null) ? new[] { SystemCoreRef }.Concat(references) : new[] { SystemCoreRef };
return CreateCompilationWithMscorlib(
new[] { Parse(text, "", parseOptions) },
references: references,
options: options,
assemblyName: assemblyName);
}
public static CSharpCompilation CreateCompilationWithMscorlibAndDocumentationComments(
string text,
IEnumerable<MetadataReference> references = null,
CSharpCompilationOptions options = null,
string assemblyName = "Test")
{
return CreateCompilationWithMscorlib(
new[] { Parse(text, options: TestOptions.RegularWithDocumentationComments) },
references: references,
options: (options ?? TestOptions.ReleaseDll).WithXmlReferenceResolver(XmlFileResolver.Default),
assemblyName: assemblyName);
}
public static CSharpCompilation CreateCompilation(
string source,
IEnumerable<MetadataReference> references = null,
CSharpCompilationOptions options = null,
string assemblyName = "")
{
return CreateCompilation(new[] { Parse(source) }, references, options, assemblyName);
}
public static CSharpCompilation CreateCompilation(
IEnumerable<string> sources,
IEnumerable<MetadataReference> references = null,
CSharpCompilationOptions options = null,
string assemblyName = "")
{
return CreateCompilation(Parse(sources), references, options, assemblyName);
}
public static CSharpCompilation CreateCompilation(
IEnumerable<SyntaxTree> trees,
IEnumerable<MetadataReference> references = null,
CSharpCompilationOptions options = null,
string assemblyName = "")
{
if (options == null)
{
options = TestOptions.ReleaseDll;
}
// Using single-threaded build if debugger attached, to simplify debugging.
if (Debugger.IsAttached)
{
options = options.WithConcurrentBuild(false);
}
return CSharpCompilation.Create(
assemblyName == "" ? GetUniqueName() : assemblyName,
trees,
references,
options);
}
public static CSharpCompilation CreateCompilation(
AssemblyIdentity identity,
string[] sources,
MetadataReference[] refs)
{
SyntaxTree[] trees = null;
if (sources != null)
{
trees = new SyntaxTree[sources.Length];
for (int i = 0; i < sources.Length; i++)
{
trees[i] = Parse(sources[i]);
}
}
var tc1 = CSharpCompilation.Create(identity.Name, options: TestOptions.ReleaseDll, references: refs, syntaxTrees: trees);
Assert.NotNull(tc1.Assembly); // force creation of SourceAssemblySymbol
((SourceAssemblySymbol)tc1.Assembly).lazyAssemblyIdentity = identity;
return tc1;
}
public CompilationVerifier CompileWithCustomILSource(string cSharpSource, string ilSource, Action<CSharpCompilation> compilationVerifier = null, bool importInternals = true, EmitOptions emitOptions = EmitOptions.All, string expectedOutput = null)
{
var compilationOptions = (expectedOutput != null) ? TestOptions.ReleaseExe : TestOptions.ReleaseDll;
if (importInternals)
{
compilationOptions = compilationOptions.WithMetadataImportOptions(MetadataImportOptions.Internal);
}
if (ilSource == null)
{
var c = CreateCompilationWithMscorlib(cSharpSource, options: compilationOptions);
return CompileAndVerify(c, emitOptions: emitOptions, expectedOutput: expectedOutput);
}
MetadataReference reference = null;
using (var tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource))
{
reference = new MetadataImageReference(ReadFromFile(tempAssembly.Path));
}
var compilation = CreateCompilationWithMscorlib(cSharpSource, new[] { reference }, compilationOptions);
if (compilationVerifier != null)
{
compilationVerifier(compilation);
}
return CompileAndVerify(compilation, emitOptions: emitOptions, expectedOutput: expectedOutput);
}
protected override Compilation GetCompilationForEmit(
IEnumerable<string> source,
MetadataReference[] additionalRefs,
CompilationOptions options)
{
return CreateCompilationWithMscorlib(
source,
references: (additionalRefs != null) ? additionalRefs.ToList() : null,
options: (CSharpCompilationOptions)options,
assemblyName: GetUniqueName());
}
/// <summary>
/// Like CompileAndVerify, but confirms that execution raises an exception.
/// </summary>
/// <typeparam name="T">Expected type of the exception.</typeparam>
/// <param name="source">Program to compile and execute.</param>
/// <param name="expectedMessage">Ignored if null.</param>
internal CompilationVerifier CompileAndVerifyException<T>(string source, string expectedMessage = null, bool allowUnsafe = false, EmitOptions emitOptions = EmitOptions.All) where T : Exception
{
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.ReleaseExe.WithAllowUnsafe(allowUnsafe));
return CompileAndVerifyException<T>(comp, expectedMessage, emitOptions);
}
internal CompilationVerifier CompileAndVerifyException<T>(CSharpCompilation comp, string expectedMessage = null, EmitOptions emitOptions = EmitOptions.All) where T : Exception
{
try
{
CompileAndVerify(comp, emitOptions: emitOptions, expectedOutput: ""); //need expected output to force execution
Assert.False(true, string.Format("Expected exception {0}({1})", typeof(T).Name, expectedMessage));
}
catch (ExecutionException x)
{
var e = x.InnerException;
Assert.IsType<T>(e);
if (expectedMessage != null)
{
Assert.Equal(expectedMessage, e.Message);
}
}
return CompileAndVerify(comp, emitOptions: emitOptions);
}
#endregion
#region Semantic Model Helpers
public Tuple<TNode, SemanticModel> GetBindingNodeAndModel<TNode>(CSharpCompilation compilation, int treeIndex = 0) where TNode : SyntaxNode
{
var node = GetBindingNode<TNode>(compilation, treeIndex);
return new Tuple<TNode, SemanticModel>(node, compilation.GetSemanticModel(compilation.SyntaxTrees[treeIndex]));
}
public Tuple<IList<TNode>, SemanticModel> GetBindingNodesAndModel<TNode>(CSharpCompilation compilation, int treeIndex = 0, int which = -1) where TNode : SyntaxNode
{
var nodes = GetBindingNodes<TNode>(compilation, treeIndex, which);
return new Tuple<IList<TNode>, SemanticModel>(nodes, compilation.GetSemanticModel(compilation.SyntaxTrees[treeIndex]));
}
/// <summary>
/// This method handles one binding text with strong SyntaxNode type
/// </summary>
/// <typeparam name="TNode"></typeparam>
/// <param name="compilation"></param>
/// <param name="treeIndex"></param>
/// <returns></returns>
public TNode GetBindingNode<TNode>(CSharpCompilation compilation, int treeIndex = 0) where TNode : SyntaxNode
{
Assert.True(compilation.SyntaxTrees.Length > treeIndex, "Compilation has enough trees");
var tree = compilation.SyntaxTrees[treeIndex];
const string bindStart = "/*<bind>*/";
const string bindEnd = "/*</bind>*/";
return FindBindingNode<TNode>(tree, bindStart, bindEnd);
}
/// <summary>
/// Find multiple binding nodes by looking for pair /*<bind#>*/ & /*</bind#>*/ in source text
/// </summary>
/// <param name="compilation"></param>
/// <param name="treeIndex">which tree</param>
/// <param name="which">
/// * if which < 0, find ALL wrpaaed nodes
/// * if which >=0, find a specific binding node wrapped by /*<bind#>*/ & /*</bind#>*/
/// e.g. if which = 1, find node wrapped by /*<bind1>*/ & /*</bind1>*/
/// </param>
/// <returns></returns>
public IList<TNode> GetBindingNodes<TNode>(CSharpCompilation compilation, int treeIndex = 0, int which = -1) where TNode : SyntaxNode
{
Assert.True(compilation.SyntaxTrees.Length > treeIndex, "Compilation has enough trees");
var tree = compilation.SyntaxTrees[treeIndex];
var nodeList = new List<TNode>();
string text = tree.GetRoot().ToFullString();
const string bindStartFmt = "/*<bind{0}>*/";
const string bindEndFmt = "/*</bind{0}>*/";
// find all
if (which < 0)
{
// assume tags with number are in increasing order, no jump
for (byte i = 0; i < 255; i++)
{
var start = String.Format(bindStartFmt, i);
var end = String.Format(bindEndFmt, i);
var bindNode = FindBindingNode<TNode>(tree, start, end);
// done
if (bindNode == null)
break;
nodeList.Add(bindNode);
}
}
else
{
var start2 = String.Format(bindStartFmt, which);
var end2 = String.Format(bindEndFmt, which);
var bindNode = FindBindingNode<TNode>(tree, start2, end2);
// done
if (bindNode != null)
nodeList.Add(bindNode);
}
return nodeList;
}
private static TNode FindBindingNode<TNode>(SyntaxTree tree, string startTag, string endTag) where TNode : SyntaxNode
{
// =================
// Get Binding Text
string text = tree.GetRoot().ToFullString();
int start = text.IndexOf(startTag);
if (start < 0)
return null;
start += startTag.Length;
int end = text.IndexOf(endTag);
Assert.True(end > start, "Bind Pos: end > start");
// get rid of white spaces if any
var bindText = text.Substring(start, end - start).Trim();
if (String.IsNullOrWhiteSpace(bindText))
return null;
// =================
// Get Binding Node
var node = tree.GetRoot().FindToken(start).Parent;
while ((node != null && node.ToString() != bindText))
{
node = node.Parent;
}
// =================
// Get Binding Node with match node type
if (node != null)
{
while ((node as TNode) == null)
{
if (node.Parent != null && node.Parent.ToString() == bindText)
{
node = node.Parent;
}
else
{
break;
}
}
}
Assert.NotNull(node); // If this trips, then node wasn't found
Assert.IsAssignableFrom(typeof(TNode), node);
Assert.Equal(bindText, node.ToString());
return ((TNode)node);
}
#endregion
#region Attributes
internal IEnumerable<string> GetAttributeNames(ImmutableArray<SynthesizedAttributeData> attributes)
{
return attributes.Select(a => a.AttributeClass.Name);
}
internal IEnumerable<string> GetAttributeNames(ImmutableArray<CSharpAttributeData> attributes)
{
return attributes.Select(a => a.AttributeClass.Name);
}
#endregion
#region Documentation Comments
internal static string GetDocumentationCommentText(CSharpCompilation compilation, params DiagnosticDescription[] expectedDiagnostics)
{
return GetDocumentationCommentText(compilation, outputName: null, filterTree: null, expectedDiagnostics: expectedDiagnostics);
}
internal static string GetDocumentationCommentText(CSharpCompilation compilation, string outputName = null, SyntaxTree filterTree = null, TextSpan? filterSpanWithinTree = null, params DiagnosticDescription[] expectedDiagnostics)
{
using (MemoryStream stream = new MemoryStream())
{
DiagnosticBag diagnostics = DiagnosticBag.GetInstance();
DocumentationCommentCompiler.WriteDocumentationCommentXml(compilation, outputName, stream, diagnostics, default(CancellationToken), filterTree, filterSpanWithinTree);
if (expectedDiagnostics != null)
{
diagnostics.Verify(expectedDiagnostics);
}
diagnostics.Free();
string text = Encoding.UTF8.GetString(stream.GetBuffer());
int length = text.IndexOf('\0');
if (length >= 0)
{
text = text.Substring(0, length);
}
return text.Trim();
}
}
#endregion Documentation Comments
#region IL Validation
internal override string VisualizeRealIL(IModuleSymbol peModule, CompilationTestData.MethodData methodData, IReadOnlyDictionary<int, string> markers)
{
return VisualizeRealIL((PEModuleSymbol)peModule, methodData, markers);
}
/// <summary>
/// Returns a string representation of IL read from metadata.
/// </summary>
/// <remarks>
/// Currently unsupported IL decoding:
/// - multidimentional arrays
/// - vararg calls
/// - winmd
/// - global methods
/// </remarks>
internal unsafe static string VisualizeRealIL(PEModuleSymbol peModule, CompilationTestData.MethodData methodData, IReadOnlyDictionary<int, string> markers)
{
var typeName = GetContainingTypeMetadataName(methodData.Method);
// TODO (tomat): global methods (typeName == null)
var type = peModule.ContainingAssembly.GetTypeByMetadataName(typeName);
// TODO (tomat): overloaded methods
var method = (PEMethodSymbol)type.GetMembers(methodData.Method.MetadataName).Single();
var bodyBlock = peModule.Module.GetMethodBodyOrThrow(method.Handle);
Assert.NotNull(bodyBlock);
var moduleDecoder = new MetadataDecoder(peModule);
var peMethod = (PEMethodSymbol)moduleDecoder.GetSymbolForILToken(method.Handle);
StringBuilder sb = new StringBuilder();
var ilBytes = bodyBlock.GetILBytes();
var ehHandlerRegions = Visualizer.GetHandlerSpans(bodyBlock.ExceptionRegions);
var methodDecoder = new MetadataDecoder(peModule, peMethod);
ImmutableArray<ILVisualizer.LocalInfo> localDefinitions;
if (!bodyBlock.LocalSignature.IsNil)
{
var signature = peModule.Module.MetadataReader.GetLocalSignature(bodyBlock.LocalSignature);
var signatureReader = peModule.Module.GetMemoryReaderOrThrow(signature);
var localInfos = methodDecoder.DecodeLocalSignatureOrThrow(ref signatureReader);
localDefinitions = ToLocalDefinitions(localInfos, methodData.ILBuilder);
}
else
{
localDefinitions = ImmutableArray.Create<ILVisualizer.LocalInfo>();
}
// TODO (tomat): the .maxstack in IL can't be less than 8, but many tests expect .maxstack < 8
int maxStack = (bodyBlock.MaxStack == 8 && methodData.ILBuilder.MaxStack < 8) ? methodData.ILBuilder.MaxStack : bodyBlock.MaxStack;
var visualizer = new Visualizer(new MetadataDecoder(peModule, peMethod));
visualizer.DumpMethod(sb, maxStack, ilBytes, localDefinitions, ehHandlerRegions, markers);
return sb.ToString();
}
private static string GetContainingTypeMetadataName(IMethodSymbol method)
{
var type = method.ContainingType;
if (type == null)
{
return null;
}
string ns = type.ContainingNamespace.MetadataName;
var result = type.MetadataName;
while ((type = type.ContainingType) != null)
{
result = type.MetadataName + "+" + result;
}
return (ns.Length > 0) ? ns + "." + result : result;
}
private static ImmutableArray<ILVisualizer.LocalInfo> ToLocalDefinitions(ImmutableArray<MetadataDecoder.LocalInfo> localInfos, ILBuilder builder)
{
if (localInfos.IsEmpty)
{
return ImmutableArray.Create<ILVisualizer.LocalInfo>();
}
var result = new ILVisualizer.LocalInfo[localInfos.Length];
for (int i = 0; i < result.Length; i++)
{
var typeRef = localInfos[i].Type;
var builderLocal = builder.LocalSlotManager.LocalsInOrder()[i];
result[i] = new ILVisualizer.LocalInfo(builderLocal.Name, typeRef, localInfos[i].IsPinned, localInfos[i].IsByRef);
}
return result.AsImmutableOrNull();
}
private sealed class Visualizer : ILVisualizer
{
private readonly MetadataDecoder decoder;
public Visualizer(MetadataDecoder decoder)
{
this.decoder = decoder;
}
public override string VisualizeUserString(uint token)
{
var reader = decoder.ModuleSymbol.Module.GetMetadataReader();
return "\"" + reader.GetUserString((UserStringHandle)MetadataTokens.Handle((int)token)) + "\"";
}
public override string VisualizeSymbol(uint token)
{
Cci.IReference reference = decoder.GetSymbolForILToken(MetadataTokens.Handle((int)token));
ISymbol symbol = reference as ISymbol;
return string.Format("\"{0}\"", symbol == null ? (object)reference : symbol.ToDisplayString(SymbolDisplayFormat.ILVisualizationFormat));
}
public override string VisualizeLocalType(object type)
{
if (type is int)
{
type = decoder.GetSymbolForILToken(MetadataTokens.Handle((int)type));
}
ISymbol symbol = type as ISymbol;
return symbol == null ? type.ToString() : symbol.ToDisplayString(SymbolDisplayFormat.ILVisualizationFormat);
}
}
#endregion
#region PDB Validation
public static string GetPdbXml(string source, CSharpCompilationOptions compilationOptions, string methodName = "", CSharpParseOptions parseOptions = null, IEnumerable<MetadataReference> references = null)
{
//Having a unique name here may be important. The infrastructure of the pdb to xml conversion
//loads the assembly into the ReflectionOnlyLoadFrom context.
//So it's probably a good idea to have a new name for each assembly.
var compilation = CreateCompilationWithMscorlibAndSystemCore(source,
references,
assemblyName: GetUniqueName(),
options: compilationOptions,
parseOptions: parseOptions
);
compilation.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Verify();
return GetPdbXml(compilation, methodName);
}
#endregion
}
}
| 41.145791 | 254 | 0.596442 | [
"Apache-2.0"
] | semihokur/pattern-matching-csharp | Src/Compilers/Test/Utilities/CSharp/CSharpTestBase.cs | 40,078 | C# |
using System.Collections.Generic;
using System.Windows.Input;
namespace Netfox.Detective.Models.Base.Detective
{
public class MenuItem
{
public List<MenuItem> MenuItems { get; } = new List<MenuItem>();
public string Header { get; set; }
public ICommand Command { get; set; }
}
} | 26.333333 | 72 | 0.664557 | [
"Apache-2.0"
] | pokornysimon/NetfoxDetective | NetfoxCore/Detective/App/Netfox.Detective/Models/Base/Detective/MenuItem.cs | 318 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.UI.Xaml.Media.Imaging;
namespace Davinci.net
{
public static class Extensions
{
public static async Task<IEnumerable<T>> ExecuteAsync<T>(this IEnumerable<Task<T>> tasks)
{
var results = new List<T>();
foreach (var task in tasks)
{
results.Add(await task);
}
return results;
}
}
} | 23.65 | 97 | 0.575053 | [
"Apache-2.0"
] | TheFo2sh/Davinci.net | Davinci.net/Extensions.cs | 475 | C# |
using System.Collections.Generic;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using System.Threading.Tasks;
namespace ServiceBusDriver.Client.UIComponents.Pages.Dashboard
{
public partial class TopicDashboard
{
public IReadOnlyDictionary<string, string> topicProperties;
[CascadingParameter]
public Task<AuthenticationState> AuthenticationState { get; set; }
protected override void OnInitialized()
{
_propertiesNotifierService.Notify += OnNotify;
}
private async Task OnNotify()
{
topicProperties = _propertiesNotifierService.TopicProperties;
await InvokeAsync(StateHasChanged);
}
}
}
| 25.4 | 74 | 0.699475 | [
"MIT"
] | beaudeanadams/ServiceBusDriver | Client/UIComponents/Pages/Dashboard/TopicDashboard.razor.cs | 764 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/winnt.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="POWER_SESSION_WINLOGON" /> struct.</summary>
public static unsafe partial class POWER_SESSION_WINLOGONTests
{
/// <summary>Validates that the <see cref="POWER_SESSION_WINLOGON" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<POWER_SESSION_WINLOGON>(), Is.EqualTo(sizeof(POWER_SESSION_WINLOGON)));
}
/// <summary>Validates that the <see cref="POWER_SESSION_WINLOGON" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(POWER_SESSION_WINLOGON).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="POWER_SESSION_WINLOGON" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
Assert.That(sizeof(POWER_SESSION_WINLOGON), Is.EqualTo(8));
}
}
}
| 39.972222 | 145 | 0.681723 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | tests/Interop/Windows/um/winnt/POWER_SESSION_WINLOGONTests.cs | 1,441 | C# |
namespace Application.Items.Commands.DeleteItem
{
using System;
using MediatR;
public class DeleteItemCommand : IRequest
{
public DeleteItemCommand(Guid id)
{
this.Id = id;
}
public Guid Id { get; }
}
} | 17.933333 | 48 | 0.572491 | [
"MIT"
] | DigitalSeas-Tech/AuctionSystem | src/Core/Application/Items/Commands/DeleteItem/DeleteItemCommand.cs | 271 | C# |
// Copyright (c) Peter Vrenken. All rights reserved. See the license on https://github.com/vrenken/EtAlii.Ubigia
namespace EtAlii.Ubigia.Persistence
{
public interface IBlobStorer
{
void Store(ContainerIdentifier container, Blob blob);
}
}
| 26.2 | 113 | 0.725191 | [
"MIT"
] | vrenken/EtAlii.Ubigia | Source/Persistence/EtAlii.Ubigia.Persistence/Blobs/IBlobStorer.cs | 264 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SyncAudioSources : MonoBehaviour, ITimedEventSync {
//set these in the inspector!
public AudioSource master;
public AudioSource slave;
/// <summary>
/// Moves audio samples for master and slave to the offset speicifed, triggered from
/// TimedEventManager game object when synchronizing playback start.
/// </summary>
/// <param name="timeOffset"></param>
public void MoveToTimeOffset(float timeOffset)
{
master.time = timeOffset;
slave.time = timeOffset;
}
void Update()
{
slave.timeSamples = master.timeSamples;
}
}
| 25.814815 | 89 | 0.680057 | [
"MIT"
] | eagee/KateAndEaganGetAPodcast | Assets/Scripts/Audio/SyncAudioSources.cs | 699 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WatchProject
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| 22.217391 | 65 | 0.612524 | [
"MIT"
] | bwosh/csharpqa | 03_Vs2015/WatchProject/Program.cs | 513 | C# |
// Copyright (c) Oleg Zudov. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Zu.TameRoslyn.Syntax
{
public partial class TameIfStatementSyntax : TameStatementSyntax
{
public new static string TypeName = "IfStatementSyntax";
private SyntaxToken _closeParenToken;
private bool _closeParenTokenIsChanged;
private string _closeParenTokenStr;
private ExpressionSyntax _condition;
private bool _conditionIsChanged;
private string _conditionStr;
private ElseClauseSyntax _else;
private bool _elseIsChanged;
private string _elseStr;
private SyntaxToken _ifKeyword;
private bool _ifKeywordIsChanged;
private string _ifKeywordStr;
private SyntaxToken _openParenToken;
private bool _openParenTokenIsChanged;
private string _openParenTokenStr;
private StatementSyntax _statement;
private bool _statementIsChanged;
private string _statementStr;
private TameExpressionSyntax _taCondition;
private TameElseClauseSyntax _taElse;
private TameStatementSyntax _taStatement;
public TameIfStatementSyntax(string code)
{
Node = SyntaxFactoryStr.ParseIfStatement(code);
AddChildren();
}
public TameIfStatementSyntax(IfStatementSyntax node)
{
Node = node;
AddChildren();
}
public TameIfStatementSyntax()
{
IfKeywordStr = DefaultValues.IfStatementSyntaxIfKeywordStr;
OpenParenTokenStr = DefaultValues.IfStatementSyntaxOpenParenTokenStr;
ConditionStr = DefaultValues.IfStatementSyntaxConditionStr;
CloseParenTokenStr = DefaultValues.IfStatementSyntaxCloseParenTokenStr;
StatementStr = DefaultValues.IfStatementSyntaxStatementStr;
ElseStr = DefaultValues.IfStatementSyntaxElseStr;
}
public override string RoslynTypeName => TypeName;
public SyntaxToken IfKeyword
{
get
{
if (_ifKeywordIsChanged)
{
if (_ifKeywordStr == null) _ifKeyword = default(SyntaxToken);
else _ifKeyword = SyntaxFactoryStr.ParseSyntaxToken(_ifKeywordStr, SyntaxKind.IfKeyword);
_ifKeywordIsChanged = false;
}
return _ifKeyword;
}
set
{
if (_ifKeyword != value)
{
_ifKeyword = value;
_ifKeywordIsChanged = false;
IsChanged = true;
}
}
}
public string IfKeywordStr
{
get
{
if (_ifKeywordIsChanged) return _ifKeywordStr;
return _ifKeywordStr = _ifKeyword.Text;
}
set
{
if (_ifKeywordStr != value)
{
_ifKeywordStr = value;
IsChanged = true;
_ifKeywordIsChanged = true;
}
}
}
public SyntaxToken OpenParenToken
{
get
{
if (_openParenTokenIsChanged)
{
if (_openParenTokenStr == null) _openParenToken = default(SyntaxToken);
else
_openParenToken =
SyntaxFactoryStr.ParseSyntaxToken(_openParenTokenStr, SyntaxKind.OpenParenToken);
_openParenTokenIsChanged = false;
}
return _openParenToken;
}
set
{
if (_openParenToken != value)
{
_openParenToken = value;
_openParenTokenIsChanged = false;
IsChanged = true;
}
}
}
public string OpenParenTokenStr
{
get
{
if (_openParenTokenIsChanged) return _openParenTokenStr;
return _openParenTokenStr = _openParenToken.Text;
}
set
{
if (_openParenTokenStr != value)
{
_openParenTokenStr = value;
IsChanged = true;
_openParenTokenIsChanged = true;
}
}
}
public ExpressionSyntax Condition
{
get
{
if (_conditionIsChanged)
{
_condition = SyntaxFactoryStr.ParseExpressionSyntax(ConditionStr);
_conditionIsChanged = false;
_taCondition = null;
}
else if (_taCondition != null && _taCondition.IsChanged)
{
_condition = (ExpressionSyntax) _taCondition.Node;
}
return _condition;
}
set
{
if (_condition != value)
{
_condition = value;
_conditionIsChanged = false;
IsChanged = true;
}
}
}
public string ConditionStr
{
get
{
if (_taCondition != null && _taCondition.IsChanged)
Condition = (ExpressionSyntax) _taCondition.Node;
if (_conditionIsChanged) return _conditionStr;
return _conditionStr = _condition?.ToFullString();
}
set
{
if (_taCondition != null && _taCondition.IsChanged)
{
Condition = (ExpressionSyntax) _taCondition.Node;
_conditionStr = _condition?.ToFullString();
}
if (_conditionStr != value)
{
_conditionStr = value;
IsChanged = true;
_conditionIsChanged = true;
_taCondition = null;
}
}
}
public TameExpressionSyntax TaCondition
{
get
{
if (_taCondition == null && Condition != null)
if (Condition is IdentifierNameSyntax)
{
var loc = new TameIdentifierNameSyntax((IdentifierNameSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is GenericNameSyntax)
{
var loc = new TameGenericNameSyntax((GenericNameSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is ParenthesizedLambdaExpressionSyntax)
{
var loc =
new TameParenthesizedLambdaExpressionSyntax(
(ParenthesizedLambdaExpressionSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is SimpleLambdaExpressionSyntax)
{
var loc =
new TameSimpleLambdaExpressionSyntax((SimpleLambdaExpressionSyntax) Condition)
{
TaParent = this
};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is AliasQualifiedNameSyntax)
{
var loc =
new TameAliasQualifiedNameSyntax((AliasQualifiedNameSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is QualifiedNameSyntax)
{
var loc = new TameQualifiedNameSyntax((QualifiedNameSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is AnonymousMethodExpressionSyntax)
{
var loc =
new TameAnonymousMethodExpressionSyntax((AnonymousMethodExpressionSyntax) Condition)
{
TaParent = this
};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is OmittedTypeArgumentSyntax)
{
var loc =
new TameOmittedTypeArgumentSyntax((OmittedTypeArgumentSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is BaseExpressionSyntax)
{
var loc = new TameBaseExpressionSyntax((BaseExpressionSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is PredefinedTypeSyntax)
{
var loc = new TamePredefinedTypeSyntax((PredefinedTypeSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is ThisExpressionSyntax)
{
var loc = new TameThisExpressionSyntax((ThisExpressionSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is NullableTypeSyntax)
{
var loc = new TameNullableTypeSyntax((NullableTypeSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is PointerTypeSyntax)
{
var loc = new TamePointerTypeSyntax((PointerTypeSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is ArrayTypeSyntax)
{
var loc = new TameArrayTypeSyntax((ArrayTypeSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is TupleTypeSyntax)
{
var loc = new TameTupleTypeSyntax((TupleTypeSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is RefTypeSyntax)
{
var loc = new TameRefTypeSyntax((RefTypeSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is AnonymousObjectCreationExpressionSyntax)
{
var loc =
new TameAnonymousObjectCreationExpressionSyntax(
(AnonymousObjectCreationExpressionSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is StackAllocArrayCreationExpressionSyntax)
{
var loc =
new TameStackAllocArrayCreationExpressionSyntax(
(StackAllocArrayCreationExpressionSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is ImplicitArrayCreationExpressionSyntax)
{
var loc =
new TameImplicitArrayCreationExpressionSyntax(
(ImplicitArrayCreationExpressionSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is InterpolatedStringExpressionSyntax)
{
var loc =
new TameInterpolatedStringExpressionSyntax((InterpolatedStringExpressionSyntax) Condition)
{
TaParent = this
};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is ConditionalAccessExpressionSyntax)
{
var loc =
new TameConditionalAccessExpressionSyntax((ConditionalAccessExpressionSyntax) Condition)
{
TaParent = this
};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is OmittedArraySizeExpressionSyntax)
{
var loc =
new TameOmittedArraySizeExpressionSyntax((OmittedArraySizeExpressionSyntax) Condition)
{
TaParent = this
};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is ElementBindingExpressionSyntax)
{
var loc =
new TameElementBindingExpressionSyntax((ElementBindingExpressionSyntax) Condition)
{
TaParent = this
};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is ObjectCreationExpressionSyntax)
{
var loc =
new TameObjectCreationExpressionSyntax((ObjectCreationExpressionSyntax) Condition)
{
TaParent = this
};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is ArrayCreationExpressionSyntax)
{
var loc =
new TameArrayCreationExpressionSyntax((ArrayCreationExpressionSyntax) Condition)
{
TaParent = this
};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is ElementAccessExpressionSyntax)
{
var loc =
new TameElementAccessExpressionSyntax((ElementAccessExpressionSyntax) Condition)
{
TaParent = this
};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is MemberBindingExpressionSyntax)
{
var loc =
new TameMemberBindingExpressionSyntax((MemberBindingExpressionSyntax) Condition)
{
TaParent = this
};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is ParenthesizedExpressionSyntax)
{
var loc =
new TameParenthesizedExpressionSyntax((ParenthesizedExpressionSyntax) Condition)
{
TaParent = this
};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is MemberAccessExpressionSyntax)
{
var loc =
new TameMemberAccessExpressionSyntax((MemberAccessExpressionSyntax) Condition)
{
TaParent = this
};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is PostfixUnaryExpressionSyntax)
{
var loc =
new TamePostfixUnaryExpressionSyntax((PostfixUnaryExpressionSyntax) Condition)
{
TaParent = this
};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is ConditionalExpressionSyntax)
{
var loc =
new TameConditionalExpressionSyntax((ConditionalExpressionSyntax) Condition)
{
TaParent = this
};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is DeclarationExpressionSyntax)
{
var loc =
new TameDeclarationExpressionSyntax((DeclarationExpressionSyntax) Condition)
{
TaParent = this
};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is ImplicitElementAccessSyntax)
{
var loc =
new TameImplicitElementAccessSyntax((ImplicitElementAccessSyntax) Condition)
{
TaParent = this
};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is InitializerExpressionSyntax)
{
var loc =
new TameInitializerExpressionSyntax((InitializerExpressionSyntax) Condition)
{
TaParent = this
};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is PrefixUnaryExpressionSyntax)
{
var loc =
new TamePrefixUnaryExpressionSyntax((PrefixUnaryExpressionSyntax) Condition)
{
TaParent = this
};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is AssignmentExpressionSyntax)
{
var loc =
new TameAssignmentExpressionSyntax((AssignmentExpressionSyntax) Condition)
{
TaParent = this
};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is InvocationExpressionSyntax)
{
var loc =
new TameInvocationExpressionSyntax((InvocationExpressionSyntax) Condition)
{
TaParent = this
};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is IsPatternExpressionSyntax)
{
var loc =
new TameIsPatternExpressionSyntax((IsPatternExpressionSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is RefValueExpressionSyntax)
{
var loc =
new TameRefValueExpressionSyntax((RefValueExpressionSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is CheckedExpressionSyntax)
{
var loc =
new TameCheckedExpressionSyntax((CheckedExpressionSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is DefaultExpressionSyntax)
{
var loc =
new TameDefaultExpressionSyntax((DefaultExpressionSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is LiteralExpressionSyntax)
{
var loc =
new TameLiteralExpressionSyntax((LiteralExpressionSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is MakeRefExpressionSyntax)
{
var loc =
new TameMakeRefExpressionSyntax((MakeRefExpressionSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is RefTypeExpressionSyntax)
{
var loc =
new TameRefTypeExpressionSyntax((RefTypeExpressionSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is BinaryExpressionSyntax)
{
var loc = new TameBinaryExpressionSyntax((BinaryExpressionSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is SizeOfExpressionSyntax)
{
var loc = new TameSizeOfExpressionSyntax((SizeOfExpressionSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is TypeOfExpressionSyntax)
{
var loc = new TameTypeOfExpressionSyntax((TypeOfExpressionSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is AwaitExpressionSyntax)
{
var loc = new TameAwaitExpressionSyntax((AwaitExpressionSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is QueryExpressionSyntax)
{
var loc = new TameQueryExpressionSyntax((QueryExpressionSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is ThrowExpressionSyntax)
{
var loc = new TameThrowExpressionSyntax((ThrowExpressionSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is TupleExpressionSyntax)
{
var loc = new TameTupleExpressionSyntax((TupleExpressionSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is CastExpressionSyntax)
{
var loc = new TameCastExpressionSyntax((CastExpressionSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
else if (Condition is RefExpressionSyntax)
{
var loc = new TameRefExpressionSyntax((RefExpressionSyntax) Condition) {TaParent = this};
loc.AddChildren();
_taCondition = loc;
}
return _taCondition;
}
set
{
if (_taCondition != value)
{
_taCondition = value;
if (_taCondition != null)
{
_taCondition.TaParent = this;
_taCondition.IsChanged = true;
}
else
{
IsChanged = true;
}
}
}
}
public SyntaxToken CloseParenToken
{
get
{
if (_closeParenTokenIsChanged)
{
if (_closeParenTokenStr == null) _closeParenToken = default(SyntaxToken);
else
_closeParenToken =
SyntaxFactoryStr.ParseSyntaxToken(_closeParenTokenStr, SyntaxKind.CloseParenToken);
_closeParenTokenIsChanged = false;
}
return _closeParenToken;
}
set
{
if (_closeParenToken != value)
{
_closeParenToken = value;
_closeParenTokenIsChanged = false;
IsChanged = true;
}
}
}
public string CloseParenTokenStr
{
get
{
if (_closeParenTokenIsChanged) return _closeParenTokenStr;
return _closeParenTokenStr = _closeParenToken.Text;
}
set
{
if (_closeParenTokenStr != value)
{
_closeParenTokenStr = value;
IsChanged = true;
_closeParenTokenIsChanged = true;
}
}
}
public StatementSyntax Statement
{
get
{
if (_statementIsChanged)
{
_statement = SyntaxFactoryStr.ParseStatementSyntax(StatementStr);
_statementIsChanged = false;
_taStatement = null;
}
else if (_taStatement != null && _taStatement.IsChanged)
{
_statement = (StatementSyntax) _taStatement.Node;
}
return _statement;
}
set
{
if (_statement != value)
{
_statement = value;
_statementIsChanged = false;
IsChanged = true;
}
}
}
public string StatementStr
{
get
{
if (_taStatement != null && _taStatement.IsChanged)
Statement = (StatementSyntax) _taStatement.Node;
if (_statementIsChanged) return _statementStr;
return _statementStr = _statement?.ToFullString();
}
set
{
if (_taStatement != null && _taStatement.IsChanged)
{
Statement = (StatementSyntax) _taStatement.Node;
_statementStr = _statement?.ToFullString();
}
if (_statementStr != value)
{
_statementStr = value;
IsChanged = true;
_statementIsChanged = true;
_taStatement = null;
}
}
}
public TameStatementSyntax TaStatement
{
get
{
if (_taStatement == null && Statement != null)
if (Statement is ForEachVariableStatementSyntax)
{
var loc =
new TameForEachVariableStatementSyntax((ForEachVariableStatementSyntax) Statement)
{
TaParent = this
};
loc.AddChildren();
_taStatement = loc;
}
else if (Statement is ForEachStatementSyntax)
{
var loc = new TameForEachStatementSyntax((ForEachStatementSyntax) Statement) {TaParent = this};
loc.AddChildren();
_taStatement = loc;
}
else if (Statement is LocalDeclarationStatementSyntax)
{
var loc =
new TameLocalDeclarationStatementSyntax((LocalDeclarationStatementSyntax) Statement)
{
TaParent = this
};
loc.AddChildren();
_taStatement = loc;
}
else if (Statement is LocalFunctionStatementSyntax)
{
var loc =
new TameLocalFunctionStatementSyntax((LocalFunctionStatementSyntax) Statement)
{
TaParent = this
};
loc.AddChildren();
_taStatement = loc;
}
else if (Statement is ExpressionStatementSyntax)
{
var loc =
new TameExpressionStatementSyntax((ExpressionStatementSyntax) Statement) {TaParent = this};
loc.AddChildren();
_taStatement = loc;
}
else if (Statement is ContinueStatementSyntax)
{
var loc =
new TameContinueStatementSyntax((ContinueStatementSyntax) Statement) {TaParent = this};
loc.AddChildren();
_taStatement = loc;
}
else if (Statement is CheckedStatementSyntax)
{
var loc = new TameCheckedStatementSyntax((CheckedStatementSyntax) Statement) {TaParent = this};
loc.AddChildren();
_taStatement = loc;
}
else if (Statement is LabeledStatementSyntax)
{
var loc = new TameLabeledStatementSyntax((LabeledStatementSyntax) Statement) {TaParent = this};
loc.AddChildren();
_taStatement = loc;
}
else if (Statement is ReturnStatementSyntax)
{
var loc = new TameReturnStatementSyntax((ReturnStatementSyntax) Statement) {TaParent = this};
loc.AddChildren();
_taStatement = loc;
}
else if (Statement is SwitchStatementSyntax)
{
var loc = new TameSwitchStatementSyntax((SwitchStatementSyntax) Statement) {TaParent = this};
loc.AddChildren();
_taStatement = loc;
}
else if (Statement is UnsafeStatementSyntax)
{
var loc = new TameUnsafeStatementSyntax((UnsafeStatementSyntax) Statement) {TaParent = this};
loc.AddChildren();
_taStatement = loc;
}
else if (Statement is BreakStatementSyntax)
{
var loc = new TameBreakStatementSyntax((BreakStatementSyntax) Statement) {TaParent = this};
loc.AddChildren();
_taStatement = loc;
}
else if (Statement is EmptyStatementSyntax)
{
var loc = new TameEmptyStatementSyntax((EmptyStatementSyntax) Statement) {TaParent = this};
loc.AddChildren();
_taStatement = loc;
}
else if (Statement is FixedStatementSyntax)
{
var loc = new TameFixedStatementSyntax((FixedStatementSyntax) Statement) {TaParent = this};
loc.AddChildren();
_taStatement = loc;
}
else if (Statement is ThrowStatementSyntax)
{
var loc = new TameThrowStatementSyntax((ThrowStatementSyntax) Statement) {TaParent = this};
loc.AddChildren();
_taStatement = loc;
}
else if (Statement is UsingStatementSyntax)
{
var loc = new TameUsingStatementSyntax((UsingStatementSyntax) Statement) {TaParent = this};
loc.AddChildren();
_taStatement = loc;
}
else if (Statement is WhileStatementSyntax)
{
var loc = new TameWhileStatementSyntax((WhileStatementSyntax) Statement) {TaParent = this};
loc.AddChildren();
_taStatement = loc;
}
else if (Statement is YieldStatementSyntax)
{
var loc = new TameYieldStatementSyntax((YieldStatementSyntax) Statement) {TaParent = this};
loc.AddChildren();
_taStatement = loc;
}
else if (Statement is GotoStatementSyntax)
{
var loc = new TameGotoStatementSyntax((GotoStatementSyntax) Statement) {TaParent = this};
loc.AddChildren();
_taStatement = loc;
}
else if (Statement is LockStatementSyntax)
{
var loc = new TameLockStatementSyntax((LockStatementSyntax) Statement) {TaParent = this};
loc.AddChildren();
_taStatement = loc;
}
else if (Statement is ForStatementSyntax)
{
var loc = new TameForStatementSyntax((ForStatementSyntax) Statement) {TaParent = this};
loc.AddChildren();
_taStatement = loc;
}
else if (Statement is TryStatementSyntax)
{
var loc = new TameTryStatementSyntax((TryStatementSyntax) Statement) {TaParent = this};
loc.AddChildren();
_taStatement = loc;
}
else if (Statement is DoStatementSyntax)
{
var loc = new TameDoStatementSyntax((DoStatementSyntax) Statement) {TaParent = this};
loc.AddChildren();
_taStatement = loc;
}
else if (Statement is IfStatementSyntax)
{
var loc = new TameIfStatementSyntax((IfStatementSyntax) Statement) {TaParent = this};
loc.AddChildren();
_taStatement = loc;
}
else if (Statement is BlockSyntax)
{
var loc = new TameBlockSyntax((BlockSyntax) Statement) {TaParent = this};
loc.AddChildren();
_taStatement = loc;
}
return _taStatement;
}
set
{
if (_taStatement != value)
{
_taStatement = value;
if (_taStatement != null)
{
_taStatement.TaParent = this;
_taStatement.IsChanged = true;
}
else
{
IsChanged = true;
}
}
}
}
public ElseClauseSyntax Else
{
get
{
if (_elseIsChanged)
{
_else = SyntaxFactoryStr.ParseElseClauseSyntax(ElseStr);
_elseIsChanged = false;
_taElse = null;
}
else if (_taElse != null && _taElse.IsChanged)
{
_else = (ElseClauseSyntax) _taElse.Node;
}
return _else;
}
set
{
if (_else != value)
{
_else = value;
_elseIsChanged = false;
IsChanged = true;
}
}
}
public string ElseStr
{
get
{
if (_taElse != null && _taElse.IsChanged)
Else = (ElseClauseSyntax) _taElse.Node;
if (_elseIsChanged) return _elseStr;
return _elseStr = _else?.ToFullString();
}
set
{
if (_taElse != null && _taElse.IsChanged)
{
Else = (ElseClauseSyntax) _taElse.Node;
_elseStr = _else?.ToFullString();
}
if (_elseStr != value)
{
_elseStr = value;
IsChanged = true;
_elseIsChanged = true;
_taElse = null;
}
}
}
public TameElseClauseSyntax TaElse
{
get
{
if (_taElse == null && Else != null)
{
_taElse = new TameElseClauseSyntax(Else) {TaParent = this};
_taElse.AddChildren();
}
return _taElse;
}
set
{
if (_taElse != value)
{
_taElse = value;
if (_taElse != null)
{
_taElse.TaParent = this;
_taElse.IsChanged = true;
}
else
{
IsChanged = true;
}
}
}
}
public override void Clear()
{
base.Clear();
_taCondition = null;
_taStatement = null;
_taElse = null;
}
public new void AddChildren()
{
base.AddChildren();
Kind = Node.Kind();
_ifKeyword = ((IfStatementSyntax) Node).IfKeyword;
_ifKeywordIsChanged = false;
_openParenToken = ((IfStatementSyntax) Node).OpenParenToken;
_openParenTokenIsChanged = false;
_condition = ((IfStatementSyntax) Node).Condition;
_conditionIsChanged = false;
_closeParenToken = ((IfStatementSyntax) Node).CloseParenToken;
_closeParenTokenIsChanged = false;
_statement = ((IfStatementSyntax) Node).Statement;
_statementIsChanged = false;
_else = ((IfStatementSyntax) Node).Else;
_elseIsChanged = false;
}
public override void SetNotChanged()
{
base.SetNotChanged();
IsChanged = false;
}
public override SyntaxNode MakeSyntaxNode()
{
var res = SyntaxFactory.IfStatement(IfKeyword, OpenParenToken, Condition, CloseParenToken, Statement, Else);
IsChanged = false;
return res;
}
public override IEnumerable<TameBaseRoslynNode> GetChildren()
{
yield break;
}
public override IEnumerable<TameBaseRoslynNode> GetTameFields()
{
if (TaCondition != null) yield return TaCondition;
if (TaStatement != null) yield return TaStatement;
if (TaElse != null) yield return TaElse;
}
public override IEnumerable<(string filedName, string value)> GetStringFields()
{
yield return ("IfKeywordStr", IfKeywordStr);
yield return ("OpenParenTokenStr", OpenParenTokenStr);
yield return ("ConditionStr", ConditionStr);
yield return ("CloseParenTokenStr", CloseParenTokenStr);
yield return ("StatementStr", StatementStr);
yield return ("ElseStr", ElseStr);
}
}
} | 41.18515 | 158 | 0.430935 | [
"Apache-2.0"
] | ToCSharp/TameRoslyn | TameRoslyn/TameRoslynSyntaxGen/TameIfStatementSyntax.cs | 43,821 | 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.Sql.V20200801Preview
{
/// <summary>
/// A virtual network rule.
/// </summary>
[AzureNativeResourceType("azure-native:sql/v20200801preview:VirtualNetworkRule")]
public partial class VirtualNetworkRule : Pulumi.CustomResource
{
/// <summary>
/// Create firewall rule before the virtual network has vnet service endpoint enabled.
/// </summary>
[Output("ignoreMissingVnetServiceEndpoint")]
public Output<bool?> IgnoreMissingVnetServiceEndpoint { get; private set; } = null!;
/// <summary>
/// Resource name.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// Virtual Network Rule State
/// </summary>
[Output("state")]
public Output<string> State { get; private set; } = null!;
/// <summary>
/// Resource type.
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// The ARM resource id of the virtual network subnet.
/// </summary>
[Output("virtualNetworkSubnetId")]
public Output<string> VirtualNetworkSubnetId { get; private set; } = null!;
/// <summary>
/// Create a VirtualNetworkRule 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 VirtualNetworkRule(string name, VirtualNetworkRuleArgs args, CustomResourceOptions? options = null)
: base("azure-native:sql/v20200801preview:VirtualNetworkRule", name, args ?? new VirtualNetworkRuleArgs(), MakeResourceOptions(options, ""))
{
}
private VirtualNetworkRule(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:sql/v20200801preview:VirtualNetworkRule", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:sql/v20200801preview:VirtualNetworkRule"},
new Pulumi.Alias { Type = "azure-native:sql:VirtualNetworkRule"},
new Pulumi.Alias { Type = "azure-nextgen:sql:VirtualNetworkRule"},
new Pulumi.Alias { Type = "azure-native:sql/v20150501preview:VirtualNetworkRule"},
new Pulumi.Alias { Type = "azure-nextgen:sql/v20150501preview:VirtualNetworkRule"},
new Pulumi.Alias { Type = "azure-native:sql/v20200202preview:VirtualNetworkRule"},
new Pulumi.Alias { Type = "azure-nextgen:sql/v20200202preview:VirtualNetworkRule"},
new Pulumi.Alias { Type = "azure-native:sql/v20201101preview:VirtualNetworkRule"},
new Pulumi.Alias { Type = "azure-nextgen:sql/v20201101preview:VirtualNetworkRule"},
new Pulumi.Alias { Type = "azure-native:sql/v20210201preview:VirtualNetworkRule"},
new Pulumi.Alias { Type = "azure-nextgen:sql/v20210201preview:VirtualNetworkRule"},
},
};
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 VirtualNetworkRule 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 VirtualNetworkRule Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new VirtualNetworkRule(name, id, options);
}
}
public sealed class VirtualNetworkRuleArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Create firewall rule before the virtual network has vnet service endpoint enabled.
/// </summary>
[Input("ignoreMissingVnetServiceEndpoint")]
public Input<bool>? IgnoreMissingVnetServiceEndpoint { get; set; }
/// <summary>
/// The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
/// <summary>
/// The name of the server.
/// </summary>
[Input("serverName", required: true)]
public Input<string> ServerName { get; set; } = null!;
/// <summary>
/// The name of the virtual network rule.
/// </summary>
[Input("virtualNetworkRuleName")]
public Input<string>? VirtualNetworkRuleName { get; set; }
/// <summary>
/// The ARM resource id of the virtual network subnet.
/// </summary>
[Input("virtualNetworkSubnetId", required: true)]
public Input<string> VirtualNetworkSubnetId { get; set; } = null!;
public VirtualNetworkRuleArgs()
{
}
}
}
| 44.359155 | 152 | 0.617717 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Sql/V20200801Preview/VirtualNetworkRule.cs | 6,299 | C# |
using System;
namespace Snowlight.Specialized
{
public class Vector2
{
internal int int_0;
internal int int_1;
public Vector2()
{
this.int_0 = 0;
this.int_1 = 0;
}
public Vector2(int int_2, int int_3)
{
this.int_0 = int_2;
this.int_1 = int_3;
}
public static Vector2 FromString(string Input)
{
string[] strArray = Input.Split(new char[] { '|' });
int result = 0;
int num2 = 0;
int.TryParse(strArray[0], out result);
if (strArray.Length > 1)
{
int.TryParse(strArray[1], out num2);
}
return new Vector2(result, num2);
}
public Vector3 GetVector3()
{
return new Vector3(this.int_0, this.int_1, 0);
}
public override string ToString()
{
return (this.int_0 + "|" + this.int_1);
}
public int Int32_0
{
get
{
return this.int_0;
}
set
{
this.int_0 = value;
}
}
public int Int32_1
{
get
{
return this.int_1;
}
set
{
this.int_1 = value;
}
}
}
}
| 20.457143 | 64 | 0.405028 | [
"MIT"
] | DaLoE99/Servidores-DaLoE | 3/BoomBang/Specialized/Vector2.cs | 1,434 | C# |
using System.Collections.Generic;
using System.Collections.ObjectModel;
using GeoAPI.Geometries;
using NetTopologySuite.Geometries;
namespace NetTopologySuite.Index.KdTree
{
/// <summary>
/// An implementation of a 2-D KD-Tree. KD-trees provide fast range searching on point data.
/// </summary>
/// <remarks>
/// This implementation supports detecting and snapping points which are closer
/// than a given distance tolerance.
/// If the same point (up to tolerance) is inserted
/// more than once , it is snapped to the existing node.
/// In other words, if a point is inserted which lies within the tolerance of a node already in the index,
/// it is snapped to that node.
/// When a point is snapped to a node then a new node is not created but the count of the existing node
/// is incremented.
/// If more than one node in the tree is within tolerance of an inserted point,
/// the closest and then lowest node is snapped to.
/// </remarks>
/// <typeparam name="T">The type of the user data object</typeparam>
/// <author>David Skea</author>
/// <author>Martin Davis</author>
public partial class KdTree<T>
where T : class
{
/// <summary>
/// Converts a collection of<see cref= "KdNode{T}" /> s to an array of <see cref="Coordinate"/>s.
/// </summary>
/// <param name="kdnodes">A collection of nodes</param>
/// <returns>An array of the coordinates represented by the nodes</returns>
public static Coordinate[] ToCoordinates(ICollection<KdNode<T>> kdnodes)
{
return ToCoordinates(kdnodes, false);
}
/// <summary>
/// Converts a collection of <see cref="KdNode{T}"/>{@link KdNode}s
/// to an array of <see cref="Coordinate"/>s,
/// specifying whether repeated nodes should be represented
/// by multiple coordinates.
/// </summary>
/// <param name="kdnodes">a collection of nodes</param>
/// <param name="includeRepeated">true if repeated nodes should
/// be included multiple times</param>
/// <returns>An array of the coordinates represented by the nodes</returns>
public static Coordinate[] ToCoordinates(ICollection<KdNode<T>> kdnodes, bool includeRepeated)
{
var coord = new CoordinateList();
foreach (var node in kdnodes)
{
int count = includeRepeated ? node.Count : 1;
for (int i = 0; i < count; i++)
{
coord.Add(node.Coordinate, true);
}
}
return coord.ToCoordinateArray();
}
private KdNode<T> _root;
private long _numberOfNodes;
private readonly double _tolerance;
/// <summary>
/// Creates a new instance of a KdTree with a snapping tolerance of 0.0.
/// (I.e. distinct points will <i>not</i> be snapped)
/// </summary>
public KdTree()
: this(0.0)
{
}
/// <summary>
/// Creates a new instance of a KdTree with a snapping distance
/// tolerance. Points which lie closer than the tolerance to a point already
/// in the tree will be treated as identical to the existing point.
/// </summary>
/// <param name="tolerance">The tolerance distance for considering two points equal</param>
public KdTree(double tolerance)
{
_tolerance = tolerance;
}
/// <summary>
/// Tests whether the index contains any items.
/// </summary>
public bool IsEmpty
{
get
{
if (_root == null) return true;
return false;
}
}
/// <summary>
/// Gets a value indicating the root node of the tree
/// </summary>
internal KdNode<T> Root => _root;
/// <summary>
/// Inserts a new point in the kd-tree, with no data.
/// </summary>
/// <param name="p">The point to insert</param>
/// <returns>The kdnode containing the point</returns>
public KdNode<T> Insert(Coordinate p)
{
return Insert(p, null);
}
/// <summary>
/// Inserts a new point into the kd-tree.
/// </summary>
/// <param name="p">The point to insert</param>
/// <param name="data">A data item for the point</param>
/// <returns>
/// A new KdNode if a new point is inserted, else an existing
/// node is returned with its counter incremented. This can be checked
/// by testing returnedNode.getCount() > 1.
/// </returns>
public KdNode<T> Insert(Coordinate p, T data)
{
if (_root == null)
{
_root = new KdNode<T>(p, data);
return _root;
}
/**
* Check if the point is already in the tree, up to tolerance.
* If tolerance is zero, this phase of the insertion can be skipped.
*/
if (_tolerance > 0)
{
var matchNode = FindBestMatchNode(p);
if (matchNode != null)
{
// point already in index - increment counter
matchNode.Increment();
return matchNode;
}
}
return InsertExact(p, data);
}
/// <summary>
/// Finds the node in the tree which is the best match for a point
/// being inserted.
/// The match is made deterministic by returning the lowest of any nodes which
/// lie the same distance from the point.
/// There may be no match if the point is not within the distance tolerance of any
/// existing node.
/// </summary>
/// <param name="p">The point being inserted</param>
/// <returns>
/// <list type="Bullet">
/// <item>the best matching node</item>
/// <item>null if no match was found</item>
/// </list>
/// </returns>
private KdNode<T> FindBestMatchNode(Coordinate p)
{
var visitor = new BestMatchVisitor<T>(p, _tolerance);
Query(visitor.QueryEnvelope(), visitor);
return visitor.Node;
}
/// <summary>
/// Inserts a point known to be beyond the distance tolerance of any existing node.
/// The point is inserted at the bottom of the exact splitting path,
/// so that tree shape is deterministic.
/// </summary>
/// <param name="p">The point to insert</param>
/// <returns>
/// <list type="Bullet">
/// <item>The data for the point</item>
/// <item>The created node</item>
/// </list>
/// </returns>
public KdNode<T> InsertExact(Coordinate p, T data)
{
var currentNode = _root;
var leafNode = _root;
bool isOddLevel = true;
bool isLessThan = true;
/**
* Traverse the tree, first cutting the plane left-right (by X ordinate)
* then top-bottom (by Y ordinate)
*/
while (currentNode != null)
{
// test if point is already a node (not strictly necessary)
if (currentNode != null)
{
bool isInTolerance = p.Distance(currentNode.Coordinate) <= _tolerance;
// check if point is already in tree (up to tolerance) and if so simply
// return existing node
if (isInTolerance)
{
currentNode.Increment();
return currentNode;
}
}
if (isOddLevel)
{
// ReSharper disable once PossibleNullReferenceException
isLessThan = p.X < currentNode.X;
}
else
{
// ReSharper disable once PossibleNullReferenceException
isLessThan = p.Y < currentNode.Y;
}
leafNode = currentNode;
currentNode = isLessThan
? currentNode.Left
: currentNode.Right;
isOddLevel = !isOddLevel;
}
// no node found, add new leaf node to tree
_numberOfNodes = _numberOfNodes + 1;
var node = new KdNode<T>(p, data);
node.Left = null;
node.Right = null;
if (isLessThan)
{
leafNode.Left = node;
}
else
{
leafNode.Right = node;
}
return node;
}
private static void QueryNode(KdNode<T> currentNode,
Envelope queryEnv, bool odd, IKdNodeVisitor<T> visitor)
{
if (currentNode == null)
return;
double min;
double max;
double discriminant;
if (odd)
{
min = queryEnv.MinX;
max = queryEnv.MaxX;
discriminant = currentNode.X;
}
else
{
min = queryEnv.MinY;
max = queryEnv.MaxY;
discriminant = currentNode.Y;
}
bool searchLeft = min < discriminant;
bool searchRight = discriminant <= max;
// search is computed via in-order traversal
if (searchLeft)
{
QueryNode(currentNode.Left, queryEnv, !odd, visitor);
}
if (queryEnv.Contains(currentNode.Coordinate))
{
visitor.Visit(currentNode);
}
if (searchRight)
{
QueryNode(currentNode.Right, queryEnv, !odd, visitor);
}
}
/// <summary>
/// Performs a range search of the points in the index.
/// </summary>
/// <param name="queryEnv">The range rectangle to query</param>
/// <param name="visitor"></param>
public void Query(Envelope queryEnv, IKdNodeVisitor<T> visitor)
{
QueryNode(_root, queryEnv, true, visitor);
}
/// <summary>
/// Performs a range search of the points in the index.
/// </summary>
/// <param name="queryEnv">The range rectangle to query</param>
/// <returns>A collection of the KdNodes found</returns>
public IList<KdNode<T>> Query(Envelope queryEnv)
{
var result = new List<KdNode<T>>();
QueryNode(_root, queryEnv, true, new KdNodeVisitor<T>(result));
return result;
}
/// <summary>
/// Performs a range search of the points in the index.
/// </summary>
/// <param name="queryEnv">The range rectangle to query</param>
/// <param name="result">A collection to accumulate the result nodes into</param>
public void Query(Envelope queryEnv, IList<KdNode<T>> result)
{
QueryNode(_root, queryEnv, true, new KdNodeVisitor<T>(result));
}
private class KdNodeVisitor<T> : IKdNodeVisitor<T> where T : class
{
private readonly IList<KdNode<T>> _result;
public KdNodeVisitor(IList<KdNode<T>> result)
{
_result = result;
}
public void Visit(KdNode<T> node)
{
_result.Add(node);
}
}
private class BestMatchVisitor<T> : IKdNodeVisitor<T> where T : class
{
private readonly double tolerance;
private KdNode<T> matchNode = null;
private double matchDist = 0.0;
private Coordinate p;
public BestMatchVisitor(Coordinate p, double tolerance)
{
this.p = p;
this.tolerance = tolerance;
}
public KdNode<T> Node => matchNode;
public Envelope QueryEnvelope()
{
var queryEnv = new Envelope(p);
queryEnv.ExpandBy(tolerance);
return queryEnv;
}
public void Visit(KdNode<T> node)
{
double dist = p.Distance(node.Coordinate);
bool isInTolerance = dist <= tolerance;
if (!isInTolerance) return;
bool update = false;
if (matchNode == null
|| dist < matchDist
// if distances are the same, record the lesser coordinate
|| (matchNode != null && dist == matchDist
&& node.Coordinate.CompareTo(matchNode.Coordinate) < 1))
{
update = true;
}
if (update)
{
matchNode = node;
matchDist = dist;
}
}
}
}
} | 34.915789 | 110 | 0.51432 | [
"EPL-1.0"
] | bouyeijiang/NetTopologySuite | NetTopologySuite/Index/KdTree/KdTree.cs | 13,270 | C# |
using System;
class Books
{
struct book
{
public string author;
public string title;
public int year;
}
static void Main()
{
const int CAPACITY = 25000;
int amount = 0;
book[] books = new book[CAPACITY];
string option;
do
{
Console.WriteLine("Choose an option:");
Console.WriteLine("...");
Console.WriteLine("X- Exit");
option = Console.ReadLine().ToUpper();
switch (option)
{
case "1":
// TO DO ...
break;
// TO DO ...
case "X":
Console.WriteLine("Bye!!");
break;
default:
Console.WriteLine("Wrong option");
break;
}
}
while (option != "X");
}
}
| 22.066667 | 55 | 0.369587 | [
"MIT"
] | Jokerlocco/2019-2020_DAM1_EjerciciosClase | chapter04-arraysStruct/184a-Books1.cs | 993 | C# |
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using BTDB.KVDBLayer;
using BTDB.ODBLayer;
namespace SimpleTester
{
public class CompactorLatencyMeasurement
{
public CompactorLatencyMeasurement()
{
}
public class SmallObject
{
public ulong Id { get; set; }
public string? Label { get; set; }
}
public class SmallObjects
{
public IOrderedDictionary<ulong, SmallObject>? Items { get; set; }
}
public void Run()
{
var collection = new InMemoryFileCollection();
using (var kvDb = new KeyValueDB(collection, new NoCompressionStrategy(), 100 * 1024 * 1024))
{
ulong itemsCount = 0;
using (var objDb = new ObjectDB())
{
objDb.Open(kvDb, false);
Console.WriteLine("started generating");
using (var tr = objDb.StartWritingTransaction().Result)
{
var objects = tr.Singleton<SmallObjects>();
while (true)
{
objects.Items!.Add(itemsCount, new SmallObject() { Id = itemsCount, Label = "bu" });
if (itemsCount % 1_000_000 == 0)
Console.WriteLine("Generated {0}", itemsCount);
if (itemsCount % 1000 == 0 && collection.GetCount() == 20)
break;
itemsCount++;
}
tr.Commit();
}
Console.WriteLine("finished generating");
using (var tr = objDb.StartWritingTransaction().Result)
{
var objects = tr.Singleton<SmallObjects>();
itemsCount = (ulong)objects.Items!.Count;
tr.Commit();
}
Console.WriteLine("removing items started");
using (var tr = objDb.StartWritingTransaction().Result)
{
var objects = tr.Singleton<SmallObjects>();
for (ulong i = 0; i < itemsCount / 5; i++)
{
if (i % 2 == 0)
continue;
objects.Items!.Remove(i);
}
tr.Commit();
}
Console.WriteLine("removing items finished");
var transactionCreationStarted = new ManualResetEventSlim(false);
var compactionFinished = new ManualResetEventSlim(false);
Task.Run(() =>
{
Console.WriteLine("Started waiting for transaction creating");
transactionCreationStarted.Wait();
Console.WriteLine("Started Compacting");
Trace.Assert(kvDb.Compact(CancellationToken.None));
Console.WriteLine("Finished Compacting");
compactionFinished.Set();
});
Console.WriteLine("Started concurrent transaction creation");
long msMax = 0;
long average = 0;
long iterations = 0;
Stopwatch watch = new Stopwatch();
while (true)
{
var compactionFinishedBeforeLasttransaction = compactionFinished.IsSet;
iterations++;
watch.Start();
var task = objDb.StartWritingTransaction();
if (!transactionCreationStarted.IsSet)
transactionCreationStarted.Set();
task.AsTask().Wait();
var ms = watch.ElapsedMilliseconds;
average += ms;
msMax = Math.Max(ms, msMax);
watch.Reset();
using (var tr = task.Result)
{
tr.Commit();
}
if ((compactionFinishedBeforeLasttransaction && compactionFinished.IsSet))
break;
}
Console.WriteLine("Finished concurrent transaction creation, longest transaction create time was {0}ms, " +
"average {1}ms, iterations {2}", msMax, average / (double)iterations, iterations);
}
}
}
}
}
| 36.586466 | 127 | 0.43917 | [
"MIT"
] | Bobris/BTDB | SimpleTester/CompactorLatencyMeasurement.cs | 4,866 | C# |
using KnightBus.Core;
namespace KnightBus.NewRelicMiddleware
{
public static class NewRelicExtensions
{
public static IHostConfiguration UseNewRelic(this IHostConfiguration configuration)
{
configuration.AddMiddleware(new NewRelicMessageMiddleware());
return configuration;
}
}
} | 26.230769 | 91 | 0.697947 | [
"MIT"
] | BookBeat/knightbus | knightbus-newrelic/src/KnightBus.NewRelic/NewRelicExtensions.cs | 343 | C# |
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace Essensoft.AspNetCore.Payment.Alipay.Response
{
/// <summary>
/// AlipayFlashsalesStockSyncUpdateResponse.
/// </summary>
public class AlipayFlashsalesStockSyncUpdateResponse : AlipayResponse
{
/// <summary>
/// 成功时返回的业务参数信息。
/// </summary>
[JsonProperty("biz_result")]
[XmlElement("biz_result")]
public string BizResult { get; set; }
/// <summary>
/// 当更新库存不成功时,错误码
/// </summary>
[JsonProperty("error_code")]
[XmlElement("error_code")]
public string ErrorCode { get; set; }
/// <summary>
/// 成功标识
/// </summary>
[JsonProperty("success")]
[XmlElement("success")]
public string Success { get; set; }
}
}
| 25.424242 | 73 | 0.573302 | [
"MIT"
] | AkonCoder/Payment | src/Essensoft.AspNetCore.Payment.Alipay/Response/AlipayFlashsalesStockSyncUpdateResponse.cs | 899 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Thrifty.Nifty.Core
{
public enum ThriftTransportType
{
Unframed,
Framed,
Http,
Header
}
}
| 15.1875 | 35 | 0.650206 | [
"Apache-2.0"
] | DavidAlphaFox/Thrifty | src/Thrifty.Nifty/Core/ThriftTransportType.cs | 245 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using ApiPeek.Core.Extensions;
namespace ApiPeek.Core.Model;
[DataContract]
public class ApiMethod : ApiBaseItem, IDetail
{
[DataMember]
public bool IsStatic { get; set; }
[DataMember]
public string ReturnType { get; set; }
[DataMember]
public ApiMethodParameter[] Parameters { get; set; }
[IgnoreDataMember]
public override string SortName => ShortString;
[IgnoreDataMember]
public override string ShortString => string.Format("{1}({2}){0} : {3}", PrefixString, Name, ParamString, ReturnType);
[IgnoreDataMember]
private string PrefixString => IsStatic ? " static" : "";
[IgnoreDataMember]
private string ParamString
{
get { return Parameters.IsNullOrEmpty() ? "" : string.Join(", ", Parameters.Select(p => p.Detail())); }
}
public void Init()
{
Parameters ??= Array.Empty<ApiMethodParameter>();
}
public static IEqualityComparer<ApiMethod> DetailComparer =
ProjectionEqualityComparer<ApiMethod>.Create(x => x.Detail);
[IgnoreDataMember]
public string Detail => InDetail();
private string detail;
public string InDetail(string indent = "")
{
if (detail == null)
{
StringBuilder sb = new StringBuilder();
if (IsStatic) sb.Append("static ");
sb.AppendFormat("public {0} {1}", ReturnType, Name);
sb.Append("(");
sb.Append(ParamString);
sb.Append(");");
detail = sb.ToString();
}
return indent + detail;
}
} | 27.540984 | 122 | 0.629762 | [
"MIT"
] | martinsuchan/ApiPeek | Source/ApiPeek.Core/Model/ApiMethod.cs | 1,680 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MonsterAtttackAction : MonoBehaviour
{
public System.Action<GameObject,float> monsterAttackAction;
public float dmg;
public void FenceAttackAction()
{
this.monsterAttackAction(this.gameObject.transform.root.gameObject,this.dmg);
}
public void Init(float dmg)
{
this.dmg = dmg;
}
}
| 23.5 | 85 | 0.716312 | [
"MIT"
] | VontineDev/ProjectA | Dev/AlphaTest/Assets/Scripts/Effect/MonsterAtttackAction.cs | 425 | C# |
using MediatR;
using AdventureWorks.Application.DataEngine;
using AdventureWorks.Application.DataEngine.DataEngine;
using AdventureWorks.Application.DataEngine.Dbo.DatabaseLog.Queries.QueryManager;
using AdventureWorks.Application.Interfaces;
namespace AdventureWorks.Application.DataEngine.Dbo.DatabaseLog.Queries.GetDatabaseLogs
{
public partial class GetDatabaseLogsListQuery : IRequest<DatabaseLogsListViewModel>, IDataTableInfo<DatabaseLogSummary>
{
public DataTableInfo<DatabaseLogSummary> DataTable { get; set; }
}
}
| 38.928571 | 123 | 0.833028 | [
"Unlicense"
] | CodeSwifterGit/adventure-works | src/AdventureWorks.Application/DataEngine/Dbo/DatabaseLog/Queries/GetDatabaseLogs/GetDatabaseLogsListQuery.cs | 545 | C# |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Apis.GKEHub.v1alpha
{
/// <summary>The GKEHub Service.</summary>
public class GKEHubService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1alpha";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public GKEHubService() : this(new Google.Apis.Services.BaseClientService.Initializer())
{
}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public GKEHubService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer)
{
Organizations = new OrganizationsResource(this);
Projects = new ProjectsResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features => new string[0];
/// <summary>Gets the service name.</summary>
public override string Name => "gkehub";
/// <summary>Gets the service base URI.</summary>
public override string BaseUri =>
#if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45
BaseUriOverride ?? "https://gkehub.googleapis.com/";
#else
"https://gkehub.googleapis.com/";
#endif
/// <summary>Gets the service base path.</summary>
public override string BasePath => "";
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri => "https://gkehub.googleapis.com/batch";
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath => "batch";
#endif
/// <summary>Available OAuth 2.0 scopes for use with the GKE Hub API.</summary>
public class Scope
{
/// <summary>
/// See, edit, configure, and delete your Google Cloud data and see the email address for your Google
/// Account.
/// </summary>
public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
}
/// <summary>Available OAuth 2.0 scope constants for use with the GKE Hub API.</summary>
public static class ScopeConstants
{
/// <summary>
/// See, edit, configure, and delete your Google Cloud data and see the email address for your Google
/// Account.
/// </summary>
public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
}
/// <summary>Gets the Organizations resource.</summary>
public virtual OrganizationsResource Organizations { get; }
/// <summary>Gets the Projects resource.</summary>
public virtual ProjectsResource Projects { get; }
}
/// <summary>A base abstract class for GKEHub requests.</summary>
public abstract class GKEHubBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
/// <summary>Constructs a new GKEHubBaseServiceRequest instance.</summary>
protected GKEHubBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1 = 0,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2 = 1,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json = 0,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media = 1,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto = 2,
}
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>
/// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required
/// unless you provide an OAuth 2.0 token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>
/// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a
/// user, but should not exceed 40 characters.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes GKEHub parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "organizations" collection of methods.</summary>
public class OrganizationsResource
{
private const string Resource = "organizations";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public OrganizationsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
Locations = new LocationsResource(service);
}
/// <summary>Gets the Locations resource.</summary>
public virtual LocationsResource Locations { get; }
/// <summary>The "locations" collection of methods.</summary>
public class LocationsResource
{
private const string Resource = "locations";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public LocationsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
Fleets = new FleetsResource(service);
}
/// <summary>Gets the Fleets resource.</summary>
public virtual FleetsResource Fleets { get; }
/// <summary>The "fleets" collection of methods.</summary>
public class FleetsResource
{
private const string Resource = "fleets";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public FleetsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>
/// Returns all fleets within an organization or a project that the caller has access to.
/// </summary>
/// <param name="parent">
/// Required. The organization or project to list for Fleets under, in the format
/// `organizations/*/locations/*` or `projects/*/locations/*`.
/// </param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>
/// Returns all fleets within an organization or a project that the caller has access to.
/// </summary>
public class ListRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.ListFleetsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>
/// Required. The organization or project to list for Fleets under, in the format
/// `organizations/*/locations/*` or `projects/*/locations/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>
/// Optional. The maximum number of fleets to return. The service may return fewer than this value.
/// If unspecified, at most 200 fleets will be returned. The maximum value is 1000; values above
/// 1000 will be coerced to 1000.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// Optional. A page token, received from a previous `ListFleets` call. Provide this to retrieve the
/// subsequent page. When paginating, all other parameters provided to `ListFleets` must match the
/// call that provided the page token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+parent}/fleets";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^organizations/[^/]+/locations/[^/]+$",
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
}
/// <summary>The "projects" collection of methods.</summary>
public class ProjectsResource
{
private const string Resource = "projects";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ProjectsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
Locations = new LocationsResource(service);
}
/// <summary>Gets the Locations resource.</summary>
public virtual LocationsResource Locations { get; }
/// <summary>The "locations" collection of methods.</summary>
public class LocationsResource
{
private const string Resource = "locations";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public LocationsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
Features = new FeaturesResource(service);
Fleets = new FleetsResource(service);
Memberships = new MembershipsResource(service);
Operations = new OperationsResource(service);
}
/// <summary>Gets the Features resource.</summary>
public virtual FeaturesResource Features { get; }
/// <summary>The "features" collection of methods.</summary>
public class FeaturesResource
{
private const string Resource = "features";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public FeaturesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Adds a new Feature.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">
/// Required. The parent (project and location) where the Feature will be created. Specified in the
/// format `projects/*/locations/*`.
/// </param>
public virtual CreateRequest Create(Google.Apis.GKEHub.v1alpha.Data.Feature body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>Adds a new Feature.</summary>
public class CreateRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.Operation>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.GKEHub.v1alpha.Data.Feature body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The parent (project and location) where the Feature will be created. Specified in the
/// format `projects/*/locations/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>The ID of the feature to create.</summary>
[Google.Apis.Util.RequestParameterAttribute("featureId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string FeatureId { get; set; }
/// <summary>
/// A request ID to identify requests. Specify a unique request ID so that if you must retry your
/// request, the server will know to ignore the request if it has already been completed. The server
/// will guarantee that for at least 60 minutes after the first request. For example, consider a
/// situation where you make an initial request and the request times out. If you make the request
/// again with the same request ID, the server can check if original operation with the same request
/// ID was received, and if so, will ignore the second request. This prevents clients from
/// accidentally creating duplicate commitments. The request ID must be a valid UUID with the
/// exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("requestId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string RequestId { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.GKEHub.v1alpha.Data.Feature Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "create";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+parent}/features";
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+$",
});
RequestParameters.Add("featureId", new Google.Apis.Discovery.Parameter
{
Name = "featureId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("requestId", new Google.Apis.Discovery.Parameter
{
Name = "requestId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Removes a Feature.</summary>
/// <param name="name">
/// Required. The Feature resource name in the format `projects/*/locations/*/features/*`.
/// </param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>Removes a Feature.</summary>
public class DeleteRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.Operation>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The Feature resource name in the format `projects/*/locations/*/features/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// If set to true, the delete will ignore any outstanding resources for this Feature (that is,
/// `FeatureState.has_resources` is set to true). These resources will NOT be cleaned up or modified
/// in any way.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("force", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> Force { get; set; }
/// <summary>
/// Optional. A request ID to identify requests. Specify a unique request ID so that if you must
/// retry your request, the server will know to ignore the request if it has already been completed.
/// The server will guarantee that for at least 60 minutes after the first request. For example,
/// consider a situation where you make an initial request and the request times out. If you make
/// the request again with the same request ID, the server can check if original operation with the
/// same request ID was received, and if so, will ignore the second request. This prevents clients
/// from accidentally creating duplicate commitments. The request ID must be a valid UUID with the
/// exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("requestId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string RequestId { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "delete";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "DELETE";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+name}";
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/features/[^/]+$",
});
RequestParameters.Add("force", new Google.Apis.Discovery.Parameter
{
Name = "force",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("requestId", new Google.Apis.Discovery.Parameter
{
Name = "requestId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Gets details of a single Feature.</summary>
/// <param name="name">
/// Required. The Feature resource name in the format `projects/*/locations/*/features/*`
/// </param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets details of a single Feature.</summary>
public class GetRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.Feature>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The Feature resource name in the format `projects/*/locations/*/features/*`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/features/[^/]+$",
});
}
}
/// <summary>
/// Gets the access control policy for a resource. Returns an empty policy if the resource exists and
/// does not have a policy set.
/// </summary>
/// <param name="resource">
/// REQUIRED: The resource for which the policy is being requested. See the operation documentation for
/// the appropriate value for this field.
/// </param>
public virtual GetIamPolicyRequest GetIamPolicy(string resource)
{
return new GetIamPolicyRequest(service, resource);
}
/// <summary>
/// Gets the access control policy for a resource. Returns an empty policy if the resource exists and
/// does not have a policy set.
/// </summary>
public class GetIamPolicyRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.Policy>
{
/// <summary>Constructs a new GetIamPolicy request.</summary>
public GetIamPolicyRequest(Google.Apis.Services.IClientService service, string resource) : base(service)
{
Resource = resource;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy is being requested. See the operation documentation
/// for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>
/// Optional. The maximum policy version that will be used to format the policy. Valid values are 0,
/// 1, and 3. Requests specifying an invalid value will be rejected. Requests for policies with any
/// conditional role bindings must specify version 3. Policies with no conditional role bindings may
/// specify any valid value or leave the field unset. The policy in the response might use the
/// policy version that you specified, or it might use a lower policy version. For example, if you
/// specify version 3, but the policy has no conditional role bindings, the response uses version 1.
/// To learn which resources support conditions in their IAM policies, see the [IAM
/// documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("options.requestedPolicyVersion", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> OptionsRequestedPolicyVersion { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "getIamPolicy";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+resource}:getIamPolicy";
/// <summary>Initializes GetIamPolicy parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/features/[^/]+$",
});
RequestParameters.Add("options.requestedPolicyVersion", new Google.Apis.Discovery.Parameter
{
Name = "options.requestedPolicyVersion",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Lists Features in a given project and location.</summary>
/// <param name="parent">
/// Required. The parent (project and location) where the Features will be listed. Specified in the
/// format `projects/*/locations/*`.
/// </param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Lists Features in a given project and location.</summary>
public class ListRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.ListFeaturesResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>
/// Required. The parent (project and location) where the Features will be listed. Specified in the
/// format `projects/*/locations/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>
/// Lists Features that match the filter expression, following the syntax outlined in
/// https://google.aip.dev/160. Examples: - Feature with the name "servicemesh" in project
/// "foo-proj": name = "projects/foo-proj/locations/global/features/servicemesh" - Features that
/// have a label called `foo`: labels.foo:* - Features that have a label called `foo` whose value is
/// `bar`: labels.foo = bar
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>
/// One or more fields to compare and use to sort the output. See
/// https://google.aip.dev/132#ordering.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("orderBy", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OrderBy { get; set; }
/// <summary>
/// When requesting a 'page' of resources, `page_size` specifies number of resources to return. If
/// unspecified or set to 0, all resources will be returned.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// Token returned by previous call to `ListFeatures` which specifies the position in the list from
/// where to continue listing the resources.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+parent}/features";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("orderBy", new Google.Apis.Discovery.Parameter
{
Name = "orderBy",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Updates an existing Feature.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// Required. The Feature resource name in the format `projects/*/locations/*/features/*`.
/// </param>
public virtual PatchRequest Patch(Google.Apis.GKEHub.v1alpha.Data.Feature body, string name)
{
return new PatchRequest(service, body, name);
}
/// <summary>Updates an existing Feature.</summary>
public class PatchRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.Operation>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.GKEHub.v1alpha.Data.Feature body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The Feature resource name in the format `projects/*/locations/*/features/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// A request ID to identify requests. Specify a unique request ID so that if you must retry your
/// request, the server will know to ignore the request if it has already been completed. The server
/// will guarantee that for at least 60 minutes after the first request. For example, consider a
/// situation where you make an initial request and the request times out. If you make the request
/// again with the same request ID, the server can check if original operation with the same request
/// ID was received, and if so, will ignore the second request. This prevents clients from
/// accidentally creating duplicate commitments. The request ID must be a valid UUID with the
/// exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("requestId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string RequestId { get; set; }
/// <summary>Mask of fields to update.</summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.GKEHub.v1alpha.Data.Feature Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "patch";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "PATCH";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+name}";
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/features/[^/]+$",
});
RequestParameters.Add("requestId", new Google.Apis.Discovery.Parameter
{
Name = "requestId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any existing policy. Can return
/// `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="resource">
/// REQUIRED: The resource for which the policy is being specified. See the operation documentation for
/// the appropriate value for this field.
/// </param>
public virtual SetIamPolicyRequest SetIamPolicy(Google.Apis.GKEHub.v1alpha.Data.SetIamPolicyRequest body, string resource)
{
return new SetIamPolicyRequest(service, body, resource);
}
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any existing policy. Can return
/// `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors.
/// </summary>
public class SetIamPolicyRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.Policy>
{
/// <summary>Constructs a new SetIamPolicy request.</summary>
public SetIamPolicyRequest(Google.Apis.Services.IClientService service, Google.Apis.GKEHub.v1alpha.Data.SetIamPolicyRequest body, string resource) : base(service)
{
Resource = resource;
Body = body;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy is being specified. See the operation documentation
/// for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.GKEHub.v1alpha.Data.SetIamPolicyRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "setIamPolicy";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+resource}:setIamPolicy";
/// <summary>Initializes SetIamPolicy parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/features/[^/]+$",
});
}
}
/// <summary>
/// Returns permissions that a caller has on the specified resource. If the resource does not exist,
/// this will return an empty set of permissions, not a `NOT_FOUND` error. Note: This operation is
/// designed to be used for building permission-aware UIs and command-line tools, not for authorization
/// checking. This operation may "fail open" without warning.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="resource">
/// REQUIRED: The resource for which the policy detail is being requested. See the operation
/// documentation for the appropriate value for this field.
/// </param>
public virtual TestIamPermissionsRequest TestIamPermissions(Google.Apis.GKEHub.v1alpha.Data.TestIamPermissionsRequest body, string resource)
{
return new TestIamPermissionsRequest(service, body, resource);
}
/// <summary>
/// Returns permissions that a caller has on the specified resource. If the resource does not exist,
/// this will return an empty set of permissions, not a `NOT_FOUND` error. Note: This operation is
/// designed to be used for building permission-aware UIs and command-line tools, not for authorization
/// checking. This operation may "fail open" without warning.
/// </summary>
public class TestIamPermissionsRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.TestIamPermissionsResponse>
{
/// <summary>Constructs a new TestIamPermissions request.</summary>
public TestIamPermissionsRequest(Google.Apis.Services.IClientService service, Google.Apis.GKEHub.v1alpha.Data.TestIamPermissionsRequest body, string resource) : base(service)
{
Resource = resource;
Body = body;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy detail is being requested. See the operation
/// documentation for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.GKEHub.v1alpha.Data.TestIamPermissionsRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "testIamPermissions";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+resource}:testIamPermissions";
/// <summary>Initializes TestIamPermissions parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/features/[^/]+$",
});
}
}
}
/// <summary>Gets the Fleets resource.</summary>
public virtual FleetsResource Fleets { get; }
/// <summary>The "fleets" collection of methods.</summary>
public class FleetsResource
{
private const string Resource = "fleets";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public FleetsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Creates a fleet.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">
/// Required. The parent (project and location) where the Fleet will be created. Specified in the format
/// `projects/*/locations/*`.
/// </param>
public virtual CreateRequest Create(Google.Apis.GKEHub.v1alpha.Data.Fleet body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>Creates a fleet.</summary>
public class CreateRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.Fleet>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.GKEHub.v1alpha.Data.Fleet body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The parent (project and location) where the Fleet will be created. Specified in the
/// format `projects/*/locations/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.GKEHub.v1alpha.Data.Fleet Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "create";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+parent}/fleets";
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+$",
});
}
}
/// <summary>Removes a Fleet. There must be no memberships remaining in the Fleet.</summary>
/// <param name="name">
/// Required. The Fleet resource name in the format `projects/*/locations/*/fleets/*`.
/// </param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>Removes a Fleet. There must be no memberships remaining in the Fleet.</summary>
public class DeleteRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.Empty>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The Fleet resource name in the format `projects/*/locations/*/fleets/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "delete";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "DELETE";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+name}";
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/fleets/[^/]+$",
});
}
}
/// <summary>Returns the details of a fleet.</summary>
/// <param name="name">
/// Required. The Fleet resource name in the format `projects/*/locations/*/fleets/*`.
/// </param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Returns the details of a fleet.</summary>
public class GetRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.Fleet>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The Fleet resource name in the format `projects/*/locations/*/fleets/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/fleets/[^/]+$",
});
}
}
/// <summary>
/// Returns all fleets within an organization or a project that the caller has access to.
/// </summary>
/// <param name="parent">
/// Required. The organization or project to list for Fleets under, in the format
/// `organizations/*/locations/*` or `projects/*/locations/*`.
/// </param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>
/// Returns all fleets within an organization or a project that the caller has access to.
/// </summary>
public class ListRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.ListFleetsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>
/// Required. The organization or project to list for Fleets under, in the format
/// `organizations/*/locations/*` or `projects/*/locations/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>
/// Optional. The maximum number of fleets to return. The service may return fewer than this value.
/// If unspecified, at most 200 fleets will be returned. The maximum value is 1000; values above
/// 1000 will be coerced to 1000.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// Optional. A page token, received from a previous `ListFleets` call. Provide this to retrieve the
/// subsequent page. When paginating, all other parameters provided to `ListFleets` must match the
/// call that provided the page token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+parent}/fleets";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+$",
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Updates a fleet.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// Output only. The full, unique resource name of this fleet in the format of
/// `projects/{project}/locations/{location}/fleets/{fleet}`. Each GCP project can have at most one
/// fleet resource, named "default".
/// </param>
public virtual PatchRequest Patch(Google.Apis.GKEHub.v1alpha.Data.Fleet body, string name)
{
return new PatchRequest(service, body, name);
}
/// <summary>Updates a fleet.</summary>
public class PatchRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.Fleet>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.GKEHub.v1alpha.Data.Fleet body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// Output only. The full, unique resource name of this fleet in the format of
/// `projects/{project}/locations/{location}/fleets/{fleet}`. Each GCP project can have at most one
/// fleet resource, named "default".
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Required. The fields to be updated;</summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.GKEHub.v1alpha.Data.Fleet Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "patch";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "PATCH";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+name}";
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/fleets/[^/]+$",
});
RequestParameters.Add("updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>Gets the Memberships resource.</summary>
public virtual MembershipsResource Memberships { get; }
/// <summary>The "memberships" collection of methods.</summary>
public class MembershipsResource
{
private const string Resource = "memberships";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public MembershipsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>
/// Creates a new Membership. **This is currently only supported for GKE clusters on Google Cloud**. To
/// register other clusters, follow the instructions at
/// https://cloud.google.com/anthos/multicluster-management/connect/registering-a-cluster.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">
/// Required. The parent (project and location) where the Memberships will be created. Specified in the
/// format `projects/*/locations/*`.
/// </param>
public virtual CreateRequest Create(Google.Apis.GKEHub.v1alpha.Data.Membership body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>
/// Creates a new Membership. **This is currently only supported for GKE clusters on Google Cloud**. To
/// register other clusters, follow the instructions at
/// https://cloud.google.com/anthos/multicluster-management/connect/registering-a-cluster.
/// </summary>
public class CreateRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.Operation>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.GKEHub.v1alpha.Data.Membership body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The parent (project and location) where the Memberships will be created. Specified in
/// the format `projects/*/locations/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>
/// Required. Client chosen ID for the membership. `membership_id` must be a valid RFC 1123
/// compliant DNS label: 1. At most 63 characters in length 2. It must consist of lower case
/// alphanumeric characters or `-` 3. It must start and end with an alphanumeric character Which can
/// be expressed as the regex: `[a-z0-9]([-a-z0-9]*[a-z0-9])?`, with a maximum length of 63
/// characters.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("membershipId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string MembershipId { get; set; }
/// <summary>
/// Optional. A request ID to identify requests. Specify a unique request ID so that if you must
/// retry your request, the server will know to ignore the request if it has already been completed.
/// The server will guarantee that for at least 60 minutes after the first request. For example,
/// consider a situation where you make an initial request and the request times out. If you make
/// the request again with the same request ID, the server can check if original operation with the
/// same request ID was received, and if so, will ignore the second request. This prevents clients
/// from accidentally creating duplicate commitments. The request ID must be a valid UUID with the
/// exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("requestId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string RequestId { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.GKEHub.v1alpha.Data.Membership Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "create";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+parent}/memberships";
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+$",
});
RequestParameters.Add("membershipId", new Google.Apis.Discovery.Parameter
{
Name = "membershipId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("requestId", new Google.Apis.Discovery.Parameter
{
Name = "requestId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>
/// Removes a Membership. **This is currently only supported for GKE clusters on Google Cloud**. To
/// unregister other clusters, follow the instructions at
/// https://cloud.google.com/anthos/multicluster-management/connect/unregistering-a-cluster.
/// </summary>
/// <param name="name">
/// Required. The Membership resource name in the format `projects/*/locations/*/memberships/*`.
/// </param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>
/// Removes a Membership. **This is currently only supported for GKE clusters on Google Cloud**. To
/// unregister other clusters, follow the instructions at
/// https://cloud.google.com/anthos/multicluster-management/connect/unregistering-a-cluster.
/// </summary>
public class DeleteRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.Operation>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The Membership resource name in the format `projects/*/locations/*/memberships/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// Optional. A request ID to identify requests. Specify a unique request ID so that if you must
/// retry your request, the server will know to ignore the request if it has already been completed.
/// The server will guarantee that for at least 60 minutes after the first request. For example,
/// consider a situation where you make an initial request and the request times out. If you make
/// the request again with the same request ID, the server can check if original operation with the
/// same request ID was received, and if so, will ignore the second request. This prevents clients
/// from accidentally creating duplicate commitments. The request ID must be a valid UUID with the
/// exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("requestId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string RequestId { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "delete";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "DELETE";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+name}";
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/memberships/[^/]+$",
});
RequestParameters.Add("requestId", new Google.Apis.Discovery.Parameter
{
Name = "requestId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>
/// Generates the manifest for deployment of the GKE connect agent. **This method is used internally by
/// Google-provided libraries.** Most clients should not need to call this method directly.
/// </summary>
/// <param name="name">
/// Required. The Membership resource name the Agent will associate with, in the format
/// `projects/*/locations/*/memberships/*`.
/// </param>
public virtual GenerateConnectManifestRequest GenerateConnectManifest(string name)
{
return new GenerateConnectManifestRequest(service, name);
}
/// <summary>
/// Generates the manifest for deployment of the GKE connect agent. **This method is used internally by
/// Google-provided libraries.** Most clients should not need to call this method directly.
/// </summary>
public class GenerateConnectManifestRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.GenerateConnectManifestResponse>
{
/// <summary>Constructs a new GenerateConnectManifest request.</summary>
public GenerateConnectManifestRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The Membership resource name the Agent will associate with, in the format
/// `projects/*/locations/*/memberships/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Optional. The image pull secret content for the registry, if not public.</summary>
[Google.Apis.Util.RequestParameterAttribute("imagePullSecretContent", Google.Apis.Util.RequestParameterType.Query)]
public virtual string ImagePullSecretContent { get; set; }
/// <summary>
/// Optional. If true, generate the resources for upgrade only. Some resources generated only for
/// installation (e.g. secrets) will be excluded.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("isUpgrade", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> IsUpgrade { get; set; }
/// <summary>
/// Optional. Namespace for GKE Connect agent resources. Defaults to `gke-connect`. The Connect
/// Agent is authorized automatically when run in the default namespace. Otherwise, explicit
/// authorization must be granted with an additional IAM binding.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("namespace", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Namespace { get; set; }
/// <summary>
/// Optional. URI of a proxy if connectivity from the agent to gkeconnect.googleapis.com requires
/// the use of a proxy. Format must be in the form `http(s)://{proxy_address}`, depending on the
/// HTTP/HTTPS protocol supported by the proxy. This will direct the connect agent's outbound
/// traffic through a HTTP(S) proxy.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("proxy", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Proxy { get; set; }
/// <summary>
/// Optional. The registry to fetch the connect agent image from. Defaults to gcr.io/gkeconnect.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("registry", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Registry { get; set; }
/// <summary>
/// Optional. The Connect agent version to use. Defaults to the most current version.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("version", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Version { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "generateConnectManifest";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+name}:generateConnectManifest";
/// <summary>Initializes GenerateConnectManifest parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/memberships/[^/]+$",
});
RequestParameters.Add("imagePullSecretContent", new Google.Apis.Discovery.Parameter
{
Name = "imagePullSecretContent",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("isUpgrade", new Google.Apis.Discovery.Parameter
{
Name = "isUpgrade",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("namespace", new Google.Apis.Discovery.Parameter
{
Name = "namespace",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("proxy", new Google.Apis.Discovery.Parameter
{
Name = "proxy",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("registry", new Google.Apis.Discovery.Parameter
{
Name = "registry",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("version", new Google.Apis.Discovery.Parameter
{
Name = "version",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Gets the details of a Membership.</summary>
/// <param name="name">
/// Required. The Membership resource name in the format `projects/*/locations/*/memberships/*`.
/// </param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets the details of a Membership.</summary>
public class GetRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.Membership>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The Membership resource name in the format `projects/*/locations/*/memberships/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/memberships/[^/]+$",
});
}
}
/// <summary>
/// Gets the access control policy for a resource. Returns an empty policy if the resource exists and
/// does not have a policy set.
/// </summary>
/// <param name="resource">
/// REQUIRED: The resource for which the policy is being requested. See the operation documentation for
/// the appropriate value for this field.
/// </param>
public virtual GetIamPolicyRequest GetIamPolicy(string resource)
{
return new GetIamPolicyRequest(service, resource);
}
/// <summary>
/// Gets the access control policy for a resource. Returns an empty policy if the resource exists and
/// does not have a policy set.
/// </summary>
public class GetIamPolicyRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.Policy>
{
/// <summary>Constructs a new GetIamPolicy request.</summary>
public GetIamPolicyRequest(Google.Apis.Services.IClientService service, string resource) : base(service)
{
Resource = resource;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy is being requested. See the operation documentation
/// for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>
/// Optional. The maximum policy version that will be used to format the policy. Valid values are 0,
/// 1, and 3. Requests specifying an invalid value will be rejected. Requests for policies with any
/// conditional role bindings must specify version 3. Policies with no conditional role bindings may
/// specify any valid value or leave the field unset. The policy in the response might use the
/// policy version that you specified, or it might use a lower policy version. For example, if you
/// specify version 3, but the policy has no conditional role bindings, the response uses version 1.
/// To learn which resources support conditions in their IAM policies, see the [IAM
/// documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("options.requestedPolicyVersion", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> OptionsRequestedPolicyVersion { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "getIamPolicy";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+resource}:getIamPolicy";
/// <summary>Initializes GetIamPolicy parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/memberships/[^/]+$",
});
RequestParameters.Add("options.requestedPolicyVersion", new Google.Apis.Discovery.Parameter
{
Name = "options.requestedPolicyVersion",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Lists Memberships in a given project and location.</summary>
/// <param name="parent">
/// Required. The parent (project and location) where the Memberships will be listed. Specified in the
/// format `projects/*/locations/*`.
/// </param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Lists Memberships in a given project and location.</summary>
public class ListRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.ListMembershipsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>
/// Required. The parent (project and location) where the Memberships will be listed. Specified in
/// the format `projects/*/locations/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>
/// Optional. Lists Memberships that match the filter expression, following the syntax outlined in
/// https://google.aip.dev/160. Examples: - Name is `bar` in project `foo-proj` and location
/// `global`: name = "projects/foo-proj/locations/global/membership/bar" - Memberships that have a
/// label called `foo`: labels.foo:* - Memberships that have a label called `foo` whose value is
/// `bar`: labels.foo = bar - Memberships in the CREATING state: state = CREATING
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>
/// Optional. One or more fields to compare and use to sort the output. See
/// https://google.aip.dev/132#ordering.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("orderBy", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OrderBy { get; set; }
/// <summary>
/// Optional. When requesting a 'page' of resources, `page_size` specifies number of resources to
/// return. If unspecified or set to 0, all resources will be returned.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// Optional. Token returned by previous call to `ListMemberships` which specifies the position in
/// the list from where to continue listing the resources.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+parent}/memberships";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("orderBy", new Google.Apis.Discovery.Parameter
{
Name = "orderBy",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>
/// Lists Memberships of admin clusters in a given project and location. **This method is only used
/// internally**.
/// </summary>
/// <param name="parent">
/// Required. The parent (project and location) where the Memberships of admin cluster will be listed.
/// Specified in the format `projects/*/locations/*`.
/// </param>
public virtual ListAdminRequest ListAdmin(string parent)
{
return new ListAdminRequest(service, parent);
}
/// <summary>
/// Lists Memberships of admin clusters in a given project and location. **This method is only used
/// internally**.
/// </summary>
public class ListAdminRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.ListAdminClusterMembershipsResponse>
{
/// <summary>Constructs a new ListAdmin request.</summary>
public ListAdminRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>
/// Required. The parent (project and location) where the Memberships of admin cluster will be
/// listed. Specified in the format `projects/*/locations/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>
/// Optional. Lists Memberships of admin clusters that match the filter expression.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>
/// Optional. One or more fields to compare and use to sort the output. See
/// https://google.aip.dev/132#ordering.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("orderBy", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OrderBy { get; set; }
/// <summary>
/// Optional. When requesting a 'page' of resources, `page_size` specifies number of resources to
/// return. If unspecified or set to 0, all resources will be returned.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// Optional. Token returned by previous call to `ListAdminClusterMemberships` which specifies the
/// position in the list from where to continue listing the resources.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "listAdmin";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+parent}/memberships:listAdmin";
/// <summary>Initializes ListAdmin parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("orderBy", new Google.Apis.Discovery.Parameter
{
Name = "orderBy",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Updates an existing Membership.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// Required. The Membership resource name in the format `projects/*/locations/*/memberships/*`.
/// </param>
public virtual PatchRequest Patch(Google.Apis.GKEHub.v1alpha.Data.Membership body, string name)
{
return new PatchRequest(service, body, name);
}
/// <summary>Updates an existing Membership.</summary>
public class PatchRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.Operation>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.GKEHub.v1alpha.Data.Membership body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The Membership resource name in the format `projects/*/locations/*/memberships/*`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// Optional. A request ID to identify requests. Specify a unique request ID so that if you must
/// retry your request, the server will know to ignore the request if it has already been completed.
/// The server will guarantee that for at least 60 minutes after the first request. For example,
/// consider a situation where you make an initial request and the request times out. If you make
/// the request again with the same request ID, the server can check if original operation with the
/// same request ID was received, and if so, will ignore the second request. This prevents clients
/// from accidentally creating duplicate commitments. The request ID must be a valid UUID with the
/// exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("requestId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string RequestId { get; set; }
/// <summary>Required. Mask of fields to update.</summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.GKEHub.v1alpha.Data.Membership Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "patch";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "PATCH";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+name}";
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/memberships/[^/]+$",
});
RequestParameters.Add("requestId", new Google.Apis.Discovery.Parameter
{
Name = "requestId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any existing policy. Can return
/// `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="resource">
/// REQUIRED: The resource for which the policy is being specified. See the operation documentation for
/// the appropriate value for this field.
/// </param>
public virtual SetIamPolicyRequest SetIamPolicy(Google.Apis.GKEHub.v1alpha.Data.SetIamPolicyRequest body, string resource)
{
return new SetIamPolicyRequest(service, body, resource);
}
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any existing policy. Can return
/// `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors.
/// </summary>
public class SetIamPolicyRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.Policy>
{
/// <summary>Constructs a new SetIamPolicy request.</summary>
public SetIamPolicyRequest(Google.Apis.Services.IClientService service, Google.Apis.GKEHub.v1alpha.Data.SetIamPolicyRequest body, string resource) : base(service)
{
Resource = resource;
Body = body;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy is being specified. See the operation documentation
/// for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.GKEHub.v1alpha.Data.SetIamPolicyRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "setIamPolicy";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+resource}:setIamPolicy";
/// <summary>Initializes SetIamPolicy parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/memberships/[^/]+$",
});
}
}
/// <summary>
/// Returns permissions that a caller has on the specified resource. If the resource does not exist,
/// this will return an empty set of permissions, not a `NOT_FOUND` error. Note: This operation is
/// designed to be used for building permission-aware UIs and command-line tools, not for authorization
/// checking. This operation may "fail open" without warning.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="resource">
/// REQUIRED: The resource for which the policy detail is being requested. See the operation
/// documentation for the appropriate value for this field.
/// </param>
public virtual TestIamPermissionsRequest TestIamPermissions(Google.Apis.GKEHub.v1alpha.Data.TestIamPermissionsRequest body, string resource)
{
return new TestIamPermissionsRequest(service, body, resource);
}
/// <summary>
/// Returns permissions that a caller has on the specified resource. If the resource does not exist,
/// this will return an empty set of permissions, not a `NOT_FOUND` error. Note: This operation is
/// designed to be used for building permission-aware UIs and command-line tools, not for authorization
/// checking. This operation may "fail open" without warning.
/// </summary>
public class TestIamPermissionsRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.TestIamPermissionsResponse>
{
/// <summary>Constructs a new TestIamPermissions request.</summary>
public TestIamPermissionsRequest(Google.Apis.Services.IClientService service, Google.Apis.GKEHub.v1alpha.Data.TestIamPermissionsRequest body, string resource) : base(service)
{
Resource = resource;
Body = body;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy detail is being requested. See the operation
/// documentation for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.GKEHub.v1alpha.Data.TestIamPermissionsRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "testIamPermissions";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+resource}:testIamPermissions";
/// <summary>Initializes TestIamPermissions parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/memberships/[^/]+$",
});
}
}
}
/// <summary>Gets the Operations resource.</summary>
public virtual OperationsResource Operations { get; }
/// <summary>The "operations" collection of methods.</summary>
public class OperationsResource
{
private const string Resource = "operations";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public OperationsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>
/// Starts asynchronous cancellation on a long-running operation. The server makes a best effort to
/// cancel the operation, but success is not guaranteed. If the server doesn't support this method, it
/// returns `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to
/// check whether the cancellation succeeded or whether the operation completed despite cancellation. On
/// successful cancellation, the operation is not deleted; instead, it becomes an operation with an
/// Operation.error value with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">The name of the operation resource to be cancelled.</param>
public virtual CancelRequest Cancel(Google.Apis.GKEHub.v1alpha.Data.CancelOperationRequest body, string name)
{
return new CancelRequest(service, body, name);
}
/// <summary>
/// Starts asynchronous cancellation on a long-running operation. The server makes a best effort to
/// cancel the operation, but success is not guaranteed. If the server doesn't support this method, it
/// returns `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to
/// check whether the cancellation succeeded or whether the operation completed despite cancellation. On
/// successful cancellation, the operation is not deleted; instead, it becomes an operation with an
/// Operation.error value with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.
/// </summary>
public class CancelRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.Empty>
{
/// <summary>Constructs a new Cancel request.</summary>
public CancelRequest(Google.Apis.Services.IClientService service, Google.Apis.GKEHub.v1alpha.Data.CancelOperationRequest body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>The name of the operation resource to be cancelled.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.GKEHub.v1alpha.Data.CancelOperationRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "cancel";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+name}:cancel";
/// <summary>Initializes Cancel parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/operations/[^/]+$",
});
}
}
/// <summary>
/// Deletes a long-running operation. This method indicates that the client is no longer interested in
/// the operation result. It does not cancel the operation. If the server doesn't support this method,
/// it returns `google.rpc.Code.UNIMPLEMENTED`.
/// </summary>
/// <param name="name">The name of the operation resource to be deleted.</param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>
/// Deletes a long-running operation. This method indicates that the client is no longer interested in
/// the operation result. It does not cancel the operation. If the server doesn't support this method,
/// it returns `google.rpc.Code.UNIMPLEMENTED`.
/// </summary>
public class DeleteRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.Empty>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the operation resource to be deleted.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "delete";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "DELETE";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+name}";
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/operations/[^/]+$",
});
}
}
/// <summary>
/// Gets the latest state of a long-running operation. Clients can use this method to poll the operation
/// result at intervals as recommended by the API service.
/// </summary>
/// <param name="name">The name of the operation resource.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>
/// Gets the latest state of a long-running operation. Clients can use this method to poll the operation
/// result at intervals as recommended by the API service.
/// </summary>
public class GetRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.Operation>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the operation resource.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/operations/[^/]+$",
});
}
}
/// <summary>
/// Lists operations that match the specified filter in the request. If the server doesn't support this
/// method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to override the
/// binding to use different resource name schemes, such as `users/*/operations`. To override the
/// binding, API services can add a binding such as `"/v1/{name=users/*}/operations"` to their service
/// configuration. For backwards compatibility, the default name includes the operations collection id,
/// however overriding users must ensure the name binding is the parent resource, without the operations
/// collection id.
/// </summary>
/// <param name="name">The name of the operation's parent resource.</param>
public virtual ListRequest List(string name)
{
return new ListRequest(service, name);
}
/// <summary>
/// Lists operations that match the specified filter in the request. If the server doesn't support this
/// method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to override the
/// binding to use different resource name schemes, such as `users/*/operations`. To override the
/// binding, API services can add a binding such as `"/v1/{name=users/*}/operations"` to their service
/// configuration. For backwards compatibility, the default name includes the operations collection id,
/// however overriding users must ensure the name binding is the parent resource, without the operations
/// collection id.
/// </summary>
public class ListRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.ListOperationsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the operation's parent resource.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>The standard list filter.</summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>The standard list page size.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>The standard list page token.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+name}/operations";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>Gets information about a location.</summary>
/// <param name="name">Resource name for the location.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets information about a location.</summary>
public class GetRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.Location>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>Resource name for the location.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+$",
});
}
}
/// <summary>Lists information about the supported locations for this service.</summary>
/// <param name="name">The resource that owns the locations collection, if applicable.</param>
public virtual ListRequest List(string name)
{
return new ListRequest(service, name);
}
/// <summary>Lists information about the supported locations for this service.</summary>
public class ListRequest : GKEHubBaseServiceRequest<Google.Apis.GKEHub.v1alpha.Data.ListLocationsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>The resource that owns the locations collection, if applicable.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// A filter to narrow down results to a preferred subset. The filtering language accepts strings like
/// `"displayName=tokyo"`, and is documented in more detail in [AIP-160](https://google.aip.dev/160).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>
/// The maximum number of results to return. If not set, the service selects a default.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// A page token received from the `next_page_token` field in the response. Send that page token to
/// receive the subsequent page.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1alpha/{+name}/locations";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
}
namespace Google.Apis.GKEHub.v1alpha.Data
{
/// <summary>**Anthos Observability**: Spec</summary>
public class AnthosObservabilityFeatureSpec : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>default membership spec for unconfigured memberships</summary>
[Newtonsoft.Json.JsonPropertyAttribute("defaultMembershipSpec")]
public virtual AnthosObservabilityMembershipSpec DefaultMembershipSpec { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>**Anthosobservability**: Per-Membership Feature spec.</summary>
public class AnthosObservabilityMembershipSpec : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// use full of metrics rather than optimized metrics. See
/// https://cloud.google.com/anthos/clusters/docs/on-prem/1.8/concepts/logging-and-monitoring#optimized_metrics_default_metrics
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("doNotOptimizeMetrics")]
public virtual System.Nullable<bool> DoNotOptimizeMetrics { get; set; }
/// <summary>
/// enable collecting and reporting metrics and logs from user apps See
/// go/onyx-application-metrics-logs-user-guide
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("enableStackdriverOnApplications")]
public virtual System.Nullable<bool> EnableStackdriverOnApplications { get; set; }
/// <summary>the version of stackdriver operator used by this feature</summary>
[Newtonsoft.Json.JsonPropertyAttribute("version")]
public virtual string Version { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Spec for App Dev Experience Feature.</summary>
public class AppDevExperienceFeatureSpec : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>State for App Dev Exp Feature.</summary>
public class AppDevExperienceFeatureState : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Status of subcomponent that detects configured Service Mesh resources.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("networkingInstallSucceeded")]
public virtual Status NetworkingInstallSucceeded { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Specifies the audit configuration for a service. The configuration determines which permission types are logged,
/// and what identities, if any, are exempted from logging. An AuditConfig must have one or more AuditLogConfigs. If
/// there are AuditConfigs for both `allServices` and a specific service, the union of the two AuditConfigs is used
/// for that service: the log_types specified in each AuditConfig are enabled, and the exempted_members in each
/// AuditLogConfig are exempted. Example Policy with multiple AuditConfigs: { "audit_configs": [ { "service":
/// "allServices", "audit_log_configs": [ { "log_type": "DATA_READ", "exempted_members": [ "user:jose@example.com" ]
/// }, { "log_type": "DATA_WRITE" }, { "log_type": "ADMIN_READ" } ] }, { "service": "sampleservice.googleapis.com",
/// "audit_log_configs": [ { "log_type": "DATA_READ" }, { "log_type": "DATA_WRITE", "exempted_members": [
/// "user:aliya@example.com" ] } ] } ] } For sampleservice, this policy enables DATA_READ, DATA_WRITE and ADMIN_READ
/// logging. It also exempts `jose@example.com` from DATA_READ logging, and `aliya@example.com` from DATA_WRITE
/// logging.
/// </summary>
public class AuditConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The configuration for logging of each type of permission.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("auditLogConfigs")]
public virtual System.Collections.Generic.IList<AuditLogConfig> AuditLogConfigs { get; set; }
/// <summary>
/// Specifies a service that will be enabled for audit logging. For example, `storage.googleapis.com`,
/// `cloudsql.googleapis.com`. `allServices` is a special value that covers all services.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("service")]
public virtual string Service { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Provides the configuration for logging a type of permissions. Example: { "audit_log_configs": [ { "log_type":
/// "DATA_READ", "exempted_members": [ "user:jose@example.com" ] }, { "log_type": "DATA_WRITE" } ] } This enables
/// 'DATA_READ' and 'DATA_WRITE' logging, while exempting jose@example.com from DATA_READ logging.
/// </summary>
public class AuditLogConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Specifies the identities that do not cause logging for this type of permission. Follows the same format of
/// Binding.members.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("exemptedMembers")]
public virtual System.Collections.Generic.IList<string> ExemptedMembers { get; set; }
/// <summary>The log type that this config enables.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("logType")]
public virtual string LogType { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Authority encodes how Google will recognize identities from this Membership. See the workload identity
/// documentation for more details: https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity
/// </summary>
public class Authority : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Output only. An identity provider that reflects the `issuer` in the workload identity pool.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("identityProvider")]
public virtual string IdentityProvider { get; set; }
/// <summary>
/// Optional. A JSON Web Token (JWT) issuer URI. `issuer` must start with `https://` and be a valid URL with
/// length &lt;2000 characters. If set, then Google will allow valid OIDC tokens from this issuer to
/// authenticate within the workload_identity_pool. OIDC discovery will be performed on this URI to validate
/// tokens from the issuer. Clearing `issuer` disables Workload Identity. `issuer` cannot be directly modified;
/// it must be cleared (and Workload Identity disabled) before using a new issuer (and re-enabling Workload
/// Identity).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("issuer")]
public virtual string Issuer { get; set; }
/// <summary>
/// Optional. OIDC verification keys for this Membership in JWKS format (RFC 7517). When this field is set, OIDC
/// discovery will NOT be performed on `issuer`, and instead OIDC tokens will be validated using this field.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("oidcJwks")]
public virtual string OidcJwks { get; set; }
/// <summary>
/// Output only. The name of the workload identity pool in which `issuer` will be recognized. There is a single
/// Workload Identity Pool per Hub that is shared between all Memberships that belong to that Hub. For a Hub
/// hosted in {PROJECT_ID}, the workload pool format is `{PROJECT_ID}.hub.id.goog`, although this is subject to
/// change in newer versions of this API.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("workloadIdentityPool")]
public virtual string WorkloadIdentityPool { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Associates `members`, or principals, with a `role`.</summary>
public class Binding : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The condition that is associated with this binding. If the condition evaluates to `true`, then this binding
/// applies to the current request. If the condition evaluates to `false`, then this binding does not apply to
/// the current request. However, a different role binding might grant the same role to one or more of the
/// principals in this binding. To learn which resources support conditions in their IAM policies, see the [IAM
/// documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("condition")]
public virtual Expr Condition { get; set; }
/// <summary>
/// Specifies the principals requesting access for a Google Cloud resource. `members` can have the following
/// values: * `allUsers`: A special identifier that represents anyone who is on the internet; with or without a
/// Google account. * `allAuthenticatedUsers`: A special identifier that represents anyone who is authenticated
/// with a Google account or a service account. * `user:{emailid}`: An email address that represents a specific
/// Google account. For example, `alice@example.com` . * `serviceAccount:{emailid}`: An email address that
/// represents a service account. For example, `my-other-app@appspot.gserviceaccount.com`. * `group:{emailid}`:
/// An email address that represents a Google group. For example, `admins@example.com`. *
/// `deleted:user:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a user that
/// has been recently deleted. For example, `alice@example.com?uid=123456789012345678901`. If the user is
/// recovered, this value reverts to `user:{emailid}` and the recovered user retains the role in the binding. *
/// `deleted:serviceAccount:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a
/// service account that has been recently deleted. For example,
/// `my-other-app@appspot.gserviceaccount.com?uid=123456789012345678901`. If the service account is undeleted,
/// this value reverts to `serviceAccount:{emailid}` and the undeleted service account retains the role in the
/// binding. * `deleted:group:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing
/// a Google group that has been recently deleted. For example, `admins@example.com?uid=123456789012345678901`.
/// If the group is recovered, this value reverts to `group:{emailid}` and the recovered group retains the role
/// in the binding. * `domain:{domain}`: The G Suite domain (primary) that represents all the users of that
/// domain. For example, `google.com` or `example.com`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("members")]
public virtual System.Collections.Generic.IList<string> Members { get; set; }
/// <summary>
/// Role that is assigned to the list of `members`, or principals. For example, `roles/viewer`, `roles/editor`,
/// or `roles/owner`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("role")]
public virtual string Role { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The request message for Operations.CancelOperation.</summary>
public class CancelOperationRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>**Cloud Audit Logging**: Spec for Audit Logging Allowlisting.</summary>
public class CloudAuditLoggingFeatureSpec : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Service account that should be allowlisted to send the audit logs; eg
/// cloudauditlogging@gcp-project.iam.gserviceaccount.com. These accounts must already exist, but do not need to
/// have any permissions granted to them. The customer's entitlements will be checked prior to allowlisting
/// (i.e. the customer must be an Anthos customer.)
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("allowlistedServiceAccounts")]
public virtual System.Collections.Generic.IList<string> AllowlistedServiceAccounts { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>**Cloud Build**: Configurations for each Cloud Build enabled cluster.</summary>
public class CloudBuildMembershipSpec : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Whether it is allowed to run the privileged builds on the cluster or not.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("securityPolicy")]
public virtual string SecurityPolicy { get; set; }
/// <summary>Version of the cloud build software on the cluster.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("version")]
public virtual string Version { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>CommonFeatureSpec contains Hub-wide configuration information</summary>
public class CommonFeatureSpec : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Anthos Observability spec</summary>
[Newtonsoft.Json.JsonPropertyAttribute("anthosobservability")]
public virtual AnthosObservabilityFeatureSpec Anthosobservability { get; set; }
/// <summary>Appdevexperience specific spec.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("appdevexperience")]
public virtual AppDevExperienceFeatureSpec Appdevexperience { get; set; }
/// <summary>Cloud Audit Logging-specific spec.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("cloudauditlogging")]
public virtual CloudAuditLoggingFeatureSpec Cloudauditlogging { get; set; }
/// <summary>Multicluster Ingress-specific spec.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("multiclusteringress")]
public virtual MultiClusterIngressFeatureSpec Multiclusteringress { get; set; }
/// <summary>Workload Certificate spec.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("workloadcertificate")]
public virtual FeatureSpec Workloadcertificate { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>CommonFeatureState contains Hub-wide Feature status information.</summary>
public class CommonFeatureState : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Appdevexperience specific state.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("appdevexperience")]
public virtual AppDevExperienceFeatureState Appdevexperience { get; set; }
/// <summary>Service Mesh-specific state.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("servicemesh")]
public virtual ServiceMeshFeatureState Servicemesh { get; set; }
/// <summary>Output only. The "running state" of the Feature in this Hub.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("state")]
public virtual FeatureState State { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Configuration for Binauthz</summary>
public class ConfigManagementBinauthzConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Whether binauthz is enabled in this cluster.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("enabled")]
public virtual System.Nullable<bool> Enabled { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>State for Binauthz</summary>
public class ConfigManagementBinauthzState : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The version of binauthz that is installed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("version")]
public virtual ConfigManagementBinauthzVersion Version { get; set; }
/// <summary>The state of the binauthz webhook.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("webhook")]
public virtual string Webhook { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The version of binauthz.</summary>
public class ConfigManagementBinauthzVersion : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The version of the binauthz webhook.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("webhookVersion")]
public virtual string WebhookVersion { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Configuration for Config Sync</summary>
public class ConfigManagementConfigSync : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Enables the installation of ConfigSync. If set to true, ConfigSync resources will be created and the other
/// ConfigSync fields will be applied if exist. If set to false, all other ConfigSync fields will be ignored,
/// ConfigSync resources will be deleted. If omitted, ConfigSync resources will be managed depends on the
/// presence of git field.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("enabled")]
public virtual System.Nullable<bool> Enabled { get; set; }
/// <summary>Git repo configuration for the cluster.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("git")]
public virtual ConfigManagementGitConfig Git { get; set; }
/// <summary>
/// Set to true to enable the Config Sync admission webhook to prevent drifts. If set to `false`, disables the
/// Config Sync admission webhook and does not prevent drifts.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("preventDrift")]
public virtual System.Nullable<bool> PreventDrift { get; set; }
/// <summary>Specifies whether the Config Sync Repo is in “hierarchical” or “unstructured” mode.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sourceFormat")]
public virtual string SourceFormat { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The state of ConfigSync's deployment on a cluster</summary>
public class ConfigManagementConfigSyncDeploymentState : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Deployment state of admission-webhook</summary>
[Newtonsoft.Json.JsonPropertyAttribute("admissionWebhook")]
public virtual string AdmissionWebhook { get; set; }
/// <summary>Deployment state of the git-sync pod</summary>
[Newtonsoft.Json.JsonPropertyAttribute("gitSync")]
public virtual string GitSync { get; set; }
/// <summary>Deployment state of the importer pod</summary>
[Newtonsoft.Json.JsonPropertyAttribute("importer")]
public virtual string Importer { get; set; }
/// <summary>Deployment state of the monitor pod</summary>
[Newtonsoft.Json.JsonPropertyAttribute("monitor")]
public virtual string Monitor { get; set; }
/// <summary>Deployment state of reconciler-manager pod</summary>
[Newtonsoft.Json.JsonPropertyAttribute("reconcilerManager")]
public virtual string ReconcilerManager { get; set; }
/// <summary>Deployment state of root-reconciler</summary>
[Newtonsoft.Json.JsonPropertyAttribute("rootReconciler")]
public virtual string RootReconciler { get; set; }
/// <summary>Deployment state of the syncer pod</summary>
[Newtonsoft.Json.JsonPropertyAttribute("syncer")]
public virtual string Syncer { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>State information for ConfigSync</summary>
public class ConfigManagementConfigSyncState : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Information about the deployment of ConfigSync, including the version of the various Pods deployed
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("deploymentState")]
public virtual ConfigManagementConfigSyncDeploymentState DeploymentState { get; set; }
/// <summary>The state of ConfigSync's process to sync configs to a cluster</summary>
[Newtonsoft.Json.JsonPropertyAttribute("syncState")]
public virtual ConfigManagementSyncState SyncState { get; set; }
/// <summary>The version of ConfigSync deployed</summary>
[Newtonsoft.Json.JsonPropertyAttribute("version")]
public virtual ConfigManagementConfigSyncVersion Version { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Specific versioning information pertaining to ConfigSync's Pods</summary>
public class ConfigManagementConfigSyncVersion : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Version of the deployed admission_webhook pod</summary>
[Newtonsoft.Json.JsonPropertyAttribute("admissionWebhook")]
public virtual string AdmissionWebhook { get; set; }
/// <summary>Version of the deployed git-sync pod</summary>
[Newtonsoft.Json.JsonPropertyAttribute("gitSync")]
public virtual string GitSync { get; set; }
/// <summary>Version of the deployed importer pod</summary>
[Newtonsoft.Json.JsonPropertyAttribute("importer")]
public virtual string Importer { get; set; }
/// <summary>Version of the deployed monitor pod</summary>
[Newtonsoft.Json.JsonPropertyAttribute("monitor")]
public virtual string Monitor { get; set; }
/// <summary>Version of the deployed reconciler-manager pod</summary>
[Newtonsoft.Json.JsonPropertyAttribute("reconcilerManager")]
public virtual string ReconcilerManager { get; set; }
/// <summary>Version of the deployed reconciler container in root-reconciler pod</summary>
[Newtonsoft.Json.JsonPropertyAttribute("rootReconciler")]
public virtual string RootReconciler { get; set; }
/// <summary>Version of the deployed syncer pod</summary>
[Newtonsoft.Json.JsonPropertyAttribute("syncer")]
public virtual string Syncer { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Model for a config file in the git repo with an associated Sync error</summary>
public class ConfigManagementErrorResource : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Group/version/kind of the resource that is causing an error</summary>
[Newtonsoft.Json.JsonPropertyAttribute("resourceGvk")]
public virtual ConfigManagementGroupVersionKind ResourceGvk { get; set; }
/// <summary>Metadata name of the resource that is causing an error</summary>
[Newtonsoft.Json.JsonPropertyAttribute("resourceName")]
public virtual string ResourceName { get; set; }
/// <summary>Namespace of the resource that is causing an error</summary>
[Newtonsoft.Json.JsonPropertyAttribute("resourceNamespace")]
public virtual string ResourceNamespace { get; set; }
/// <summary>Path in the git repo of the erroneous config</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sourcePath")]
public virtual string SourcePath { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>State of Policy Controller installation.</summary>
public class ConfigManagementGatekeeperDeploymentState : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Status of gatekeeper-audit deployment.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("gatekeeperAudit")]
public virtual string GatekeeperAudit { get; set; }
/// <summary>Status of gatekeeper-controller-manager pod.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("gatekeeperControllerManagerState")]
public virtual string GatekeeperControllerManagerState { get; set; }
/// <summary>Status of the pod serving the mutation webhook.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("gatekeeperMutation")]
public virtual string GatekeeperMutation { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Git repo configuration for a single cluster.</summary>
public class ConfigManagementGitConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The GCP Service Account Email used for auth when secret_type is gcpServiceAccount.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("gcpServiceAccountEmail")]
public virtual string GcpServiceAccountEmail { get; set; }
/// <summary>URL for the HTTPS proxy to be used when communicating with the Git repo.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("httpsProxy")]
public virtual string HttpsProxy { get; set; }
/// <summary>
/// The path within the Git repository that represents the top level of the repo to sync. Default: the root
/// directory of the repository.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("policyDir")]
public virtual string PolicyDir { get; set; }
/// <summary>
/// Type of secret configured for access to the Git repo. Must be one of ssh, cookiefile, gcenode, token,
/// gcpserviceaccount or none. The validation of this is case-sensitive. Required.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("secretType")]
public virtual string SecretType { get; set; }
/// <summary>The branch of the repository to sync from. Default: master.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("syncBranch")]
public virtual string SyncBranch { get; set; }
/// <summary>The URL of the Git repository to use as the source of truth.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("syncRepo")]
public virtual string SyncRepo { get; set; }
/// <summary>Git revision (tag or hash) to check out. Default HEAD.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("syncRev")]
public virtual string SyncRev { get; set; }
/// <summary>Period in seconds between consecutive syncs. Default: 15.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("syncWaitSecs")]
public virtual System.Nullable<long> SyncWaitSecs { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A Kubernetes object's GVK</summary>
public class ConfigManagementGroupVersionKind : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Kubernetes Group</summary>
[Newtonsoft.Json.JsonPropertyAttribute("group")]
public virtual string Group { get; set; }
/// <summary>Kubernetes Kind</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>Kubernetes Version</summary>
[Newtonsoft.Json.JsonPropertyAttribute("version")]
public virtual string Version { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Configuration for Hierarchy Controller</summary>
public class ConfigManagementHierarchyControllerConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Whether hierarchical resource quota is enabled in this cluster.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("enableHierarchicalResourceQuota")]
public virtual System.Nullable<bool> EnableHierarchicalResourceQuota { get; set; }
/// <summary>Whether pod tree labels are enabled in this cluster.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("enablePodTreeLabels")]
public virtual System.Nullable<bool> EnablePodTreeLabels { get; set; }
/// <summary>Whether Hierarchy Controller is enabled in this cluster.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("enabled")]
public virtual System.Nullable<bool> Enabled { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Deployment state for Hierarchy Controller</summary>
public class ConfigManagementHierarchyControllerDeploymentState : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The deployment state for Hierarchy Controller extension (e.g. v0.7.0-hc.1)</summary>
[Newtonsoft.Json.JsonPropertyAttribute("extension")]
public virtual string Extension { get; set; }
/// <summary>The deployment state for open source HNC (e.g. v0.7.0-hc.0)</summary>
[Newtonsoft.Json.JsonPropertyAttribute("hnc")]
public virtual string Hnc { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>State for Hierarchy Controller</summary>
public class ConfigManagementHierarchyControllerState : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The deployment state for Hierarchy Controller</summary>
[Newtonsoft.Json.JsonPropertyAttribute("state")]
public virtual ConfigManagementHierarchyControllerDeploymentState State { get; set; }
/// <summary>The version for Hierarchy Controller</summary>
[Newtonsoft.Json.JsonPropertyAttribute("version")]
public virtual ConfigManagementHierarchyControllerVersion Version { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Version for Hierarchy Controller</summary>
public class ConfigManagementHierarchyControllerVersion : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Version for Hierarchy Controller extension</summary>
[Newtonsoft.Json.JsonPropertyAttribute("extension")]
public virtual string Extension { get; set; }
/// <summary>Version for open source HNC</summary>
[Newtonsoft.Json.JsonPropertyAttribute("hnc")]
public virtual string Hnc { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Errors pertaining to the installation of ACM</summary>
public class ConfigManagementInstallError : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A string representing the user facing error message</summary>
[Newtonsoft.Json.JsonPropertyAttribute("errorMessage")]
public virtual string ErrorMessage { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// **Anthos Config Management**: Configuration for a single cluster. Intended to parallel the ConfigManagement CR.
/// </summary>
public class ConfigManagementMembershipSpec : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Binauthz conifguration for the cluster.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("binauthz")]
public virtual ConfigManagementBinauthzConfig Binauthz { get; set; }
/// <summary>Config Sync configuration for the cluster.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("configSync")]
public virtual ConfigManagementConfigSync ConfigSync { get; set; }
/// <summary>Hierarchy Controller configuration for the cluster.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("hierarchyController")]
public virtual ConfigManagementHierarchyControllerConfig HierarchyController { get; set; }
/// <summary>Policy Controller configuration for the cluster.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("policyController")]
public virtual ConfigManagementPolicyController PolicyController { get; set; }
/// <summary>Version of ACM installed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("version")]
public virtual string Version { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>**Anthos Config Management**: State for a single cluster.</summary>
public class ConfigManagementMembershipState : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Binauthz status</summary>
[Newtonsoft.Json.JsonPropertyAttribute("binauthzState")]
public virtual ConfigManagementBinauthzState BinauthzState { get; set; }
/// <summary>
/// The user-defined name for the cluster used by ClusterSelectors to group clusters together. This should match
/// Membership's membership_name, unless the user installed ACM on the cluster manually prior to enabling the
/// ACM hub feature. Unique within a Anthos Config Management installation.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("clusterName")]
public virtual string ClusterName { get; set; }
/// <summary>Current sync status</summary>
[Newtonsoft.Json.JsonPropertyAttribute("configSyncState")]
public virtual ConfigManagementConfigSyncState ConfigSyncState { get; set; }
/// <summary>Hierarchy Controller status</summary>
[Newtonsoft.Json.JsonPropertyAttribute("hierarchyControllerState")]
public virtual ConfigManagementHierarchyControllerState HierarchyControllerState { get; set; }
/// <summary>
/// Membership configuration in the cluster. This represents the actual state in the cluster, while the
/// MembershipSpec in the FeatureSpec represents the intended state
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("membershipSpec")]
public virtual ConfigManagementMembershipSpec MembershipSpec { get; set; }
/// <summary>Current install status of ACM's Operator</summary>
[Newtonsoft.Json.JsonPropertyAttribute("operatorState")]
public virtual ConfigManagementOperatorState OperatorState { get; set; }
/// <summary>PolicyController status</summary>
[Newtonsoft.Json.JsonPropertyAttribute("policyControllerState")]
public virtual ConfigManagementPolicyControllerState PolicyControllerState { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>State information for an ACM's Operator</summary>
public class ConfigManagementOperatorState : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The state of the Operator's deployment</summary>
[Newtonsoft.Json.JsonPropertyAttribute("deploymentState")]
public virtual string DeploymentState { get; set; }
/// <summary>Install errors.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("errors")]
public virtual System.Collections.Generic.IList<ConfigManagementInstallError> Errors { get; set; }
/// <summary>The semenatic version number of the operator</summary>
[Newtonsoft.Json.JsonPropertyAttribute("version")]
public virtual string Version { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Configuration for Policy Controller</summary>
public class ConfigManagementPolicyController : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Sets the interval for Policy Controller Audit Scans (in seconds). When set to 0, this disables audit
/// functionality altogether.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("auditIntervalSeconds")]
public virtual System.Nullable<long> AuditIntervalSeconds { get; set; }
/// <summary>
/// Enables the installation of Policy Controller. If false, the rest of PolicyController fields take no effect.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("enabled")]
public virtual System.Nullable<bool> Enabled { get; set; }
/// <summary>
/// The set of namespaces that are excluded from Policy Controller checks. Namespaces do not need to currently
/// exist on the cluster.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("exemptableNamespaces")]
public virtual System.Collections.Generic.IList<string> ExemptableNamespaces { get; set; }
/// <summary>Logs all denies and dry run failures.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("logDeniesEnabled")]
public virtual System.Nullable<bool> LogDeniesEnabled { get; set; }
/// <summary>Enable users to try out mutation for PolicyController.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("mutationEnabled")]
public virtual System.Nullable<bool> MutationEnabled { get; set; }
/// <summary>
/// Enables the ability to use Constraint Templates that reference to objects other than the object currently
/// being evaluated.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("referentialRulesEnabled")]
public virtual System.Nullable<bool> ReferentialRulesEnabled { get; set; }
/// <summary>Installs the default template library along with Policy Controller.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("templateLibraryInstalled")]
public virtual System.Nullable<bool> TemplateLibraryInstalled { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>State for PolicyControllerState.</summary>
public class ConfigManagementPolicyControllerState : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The state about the policy controller installation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("deploymentState")]
public virtual ConfigManagementGatekeeperDeploymentState DeploymentState { get; set; }
/// <summary>The version of Gatekeeper Policy Controller deployed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("version")]
public virtual ConfigManagementPolicyControllerVersion Version { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The build version of Gatekeeper Policy Controller is using.</summary>
public class ConfigManagementPolicyControllerVersion : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The gatekeeper image tag that is composed of ACM version, git tag, build number.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("version")]
public virtual string Version { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>An ACM created error representing a problem syncing configurations</summary>
public class ConfigManagementSyncError : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>An ACM defined error code</summary>
[Newtonsoft.Json.JsonPropertyAttribute("code")]
public virtual string Code { get; set; }
/// <summary>A description of the error</summary>
[Newtonsoft.Json.JsonPropertyAttribute("errorMessage")]
public virtual string ErrorMessage { get; set; }
/// <summary>A list of config(s) associated with the error, if any</summary>
[Newtonsoft.Json.JsonPropertyAttribute("errorResources")]
public virtual System.Collections.Generic.IList<ConfigManagementErrorResource> ErrorResources { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>State indicating an ACM's progress syncing configurations to a cluster</summary>
public class ConfigManagementSyncState : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Sync status code</summary>
[Newtonsoft.Json.JsonPropertyAttribute("code")]
public virtual string Code { get; set; }
/// <summary>
/// A list of errors resulting from problematic configs. This list will be truncated after 100 errors, although
/// it is unlikely for that many errors to simultaneously exist.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("errors")]
public virtual System.Collections.Generic.IList<ConfigManagementSyncError> Errors { get; set; }
/// <summary>Token indicating the state of the importer.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("importToken")]
public virtual string ImportToken { get; set; }
/// <summary>
/// Deprecated: use last_sync_time instead. Timestamp of when ACM last successfully synced the repo The time
/// format is specified in https://golang.org/pkg/time/#Time.String
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("lastSync")]
public virtual string LastSync { get; set; }
/// <summary>Timestamp type of when ACM last successfully synced the repo</summary>
[Newtonsoft.Json.JsonPropertyAttribute("lastSyncTime")]
public virtual object LastSyncTime { get; set; }
/// <summary>Token indicating the state of the repo.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sourceToken")]
public virtual string SourceToken { get; set; }
/// <summary>Token indicating the state of the syncer.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("syncToken")]
public virtual string SyncToken { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>ConnectAgentResource represents a Kubernetes resource manifest for Connect Agent deployment.</summary>
public class ConnectAgentResource : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>YAML manifest of the resource.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("manifest")]
public virtual string Manifest { get; set; }
/// <summary>Kubernetes type of the resource.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("type")]
public virtual TypeMeta Type { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>EdgeCluster contains information specific to Google Edge Clusters.</summary>
public class EdgeCluster : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Immutable. Self-link of the GCP resource for the Edge Cluster. For example:
/// //edgecontainer.googleapis.com/projects/my-project/locations/us-west1-a/clusters/my-cluster
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("resourceLink")]
public virtual string ResourceLink { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical
/// example is to use it as the request or the response type of an API method. For instance: service Foo { rpc
/// Bar(google.protobuf.Empty) returns (google.protobuf.Empty); }
/// </summary>
public class Empty : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Represents a textual expression in the Common Expression Language (CEL) syntax. CEL is a C-like expression
/// language. The syntax and semantics of CEL are documented at https://github.com/google/cel-spec. Example
/// (Comparison): title: "Summary size limit" description: "Determines if a summary is less than 100 chars"
/// expression: "document.summary.size() &lt; 100" Example (Equality): title: "Requestor is owner" description:
/// "Determines if requestor is the document owner" expression: "document.owner == request.auth.claims.email"
/// Example (Logic): title: "Public documents" description: "Determine whether the document should be publicly
/// visible" expression: "document.type != 'private' &amp;&amp; document.type != 'internal'" Example (Data
/// Manipulation): title: "Notification string" description: "Create a notification string with a timestamp."
/// expression: "'New message received at ' + string(document.create_time)" The exact variables and functions that
/// may be referenced within an expression are determined by the service that evaluates it. See the service
/// documentation for additional information.
/// </summary>
public class Expr : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Optional. Description of the expression. This is a longer text which describes the expression, e.g. when
/// hovered over it in a UI.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("description")]
public virtual string Description { get; set; }
/// <summary>Textual representation of an expression in Common Expression Language syntax.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("expression")]
public virtual string Expression { get; set; }
/// <summary>
/// Optional. String indicating the location of the expression for error reporting, e.g. a file name and a
/// position in the file.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("location")]
public virtual string Location { get; set; }
/// <summary>
/// Optional. Title for the expression, i.e. a short string describing its purpose. This can be used e.g. in UIs
/// which allow to enter the expression.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("title")]
public virtual string Title { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Feature represents the settings and status of any Hub Feature.</summary>
public class Feature : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. When the Feature resource was created.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("createTime")]
public virtual object CreateTime { get; set; }
/// <summary>Output only. When the Feature resource was deleted.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("deleteTime")]
public virtual object DeleteTime { get; set; }
/// <summary>GCP labels for this Feature.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("labels")]
public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; }
/// <summary>
/// Optional. Membership-specific configuration for this Feature. If this Feature does not support any
/// per-Membership configuration, this field may be unused. The keys indicate which Membership the configuration
/// is for, in the form: `projects/{p}/locations/{l}/memberships/{m}` Where {p} is the project, {l} is a valid
/// location and {m} is a valid Membership in this project at that location. {p} WILL match the Feature's
/// project. {p} will always be returned as the project number, but the project ID is also accepted during
/// input. If the same Membership is specified in the map twice (using the project ID form, and the project
/// number form), exactly ONE of the entries will be saved, with no guarantees as to which. For this reason, it
/// is recommended the same format be used for all entries when mutating a Feature.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("membershipSpecs")]
public virtual System.Collections.Generic.IDictionary<string, MembershipFeatureSpec> MembershipSpecs { get; set; }
/// <summary>
/// Output only. Membership-specific Feature status. If this Feature does report any per-Membership status, this
/// field may be unused. The keys indicate which Membership the state is for, in the form:
/// `projects/{p}/locations/{l}/memberships/{m}` Where {p} is the project number, {l} is a valid location and
/// {m} is a valid Membership in this project at that location. {p} MUST match the Feature's project number.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("membershipStates")]
public virtual System.Collections.Generic.IDictionary<string, MembershipFeatureState> MembershipStates { get; set; }
/// <summary>
/// Output only. The full, unique name of this Feature resource in the format
/// `projects/*/locations/*/features/*`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Output only. State of the Feature resource itself.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("resourceState")]
public virtual FeatureResourceState ResourceState { get; set; }
/// <summary>
/// Optional. Hub-wide Feature configuration. If this Feature does not support any Hub-wide configuration, this
/// field may be unused.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("spec")]
public virtual CommonFeatureSpec Spec { get; set; }
/// <summary>Output only. The Hub-wide Feature state.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("state")]
public virtual CommonFeatureState State { get; set; }
/// <summary>Output only. When the Feature resource was last updated.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateTime")]
public virtual object UpdateTime { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// FeatureResourceState describes the state of a Feature *resource* in the GkeHub API. See `FeatureState` for the
/// "running state" of the Feature in the Hub and across Memberships.
/// </summary>
public class FeatureResourceState : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The current state of the Feature resource in the Hub API.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("state")]
public virtual string State { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>**Workload Certificate**: The Hub-wide input for the WorkloadCertificate feature.</summary>
public class FeatureSpec : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Specifies default membership spec. Users can override the default in the member_configs for each member.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("defaultConfig")]
public virtual MembershipSpec DefaultConfig { get; set; }
/// <summary>Immutable. Specifies CA configuration.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("provisionGoogleCa")]
public virtual string ProvisionGoogleCa { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// FeatureState describes the high-level state of a Feature. It may be used to describe a Feature's state at the
/// environ-level, or per-membershop, depending on the context.
/// </summary>
public class FeatureState : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The high-level, machine-readable status of this Feature.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("code")]
public virtual string Code { get; set; }
/// <summary>A human-readable description of the current status.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("description")]
public virtual string Description { get; set; }
/// <summary>The time this status and any related Feature-specific details were updated.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateTime")]
public virtual object UpdateTime { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Fleet contains the Fleet-wide metadata and configuration.</summary>
public class Fleet : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. When the Fleet was created.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("createTime")]
public virtual object CreateTime { get; set; }
/// <summary>Output only. When the Fleet was deleted.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("deleteTime")]
public virtual object DeleteTime { get; set; }
/// <summary>
/// Optional. A user-assigned display name of the Fleet. When present, it must be between 4 to 30 characters.
/// Allowed characters are: lowercase and uppercase letters, numbers, hyphen, single-quote, double-quote, space,
/// and exclamation point. Example: `Production Fleet`
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("displayName")]
public virtual string DisplayName { get; set; }
/// <summary>
/// The name for the fleet. The name must meet the following constraints: + The name of a fleet should be unique
/// within the organization; + It must consist of lower case alphanumeric characters or `-`; + The length of the
/// name must be less than or equal to 63; + Unicode names must be expressed in Punycode format (rfc3492).
/// Examples: + prod-fleet + xn--wlq33vhyw9jb (Punycode form for "生产环境")
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("fleetName")]
public virtual string FleetName { get; set; }
/// <summary>
/// Output only. The full, unique resource name of this fleet in the format of
/// `projects/{project}/locations/{location}/fleets/{fleet}`. Each GCP project can have at most one fleet
/// resource, named "default".
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>
/// Output only. Google-generated UUID for this resource. This is unique across all Fleet resources. If a Fleet
/// resource is deleted and another resource with the same name is created, it gets a different uid.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("uid")]
public virtual string Uid { get; set; }
/// <summary>Output only. When the Fleet was last updated.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateTime")]
public virtual object UpdateTime { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// GenerateConnectManifestResponse contains manifest information for installing/upgrading a Connect agent.
/// </summary>
public class GenerateConnectManifestResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The ordered list of Kubernetes resources that need to be applied to the cluster for GKE Connect agent
/// installation/upgrade.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("manifest")]
public virtual System.Collections.Generic.IList<ConnectAgentResource> Manifest { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>GkeCluster contains information specific to GKE clusters.</summary>
public class GkeCluster : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Output only. If cluster_missing is set then it denotes that the GKE cluster no longer exists in the GKE
/// Control Plane.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("clusterMissing")]
public virtual System.Nullable<bool> ClusterMissing { get; set; }
/// <summary>
/// Immutable. Self-link of the GCP resource for the GKE cluster. For example:
/// //container.googleapis.com/projects/my-project/locations/us-west1-a/clusters/my-cluster Zonal clusters are
/// also supported.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("resourceLink")]
public virtual string ResourceLink { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// The `Status` type defines a logical error model that is suitable for different programming environments,
/// including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains
/// three pieces of data: error code, error message, and error details. You can find out more about this error model
/// and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors).
/// </summary>
public class GoogleRpcStatus : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The status code, which should be an enum value of google.rpc.Code.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("code")]
public virtual System.Nullable<int> Code { get; set; }
/// <summary>
/// A list of messages that carry the error details. There is a common set of message types for APIs to use.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("details")]
public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string, object>> Details { get; set; }
/// <summary>
/// A developer-facing error message, which should be in English. Any user-facing error message should be
/// localized and sent in the google.rpc.Status.details field, or localized by the client.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("message")]
public virtual string Message { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Configuration of an auth method for a member/cluster. Only one authentication method (e.g., OIDC and LDAP) can
/// be set per AuthMethod.
/// </summary>
public class IdentityServiceAuthMethod : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Identifier for auth config.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>OIDC specific configuration.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("oidcConfig")]
public virtual IdentityServiceOidcConfig OidcConfig { get; set; }
/// <summary>Proxy server address to use for auth method.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("proxy")]
public virtual string Proxy { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>**Anthos Identity Service**: Configuration for a single Membership.</summary>
public class IdentityServiceMembershipSpec : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A member may support multiple auth methods.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("authMethods")]
public virtual System.Collections.Generic.IList<IdentityServiceAuthMethod> AuthMethods { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>**Anthos Identity Service**: State for a single Membership.</summary>
public class IdentityServiceMembershipState : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The reason of the failure.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("failureReason")]
public virtual string FailureReason { get; set; }
/// <summary>
/// Installed AIS version. This is the AIS version installed on this member. The values makes sense iff state is
/// OK.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("installedVersion")]
public virtual string InstalledVersion { get; set; }
/// <summary>Last reconciled membership configuration</summary>
[Newtonsoft.Json.JsonPropertyAttribute("memberConfig")]
public virtual IdentityServiceMembershipSpec MemberConfig { get; set; }
/// <summary>Deployment state on this member</summary>
[Newtonsoft.Json.JsonPropertyAttribute("state")]
public virtual string State { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Configuration for OIDC Auth flow.</summary>
public class IdentityServiceOidcConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>PEM-encoded CA for OIDC provider.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("certificateAuthorityData")]
public virtual string CertificateAuthorityData { get; set; }
/// <summary>ID for OIDC client application.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("clientId")]
public virtual string ClientId { get; set; }
/// <summary>Input only. Unencrypted OIDC client secret will be passed to the GKE Hub CLH.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("clientSecret")]
public virtual string ClientSecret { get; set; }
/// <summary>
/// Flag to denote if reverse proxy is used to connect to auth provider. This flag should be set to true when
/// provider is not reachable by Google Cloud Console.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("deployCloudConsoleProxy")]
public virtual System.Nullable<bool> DeployCloudConsoleProxy { get; set; }
/// <summary>Enable access token.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("enableAccessToken")]
public virtual System.Nullable<bool> EnableAccessToken { get; set; }
/// <summary>Output only. Encrypted OIDC Client secret</summary>
[Newtonsoft.Json.JsonPropertyAttribute("encryptedClientSecret")]
public virtual string EncryptedClientSecret { get; set; }
/// <summary>Comma-separated list of key-value pairs.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("extraParams")]
public virtual string ExtraParams { get; set; }
/// <summary>Prefix to prepend to group name.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("groupPrefix")]
public virtual string GroupPrefix { get; set; }
/// <summary>Claim in OIDC ID token that holds group information.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("groupsClaim")]
public virtual string GroupsClaim { get; set; }
/// <summary>
/// URI for the OIDC provider. This should point to the level below .well-known/openid-configuration.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("issuerUri")]
public virtual string IssuerUri { get; set; }
/// <summary>Registered redirect uri to redirect users going through OAuth flow using kubectl plugin.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kubectlRedirectUri")]
public virtual string KubectlRedirectUri { get; set; }
/// <summary>Comma-separated list of identifiers.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("scopes")]
public virtual string Scopes { get; set; }
/// <summary>Claim in OIDC ID token that holds username.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("userClaim")]
public virtual string UserClaim { get; set; }
/// <summary>Prefix to prepend to user name.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("userPrefix")]
public virtual string UserPrefix { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// KubernetesMetadata provides informational metadata for Memberships representing Kubernetes clusters.
/// </summary>
public class KubernetesMetadata : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. Kubernetes API server version string as reported by `/version`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kubernetesApiServerVersion")]
public virtual string KubernetesApiServerVersion { get; set; }
/// <summary>
/// Output only. The total memory capacity as reported by the sum of all Kubernetes nodes resources, defined in
/// MB.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("memoryMb")]
public virtual System.Nullable<int> MemoryMb { get; set; }
/// <summary>Output only. Node count as reported by Kubernetes nodes resources.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nodeCount")]
public virtual System.Nullable<int> NodeCount { get; set; }
/// <summary>
/// Output only. Node providerID as reported by the first node in the list of nodes on the Kubernetes endpoint.
/// On Kubernetes platforms that support zero-node clusters (like GKE-on-GCP), the node_count will be zero and
/// the node_provider_id will be empty.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("nodeProviderId")]
public virtual string NodeProviderId { get; set; }
/// <summary>
/// Output only. The time at which these details were last updated. This update_time is different from the
/// Membership-level update_time since EndpointDetails are updated internally for API consumers.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateTime")]
public virtual object UpdateTime { get; set; }
/// <summary>Output only. vCPU count as reported by Kubernetes nodes resources.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("vcpuCount")]
public virtual System.Nullable<int> VcpuCount { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// KubernetesResource contains the YAML manifests and configuration for Membership Kubernetes resources in the
/// cluster. After CreateMembership or UpdateMembership, these resources should be re-applied in the cluster.
/// </summary>
public class KubernetesResource : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Output only. The Kubernetes resources for installing the GKE Connect agent This field is only populated in
/// the Membership returned from a successful long-running operation from CreateMembership or UpdateMembership.
/// It is not populated during normal GetMembership or ListMemberships requests. To get the resource manifest
/// after the initial registration, the caller should make a UpdateMembership call with an empty field mask.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("connectResources")]
public virtual System.Collections.Generic.IList<ResourceManifest> ConnectResources { get; set; }
/// <summary>
/// Input only. The YAML representation of the Membership CR. This field is ignored for GKE clusters where Hub
/// can read the CR directly. Callers should provide the CR that is currently present in the cluster during
/// CreateMembership or UpdateMembership, or leave this field empty if none exists. The CR manifest is used to
/// validate the cluster has not been registered with another Membership.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("membershipCrManifest")]
public virtual string MembershipCrManifest { get; set; }
/// <summary>
/// Output only. Additional Kubernetes resources that need to be applied to the cluster after Membership
/// creation, and after every update. This field is only populated in the Membership returned from a successful
/// long-running operation from CreateMembership or UpdateMembership. It is not populated during normal
/// GetMembership or ListMemberships requests. To get the resource manifest after the initial registration, the
/// caller should make a UpdateMembership call with an empty field mask.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("membershipResources")]
public virtual System.Collections.Generic.IList<ResourceManifest> MembershipResources { get; set; }
/// <summary>Optional. Options for Kubernetes resource generation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("resourceOptions")]
public virtual ResourceOptions ResourceOptions { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for the `GkeHub.ListAdminClusterMemberships` method.</summary>
public class ListAdminClusterMembershipsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The list of matching Memberships of admin clusters.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("adminClusterMemberships")]
public virtual System.Collections.Generic.IList<Membership> AdminClusterMemberships { get; set; }
/// <summary>
/// A token to request the next page of resources from the `ListAdminClusterMemberships` method. The value of an
/// empty string means that there are no more resources to return.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>List of locations that could not be reached while fetching this list.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("unreachable")]
public virtual System.Collections.Generic.IList<string> Unreachable { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for the `GkeHub.ListFeatures` method.</summary>
public class ListFeaturesResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// A token to request the next page of resources from the `ListFeatures` method. The value of an empty string
/// means that there are no more resources to return.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The list of matching Features</summary>
[Newtonsoft.Json.JsonPropertyAttribute("resources")]
public virtual System.Collections.Generic.IList<Feature> Resources { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for the `GkeHub.ListFleetsResponse` method.</summary>
public class ListFleetsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The list of matching fleets.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("fleets")]
public virtual System.Collections.Generic.IList<Fleet> Fleets { get; set; }
/// <summary>
/// A token, which can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no
/// subsequent pages. The token is only valid for 1h.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response message for Locations.ListLocations.</summary>
public class ListLocationsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A list of locations that matches the specified filter in the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("locations")]
public virtual System.Collections.Generic.IList<Location> Locations { get; set; }
/// <summary>The standard List next-page token.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for the `GkeHub.ListMemberships` method.</summary>
public class ListMembershipsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// A token to request the next page of resources from the `ListMemberships` method. The value of an empty
/// string means that there are no more resources to return.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The list of matching Memberships.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("resources")]
public virtual System.Collections.Generic.IList<Membership> Resources { get; set; }
/// <summary>List of locations that could not be reached while fetching this list.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("unreachable")]
public virtual System.Collections.Generic.IList<string> Unreachable { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response message for Operations.ListOperations.</summary>
public class ListOperationsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The standard List next-page token.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>A list of operations that matches the specified filter in the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("operations")]
public virtual System.Collections.Generic.IList<Operation> Operations { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A resource that represents Google Cloud Platform location.</summary>
public class Location : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The friendly name for this location, typically a nearby city name. For example, "Tokyo".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("displayName")]
public virtual string DisplayName { get; set; }
/// <summary>
/// Cross-service attributes for the location. For example {"cloud.googleapis.com/region": "us-east1"}
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("labels")]
public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; }
/// <summary>The canonical id for this location. For example: `"us-east1"`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("locationId")]
public virtual string LocationId { get; set; }
/// <summary>Service-specific metadata. For example the available capacity at the given location.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("metadata")]
public virtual System.Collections.Generic.IDictionary<string, object> Metadata { get; set; }
/// <summary>
/// Resource name for the location, which may vary between implementations. For example:
/// `"projects/example-project/locations/us-east1"`
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Membership contains information about a member cluster.</summary>
public class Membership : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Optional. How to identify workloads from this Membership. See the documentation on Workload Identity for
/// more details: https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("authority")]
public virtual Authority Authority { get; set; }
/// <summary>Output only. When the Membership was created.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("createTime")]
public virtual object CreateTime { get; set; }
/// <summary>Output only. When the Membership was deleted.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("deleteTime")]
public virtual object DeleteTime { get; set; }
/// <summary>
/// Output only. Description of this membership, limited to 63 characters. Must match the regex: `a-zA-Z0-9*`
/// This field is present for legacy purposes.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("description")]
public virtual string Description { get; set; }
/// <summary>Optional. Endpoint information to reach this member.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("endpoint")]
public virtual MembershipEndpoint Endpoint { get; set; }
/// <summary>
/// Optional. An externally-generated and managed ID for this Membership. This ID may be modified after
/// creation, but this is not recommended. The ID must match the regex: `a-zA-Z0-9*` If this Membership
/// represents a Kubernetes cluster, this value should be set to the UID of the `kube-system` namespace object.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("externalId")]
public virtual string ExternalId { get; set; }
/// <summary>Optional. GCP labels for this membership.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("labels")]
public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; }
/// <summary>
/// Output only. For clusters using Connect, the timestamp of the most recent connection established with Google
/// Cloud. This time is updated every several minutes, not continuously. For clusters that do not use GKE
/// Connect, or that have never connected successfully, this field will be unset.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("lastConnectionTime")]
public virtual object LastConnectionTime { get; set; }
/// <summary>
/// Output only. The full, unique name of this Membership resource in the format
/// `projects/*/locations/*/memberships/{membership_id}`, set during creation. `membership_id` must be a valid
/// RFC 1123 compliant DNS label: 1. At most 63 characters in length 2. It must consist of lower case
/// alphanumeric characters or `-` 3. It must start and end with an alphanumeric character Which can be
/// expressed as the regex: `[a-z0-9]([-a-z0-9]*[a-z0-9])?`, with a maximum length of 63 characters.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Output only. State of the Membership resource.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("state")]
public virtual MembershipState State { get; set; }
/// <summary>
/// Output only. Google-generated UUID for this resource. This is unique across all Membership resources. If a
/// Membership resource is deleted and another resource with the same name is created, it gets a different
/// unique_id.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("uniqueId")]
public virtual string UniqueId { get; set; }
/// <summary>Output only. When the Membership was last updated.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateTime")]
public virtual object UpdateTime { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// MembershipEndpoint contains information needed to contact a Kubernetes API, endpoint and any additional
/// Kubernetes metadata.
/// </summary>
public class MembershipEndpoint : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. Specific information for a Google Edge cluster.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("edgeCluster")]
public virtual EdgeCluster EdgeCluster { get; set; }
/// <summary>Optional. Specific information for a GKE-on-GCP cluster.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("gkeCluster")]
public virtual GkeCluster GkeCluster { get; set; }
/// <summary>Output only. Useful Kubernetes-specific metadata.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kubernetesMetadata")]
public virtual KubernetesMetadata KubernetesMetadata { get; set; }
/// <summary>
/// Optional. The in-cluster Kubernetes Resources that should be applied for a correctly registered cluster, in
/// the steady state. These resources: * Ensure that the cluster is exclusively registered to one and only one
/// Hub Membership. * Propagate Workload Pool Information available in the Membership Authority field. * Ensure
/// proper initial configuration of default Hub Features.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("kubernetesResource")]
public virtual KubernetesResource KubernetesResource { get; set; }
/// <summary>Optional. Specific information for a GKE Multi-Cloud cluster.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("multiCloudCluster")]
public virtual MultiCloudCluster MultiCloudCluster { get; set; }
/// <summary>
/// Optional. Specific information for a GKE On-Prem cluster. An onprem user-cluster who has no resourceLink is
/// not allowed to use this field, it should have a nil "type" instead.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("onPremCluster")]
public virtual OnPremCluster OnPremCluster { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>MembershipFeatureSpec contains configuration information for a single Membership.</summary>
public class MembershipFeatureSpec : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Anthos Observability-specific spec</summary>
[Newtonsoft.Json.JsonPropertyAttribute("anthosobservability")]
public virtual AnthosObservabilityMembershipSpec Anthosobservability { get; set; }
/// <summary>Cloud Build-specific spec</summary>
[Newtonsoft.Json.JsonPropertyAttribute("cloudbuild")]
public virtual CloudBuildMembershipSpec Cloudbuild { get; set; }
/// <summary>Config Management-specific spec.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("configmanagement")]
public virtual ConfigManagementMembershipSpec Configmanagement { get; set; }
/// <summary>Identity Service-specific spec.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("identityservice")]
public virtual IdentityServiceMembershipSpec Identityservice { get; set; }
/// <summary>Anthos Service Mesh-specific spec</summary>
[Newtonsoft.Json.JsonPropertyAttribute("mesh")]
public virtual ServiceMeshMembershipSpec Mesh { get; set; }
/// <summary>Policy Controller spec.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("policycontroller")]
public virtual PolicyControllerMembershipSpec Policycontroller { get; set; }
/// <summary>Workload Certificate spec.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("workloadcertificate")]
public virtual MembershipSpec Workloadcertificate { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>MembershipFeatureState contains Feature status information for a single Membership.</summary>
public class MembershipFeatureState : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Appdevexperience specific state.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("appdevexperience")]
public virtual AppDevExperienceFeatureState Appdevexperience { get; set; }
/// <summary>Config Management-specific state.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("configmanagement")]
public virtual ConfigManagementMembershipState Configmanagement { get; set; }
/// <summary>Identity Service-specific state.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("identityservice")]
public virtual IdentityServiceMembershipState Identityservice { get; set; }
/// <summary>Metering-specific spec.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("metering")]
public virtual MeteringMembershipState Metering { get; set; }
/// <summary>Policycontroller-specific state.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("policycontroller")]
public virtual PolicyControllerMembershipState Policycontroller { get; set; }
/// <summary>Service Mesh-specific state.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("servicemesh")]
public virtual ServiceMeshMembershipState Servicemesh { get; set; }
/// <summary>The high-level state of this Feature for a single membership.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("state")]
public virtual FeatureState State { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>**Workload Certificate**: The membership-specific input for WorkloadCertificate feature.</summary>
public class MembershipSpec : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Specifies workload certificate management.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("certificateManagement")]
public virtual string CertificateManagement { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>MembershipState describes the state of a Membership resource.</summary>
public class MembershipState : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. The current state of the Membership resource.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("code")]
public virtual string Code { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>**Metering**: Per-Membership Feature State.</summary>
public class MeteringMembershipState : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The time stamp of the most recent measurement of the number of vCPUs in the cluster.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("lastMeasurementTime")]
public virtual object LastMeasurementTime { get; set; }
/// <summary>
/// The vCPUs capacity in the cluster according to the most recent measurement (1/1000 precision).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("preciseLastMeasuredClusterVcpuCapacity")]
public virtual System.Nullable<float> PreciseLastMeasuredClusterVcpuCapacity { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>MultiCloudCluster contains information specific to GKE Multi-Cloud clusters.</summary>
public class MultiCloudCluster : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Output only. If cluster_missing is set then it denotes that API(gkemulticloud.googleapis.com) resource for
/// this GKE Multi-Cloud cluster no longer exists.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("clusterMissing")]
public virtual System.Nullable<bool> ClusterMissing { get; set; }
/// <summary>
/// Immutable. Self-link of the GCP resource for the GKE Multi-Cloud cluster. For example:
/// //gkemulticloud.googleapis.com/projects/my-project/locations/us-west1-a/awsClusters/my-cluster
/// //gkemulticloud.googleapis.com/projects/my-project/locations/us-west1-a/azureClusters/my-cluster
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("resourceLink")]
public virtual string ResourceLink { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>**Multi-cluster Ingress**: The configuration for the MultiClusterIngress feature.</summary>
public class MultiClusterIngressFeatureSpec : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Deprecated: This field will be ignored and should not be set. Customer's billing structure.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("billing")]
public virtual string Billing { get; set; }
/// <summary>
/// Fully-qualified Membership name which hosts the MultiClusterIngress CRD. Example:
/// `projects/foo-proj/locations/global/memberships/bar`
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("configMembership")]
public virtual string ConfigMembership { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>OnPremCluster contains information specific to GKE On-Prem clusters.</summary>
public class OnPremCluster : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Immutable. Whether the cluster is an admin cluster.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("adminCluster")]
public virtual System.Nullable<bool> AdminCluster { get; set; }
/// <summary>
/// Output only. If cluster_missing is set then it denotes that API(gkeonprem.googleapis.com) resource for this
/// GKE On-Prem cluster no longer exists.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("clusterMissing")]
public virtual System.Nullable<bool> ClusterMissing { get; set; }
/// <summary>
/// Immutable. Self-link of the GCP resource for the GKE On-Prem cluster. For example:
/// //gkeonprem.googleapis.com/projects/my-project/locations/us-west1-a/vmwareClusters/my-cluster
/// //gkeonprem.googleapis.com/projects/my-project/locations/us-west1-a/bareMetalClusters/my-cluster
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("resourceLink")]
public virtual string ResourceLink { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>This resource represents a long-running operation that is the result of a network API call.</summary>
public class Operation : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed,
/// and either `error` or `response` is available.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("done")]
public virtual System.Nullable<bool> Done { get; set; }
/// <summary>The error result of the operation in case of failure or cancellation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("error")]
public virtual GoogleRpcStatus Error { get; set; }
/// <summary>
/// Service-specific metadata associated with the operation. It typically contains progress information and
/// common metadata such as create time. Some services might not provide such metadata. Any method that returns
/// a long-running operation should document the metadata type, if any.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("metadata")]
public virtual System.Collections.Generic.IDictionary<string, object> Metadata { get; set; }
/// <summary>
/// The server-assigned name, which is only unique within the same service that originally returns it. If you
/// use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>
/// The normal response of the operation in case of success. If the original method returns no data on success,
/// such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard
/// `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have
/// the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name is
/// `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("response")]
public virtual System.Collections.Generic.IDictionary<string, object> Response { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents the metadata of the long-running operation.</summary>
public class OperationMetadata : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. API version used to start the operation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("apiVersion")]
public virtual string ApiVersion { get; set; }
/// <summary>
/// Output only. Identifies whether the user has requested cancellation of the operation. Operations that have
/// successfully been cancelled have Operation.error value with a google.rpc.Status.code of 1, corresponding to
/// `Code.CANCELLED`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("cancelRequested")]
public virtual System.Nullable<bool> CancelRequested { get; set; }
/// <summary>Output only. The time the operation was created.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("createTime")]
public virtual object CreateTime { get; set; }
/// <summary>Output only. The time the operation finished running.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("endTime")]
public virtual object EndTime { get; set; }
/// <summary>Output only. Human-readable status of the operation, if any.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("statusDetail")]
public virtual string StatusDetail { get; set; }
/// <summary>Output only. Server-defined resource path for the target of the operation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("target")]
public virtual string Target { get; set; }
/// <summary>Output only. Name of the verb executed by the operation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("verb")]
public virtual string Verb { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// An Identity and Access Management (IAM) policy, which specifies access controls for Google Cloud resources. A
/// `Policy` is a collection of `bindings`. A `binding` binds one or more `members`, or principals, to a single
/// `role`. Principals can be user accounts, service accounts, Google groups, and domains (such as G Suite). A
/// `role` is a named list of permissions; each `role` can be an IAM predefined role or a user-created custom role.
/// For some types of Google Cloud resources, a `binding` can also specify a `condition`, which is a logical
/// expression that allows access to a resource only if the expression evaluates to `true`. A condition can add
/// constraints based on attributes of the request, the resource, or both. To learn which resources support
/// conditions in their IAM policies, see the [IAM
/// documentation](https://cloud.google.com/iam/help/conditions/resource-policies). **JSON example:** { "bindings":
/// [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com",
/// "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] },
/// { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": {
/// "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time
/// &lt; timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 } **YAML example:**
/// bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com -
/// serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin -
/// members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable
/// access description: Does not grant access after Sep 2020 expression: request.time &lt;
/// timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3 For a description of IAM and its features,
/// see the [IAM documentation](https://cloud.google.com/iam/docs/).
/// </summary>
public class Policy : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Specifies cloud audit logging configuration for this policy.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("auditConfigs")]
public virtual System.Collections.Generic.IList<AuditConfig> AuditConfigs { get; set; }
/// <summary>
/// Associates a list of `members`, or principals, with a `role`. Optionally, may specify a `condition` that
/// determines how and when the `bindings` are applied. Each of the `bindings` must contain at least one
/// principal. The `bindings` in a `Policy` can refer to up to 1,500 principals; up to 250 of these principals
/// can be Google groups. Each occurrence of a principal counts towards these limits. For example, if the
/// `bindings` grant 50 different roles to `user:alice@example.com`, and not to any other principal, then you
/// can add another 1,450 principals to the `bindings` in the `Policy`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("bindings")]
public virtual System.Collections.Generic.IList<Binding> Bindings { get; set; }
/// <summary>
/// `etag` is used for optimistic concurrency control as a way to help prevent simultaneous updates of a policy
/// from overwriting each other. It is strongly suggested that systems make use of the `etag` in the
/// read-modify-write cycle to perform policy updates in order to avoid race conditions: An `etag` is returned
/// in the response to `getIamPolicy`, and systems are expected to put that etag in the request to
/// `setIamPolicy` to ensure that their change will be applied to the same version of the policy. **Important:**
/// If you use IAM Conditions, you must include the `etag` field whenever you call `setIamPolicy`. If you omit
/// this field, then IAM allows you to overwrite a version `3` policy with a version `1` policy, and all of the
/// conditions in the version `3` policy are lost.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>
/// Specifies the format of the policy. Valid values are `0`, `1`, and `3`. Requests that specify an invalid
/// value are rejected. Any operation that affects conditional role bindings must specify version `3`. This
/// requirement applies to the following operations: * Getting a policy that includes a conditional role binding
/// * Adding a conditional role binding to a policy * Changing a conditional role binding in a policy * Removing
/// any role binding, with or without a condition, from a policy that includes conditions **Important:** If you
/// use IAM Conditions, you must include the `etag` field whenever you call `setIamPolicy`. If you omit this
/// field, then IAM allows you to overwrite a version `3` policy with a version `1` policy, and all of the
/// conditions in the version `3` policy are lost. If a policy does not include any conditions, operations on
/// that policy may specify any valid version or leave the field unset. To learn which resources support
/// conditions in their IAM policies, see the [IAM
/// documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("version")]
public virtual System.Nullable<int> Version { get; set; }
}
/// <summary>Configuration for Policy Controller</summary>
public class PolicyControllerHubConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Sets the interval for Policy Controller Audit Scans (in seconds). When set to 0, this disables audit
/// functionality altogether.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("auditIntervalSeconds")]
public virtual System.Nullable<long> AuditIntervalSeconds { get; set; }
/// <summary>
/// The set of namespaces that are excluded from Policy Controller checks. Namespaces do not need to currently
/// exist on the cluster.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("exemptableNamespaces")]
public virtual System.Collections.Generic.IList<string> ExemptableNamespaces { get; set; }
/// <summary>
/// The install_spec represents the intended state specified by the latest request that mutated install_spec in
/// the feature spec, not the lifecycle state of the feature observed by the Hub feature controller that is
/// reported in the feature state.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("installSpec")]
public virtual string InstallSpec { get; set; }
/// <summary>Logs all denies and dry run failures.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("logDeniesEnabled")]
public virtual System.Nullable<bool> LogDeniesEnabled { get; set; }
/// <summary>Enables the ability to mutate resources using Policy Controller.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("mutationEnabled")]
public virtual System.Nullable<bool> MutationEnabled { get; set; }
/// <summary>
/// Enables the ability to use Constraint Templates that reference to objects other than the object currently
/// being evaluated.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("referentialRulesEnabled")]
public virtual System.Nullable<bool> ReferentialRulesEnabled { get; set; }
/// <summary>Configures the library templates to install along with Policy Controller.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("templateLibraryConfig")]
public virtual PolicyControllerTemplateLibraryConfig TemplateLibraryConfig { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>State of the Policy Controller.</summary>
public class PolicyControllerHubState : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Map from deployment name to deployment state. Example deployments are gatekeeper-controller-manager,
/// gatekeeper-audit deployment, and gatekeeper-mutation.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("deploymentStates")]
public virtual System.Collections.Generic.IDictionary<string, string> DeploymentStates { get; set; }
/// <summary>The version of Gatekeeper Policy Controller deployed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("version")]
public virtual PolicyControllerHubVersion Version { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The build version of Gatekeeper that Policy Controller is using.</summary>
public class PolicyControllerHubVersion : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The gatekeeper image tag that is composed of ACM version, git tag, build number.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("version")]
public virtual string Version { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// **Policy Controller**: Configuration for a single cluster. Intended to parallel the PolicyController CR.
/// </summary>
public class PolicyControllerMembershipSpec : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Policy Controller configuration for the cluster.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("policyControllerHubConfig")]
public virtual PolicyControllerHubConfig PolicyControllerHubConfig { get; set; }
/// <summary>Version of Policy Controller installed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("version")]
public virtual string Version { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>**Policy Controller**: State for a single cluster.</summary>
public class PolicyControllerMembershipState : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The user-defined name for the cluster used by ClusterSelectors to group clusters together. This should match
/// Membership's membership_name, unless the user installed PC on the cluster manually prior to enabling the PC
/// hub feature. Unique within a Policy Controller installation.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("clusterName")]
public virtual string ClusterName { get; set; }
/// <summary>
/// Membership configuration in the cluster. This represents the actual state in the cluster, while the
/// MembershipSpec in the FeatureSpec represents the intended state
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("membershipSpec")]
public virtual PolicyControllerMembershipSpec MembershipSpec { get; set; }
/// <summary>Policy Controller state observed by the Policy Controller Hub</summary>
[Newtonsoft.Json.JsonPropertyAttribute("policyControllerHubState")]
public virtual PolicyControllerHubState PolicyControllerHubState { get; set; }
/// <summary>The lifecycle state Policy Controller is in.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("state")]
public virtual string State { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The config specifying which default library templates to install.</summary>
public class PolicyControllerTemplateLibraryConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Whether the standard template library should be installed or not.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("included")]
public virtual System.Nullable<bool> Included { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>ResourceManifest represents a single Kubernetes resource to be applied to the cluster.</summary>
public class ResourceManifest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Whether the resource provided in the manifest is `cluster_scoped`. If unset, the manifest is assumed to be
/// namespace scoped. This field is used for REST mapping when applying the resource in a cluster.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("clusterScoped")]
public virtual System.Nullable<bool> ClusterScoped { get; set; }
/// <summary>YAML manifest of the resource.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("manifest")]
public virtual string Manifest { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>ResourceOptions represent options for Kubernetes resource generation.</summary>
public class ResourceOptions : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Optional. The Connect agent version to use for connect_resources. Defaults to the latest GKE Connect
/// version. The version must be a currently supported version, obsolete versions will be rejected.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("connectVersion")]
public virtual string ConnectVersion { get; set; }
/// <summary>
/// Optional. Major version of the Kubernetes cluster. This is only used to determine which version to use for
/// the CustomResourceDefinition resources, `apiextensions/v1beta1` or`apiextensions/v1`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("k8sVersion")]
public virtual string K8sVersion { get; set; }
/// <summary>
/// Optional. Use `apiextensions/v1beta1` instead of `apiextensions/v1` for CustomResourceDefinition resources.
/// This option should be set for clusters with Kubernetes apiserver versions &lt;1.16.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("v1beta1Crd")]
public virtual System.Nullable<bool> V1beta1Crd { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// AnalysisMessage is a single message produced by an analyzer, and it used to communicate to the end user about
/// the state of their Service Mesh configuration.
/// </summary>
public class ServiceMeshAnalysisMessage : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// A UI can combine these args with a template (based on message_base.type) to produce an internationalized
/// message.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("args")]
public virtual System.Collections.Generic.IDictionary<string, object> Args { get; set; }
/// <summary>
/// A human readable description of what the error means. It is suitable for non-internationalize display
/// purposes.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("description")]
public virtual string Description { get; set; }
/// <summary>Details common to all types of Istio and ServiceMesh analysis messages.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("messageBase")]
public virtual ServiceMeshAnalysisMessageBase MessageBase { get; set; }
/// <summary>
/// A list of strings specifying the resource identifiers that were the cause of message generation. A "path"
/// here may be: * MEMBERSHIP_ID if the cause is a specific member cluster *
/// MEMBERSHIP_ID/(NAMESPACE\/)?RESOURCETYPE/NAME if the cause is a resource in a cluster
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("resourcePaths")]
public virtual System.Collections.Generic.IList<string> ResourcePaths { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>AnalysisMessageBase describes some common information that is needed for all messages.</summary>
public class ServiceMeshAnalysisMessageBase : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A url pointing to the Service Mesh or Istio documentation for this specific error type.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("documentationUrl")]
public virtual string DocumentationUrl { get; set; }
/// <summary>Represents how severe a message is.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("level")]
public virtual string Level { get; set; }
/// <summary>Represents the specific type of a message.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("type")]
public virtual ServiceMeshType Type { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Status of control plane management.</summary>
public class ServiceMeshControlPlaneManagement : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Explanation of state.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("details")]
public virtual System.Collections.Generic.IList<ServiceMeshStatusDetails> Details { get; set; }
/// <summary>LifecycleState of control plane management.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("state")]
public virtual string State { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>**Service Mesh**: State for the whole Hub, as analyzed by the Service Mesh Hub Controller.</summary>
public class ServiceMeshFeatureState : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. Results of running Service Mesh analyzers.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("analysisMessages")]
public virtual System.Collections.Generic.IList<ServiceMeshAnalysisMessage> AnalysisMessages { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>**Service Mesh**: Spec for a single Membership for the servicemesh feature</summary>
public class ServiceMeshMembershipSpec : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Enables automatic control plane management.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("controlPlane")]
public virtual string ControlPlane { get; set; }
/// <summary>Determines which release channel to use for default injection and service mesh APIs.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("defaultChannel")]
public virtual string DefaultChannel { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// **Service Mesh**: State for a single Membership, as analyzed by the Service Mesh Hub Controller.
/// </summary>
public class ServiceMeshMembershipState : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. Results of running Service Mesh analyzers.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("analysisMessages")]
public virtual System.Collections.Generic.IList<ServiceMeshAnalysisMessage> AnalysisMessages { get; set; }
/// <summary>
/// The API version (i.e. Istio CRD version) for configuring service mesh in this cluster. This version is
/// influenced by the `default_channel` field.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("configApiVersion")]
public virtual string ConfigApiVersion { get; set; }
/// <summary>Output only. Status of control plane management</summary>
[Newtonsoft.Json.JsonPropertyAttribute("controlPlaneManagement")]
public virtual ServiceMeshControlPlaneManagement ControlPlaneManagement { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Structured and human-readable details for a status.</summary>
public class ServiceMeshStatusDetails : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A machine-readable code that further describes a broad status.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("code")]
public virtual string Code { get; set; }
/// <summary>Human-readable explanation of code.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("details")]
public virtual string Details { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// A unique identifier for the type of message. Display_name is intended to be human-readable, code is intended to
/// be machine readable. There should be a one-to-one mapping between display_name and code. (i.e. do not re-use
/// display_names or codes between message types.) See istio.analysis.v1alpha1.AnalysisMessageBase.Type
/// </summary>
public class ServiceMeshType : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// A 7 character code matching `^IST[0-9]{4}$` or `^ASM[0-9]{4}$`, intended to uniquely identify the message
/// type. (e.g. "IST0001" is mapped to the "InternalError" message type.)
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("code")]
public virtual string Code { get; set; }
/// <summary>
/// A human-readable name for the message type. e.g. "InternalError", "PodMissingProxy". This should be the same
/// for all messages of the same type. (This corresponds to the `name` field in open-source Istio.)
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("displayName")]
public virtual string DisplayName { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request message for `SetIamPolicy` method.</summary>
public class SetIamPolicyRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// REQUIRED: The complete policy to be applied to the `resource`. The size of the policy is limited to a few
/// 10s of KB. An empty policy is a valid policy but certain Google Cloud services (such as Projects) might
/// reject them.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("policy")]
public virtual Policy Policy { get; set; }
/// <summary>
/// OPTIONAL: A FieldMask specifying which fields of the policy to modify. Only the fields in the mask will be
/// modified. If no mask is provided, the following default mask is used: `paths: "bindings, etag"`
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateMask")]
public virtual object UpdateMask { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Status specifies state for the subcomponent.</summary>
public class Status : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Code specifies AppDevExperienceFeature's subcomponent ready state.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("code")]
public virtual string Code { get; set; }
/// <summary>Description is populated if Code is Failed, explaining why it has failed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("description")]
public virtual string Description { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request message for `TestIamPermissions` method.</summary>
public class TestIamPermissionsRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The set of permissions to check for the `resource`. Permissions with wildcards (such as `*` or `storage.*`)
/// are not allowed. For more information see [IAM
/// Overview](https://cloud.google.com/iam/docs/overview#permissions).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("permissions")]
public virtual System.Collections.Generic.IList<string> Permissions { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for `TestIamPermissions` method.</summary>
public class TestIamPermissionsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A subset of `TestPermissionsRequest.permissions` that the caller is allowed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("permissions")]
public virtual System.Collections.Generic.IList<string> Permissions { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// TypeMeta is the type information needed for content unmarshalling of Kubernetes resources in the manifest.
/// </summary>
public class TypeMeta : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>APIVersion of the resource (e.g. v1).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("apiVersion")]
public virtual string ApiVersion { get; set; }
/// <summary>Kind of the resource (e.g. Deployment).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| 52.484288 | 194 | 0.586892 | [
"Apache-2.0"
] | wonderfly/google-api-dotnet-client | Src/Generated/Google.Apis.GKEHub.v1alpha/Google.Apis.GKEHub.v1alpha.cs | 272,254 | C# |
using BlazorDemo.Data;
using BlazorDemo.Options;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace BlazorDemo
{
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddOptions<ApplicationSettings>();
services.AddHttpClient();
services.AddSingleton<WeatherForecastService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
}
| 33.689655 | 144 | 0.599284 | [
"MIT"
] | VitorRigoni/BlazorDemo | Startup.cs | 1,954 | C# |
// Copyright © 2017 onwards, Andrew Whewell
// All rights reserved.
//
// Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using VirtualRadar.Interface.Database;
namespace VirtualRadar.Database.BaseStation
{
/// <summary>
/// Builds Dapper parameters from BaseStation database objects.
/// </summary>
public static class ParameterBuilder
{
/// <summary>
/// Builds a Dapper parameters object for an aircraft.
/// </summary>
/// <param name="aircraft"></param>
/// <param name="includeAircraftID"></param>
/// <returns></returns>
public static DynamicParameters FromAircraft(BaseStationAircraft aircraft, bool includeAircraftID = true)
{
var result = new DynamicParameters();
if(includeAircraftID) {
result.Add(nameof(aircraft.AircraftID), value: aircraft.AircraftID);
}
result.Add(nameof(aircraft.AircraftClass), value: aircraft.AircraftClass);
result.Add(nameof(aircraft.CofACategory), value: aircraft.CofACategory);
result.Add(nameof(aircraft.CofAExpiry), value: aircraft.CofAExpiry);
result.Add(nameof(aircraft.Country), value: aircraft.Country);
result.Add(nameof(aircraft.CurrentRegDate), value: aircraft.CurrentRegDate);
result.Add(nameof(aircraft.DeRegDate), value: aircraft.DeRegDate);
result.Add(nameof(aircraft.Engines), value: aircraft.Engines);
result.Add(nameof(aircraft.FirstCreated), value: aircraft.FirstCreated);
result.Add(nameof(aircraft.FirstRegDate), value: aircraft.FirstRegDate);
result.Add(nameof(aircraft.GenericName), value: aircraft.GenericName);
result.Add(nameof(aircraft.ICAOTypeCode), value: aircraft.ICAOTypeCode);
result.Add(nameof(aircraft.InfoUrl), value: aircraft.InfoUrl);
result.Add(nameof(aircraft.Interested), value: aircraft.Interested);
result.Add(nameof(aircraft.LastModified), value: aircraft.LastModified);
result.Add(nameof(aircraft.Manufacturer), value: aircraft.Manufacturer);
result.Add(nameof(aircraft.ModeS), value: aircraft.ModeS);
result.Add(nameof(aircraft.ModeSCountry), value: aircraft.ModeSCountry);
result.Add(nameof(aircraft.MTOW), value: aircraft.MTOW);
result.Add(nameof(aircraft.OperatorFlagCode), value: aircraft.OperatorFlagCode);
result.Add(nameof(aircraft.OwnershipStatus), value: aircraft.OwnershipStatus);
result.Add(nameof(aircraft.PictureUrl1), value: aircraft.PictureUrl1);
result.Add(nameof(aircraft.PictureUrl2), value: aircraft.PictureUrl2);
result.Add(nameof(aircraft.PictureUrl3), value: aircraft.PictureUrl3);
result.Add(nameof(aircraft.PopularName), value: aircraft.PopularName);
result.Add(nameof(aircraft.PreviousID), value: aircraft.PreviousID);
result.Add(nameof(aircraft.Registration), value: aircraft.Registration);
result.Add(nameof(aircraft.RegisteredOwners), value: aircraft.RegisteredOwners);
result.Add(nameof(aircraft.SerialNo), value: aircraft.SerialNo);
result.Add(nameof(aircraft.Status), value: aircraft.Status);
result.Add(nameof(aircraft.TotalHours), value: aircraft.TotalHours);
result.Add(nameof(aircraft.Type), value: aircraft.Type);
result.Add(nameof(aircraft.UserNotes), value: aircraft.UserNotes);
result.Add(nameof(aircraft.UserTag), value: aircraft.UserTag);
result.Add(nameof(aircraft.YearBuilt), value: aircraft.YearBuilt);
result.Add(nameof(aircraft.UserString1), value: aircraft.UserString1);
result.Add(nameof(aircraft.UserString2), value: aircraft.UserString2);
result.Add(nameof(aircraft.UserString3), value: aircraft.UserString3);
result.Add(nameof(aircraft.UserString4), value: aircraft.UserString4);
result.Add(nameof(aircraft.UserString5), value: aircraft.UserString5);
result.Add(nameof(aircraft.UserBool1), value: aircraft.UserBool1);
result.Add(nameof(aircraft.UserBool2), value: aircraft.UserBool2);
result.Add(nameof(aircraft.UserBool3), value: aircraft.UserBool3);
result.Add(nameof(aircraft.UserBool4), value: aircraft.UserBool4);
result.Add(nameof(aircraft.UserBool5), value: aircraft.UserBool5);
result.Add(nameof(aircraft.UserInt1), value: aircraft.UserInt1);
result.Add(nameof(aircraft.UserInt2), value: aircraft.UserInt2);
result.Add(nameof(aircraft.UserInt3), value: aircraft.UserInt3);
result.Add(nameof(aircraft.UserInt4), value: aircraft.UserInt4);
result.Add(nameof(aircraft.UserInt5), value: aircraft.UserInt5);
return result;
}
/// <summary>
/// Returns parameters for a flight.
/// </summary>
/// <param name="flight"></param>
/// <param name="includeFlightID"></param>
/// <returns></returns>
public static DynamicParameters FromFlight(BaseStationFlight flight, bool includeFlightID = true)
{
var result = new DynamicParameters();
if(includeFlightID) {
result.Add(nameof(flight.FlightID), value: flight.FlightID);
}
result.Add(nameof(flight.AircraftID), value: flight.AircraftID);
result.Add(nameof(flight.Callsign), value: flight.Callsign);
result.Add(nameof(flight.EndTime), value: flight.EndTime);
result.Add(nameof(flight.FirstAltitude), value: flight.FirstAltitude);
result.Add(nameof(flight.FirstGroundSpeed), value: flight.FirstGroundSpeed);
result.Add(nameof(flight.FirstIsOnGround), value: flight.FirstIsOnGround);
result.Add(nameof(flight.FirstLat), value: flight.FirstLat);
result.Add(nameof(flight.FirstLon), value: flight.FirstLon);
result.Add(nameof(flight.FirstSquawk), value: flight.FirstSquawk);
result.Add(nameof(flight.FirstTrack), value: flight.FirstTrack);
result.Add(nameof(flight.FirstVerticalRate), value: flight.FirstVerticalRate);
result.Add(nameof(flight.HadAlert), value: flight.HadAlert);
result.Add(nameof(flight.HadEmergency), value: flight.HadEmergency);
result.Add(nameof(flight.HadSpi), value: flight.HadSpi);
result.Add(nameof(flight.LastAltitude), value: flight.LastAltitude);
result.Add(nameof(flight.LastGroundSpeed), value: flight.LastGroundSpeed);
result.Add(nameof(flight.LastIsOnGround), value: flight.LastIsOnGround);
result.Add(nameof(flight.LastLat), value: flight.LastLat);
result.Add(nameof(flight.LastLon), value: flight.LastLon);
result.Add(nameof(flight.LastSquawk), value: flight.LastSquawk);
result.Add(nameof(flight.LastTrack), value: flight.LastTrack);
result.Add(nameof(flight.LastVerticalRate), value: flight.LastVerticalRate);
result.Add(nameof(flight.NumADSBMsgRec), value: flight.NumADSBMsgRec);
result.Add(nameof(flight.NumModeSMsgRec), value: flight.NumModeSMsgRec);
result.Add(nameof(flight.NumIDMsgRec), value: flight.NumIDMsgRec);
result.Add(nameof(flight.NumSurPosMsgRec), value: flight.NumSurPosMsgRec);
result.Add(nameof(flight.NumAirPosMsgRec), value: flight.NumAirPosMsgRec);
result.Add(nameof(flight.NumAirVelMsgRec), value: flight.NumAirVelMsgRec);
result.Add(nameof(flight.NumSurAltMsgRec), value: flight.NumSurAltMsgRec);
result.Add(nameof(flight.NumSurIDMsgRec), value: flight.NumSurIDMsgRec);
result.Add(nameof(flight.NumAirToAirMsgRec), value: flight.NumAirToAirMsgRec);
result.Add(nameof(flight.NumAirCallRepMsgRec), value: flight.NumAirCallRepMsgRec);
result.Add(nameof(flight.NumPosMsgRec), value: flight.NumPosMsgRec);
result.Add(nameof(flight.SessionID), value: flight.SessionID);
result.Add(nameof(flight.StartTime), value: flight.StartTime);
result.Add(nameof(flight.UserNotes), value: flight.UserNotes);
return result;
}
/// <summary>
/// Generates parameters for a DB history object.
/// </summary>
/// <param name="dbHistory"></param>
/// <param name="includeHistoryID"></param>
/// <returns></returns>
public static DynamicParameters FromDBHistory(BaseStationDBHistory dbHistory, bool includeHistoryID = true)
{
var result = new DynamicParameters();
if(includeHistoryID) {
result.Add(nameof(dbHistory.DBHistoryID), value: dbHistory.DBHistoryID);
}
result.Add(nameof(dbHistory.TimeStamp), value: dbHistory.TimeStamp);
result.Add(nameof(dbHistory.Description), value: dbHistory.Description);
return result;
}
/// <summary>
/// Generates parameters for a DB info object.
/// </summary>
/// <param name="dbInfo"></param>
/// <returns></returns>
public static DynamicParameters FromDBInfo(BaseStationDBInfo dbInfo)
{
var result = new DynamicParameters();
result.Add(nameof(dbInfo.OriginalVersion), value: dbInfo.OriginalVersion);
result.Add(nameof(dbInfo.CurrentVersion), value: dbInfo.CurrentVersion);
return result;
}
/// <summary>
/// Generates parameters for a location object.
/// </summary>
/// <param name="location"></param>
/// <param name="includeLocationID"></param>
/// <returns></returns>
public static DynamicParameters FromLocation(BaseStationLocation location, bool includeLocationID = true)
{
var result = new DynamicParameters();
if(includeLocationID) {
result.Add(nameof(location.LocationID), value: location.LocationID);
}
result.Add(nameof(location.LocationName), value: location.LocationName);
result.Add(nameof(location.Latitude), value: location.Latitude);
result.Add(nameof(location.Longitude), value: location.Longitude);
result.Add(nameof(location.Altitude), value: location.Altitude);
return result;
}
/// <summary>
/// Generates parameters for a session object.
/// </summary>
/// <param name="session"></param>
/// <param name="includeSessionID"></param>
/// <returns></returns>
public static DynamicParameters FromSession(BaseStationSession session, bool includeSessionID = true)
{
var result = new DynamicParameters();
if(includeSessionID) {
result.Add(nameof(session.SessionID), value: session.SessionID);
}
result.Add(nameof(session.LocationID), value: session.LocationID);
result.Add(nameof(session.StartTime), value: session.StartTime);
result.Add(nameof(session.EndTime), value: session.EndTime);
return result;
}
/// <summary>
/// Generates parameters for a system event object.
/// </summary>
/// <param name="systemEvent"></param>
/// <param name="includeSystemEventID"></param>
/// <returns></returns>
public static DynamicParameters FromSystemEvent(BaseStationSystemEvents systemEvent, bool includeSystemEventID = true)
{
var result = new DynamicParameters();
if(includeSystemEventID) {
result.Add(nameof(systemEvent.SystemEventsID), value: systemEvent.SystemEventsID);
}
result.Add(nameof(systemEvent.TimeStamp), value: systemEvent.TimeStamp);
result.Add(nameof(systemEvent.App), value: systemEvent.App);
result.Add(nameof(systemEvent.Msg), value: systemEvent.Msg);
return result;
}
/// <summary>
/// Normalises a Mode-S ICAO24.
/// </summary>
/// <param name="icao"></param>
/// <returns></returns>
public static string NormaliseAircraftIcao(string icao)
{
return (icao ?? "").ToUpper();
}
}
}
| 59.840637 | 750 | 0.618908 | [
"BSD-3-Clause"
] | AlexAX135/vrs | VirtualRadar.Database/BaseStation/ParameterBuilder.cs | 15,023 | C# |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace Abacuza.Services.Identity.Controllers.Account
{
public class RedirectViewModel
{
public string RedirectUrl { get; set; }
}
} | 27.75 | 107 | 0.726727 | [
"Apache-2.0"
] | daxnet/abacuza | src/services/auth/Abacuza.Services.Identity/Controllers/Account/RedirectViewModel.cs | 333 | C# |
namespace AAWebSmartHouse.Data.Services
{
using System;
using System.Data.Entity;
using System.Linq;
using AAWebSmartHouse.Common;
using AAWebSmartHouse.Data.Models;
using AAWebSmartHouse.Data.Services.Contracts;
public class SensorValuesService : ISensorValuesService
{
private readonly IRepository<SensorValue> sensorData;
public SensorValuesService(
IRepository<SensorValue> sensorDataRepo)
{
this.sensorData = sensorDataRepo;
}
public IQueryable<SensorValue> GetSensorValueById(int sensorValueId)
{
return this.sensorData
.All()
.Where(u => u.SensorValueId == sensorValueId);
}
//filter and agregate(day/week/month)
public IQueryable<SensorValue> GetSensorValuesPagedOrderdAndAgregated(int sensorId, int page = 1, int pageSize = GlobalConstants.DefaultPageSize, bool orderAscendingByDate = false, SensorAggregationType aggregation = SensorAggregationType.ByHour)
{
var query = this.sensorData.All();
var parmSensorId = new MySql.Data.MySqlClient.MySqlParameter("@SensorId", sensorId);
var parmTake = new MySql.Data.MySqlClient.MySqlParameter("@take", pageSize);
var parmSkip = new MySql.Data.MySqlClient.MySqlParameter("@skip", (page - 1) * pageSize);
switch (aggregation)
{
case SensorAggregationType.ByHour:
query = query.Where(s => s.SensorId == sensorId);
if (orderAscendingByDate)
{
query = query.OrderBy(it => it.SensorValueDateTime);
}
else
{
query = query.OrderByDescending(it => it.SensorValueDateTime);
}
return query.Skip((page - 1) * pageSize).Take(pageSize);
case SensorAggregationType.ByDay:
return this.sensorData
.CustomQuery(@"SELECT year(`SensorValueDateTime`) * 10000 + month(`SensorValueDateTime`) * 100 + day(`SensorValueDateTime`) as `SensorValueId`,avg(`Value`) as `Value`,`SensorId`,`SensorValueDateTime`
FROM `sensorvalues`
WHERE `SensorId` = @SensorId
GROUP BY year(`SensorValueDateTime`) * 10000 + month(`SensorValueDateTime`) * 100 + day(`SensorValueDateTime`)
ORDER BY SensorValueDateTime" + (orderAscendingByDate ? "" : " desc") + @"
LIMIT @skip, @take", parmSensorId, parmSkip, parmTake);
case SensorAggregationType.ByWeek:
return this.sensorData
.CustomQuery(@"SELECT year(`SensorValueDateTime`) * 100 + weekofyear(`SensorValueDateTime`) as `SensorValueId`,avg(`Value`) as `Value`,`SensorId`,`SensorValueDateTime`
FROM `sensorvalues`
WHERE `SensorId` = @SensorId
GROUP BY year(`SensorValueDateTime`) * 100 + weekofyear(`SensorValueDateTime`)
ORDER BY SensorValueDateTime" + (orderAscendingByDate ? "" : " desc") + @"
LIMIT @skip, @take", parmSensorId, parmSkip, parmTake);
case SensorAggregationType.ByMonth:
return this.sensorData
.CustomQuery(@"SELECT year(`SensorValueDateTime`) * 100 + month(`SensorValueDateTime`) as `SensorValueId`,avg(`Value`) as `Value`,`SensorId`,`SensorValueDateTime`
FROM `sensorvalues`
WHERE `SensorId` = @SensorId
GROUP BY year(`SensorValueDateTime`) * 100 + month(`SensorValueDateTime`)
ORDER BY SensorValueDateTime" + (orderAscendingByDate ? "" : " desc") + @"
LIMIT @skip, @take", parmSensorId, parmSkip, parmTake);
default:
throw new ArgumentException("Unknown aggregation type.", "aggregation");
}
}
public int GetSensorValuesCountByAggregation(int sensorId, SensorAggregationType aggregation = SensorAggregationType.ByHour)
{
var query = this.sensorData.All();
var parmSensorId = new MySql.Data.MySqlClient.MySqlParameter("@SensorId", sensorId);
switch (aggregation)
{
case SensorAggregationType.ByHour:
return query.Where(s => s.SensorId == sensorId).Count();
case SensorAggregationType.ByDay:
return this.sensorData
.CustomQuery<int>(@"SELECT year(`SensorValueDateTime`) * 100 + month(`SensorValueDateTime`) as `SensorValueId`
FROM `sensorvalues`
WHERE `SensorId` = @SensorId
GROUP BY year(`SensorValueDateTime`) * 10000 + month(`SensorValueDateTime`) * 100 + day(`SensorValueDateTime`)", parmSensorId)
.Count();
case SensorAggregationType.ByWeek:
return this.sensorData
.CustomQuery<int>(@"SELECT year(`SensorValueDateTime`) * 100 + weekofyear(`SensorValueDateTime`) as `SensorValueId`
FROM `sensorvalues`
WHERE `SensorId` = @SensorId
GROUP BY year(`SensorValueDateTime`) * 100 + weekofyear(`SensorValueDateTime`)", parmSensorId)
.Count();
case SensorAggregationType.ByMonth:
return this.sensorData
.CustomQuery<int>(@"SELECT year(`SensorValueDateTime`) * 100 + month(`SensorValueDateTime`) as `SensorValueId`
FROM `sensorvalues`
WHERE `SensorId` = @SensorId
GROUP BY year(`SensorValueDateTime`) * 100 + month(`SensorValueDateTime`)", parmSensorId)
.Count();
default:
throw new ArgumentException("Unknown aggregation type.", "aggregation");
}
}
}
} | 49.666667 | 254 | 0.622395 | [
"MIT"
] | Obelixx/AASmartHouse | AAWebSmartHouse/Data/Services/AAWebSmartHouse.Data.Services/SensorValuesService.cs | 5,664 | C# |
namespace BGTATKO.Web.ViewModels.Users
{
using System;
using Data.Models;
using Services.Mapping;
public class PostFromUserViewModel : IMapFrom<Post>
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public string CategoryName { get; set; }
public int CategoryId { get; set; }
public DateTime CreatedOn { get; set; }
public string TimeSincePosted => this.CreatedOn.Date == DateTime.UtcNow.Date
? "Today"
: $"{(DateTime.UtcNow.Date - this.CreatedOn.Date).TotalDays} days ago";
public int CommentsCount { get; set; }
}
}
| 24.642857 | 84 | 0.607246 | [
"MIT"
] | kriss98/BG-TATKO | src/Web/BGTATKO.Web.ViewModels/Users/PostFromUserViewModel.cs | 692 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.HDInsight.Commands;
using Microsoft.Azure.Commands.HDInsight.Models;
using Microsoft.Azure.Commands.HDInsight.Models.Management;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Graph.RBAC.Version1_6;
using Microsoft.Azure.Management.HDInsight.Models;
using Microsoft.WindowsAzure.Commands.Common;
using Microsoft.WindowsAzure.Commands.Common.CustomAttributes;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.HDInsight
{
[Cmdlet("New", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "HDInsightCluster",DefaultParameterSetName = DefaultParameterSet),OutputType(typeof(AzureHDInsightCluster))]
public class NewAzureHDInsightClusterCommand : HDInsightCmdletBase
{
private ClusterCreateParameters parameters;
private const string CertificateFilePathSet = "CertificateFilePath";
private const string CertificateFileContentsSet = "CertificateFileContents";
private const string DefaultParameterSet = "Default";
#region These fields are marked obsolete in ClusterCreateParameters
private string _defaultStorageAccountName;
private string _defaultStorageAccountKey;
private string _defaultStorageContainer;
private OSType? _osType;
#endregion
#region Input Parameter Definitions
[Parameter(
Position = 0,
Mandatory = true,
HelpMessage = "Gets or sets the datacenter location for the cluster.")]
[LocationCompleter("Microsoft.HDInsight/clusters")]
public string Location
{
get { return parameters.Location; }
set { parameters.Location = value; }
}
[Parameter(
Position = 1,
Mandatory = true,
HelpMessage = "Gets or sets the name of the resource group.")]
[ResourceGroupCompleter]
public string ResourceGroupName { get; set; }
[Parameter(
Position = 2,
Mandatory = true,
HelpMessage = "Gets or sets the name of the cluster.")]
public string ClusterName { get; set; }
[Parameter(
Position = 3,
Mandatory = true,
HelpMessage = "Gets or sets the number of workernodes for the cluster.")]
public int ClusterSizeInNodes
{
get { return parameters.ClusterSizeInNodes; }
set { parameters.ClusterSizeInNodes = value; }
}
[Parameter(
Position = 4,
Mandatory = true,
HelpMessage = "Gets or sets the login for the cluster's user.")]
public PSCredential HttpCredential { get; set; }
[CmdletParameterBreakingChange("DefaultStorageAccountName", ReplaceMentCmdletParameterName = "StorageAccountResourceId")]
[Parameter(
Position = 5,
HelpMessage = "Gets or sets the StorageName for the default Azure Storage Account or the default Data Lake Store Account.")]
public string DefaultStorageAccountName
{
get { return _defaultStorageAccountName; }
set { _defaultStorageAccountName = value; }
}
[CmdletParameterBreakingChange("DefaultStorageAccountKey", ReplaceMentCmdletParameterName = "StorageAccountKey")]
[Parameter(
Position = 6,
HelpMessage = "Gets or sets the StorageKey for the default Azure Storage Account.")]
public string DefaultStorageAccountKey
{
get { return _defaultStorageAccountKey; }
set { _defaultStorageAccountKey = value; }
}
[CmdletParameterBreakingChange("DefaultStorageAccountType", ReplaceMentCmdletParameterName = "StorageAccountType")]
[Parameter(
HelpMessage = "Gets or sets the type of the default storage account.")]
public StorageType? DefaultStorageAccountType { get; set; }
[Parameter(ValueFromPipeline = true,
HelpMessage = "The HDInsight cluster configuration to use when creating the new cluster.")]
public AzureHDInsightConfig Config
{
get
{
var result = new AzureHDInsightConfig
{
ClusterType = parameters.ClusterType,
ClusterTier = parameters.ClusterTier,
DefaultStorageAccountType = DefaultStorageAccountType ?? StorageType.AzureStorage,
DefaultStorageAccountName = _defaultStorageAccountName,
DefaultStorageAccountKey = _defaultStorageAccountKey,
WorkerNodeSize = parameters.WorkerNodeSize,
HeadNodeSize = parameters.HeadNodeSize,
EdgeNodeSize = parameters.EdgeNodeSize,
ZookeeperNodeSize = parameters.ZookeeperNodeSize,
HiveMetastore = HiveMetastore,
OozieMetastore = OozieMetastore,
ObjectId = ObjectId,
ApplicationId = ApplicationId,
AADTenantId = AadTenantId,
CertificateFileContents = CertificateFileContents,
CertificateFilePath = CertificateFilePath,
CertificatePassword = CertificatePassword,
SecurityProfile = SecurityProfile,
DisksPerWorkerNode = DisksPerWorkerNode,
MinSupportedTlsVersion = MinSupportedTlsVersion,
AssignedIdentity = AssignedIdentity,
EncryptionAlgorithm = EncryptionAlgorithm,
EncryptionKeyName = EncryptionKeyName,
EncryptionKeyVersion = EncryptionKeyVersion,
EncryptionVaultUri = EncryptionVaultUri,
PublicNetworkAccessType = PublicNetworkAccessType,
OutboundPublicNetworkAccessType = OutboundPublicNetworkAccessType,
EncryptionInTransit = EncryptionInTransit,
EncryptionAtHost = EncryptionAtHost
};
foreach (
var storageAccount in
parameters.AdditionalStorageAccounts.Where(
storageAccount => !result.AdditionalStorageAccounts.ContainsKey(storageAccount.Key)))
{
result.AdditionalStorageAccounts.Add(storageAccount.Key, storageAccount.Value);
}
foreach (var val in parameters.Configurations.Where(val => !result.Configurations.ContainsKey(val.Key)))
{
result.Configurations.Add(val.Key, DictionaryToHashtable(val.Value));
}
foreach (var action in parameters.ScriptActions.Where(action => !result.ScriptActions.ContainsKey(action.Key)))
{
result.ScriptActions.Add(action.Key, action.Value.Select(a => new AzureHDInsightScriptAction(a)).ToList());
}
foreach (var component in parameters.ComponentVersion.Where(component => !result.ComponentVersion.ContainsKey(component.Key)))
{
result.ComponentVersion.Add(component.Key, component.Value);
}
return result;
}
set
{
parameters.ClusterType = value.ClusterType;
parameters.ClusterTier = value.ClusterTier;
if (DefaultStorageAccountType == null)
{
DefaultStorageAccountType = value.DefaultStorageAccountType;
}
if (string.IsNullOrWhiteSpace(_defaultStorageAccountName))
{
_defaultStorageAccountName = value.DefaultStorageAccountName;
}
if (string.IsNullOrWhiteSpace(_defaultStorageAccountKey))
{
_defaultStorageAccountKey = value.DefaultStorageAccountKey;
}
parameters.WorkerNodeSize = value.WorkerNodeSize;
parameters.HeadNodeSize = value.HeadNodeSize;
parameters.EdgeNodeSize = value.EdgeNodeSize;
parameters.ZookeeperNodeSize = value.ZookeeperNodeSize;
HiveMetastore = value.HiveMetastore;
OozieMetastore = value.OozieMetastore;
CertificateFileContents = value.CertificateFileContents;
CertificateFilePath = value.CertificateFilePath;
AadTenantId = value.AADTenantId;
ObjectId = value.ObjectId;
ApplicationId = value.ApplicationId;
CertificatePassword = value.CertificatePassword;
SecurityProfile = value.SecurityProfile;
DisksPerWorkerNode = value.DisksPerWorkerNode;
MinSupportedTlsVersion = value.MinSupportedTlsVersion;
AssignedIdentity = value.AssignedIdentity;
EncryptionAlgorithm = value.EncryptionAlgorithm;
EncryptionKeyName = value.EncryptionKeyName;
EncryptionKeyVersion = value.EncryptionKeyVersion;
EncryptionVaultUri = value.EncryptionVaultUri;
PublicNetworkAccessType = value.PublicNetworkAccessType;
OutboundPublicNetworkAccessType = value.OutboundPublicNetworkAccessType;
EncryptionInTransit = value.EncryptionInTransit;
EncryptionAtHost = value.EncryptionAtHost;
foreach (
var storageAccount in
value.AdditionalStorageAccounts.Where(
storageAccount => !parameters.AdditionalStorageAccounts.ContainsKey(storageAccount.Key)))
{
parameters.AdditionalStorageAccounts.Add(storageAccount.Key, storageAccount.Value);
}
foreach (var val in value.Configurations.Where(val => !parameters.Configurations.ContainsKey(val.Key)))
{
parameters.Configurations.Add(val.Key, HashtableToDictionary(val.Value));
}
foreach (var action in value.ScriptActions.Where(action => !parameters.ScriptActions.ContainsKey(action.Key)))
{
parameters.ScriptActions.Add(action.Key, action.Value.Select(a => a.GetScriptActionFromPSModel()).ToList());
}
foreach (var component in value.ComponentVersion.Where(component => !parameters.ComponentVersion.ContainsKey(component.Key)))
{
parameters.ComponentVersion.Add(component.Key, component.Value);
}
}
}
[Parameter(HelpMessage = "Gets or sets the database to store the metadata for Oozie.")]
public AzureHDInsightMetastore OozieMetastore { get; set; }
[Parameter(HelpMessage = "Gets or sets the database to store the metadata for Hive.")]
public AzureHDInsightMetastore HiveMetastore { get; set; }
[Parameter(HelpMessage = "Gets additional Azure Storage Account that you want to enable access to.")]
public Dictionary<string, string> AdditionalStorageAccounts { get; private set; }
[Parameter(HelpMessage = "Gets the configurations of this HDInsight cluster.")]
public Dictionary<string, Dictionary<string, string>> Configurations { get; private set; }
[Parameter(HelpMessage = "Gets config actions for the cluster.")]
public Dictionary<ClusterNodeType, List<AzureHDInsightScriptAction>> ScriptActions { get; private set; }
[CmdletParameterBreakingChange("DefaultStorageContainer", ReplaceMentCmdletParameterName = "StorageContainer")]
[Parameter(HelpMessage = "Gets or sets the StorageContainer name for the default Azure Storage Account")]
public string DefaultStorageContainer
{
get { return _defaultStorageContainer; }
set { _defaultStorageContainer = value; }
}
[CmdletParameterBreakingChange("DefaultStorageRootPath", ReplaceMentCmdletParameterName = "StorageRootPath")]
[Parameter(HelpMessage = "Gets or sets the path to the root of the cluster in the default Data Lake Store Account.")]
public string DefaultStorageRootPath { get; set; }
[Parameter(HelpMessage = "Gets or sets the version of the HDInsight cluster.")]
public string Version
{
get { return parameters.Version; }
set { parameters.Version = value; }
}
[Parameter(HelpMessage = "Gets or sets the size of the Head Node.")]
public string HeadNodeSize
{
get { return parameters.HeadNodeSize; }
set { parameters.HeadNodeSize = value; }
}
[Parameter(HelpMessage = "Gets or sets the size of the Data Node.")]
public string WorkerNodeSize
{
get { return parameters.WorkerNodeSize; }
set { parameters.WorkerNodeSize = value; }
}
[Parameter(HelpMessage = "Gets or sets the size of the Edge Node if available for the cluster type.")]
public string EdgeNodeSize
{
get { return parameters.EdgeNodeSize; }
set { parameters.EdgeNodeSize = value; }
}
[Parameter(HelpMessage = "Gets or sets the size of the Zookeeper Node.")]
public string ZookeeperNodeSize
{
get { return parameters.ZookeeperNodeSize; }
set { parameters.ZookeeperNodeSize = value; }
}
[Parameter(HelpMessage = "Gets or sets the flavor for a cluster.")]
public string ClusterType
{
get { return parameters.ClusterType; }
set { parameters.ClusterType = value; }
}
[Parameter(HelpMessage = "Gets or sets the version for a service in the cluster.")]
public Dictionary<string, string> ComponentVersion { get; set; }
[Parameter(HelpMessage = "Gets or sets the virtual network guid for this HDInsight cluster.")]
public string VirtualNetworkId
{
get { return parameters.VirtualNetworkId; }
set { parameters.VirtualNetworkId = value; }
}
[Parameter(HelpMessage = "Gets or sets the subnet name for this HDInsight cluster.")]
public string SubnetName
{
get { return parameters.SubnetName; }
set { parameters.SubnetName = value; }
}
[Parameter(HelpMessage = "Gets or sets the type of operating system installed on cluster nodes.")]
public OSType OSType
{
get { return _osType ?? OSType.Linux; }
set { _osType = value; }
}
[Parameter(HelpMessage = "Gets or sets the cluster tier for this HDInsight cluster.")]
public Tier ClusterTier
{
get { return parameters.ClusterTier; }
set { parameters.ClusterTier = value; }
}
[Parameter(HelpMessage = "Gets or sets SSH credential.")]
public PSCredential SshCredential { get; set; }
[Parameter(HelpMessage = "Gets or sets the public key to be used for SSH.")]
public string SshPublicKey { get; set; }
[Parameter(HelpMessage = "Gets or sets the credential for RDP access to the cluster.")]
public PSCredential RdpCredential { get; set; }
[Parameter(HelpMessage = "Gets or sets the expiry DateTime for RDP access on the cluster.")]
public DateTime RdpAccessExpiry
{
get { return parameters.RdpAccessExpiry; }
set { parameters.RdpAccessExpiry = value; }
}
[Parameter(HelpMessage = "Gets or sets the Service Principal Object Id for accessing Azure Data Lake.")]
public Guid ObjectId { get; set; }
[Parameter(HelpMessage = "Gets or sets the Service Principal Application Id for accessing Azure Data Lake.")]
public Guid ApplicationId { get; set; }
[Parameter(HelpMessage = "Gets or sets the Service Principal Certificate file path for accessing Azure Data Lake.",
ParameterSetName = CertificateFilePathSet)]
public string CertificateFilePath { get; set; }
[Parameter(HelpMessage = "Gets or sets the Service Principal Certificate file contents for accessing Azure Data Lake.",
ParameterSetName = CertificateFileContentsSet)]
public byte[] CertificateFileContents { get; set; }
[Parameter(HelpMessage = "Gets or sets the Service Principal Certificate Password for accessing Azure Data Lake.")]
public string CertificatePassword { get; set; }
[Parameter(HelpMessage = "Gets or sets the Service Principal AAD Tenant Id for accessing Azure Data Lake.")]
public Guid AadTenantId { get; set; }
[Parameter(HelpMessage = "Gets or sets Security Profile which is used for creating secure cluster.")]
public AzureHDInsightSecurityProfile SecurityProfile { get; set; }
[Parameter(HelpMessage = "Gets or sets the number of disks for worker node role in the cluster.")]
public int DisksPerWorkerNode { get; set; }
[Parameter(HelpMessage = "Gets or sets the minimal supported TLS version.")]
public string MinSupportedTlsVersion { get; set; }
[Parameter(HelpMessage = "Gets or sets the assigned identity.")]
public string AssignedIdentity { get; set; }
[Parameter(HelpMessage = "Gets or sets the encryption algorithm.")]
[ValidateSet(JsonWebKeyEncryptionAlgorithm.RSAOAEP, JsonWebKeyEncryptionAlgorithm.RSAOAEP256, JsonWebKeyEncryptionAlgorithm.RSA15)]
public string EncryptionAlgorithm { get; set; }
[Parameter(HelpMessage = "Gets or sets the encryption key name.")]
public string EncryptionKeyName { get; set; }
[Parameter(HelpMessage = "Gets or sets the encryption key version.")]
public string EncryptionKeyVersion { get; set; }
[Parameter(HelpMessage = "Gets or sets the encryption vault uri.")]
public string EncryptionVaultUri { get; set; }
[CmdletParameterBreakingChange("PublicNetworkAccessType", ChangeDescription = "This parameter is being deprecated.")]
[Parameter(HelpMessage = "Gets or sets the public network access type.")]
[ValidateSet(PublicNetworkAccess.InboundAndOutbound, PublicNetworkAccess.OutboundOnly, IgnoreCase = true)]
public string PublicNetworkAccessType { get; set; }
[CmdletParameterBreakingChange("OutboundPublicNetworkAccessType", ChangeDescription = "This parameter is being deprecated.")]
[Parameter(HelpMessage = "Gets or sets the outbound access type to the public network.")]
[ValidateSet(OutboundOnlyPublicNetworkAccessType.PublicLoadBalancer, OutboundOnlyPublicNetworkAccessType.UDR, IgnoreCase = true)]
public string OutboundPublicNetworkAccessType { get; set; }
[Parameter(HelpMessage = "Gets or sets the flag which indicates whether enable encryption in transit or not.")]
public bool? EncryptionInTransit { get; set; }
[Parameter(HelpMessage = "Gets or sets the flag which indicates whether enable encryption at host or not.")]
public bool? EncryptionAtHost { get; set; }
[Parameter(HelpMessage = "Gets or sets the autoscale configuration")]
public AzureHDInsightAutoscale AutoscaleConfiguration { get; set; }
#endregion
public NewAzureHDInsightClusterCommand()
{
parameters = new ClusterCreateParameters();
AdditionalStorageAccounts = new Dictionary<string, string>();
Configurations = new Dictionary<string, Dictionary<string, string>>();
ScriptActions = new Dictionary<ClusterNodeType, List<AzureHDInsightScriptAction>>();
ComponentVersion = new Dictionary<string, string>();
}
public override void ExecuteCmdlet()
{
parameters.UserName = HttpCredential.UserName;
parameters.Password = HttpCredential.Password.ConvertToString();
if (RdpCredential != null)
{
parameters.RdpUsername = RdpCredential.UserName;
parameters.RdpPassword = RdpCredential.Password.ConvertToString();
}
if (SshCredential != null)
{
parameters.SshUserName = SshCredential.UserName;
if (!string.IsNullOrEmpty(SshCredential.Password.ConvertToString()))
{
parameters.SshPassword = SshCredential.Password.ConvertToString();
}
if (!string.IsNullOrEmpty(SshPublicKey))
{
parameters.SshPublicKey = SshPublicKey;
}
}
if (DefaultStorageAccountType==null || DefaultStorageAccountType == StorageType.AzureStorage)
{
parameters.DefaultStorageInfo = new AzureStorageInfo(DefaultStorageAccountName, DefaultStorageAccountKey, DefaultStorageContainer);
}
else
{
parameters.DefaultStorageInfo = new AzureDataLakeStoreInfo(DefaultStorageAccountName, DefaultStorageRootPath);
}
foreach (
var storageAccount in
AdditionalStorageAccounts.Where(
storageAccount => !parameters.AdditionalStorageAccounts.ContainsKey(storageAccount.Key)))
{
parameters.AdditionalStorageAccounts.Add(storageAccount.Key, storageAccount.Value);
}
foreach (var config in Configurations.Where(config => !parameters.Configurations.ContainsKey(config.Key)))
{
parameters.Configurations.Add(config.Key, config.Value);
}
foreach (var action in ScriptActions.Where(action => parameters.ScriptActions.ContainsKey(action.Key)))
{
parameters.ScriptActions.Add(action.Key,
action.Value.Select(a => a.GetScriptActionFromPSModel()).ToList());
}
foreach (var component in ComponentVersion.Where(component => !parameters.ComponentVersion.ContainsKey(component.Key)))
{
parameters.ComponentVersion.Add(component.Key, component.Value);
}
if (OozieMetastore != null)
{
var metastore = OozieMetastore;
parameters.OozieMetastore = new Metastore(metastore.SqlAzureServerName, metastore.DatabaseName, metastore.Credential.UserName, metastore.Credential.Password.ConvertToString());
}
if (HiveMetastore != null)
{
var metastore = HiveMetastore;
parameters.HiveMetastore = new Metastore(metastore.SqlAzureServerName, metastore.DatabaseName, metastore.Credential.UserName, metastore.Credential.Password.ConvertToString());
}
if (!string.IsNullOrEmpty(CertificatePassword))
{
if (!string.IsNullOrEmpty(CertificateFilePath))
{
CertificateFileContents = File.ReadAllBytes(CertificateFilePath);
}
var servicePrincipal = new Management.HDInsight.Models.ServicePrincipal(
GetApplicationId(ApplicationId), GetTenantId(AadTenantId), CertificateFileContents,
CertificatePassword);
parameters.Principal = servicePrincipal;
}
if (SecurityProfile != null)
{
parameters.SecurityProfile = new SecurityProfile()
{
DirectoryType = DirectoryType.ActiveDirectory,
Domain = SecurityProfile.Domain,
DomainUsername =
SecurityProfile.DomainUserCredential != null
? SecurityProfile.DomainUserCredential.UserName
: null,
DomainUserPassword =
SecurityProfile.DomainUserCredential != null &&
SecurityProfile.DomainUserCredential.Password != null
? SecurityProfile.DomainUserCredential.Password.ConvertToString()
: null,
OrganizationalUnitDN = SecurityProfile.OrganizationalUnitDN,
LdapsUrls = SecurityProfile.LdapsUrls,
ClusterUsersGroupDNs = SecurityProfile.ClusterUsersGroupDNs
};
}
if (DisksPerWorkerNode > 0)
{
parameters.WorkerNodeDataDisksGroups = new List<DataDisksGroups>()
{
new DataDisksGroups()
{
DisksPerNode = DisksPerWorkerNode
}
};
}
if (EncryptionKeyName != null && EncryptionKeyVersion != null && EncryptionVaultUri !=null && AssignedIdentity != null)
{
parameters.ClusterIdentity = new ClusterIdentity
{
Type = ResourceIdentityType.UserAssigned,
UserAssignedIdentities = new Dictionary<string, ClusterIdentityUserAssignedIdentitiesValue>
{
{ AssignedIdentity, new ClusterIdentityUserAssignedIdentitiesValue() }
}
};
parameters.DiskEncryptionProperties = new DiskEncryptionProperties()
{
KeyName = EncryptionKeyName,
KeyVersion = EncryptionKeyVersion,
VaultUri = EncryptionVaultUri,
EncryptionAlgorithm = EncryptionAlgorithm != null ? EncryptionAlgorithm : JsonWebKeyEncryptionAlgorithm.RSAOAEP,
MsiResourceId = AssignedIdentity
};
}
if (EncryptionAtHost != null)
{
if (parameters.DiskEncryptionProperties != null)
{
parameters.DiskEncryptionProperties.EncryptionAtHost = EncryptionAtHost;
}
else
{
parameters.DiskEncryptionProperties = new DiskEncryptionProperties()
{
EncryptionAtHost = EncryptionAtHost
};
}
}
Autoscale autoscaleParameter = null;
if (AutoscaleConfiguration != null)
{
autoscaleParameter = AutoscaleConfiguration.ToAutoscale();
}
var cluster = HDInsightManagementClient.CreateNewCluster(ResourceGroupName, ClusterName, OSType, parameters, MinSupportedTlsVersion, this.DefaultContext.Environment.ActiveDirectoryAuthority, this.DefaultContext.Environment.DataLakeEndpointResourceId, PublicNetworkAccessType, OutboundPublicNetworkAccessType, EncryptionInTransit, autoscaleParameter);
if (cluster != null)
{
WriteObject(new AzureHDInsightCluster(cluster));
}
}
private static Hashtable DictionaryToHashtable(Dictionary<string, string> dictionary)
{
return new Hashtable(dictionary);
}
private static Dictionary<string, string> HashtableToDictionary(Hashtable table)
{
return table
.Cast<DictionaryEntry>()
.ToDictionary(kvp => (string)kvp.Key, kvp => (string)kvp.Value);
}
//Get TenantId for the subscription if user doesn't provide this parameter
private Guid GetTenantId(Guid tenantId)
{
if (tenantId != Guid.Empty)
{
return tenantId;
}
var tenantIdStr = DefaultProfile.DefaultContext.Subscription.GetPropertyAsArray(AzureSubscription.Property.Tenants).FirstOrDefault();
return new Guid(tenantIdStr);
}
//Get ApplicationId of Service Principal if user doesn't provide this parameter
private Guid GetApplicationId(Guid applicationId)
{
if (applicationId != Guid.Empty)
{
return applicationId;
}
GraphRbacManagementClient graphClient = AzureSession.Instance.ClientFactory.CreateArmClient<GraphRbacManagementClient>(
DefaultProfile.DefaultContext, AzureEnvironment.Endpoint.Graph);
graphClient.TenantID = DefaultProfile.DefaultContext.Tenant.Id.ToString();
Microsoft.Azure.Graph.RBAC.Version1_6.Models.ServicePrincipal sp=null;
try
{
sp = graphClient.ServicePrincipals.Get(ObjectId.ToString());
}
catch(Microsoft.Azure.Graph.RBAC.Version1_6.Models.GraphErrorException e)
{
string errorMessage = e.Message + ". Please specify Application Id explicitly by providing ApplicationId parameter and retry.";
throw new Microsoft.Azure.Graph.RBAC.Version1_6.Models.GraphErrorException(errorMessage);
}
var spApplicationId = Guid.Empty;
Guid.TryParse(sp.AppId, out spApplicationId);
Debug.Assert(spApplicationId != Guid.Empty);
return spApplicationId;
}
}
}
| 48.458787 | 363 | 0.610161 | [
"MIT"
] | DaeunYim/azure-powershell | src/HDInsight/HDInsight/ManagementCommands/NewAzureHDInsightClusterCommand.cs | 30,519 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
namespace NavigationProperties.Areas.Identity.Pages
{
[AllowAnonymous]
public class ErrorModel : PageModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
} | 28.615385 | 92 | 0.721774 | [
"MIT"
] | lhendinha/NavigationProperties---ASP.NET-Core-2.1.300 | NavigationProperties/Areas/Identity/Pages/Error.cshtml.cs | 746 | C# |
using BenchmarkDotNet.Attributes;
using EnumStringValues;
namespace StringyEnums.Benchmarks
{
[MemoryDiagnoser]
[Config(typeof(NoOptimizationConfig))]
public class EnumStringValuesExtensionBenchmark
{
[GlobalSetup]
public void Setup()
{
EnumStringValues.EnumExtensions.Behaviour.UseCaching = true;
BenchmarkEnum.Val5.GetStringValue();
"Value 5".ParseToEnum<BenchmarkEnum>();
}
[Benchmark]
public string GetStringValue()
=> BenchmarkEnum.Val5.GetStringValue();
[Benchmark]
public BenchmarkEnum ParseToEnum()
=> "Value 5".ParseToEnum<BenchmarkEnum>();
}
}
| 21.25 | 63 | 0.754622 | [
"MIT"
] | TwentyFourMinutes/StringyEnums | src/StringyEnums/StringyEnums.Benchmarks/Benchmarks/EnumStringValuesExtensionBenchmark.cs | 597 | C# |
//
// Auto-generated from generator.cs, do not edit
//
// We keep references to objects, so warning 414 is expected
#pragma warning disable 414
using System;
using System.Drawing;
using System.Diagnostics;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
using UIKit;
using GLKit;
using Metal;
using CoreML;
using MapKit;
using Photos;
using ModelIO;
using Network;
using SceneKit;
using Contacts;
using Security;
using Messages;
using AudioUnit;
using CoreVideo;
using CoreMedia;
using QuickLook;
using CoreImage;
using SpriteKit;
using Foundation;
using CoreMotion;
using ObjCRuntime;
using AddressBook;
using MediaPlayer;
using GameplayKit;
using CoreGraphics;
using CoreLocation;
using AVFoundation;
using NewsstandKit;
using FileProvider;
using CoreAnimation;
using CoreFoundation;
using NetworkExtension;
#nullable enable
namespace CleverTapSDK {
[Register("CTInAppResources", true)]
public unsafe partial class CTInAppResources : NSObject {
[BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)]
static readonly IntPtr class_ptr = Class.GetHandle ("CTInAppResources");
public override IntPtr ClassHandle { get { return class_ptr; } }
[BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)]
[EditorBrowsable (EditorBrowsableState.Advanced)]
[Export ("init")]
public CTInAppResources () : base (NSObjectFlag.Empty)
{
IsDirectBinding = GetType ().Assembly == global::ApiDefinition.Messaging.this_assembly;
if (IsDirectBinding) {
InitializeHandle (global::ApiDefinition.Messaging.IntPtr_objc_msgSend (this.Handle, global::ObjCRuntime.Selector.GetHandle ("init")), "init");
} else {
InitializeHandle (global::ApiDefinition.Messaging.IntPtr_objc_msgSendSuper (this.SuperHandle, global::ObjCRuntime.Selector.GetHandle ("init")), "init");
}
}
[BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)]
[EditorBrowsable (EditorBrowsableState.Advanced)]
protected CTInAppResources (NSObjectFlag t) : base (t)
{
IsDirectBinding = GetType ().Assembly == global::ApiDefinition.Messaging.this_assembly;
}
[BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)]
[EditorBrowsable (EditorBrowsableState.Advanced)]
protected internal CTInAppResources (IntPtr handle) : base (handle)
{
IsDirectBinding = GetType ().Assembly == global::ApiDefinition.Messaging.this_assembly;
}
[Export ("imageForName:type:")]
[BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)]
public static global::UIKit.UIImage ImageForName (string name, string type)
{
if (name == null)
ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (name));
if (type == null)
ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (type));
var nsname = NSString.CreateNative (name);
var nstype = NSString.CreateNative (type);
global::UIKit.UIImage ret;
ret = Runtime.GetNSObject<global::UIKit.UIImage> (global::ApiDefinition.Messaging.IntPtr_objc_msgSend_IntPtr_IntPtr (class_ptr, Selector.GetHandle ("imageForName:type:"), nsname, nstype));
NSString.ReleaseNative (nsname);
NSString.ReleaseNative (nstype);
return ret!;
}
[Export ("XibNameForControllerName:")]
[BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)]
public static string XibNameForControllerName (string controllerName)
{
if (controllerName == null)
ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (controllerName));
var nscontrollerName = NSString.CreateNative (controllerName);
string ret;
ret = NSString.FromHandle (global::ApiDefinition.Messaging.IntPtr_objc_msgSend_IntPtr (class_ptr, Selector.GetHandle ("XibNameForControllerName:"), nscontrollerName));
NSString.ReleaseNative (nscontrollerName);
return ret!;
}
[BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)]
public static NSBundle Bundle {
[Export ("bundle")]
get {
NSBundle ret;
ret = Runtime.GetNSObject<NSBundle> (global::ApiDefinition.Messaging.IntPtr_objc_msgSend (class_ptr, Selector.GetHandle ("bundle")));
return ret!;
}
}
[BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)]
public static global::UIKit.UIApplication SharedApplication {
[Export ("getSharedApplication")]
get {
global::UIKit.UIApplication ret;
ret = Runtime.GetNSObject<global::UIKit.UIApplication> (global::ApiDefinition.Messaging.IntPtr_objc_msgSend (class_ptr, Selector.GetHandle ("getSharedApplication")));
return ret!;
}
}
} /* class CTInAppResources */
}
| 33.277778 | 192 | 0.766903 | [
"MIT"
] | CleverTap/clevertap-xamarin | clevertap-component/src/ios/CleverTap.Bindings.iOS/obj/Debug/iOS/CleverTapSDK/CTInAppResources.g.cs | 4,792 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using System.Reflection;
#pragma warning disable 659 // overrides AddToHashCodeCombiner instead
namespace EZNEW.Expressions
{
// BinaryExpression fingerprint class
// Useful for things like array[index]
[SuppressMessage("Microsoft.Usage", "CA2218:OverrideGetHashCodeOnOverridingEquals", Justification = "Overrides AddToHashCodeCombiner() instead.")]
public sealed class BinaryExpressionFingerprint : ExpressionFingerprint
{
public BinaryExpressionFingerprint(ExpressionType nodeType, Type type, MethodInfo method)
: base(nodeType, type)
{
// Other properties on BinaryExpression (like IsLifted / IsLiftedToNull) are simply derived
// from Type and NodeType, so they're not necessary for inclusion in the fingerprint.
Method = method;
}
// http://msdn.microsoft.com/en-us/library/system.linq.expressions.binaryexpression.method.aspx
public MethodInfo Method { get; private set; }
public override bool Equals(object obj)
{
BinaryExpressionFingerprint other = obj as BinaryExpressionFingerprint;
return (other != null)
&& Equals(this.Method, other.Method)
&& this.Equals(other);
}
internal override void AddToHashCodeCombiner(HashCodeCombiner combiner)
{
combiner.AddObject(Method);
base.AddToHashCodeCombiner(combiner);
}
}
}
| 38.666667 | 151 | 0.67069 | [
"MIT"
] | eznew-net/EZNEW.Develop | EZNEW/Expressions/BinaryExpressionFingerprint.cs | 1,742 | C# |
// Copyright 2017 the original author or 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Microsoft.Extensions.Options;
using Steeltoe.Common.HealthChecks;
using Steeltoe.Management.Endpoint.Test;
using System;
using System.Collections.Generic;
using Xunit;
namespace Steeltoe.Management.Endpoint.Health.Test
{
public class HealthEndpointTest : BaseTest
{
[Fact]
public void Constructor_ThrowsOptionsNull()
{
Assert.Throws<ArgumentNullException>(() => new HealthEndpointCore(null, null, null, null, null));
Assert.Throws<ArgumentNullException>(() => new HealthEndpointCore(new HealthEndpointOptions(), null, null, null, null));
Assert.Throws<ArgumentNullException>(() => new HealthEndpointCore(new HealthEndpointOptions(), new HealthRegistrationsAggregator(), null, null, null));
Assert.Throws<ArgumentNullException>(() => new HealthEndpointCore(new HealthEndpointOptions(), new HealthRegistrationsAggregator(), new List<IHealthContributor>(), null, null));
var svcOptions = default(IOptionsMonitor<Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckServiceOptions>);
Assert.Throws<ArgumentNullException>(() => new HealthEndpointCore(new HealthEndpointOptions(), new HealthRegistrationsAggregator(), new List<IHealthContributor>(), svcOptions, null));
}
}
}
| 50.105263 | 195 | 0.741597 | [
"Apache-2.0"
] | FrancisChung/steeltoe | src/Management/test/EndpointCore.Test/Health/HealthEndpointTest.cs | 1,906 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNet.Facebook.Models;
using Microsoft.AspNet.Facebook.Realtime;
using Microsoft.TestCommon;
namespace Microsoft.AspNet.Facebook.Test
{
public class FacebookRealtimeControllerTest
{
private const string AppSignatureHeader1 = "sha1=dbb5c0bfaac69ffee7b633e88d85e107fba7ecca";
private const string AppSecret1 = "f8ad79c0081a80bb885e2b280c3f8442";
private const string AppSignatureHeader2 = "sha1=3ee3a233ca0c872cae6b40d38a99dff26bf8eb27";
private const string AppSecret2 = "134cfa3691d1f51c64e70700f397ed20";
private const string ContentString = "{\"object\":\"user\",\"entry\":[{\"uid\":\"17825901\",\"id\":\"17825901\",\"time\":1352251746,\"changed_fields\":[\"likes\"]}]}";
[Fact]
public void Overriding_VerificationToken()
{
var userRealTimeController = new UserRealtimeCallbackController();
Assert.Equal(null, userRealTimeController.VerifyToken);
userRealTimeController = new UserRealtimeCallbackController(null, "foo");
Assert.Equal("foo", userRealTimeController.VerifyToken);
userRealTimeController = new UserRealtimeCallbackController(null, String.Empty);
Assert.Equal(String.Empty, userRealTimeController.VerifyToken);
}
[Theory]
[InlineData("123456", "foo")]
[InlineData("654321", "bar")]
public void Get_ReturnsOk_WithValidParameters(string challenge, string verifyToken)
{
var userRealTimeController = new UserRealtimeCallbackController(null, verifyToken);
userRealTimeController.Request = new HttpRequestMessage();
var subscriptionVerification = new SubscriptionVerification
{
Challenge = challenge,
Mode = "subscribe",
Verify_Token = verifyToken
};
Assert.Equal(challenge, userRealTimeController.Get(subscriptionVerification).Content.ReadAsStringAsync().Result);
}
[Theory]
[InlineData(null, "foo", HttpStatusCode.BadRequest)]
[InlineData("654321", null, HttpStatusCode.BadRequest)]
[InlineData("654321", "", HttpStatusCode.BadRequest)]
[InlineData("", "bar", HttpStatusCode.BadRequest)]
[InlineData("654321", "bar", HttpStatusCode.OK)]
public void Get_ReturnsExpectedStatusCode(string challenge, string verifyToken, HttpStatusCode expectedStatusCode)
{
var userRealTimeController = new UserRealtimeCallbackController(null, verifyToken);
userRealTimeController.Request = new HttpRequestMessage();
var subscriptionVerification = new SubscriptionVerification
{
Challenge = challenge,
Mode = "subscribe",
Verify_Token = "bar"
};
Assert.Equal(expectedStatusCode, userRealTimeController.Get(subscriptionVerification).StatusCode);
}
[Theory]
[InlineData(ContentString, AppSignatureHeader1, AppSecret1)]
[InlineData(ContentString, AppSignatureHeader2, AppSecret2)]
public void Post_ReturnsOk_WithValidParameters(string contentString, string headerValue, string appSecret)
{
var userRealTimeController = new UserRealtimeCallbackController(appSecret, null);
userRealTimeController.Request = new HttpRequestMessage
{
Content = new StringContent(contentString, Encoding.UTF8, "text/json")
};
var request = userRealTimeController.Request;
request.Headers.Add("X-Hub-Signature", headerValue);
Assert.Equal(HttpStatusCode.OK, userRealTimeController.Post().Result.StatusCode);
}
[Theory]
[InlineData(ContentString, AppSignatureHeader1, AppSecret2)]
[InlineData(ContentString, AppSignatureHeader2, AppSecret1)]
[InlineData(ContentString, null, AppSecret2)]
[InlineData(ContentString, AppSignatureHeader1, null)]
public void Post_ReturnsBadRequest_WithInValidParameters(string contentString, string headerValue, string AppSecret)
{
var userRealTimeController = new UserRealtimeCallbackController(AppSecret, null);
userRealTimeController.Request = new HttpRequestMessage
{
Content = new StringContent(contentString, Encoding.UTF8, "text/json")
};
var request = userRealTimeController.Request;
if (headerValue != null)
{
request.Headers.Add("X-Hub-Signature", headerValue);
}
Assert.Equal(HttpStatusCode.BadRequest, userRealTimeController.Post().Result.StatusCode);
}
private sealed class UserRealtimeCallbackController : FacebookRealtimeUpdateController
{
private string _verifyToken;
public UserRealtimeCallbackController() : this(null, null) { }
public UserRealtimeCallbackController(string appSecret, string verifyToken)
{
FacebookConfiguration.AppSecret = appSecret;
_verifyToken = verifyToken;
}
public override string VerifyToken
{
get
{
return _verifyToken;
}
}
public override Task HandleUpdateAsync(ChangeNotification notification)
{
return Task.FromResult(0);
}
}
}
}
| 43.787879 | 175 | 0.655709 | [
"Apache-2.0"
] | Darth-Fx/AspNetMvcStack | test/Microsoft.AspNet.Facebook.Test/FacebookRealtimeControllerTest.cs | 5,782 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace CAESAR.Chess.Helpers
{
/// <summary>
/// Extensions for <seealso cref="IEnumerable{T}" />
/// </summary>
public static class LinqExtensions
{
/// <summary>
/// A random number generator
/// </summary>
private static readonly Random _random = new Random();
/// <summary>
/// Takes the <seealso cref="IEnumerable{TSource}" />, as long as a while condition is met, until a specified condition
/// is satisfied.
/// </summary>
/// <typeparam name="TSource">The type of item in the <seealso cref="IEnumerable{TSource}" />.</typeparam>
/// <param name="list">The <seealso cref="IEnumerable{TSource}" /> of items from which to take.</param>
/// <param name="whilePredicate">The while condition.</param>
/// <param name="untilPredicate">The until condition./</param>
/// <returns></returns>
public static IEnumerable<TSource> TakeWhileUntil<TSource>(this IEnumerable<TSource> list,
Func<TSource, bool> whilePredicate, Func<TSource, bool> untilPredicate)
{
foreach (var item in list)
{
var currentItem = item;
if (whilePredicate(item) || untilPredicate(item))
yield return item;
if (!whilePredicate(currentItem) && untilPredicate(currentItem))
yield break;
}
}
/// <summary>
/// Selects a random element from an <seealso cref="IEnumerable{TSource}" />, with an optional condition.
/// </summary>
/// <typeparam name="TSource">The type of items in the <seealso cref="IEnumerable{TSource}" />.</typeparam>
/// <param name="source">The <seealso cref="IEnumerable{TSource}" /> of items from which to select a random element.</param>
/// <param name="whilePredicate">The optional where condition with which to select the random element.</param>
/// <returns>
/// A random <seealso cref="TSource" /> from the <seealso cref="IEnumerable{TSource}" /> matching the
/// <seealso cref="whilePredicate" />.
/// </returns>
public static TSource Random<TSource>(this IEnumerable<TSource> source,
Func<TSource, bool> whilePredicate = null)
{
whilePredicate = whilePredicate ?? (x => true);
var list = source.Where(whilePredicate).ToList();
var count = list.Count;
var index = _random.Next(count);
return list[index];
}
/// <summary>
/// Selects a random element from an <seealso cref="IEnumerable{TSource}" />, with an optional condition. If no such
/// element is found, the default value of the <seealso cref="TSource" /> is returned.
/// </summary>
/// <typeparam name="TSource">The type of items in the <seealso cref="IEnumerable{TSource}" />.</typeparam>
/// <param name="source">The <seealso cref="IEnumerable{TSource}" /> of items from which to select a random element.</param>
/// <param name="whilePredicate">The optional where condition with which to select the random element.</param>
/// <returns>
/// A random <seealso cref="TSource" /> from the <seealso cref="IEnumerable{TSource}" /> matching the
/// <seealso cref="whilePredicate" />. If no such element is found, the default value of the <seealso cref="TSource" />
/// is returned.
/// </returns>
public static TSource RandomOrDefault<TSource>(this IEnumerable<TSource> source,
Func<TSource, bool> whilePredicate = null)
{
try
{
return source.Random(whilePredicate);
}
catch
{
return default(TSource);
}
}
}
} | 47.404762 | 132 | 0.585635 | [
"MIT"
] | artfuldev/CAESAR | src/CAESAR.Chess/Helpers/LinqExtensions.cs | 3,984 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using HarmonyLib;
using Overload;
using UnityEngine;
namespace GameMod {
// disable receiving server position on observer mode
[HarmonyPatch(typeof(Client), "ReconcileServerPlayerState")]
class MPObserverReconcile
{
static bool Prefix()
{
return !MPObserver.Enabled;
}
}
public static class MPObserver
{
public static bool Enabled;
public static Player ObservedPlayer = null;
public static bool ThirdPerson = false;
public static Vector3 SavedPosition = Vector3.zero;
public static Quaternion SavedRotation = Quaternion.identity;
public static Quaternion LastRotation = Quaternion.identity;
public static void Enable()
{
if (Enabled)
return;
Enabled = true;
PlayerShip.EnablePlayerLevelCollision(false);
ChunkManager.ForceActivateAll();
RenderSettings.skybox = null;
GameplayManager.m_use_segment_visibility = false;
GameManager.m_player_ship.c_camera.useOcclusionCulling = false;
if (GameplayManager.IsMultiplayer)
{
NetworkMatch.m_show_enemy_names = MatchShowEnemyNames.ALWAYS;
GameplayManager.AddHUDMessage("Observer mode - Use switch weapon to select player, fire missle for third person view");
}
else
{
GameManager.m_local_player.SetCheaterFlag(true);
foreach (var robot in RobotManager.m_master_robot_list)
if (robot != null && !robot.gameObject.activeSelf)
robot.gameObject.SetActive(true);
GameplayManager.AddHUDMessage("Observer mode enabled");
}
}
public static void SetPlayerVisibility(Player player, bool visible)
{
foreach (var child in player.c_player_ship.GetComponentsInChildren<MeshRenderer>())
{
child.enabled = visible;
}
}
public static void SetObservedPlayer(Player player)
{
if (ObservedPlayer == null)
{
SavedPosition = GameManager.m_player_ship.c_transform.position;
SavedRotation = GameManager.m_player_ship.c_transform.rotation;
}
else
{
SetPlayerVisibility(ObservedPlayer, true);
}
ObservedPlayer = player;
if (ObservedPlayer == null)
{
GameManager.m_player_ship.c_transform.position = SavedPosition;
GameManager.m_player_ship.c_transform.rotation = SavedRotation;
}
else
{
SetPlayerVisibility(ObservedPlayer, ThirdPerson);
}
GameManager.m_viewer.SetDamageEffects(-999);
}
public static void SwitchObservedPlayer(bool prev)
{
int playerNum = ObservedPlayer == null ? -1 : Overload.NetworkManager.m_Players.IndexOf(ObservedPlayer);
while (true)
{
playerNum += prev ? -1 : 1;
if (playerNum < -1)
{
playerNum = Overload.NetworkManager.m_Players.Count - 1;
}
else if (playerNum >= Overload.NetworkManager.m_Players.Count)
{
playerNum = -1;
}
if (playerNum == -1 || !Overload.NetworkManager.m_Players[playerNum].m_spectator)
{
break;
}
}
SetObservedPlayer(playerNum == -1 ? null : Overload.NetworkManager.m_Players[playerNum]);
}
}
// detect "observer" cheat code
[HarmonyPatch(typeof(PlayerShip))]
[HarmonyPatch("FrameUpdateReadKeysFromInput")]
class MPObserverReadKeys
{
private static string code = "observer";
private static int codeIdx = 0;
static void Prefix()
{
foreach (char c in Input.inputString)
{
if (code[codeIdx] == c)
if (++codeIdx < code.Length)
continue;
else if (!GameplayManager.IsMultiplayer)
MPObserver.Enable();
codeIdx = 0;
}
}
}
// disable observer mode on new game
[HarmonyPatch(typeof(GameplayManager), "CreateNewGame")]
class MPObserverReset
{
static void Prefix()
{
GameplayManager.m_use_segment_visibility = true;
MPObserver.Enabled = false;
MPObserver.ObservedPlayer = null;
MPObserver.ThirdPerson = false;
MPObserver.SavedPosition = Vector3.zero;
MPObserver.SavedRotation = Quaternion.identity;
MPObserver.LastRotation = Quaternion.identity;
if (GameManager.m_player_ship != null && GameManager.m_player_ship.c_camera != null)
GameManager.m_player_ship.c_camera.useOcclusionCulling = true;
}
}
// force robots active for (sp) observer mode
[HarmonyPatch(typeof(RobotManager), "ActivateRobot")]
class RobotActivatePatch
{
static void Prefix(ref bool force_active)
{
if (MPObserver.Enabled)
force_active = true;
}
}
// Don't do chunk/probe/light (de)activation for observer
[HarmonyPatch(typeof(RobotManager), "Update")]
class MPObserverChunks
{
static bool Prefix()
{
return !GameManager.m_local_player.m_spectator;
}
}
// Don't do light (de)activation for observer
[HarmonyPatch(typeof(ChunkManager), "UpdateLights")]
class MPObserverLights
{
static bool Prefix()
{
return !GameManager.m_local_player.m_spectator;
}
}
// Don't do light fade for observer
[HarmonyPatch(typeof(ChunkManager), "FadeLights")]
class MPObserverLightsFade
{
static bool Prefix()
{
return !GameManager.m_local_player.m_spectator;
}
}
// Modify level / settings for observer. Need to wait for OnMatchStart to be sure m_spectator is set
[HarmonyPatch(typeof(Client), "OnMatchStart")]
class MPObserverModifyLevel
{
static void Postfix()
{
//Debug.Log("OnMatchStart player " + GameManager.m_local_player.m_mp_name + " observer " + GameManager.m_local_player.m_spectator);
if (GameplayManager.IsDedicatedServer() || !GameManager.m_local_player.m_spectator)
return;
MPObserver.Enable();
}
}
[HarmonyPatch(typeof(Server), "AllConnectionsHavePlayerReadyForCountdown")]
class MPObserverSpawnPatch
{
static void Postfix(bool __result)
{
if (!__result)
return;
foreach (KeyValuePair<int, PlayerLobbyData> keyValuePair in NetworkMatch.m_players)
if (keyValuePair.Value.m_name.StartsWith("OBSERVER"))
{
Player player = Server.FindPlayerByConnectionId(keyValuePair.Value.m_id);
if (!player || player.m_spectator)
continue;
Debug.LogFormat("Enabling spectator for {0}", player.m_mp_name);
player.Networkm_spectator = true;
Debug.LogFormat("Enabled spectator for {0}", player.m_mp_name);
}
}
}
[HarmonyPatch(typeof(PlayerShip), "Update")]
class MPObserverFollowPlayer
{
static void Postfix(PlayerShip __instance)
{
if (MPObserver.Enabled && MPObserver.ObservedPlayer != null && __instance.isLocalPlayer)
{
var player = MPObserver.ObservedPlayer;
__instance.c_transform.position = (__instance.c_transform.position + player.transform.position) / 2;
if (player.c_player_ship.m_dead || player.c_player_ship.m_dying)
{
__instance.c_transform.position -= MPObserver.LastRotation * (Vector3.forward * 2);
__instance.c_transform.rotation = MPObserver.LastRotation;
MPObserver.SetPlayerVisibility(player, true);
}
else
{
MPObserver.LastRotation = __instance.c_transform.rotation = Quaternion.Lerp(__instance.c_transform.rotation, MPObserver.ObservedPlayer.transform.rotation, 0.5f);
if (MPObserver.ThirdPerson)
{
__instance.c_transform.position -= __instance.c_transform.rotation * new Vector3(0, -0.5f, 2f);
}
MPObserver.SetPlayerVisibility(player, MPObserver.ThirdPerson);
}
}
}
}
// Remove very slow turning with observer (spectator) mode
[HarmonyPatch(typeof(PlayerShip), "FixedUpdateProcessControlsInternal")]
class MPObserverFixedUpdateProcess
{
static bool Prefix(PlayerShip __instance)
{
return !(MPObserver.Enabled && MPObserver.ObservedPlayer != null);
}
static IEnumerable<CodeInstruction> Transpiler(ILGenerator ilGen, IEnumerable<CodeInstruction> instructions)
{
var playerShip_c_player_Field = AccessTools.Field(typeof(PlayerShip), "c_player");
var player_m_spectator_Field = AccessTools.Field(typeof(Player), "m_spectator");
int n = 0;
var codes = new List<CodeInstruction>(instructions);
for (var i = 0; i < codes.Count; i++)
{
if (n == 0 && codes[i].opcode == OpCodes.Callvirt && (codes[i].operand as MemberInfo).Name == "get_mass" &&
codes[i + 1].opcode == OpCodes.Mul)
{
Label l = ilGen.DefineLabel();
codes[i + 2].labels.Add(l);
var newCodes = new[] {
new CodeInstruction(OpCodes.Ldarg_0),
new CodeInstruction(OpCodes.Ldfld, playerShip_c_player_Field),
new CodeInstruction(OpCodes.Ldfld, player_m_spectator_Field),
new CodeInstruction(OpCodes.Brfalse, l),
new CodeInstruction(OpCodes.Ldc_R4, 2f),
new CodeInstruction(OpCodes.Mul) };
codes.InsertRange(i + 2, newCodes);
i += 2 + newCodes.Length - 1;
n++;
}
else if (codes[i].opcode == OpCodes.Ldfld && (codes[i].operand as FieldInfo).Name == "m_spectator" &&
codes[i + 1].opcode == OpCodes.Brfalse &&
i > 2 && codes[i - 1].opcode == OpCodes.Ldfld && codes[i - 2].opcode == OpCodes.Ldarg_0)
{
// codes[i].opcodes = OpCodes.Ldc_I4_0 doesn't work? (class still on stack?)
//codes[i] = new CodeInstruction(OpCodes.Ldc_I4_0);
codes[i - 2] = new CodeInstruction(OpCodes.Br, codes[i + 1].operand);
n++;
break;
}
}
Debug.Log("Patched FixedUpdateProcessControlsInternal n=" + n);
return codes;
}
}
// remove m_spectator check so it also receives fire messages
[HarmonyPatch(typeof(Server), "SendProjectileFiredToClients")]
class MPObserverFired
{
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> codes)
{
CodeInstruction last = null;
int state = 0; // 0 = before m_spectator, 1 = wait for brtrue, 2 = after brtrue
foreach (var code in codes)
{
if (state == 0 && code.opcode == OpCodes.Ldfld && (code.operand as FieldInfo).Name == "m_spectator")
{
last = null; // also remove previous Ldloc0
state = 1;
continue;
}
else if (state == 1)
{
if (code.opcode == OpCodes.Brtrue)
state = 2;
continue;
}
if (last != null)
yield return last;
last = code;
}
if (last != null)
yield return last;
}
}
[HarmonyPatch(typeof(Player), "CmdSendFullChat")]
class MPObserverChat
{
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> codes)
{
CodeInstruction last = null;
foreach (var c in codes)
{
// replace xxx.m_spectator with false
if (c.opcode == OpCodes.Ldfld && ((FieldInfo)c.operand).Name == "m_spectator")
{
last = new CodeInstruction(OpCodes.Ldc_I4_0);
continue;
}
if (last != null)
yield return last;
last = c;
}
yield return last;
}
}
// show parts of the hud in observer mode
[HarmonyPatch(typeof(UIElement), "DrawHUD")]
class MPObserverHUD
{
private static MethodInfo _UIElement_getAlphaEyeGaze_Method = typeof(UIElement).GetMethod("getAlphaEyeGaze", BindingFlags.NonPublic | BindingFlags.Instance);
static float getAlphaEyeGaze(UIElement uie, string pos)
{
return (float)_UIElement_getAlphaEyeGaze_Method.Invoke(uie, new object[] { pos });
}
private static MethodInfo _UIElement_DrawMpScoreboardRaw_Method = typeof(UIElement).GetMethod("DrawMpScoreboardRaw", BindingFlags.NonPublic | BindingFlags.Instance);
static void DrawMpScoreboardRaw(UIElement uie, Vector2 vector)
{
_UIElement_DrawMpScoreboardRaw_Method.Invoke(uie, new object[] { vector });
}
public static void DrawFullScreenEffects()
{
if (MPObserver.ObservedPlayer == null)
{
return;
}
PlayerShip player_ship = MPObserver.ObservedPlayer.c_player_ship;
Vector2 position;
position.x = 576f;
position.y = 576f;
if (UIManager.ui_bg_fade > 0f)
{
UIManager.DrawQuadUIInner(position, 15f, 15f, Color.black, UIManager.ui_bg_fade, 11, 0.8f);
if (!UIManager.ui_blocker_active && UIManager.ui_bg_fade >= 1f)
{
UIManager.ui_blocker_active = true;
GameManager.m_player_ship.c_bright_blocker_go.SetActive(true);
if (GameManager.m_mesh_container != null)
{
GameManager.m_mesh_container.SetActive(false);
}
}
}
if (UIManager.ui_blocker_active && UIManager.ui_bg_fade < 1f)
{
UIManager.ui_blocker_active = false;
GameManager.m_player_ship.c_bright_blocker_go.SetActive(false);
if (GameManager.m_mesh_container != null)
{
GameManager.m_mesh_container.SetActive(true);
}
}
position.x = -576f;
position.y = 576f;
if (GameplayManager.GamePaused)
{
UIManager.menu_flash_fade = Mathf.Max(0f, UIManager.menu_flash_fade - RUtility.FRAMETIME_UI * 2f);
}
else
{
UIManager.menu_flash_fade = Mathf.Min(1f, UIManager.menu_flash_fade + RUtility.FRAMETIME_UI * 4f);
}
if (UIManager.menu_flash_fade > 0f && (!player_ship.m_dying || player_ship.m_player_died_due_to_timer))
{
if (player_ship.m_damage_flash_slow > 0f)
{
float a = UIManager.menu_flash_fade * Mathf.Min(0.1f, player_ship.m_damage_flash_slow * 0.1f) + Mathf.Min(0.2f, player_ship.m_damage_flash_fast * 0.2f);
UIManager.DrawQuadUI(position, 15f, 15f, UIManager.m_col_damage, a, 11);
}
if (player_ship.m_pickup_flash > 0f)
{
float a2 = UIManager.menu_flash_fade * Mathf.Clamp01(player_ship.m_pickup_flash * player_ship.m_pickup_flash) * 0.25f;
UIManager.DrawQuadUI(position, 15f, 15f, UIManager.m_col_white, a2, 11);
}
if (player_ship.m_energy_flash > 0f)
{
float a3 = UIManager.menu_flash_fade * (player_ship.m_energy_flash - 0.2f) * (player_ship.m_energy_flash - 0.2f) * 0.15f;
UIManager.DrawQuadUI(position, 15f, 15f, UIManager.m_col_hi3, a3, 11);
}
}
}
static void Prefix(UIElement __instance)
{
if (!GameManager.m_local_player.m_spectator || !GameplayManager.ShowHud || Overload.NetworkManager.IsHeadless() ||
GameManager.m_local_player.m_pregame)
return;
var uie = __instance;
float alpha = uie.m_alpha;
uie.m_alpha *= UIElement.HUD_ALPHA;
uie.DrawMessages();
Vector2 vector;
if (!GameplayManager.ShowMpScoreboard)
{
vector.y = UIManager.UI_TOP + 70f;
vector.x = UIManager.UI_RIGHT - 20f;
uie.m_alpha = Mathf.Min(getAlphaEyeGaze(uie, "upperright"), uie.m_alpha);
//uie.DrawXPTotalSmall(vector);
vector.y += 26f;
vector.x -= 89f;
uie.DrawHUDScoreInfo(vector);
}
else
{
vector.y = -240f;
vector.x = 0f;
uie.DrawStringSmall(NetworkMatch.GetModeString(MatchMode.NUM), vector, 0.75f, StringOffset.CENTER, UIManager.m_col_ui5, 1f, -1f);
vector.y += 25f;
uie.DrawStringSmall(GameplayManager.Level.DisplayName, vector, 0.5f, StringOffset.CENTER, UIManager.m_col_ui1, 1f, -1f);
vector.y += 35f;
DrawMpScoreboardRaw(uie, vector);
}
uie.m_alpha = alpha;
if (MPObserver.ObservedPlayer == null)
{
return;
}
var player = MPObserver.ObservedPlayer;
var player_ship = player.c_player_ship;
vector.x = UIManager.UI_RIGHT - 270f;
vector.y = UIManager.UI_BOTTOM - 70f - 22f * 4;
if (MPModPrivateData.AssistScoring) {
vector.y += 22f;
}
uie.DrawStringSmall("NOW OBSERVING:", vector, 0.35f, StringOffset.LEFT, UIManager.m_col_hi3, uie.m_alpha, -1f);
vector.y += 22f;
uie.DrawStringSmall("KILLS:", vector, 0.35f, StringOffset.LEFT, UIManager.m_col_hi3, uie.m_alpha, -1f);
if (MPModPrivateData.AssistScoring) {
vector.y += 22f;
uie.DrawStringSmall("ASSISTS:", vector, 0.35f, StringOffset.LEFT, UIManager.m_col_hi3, uie.m_alpha, -1f);
}
vector.y += 22f;
uie.DrawStringSmall("DEATHS:", vector, 0.35f, StringOffset.LEFT, UIManager.m_col_hi3, uie.m_alpha, -1f);
vector.x = UIManager.UI_RIGHT - 20f;
vector.y = UIManager.UI_BOTTOM - 70f - 22f * 4;
uie.DrawStringSmall(player.m_mp_name, vector, 0.35f, StringOffset.RIGHT, UIManager.m_col_hi3, uie.m_alpha, -1f);
vector.y += 22f;
uie.DrawDigitsVariable(vector, player.m_kills, 0.4f, StringOffset.RIGHT, UIManager.m_col_hi3, uie.m_alpha);
vector.y += 22f;
uie.DrawDigitsVariable(vector, player.m_assists, 0.4f, StringOffset.RIGHT, UIManager.m_col_hi3, uie.m_alpha);
vector.y += 22f;
uie.DrawDigitsVariable(vector, player.m_deaths, 0.4f, StringOffset.RIGHT, UIManager.m_col_hi3, uie.m_alpha);
if (player_ship.c_player == MPObserver.ObservedPlayer && !MPObserver.ThirdPerson && !player_ship.m_dead && !player_ship.m_dying)
{
DrawFullScreenEffects();
}
}
}
// Handle input for observer mode. Note: Is there a better method to hook than this?
[HarmonyPatch(typeof(Controls), "UpdateKey")]
class MPObserverControlsUpdateKey
{
static bool Prefix(CCInput cc_type)
{
if (MPObserver.Enabled && GameplayManager.IsMultiplayerActive)
{
if (cc_type == CCInput.FIRE_FLARE)
{
return false;
}
}
return true;
}
static void Postfix(CCInput cc_type)
{
if (MPObserver.Enabled && GameplayManager.IsMultiplayerActive)
{
if (cc_type == CCInput.SWITCH_WEAPON && Controls.JustPressed(CCInput.SWITCH_WEAPON))
{
MPObserver.SwitchObservedPlayer(false);
}
if (cc_type == CCInput.PREV_WEAPON && Controls.JustPressed(CCInput.PREV_WEAPON))
{
MPObserver.SwitchObservedPlayer(true);
}
if (cc_type == CCInput.FIRE_WEAPON && Controls.JustPressed(CCInput.FIRE_WEAPON) && MPObserver.ObservedPlayer != null)
{
MPObserver.SetObservedPlayer(null);
}
if (cc_type == CCInput.FIRE_MISSILE && Controls.JustPressed(CCInput.FIRE_MISSILE) && MPObserver.ObservedPlayer != null)
{
MPObserver.ThirdPerson = !MPObserver.ThirdPerson;
MPObserver.SetPlayerVisibility(MPObserver.ObservedPlayer, MPObserver.ThirdPerson);
GameManager.m_viewer.SetDamageEffects(-999);
}
if (cc_type == CCInput.SWITCH_MISSILE && Controls.JustPressed(CCInput.SWITCH_MISSILE) && CTF.IsActive)
{
var player = (from f in CTF.PlayerHasFlag
join p in Overload.NetworkManager.m_Players on f.Key equals p.netId
where p.m_mp_team == MpTeam.TEAM0
select p).FirstOrDefault();
if (player == null)
{
GameplayManager.AddHUDMessage($"No {MPTeams.TeamName(MpTeam.TEAM0)} player is carrying a flag.");
}
else
{
MPObserver.SetObservedPlayer(player);
}
}
if (cc_type == CCInput.PREV_MISSILE && Controls.JustPressed(CCInput.PREV_MISSILE) && CTF.IsActive)
{
var player = (from f in CTF.PlayerHasFlag
join p in Overload.NetworkManager.m_Players on f.Key equals p.netId
where p.m_mp_team == MpTeam.TEAM1
select p).FirstOrDefault();
if (player == null)
{
GameplayManager.AddHUDMessage($"No {MPTeams.TeamName(MpTeam.TEAM1)} player is carrying a flag.");
}
else
{
MPObserver.SetObservedPlayer(player);
}
}
}
}
}
// Handle what happens when a player leaves.
[HarmonyPatch(typeof(NetworkManager), "RemovePlayer")]
class MPObserverNetworkManagerRemovePlayer {
static void Prefix(Player player)
{
if (player == MPObserver.ObservedPlayer)
{
MPObserver.SetObservedPlayer(null);
}
}
}
[HarmonyPatch(typeof(PlayerShip), "DrawEffectMesh")]
class MPObserverDisableEffectMeshForObservedPlayer
{
static bool Prefix(PlayerShip __instance)
{
return !(MPObserver.ObservedPlayer == __instance.c_player && !MPObserver.ThirdPerson && !__instance.m_dead && !__instance.m_dying);
}
}
[HarmonyPatch(typeof(PlayerShip), "RpcApplyDamage")]
class MPObserverSetDamageEffects
{
static void Postfix(PlayerShip __instance, float hitpoints, float damage, float damage_scaled, float damage_min)
{
if (MPObserver.ObservedPlayer == __instance.c_player && !MPObserver.ThirdPerson && !__instance.m_dead && !__instance.m_dying)
{
// NOTE: This appears to be a bug with the base game... __instance.c_player.m_hitpoints is the value AFTER the damage taken, but shouldn't this be the value BEFORE the damage taken?
float damageEffects = Mathf.Min(__instance.c_player.m_hitpoints, damage_scaled);
GameManager.m_viewer.SetDamageEffects(damageEffects);
}
}
}
// Support for display health bars above players
public class MPObserverDamageLog
{
public float dmg;
public float timer;
}
public static class MPObserverDamage
{
public static Dictionary<Player, List<MPObserverDamageLog>> playerDamages = new Dictionary<Player, List<MPObserverDamageLog>>();
public static void AddDamage(Player player, float dmg, float timer = 2f)
{
if (!MPObserverDamage.playerDamages.ContainsKey(player))
{
MPObserverDamage.playerDamages.Add(player, new List<MPObserverDamageLog> { new MPObserverDamageLog { dmg = dmg, timer = timer } });
}
else
{
MPObserverDamage.playerDamages[player].Add(new MPObserverDamageLog { dmg = dmg, timer = timer });
}
}
}
// Process damage log dropoffs
[HarmonyPatch(typeof(PlayerShip), "Update")]
class MPObserver_PlayerShip_Update
{
static void Postfix(PlayerShip __instance)
{
if (!MPObserver.Enabled)
return;
if (MPObserverDamage.playerDamages.ContainsKey(__instance.c_player))
{
foreach (var dmg in MPObserverDamage.playerDamages[__instance.c_player])
{
dmg.timer -= RUtility.FRAMETIME_UI;
}
MPObserverDamage.playerDamages[__instance.c_player].RemoveAll(x => x.timer < 0f);
}
}
}
// Display health bar above players
[HarmonyPatch(typeof(UIManager), "DrawMpPlayerName")]
class MPObserver_UIManager_DrawMpPlayerName
{
static void Postfix(Player player, Vector2 offset)
{
if (!MPObserver.Enabled)
return;
offset.y -= 3f;
Color c1 = Color.Lerp(HSBColor.ConvertToColor(0.4f, 0.85f, 0.1f), HSBColor.ConvertToColor(0.4f, 0.8f, 0.15f), UnityEngine.Random.value * UIElement.FLICKER);
Color c3 = Color.Lerp(player.m_mp_data.color, UIManager.m_col_white2, player.c_player_ship.m_damage_flash_fast);
float w = 3.5f;
float h = 1f;
UIManager.DrawStringAlignCenter(player.m_hitpoints.ToString("n1"), offset + Vector2.up * -3f, 0.8f, c3);
UIManager.DrawQuadBarHorizontal(offset, w+0.25f, h+0.25f, 0f, HSBColor.ConvertToColor(0.4f, 0.1f, 0.1f), 7);
float health = System.Math.Min(player.m_hitpoints, 100f) / 100f * w;
offset.x = w - health;
UIManager.DrawQuadUIInner(offset, health, h, c1, 1f, 11, 1f);
if (MPObserverDamage.playerDamages.ContainsKey(player) && MPObserverDamage.playerDamages[player].Sum(x => x.dmg) > 0f)
{
float dmg = System.Math.Max(0, System.Math.Min(100f - health, MPObserverDamage.playerDamages[player].Sum(x => x.dmg) / 100 * w));
Color c2 = Color.Lerp(HSBColor.ConvertToColor(0f, 1f, 0.90f), HSBColor.ConvertToColor(0f, 0.9f, 1f), UnityEngine.Random.value * UIElement.FLICKER);
offset.x -= health + dmg;
UIManager.DrawQuadUIInner(offset, dmg, h, c2, 1f, 11, 1f);
}
}
}
// Add Observer damage record
[HarmonyPatch(typeof(PlayerShip), "RpcApplyDamage")]
class MPObserver_PlayerShip_RpcApplyDamage
{
static void Postfix(PlayerShip __instance, float hitpoints, float damage, float damage_scaled, float damage_min)
{
if (!MPObserver.Enabled)
return;
__instance.m_damage_flash_slow = 0f;
MPObserverDamage.AddDamage(__instance.c_player, damage_scaled);
}
}
}
| 40.324513 | 197 | 0.562187 | [
"MIT"
] | arbruijn/olmod-fork | GameMod/MPObserver.cs | 28,955 | C# |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Linq;
using Microsoft.Extensions.JsonParser.Sources;
namespace Microsoft.DotNet.ProjectModel.Files
{
public class PackIncludeEntry
{
public string Target { get; }
public string[] SourceGlobs { get; }
public int Line { get; }
public int Column { get; }
internal PackIncludeEntry(string target, JsonValue json)
: this(target, ExtractValues(json), json.Line, json.Column)
{
}
public PackIncludeEntry(string target, string[] sourceGlobs, int line, int column)
{
Target = target;
SourceGlobs = sourceGlobs;
Line = line;
Column = column;
}
private static string[] ExtractValues(JsonValue json)
{
var valueAsString = json as JsonString;
if (valueAsString != null)
{
return new string[] { valueAsString.Value };
}
var valueAsArray = json as JsonArray;
if(valueAsArray != null)
{
return valueAsArray.Values.Select(v => v.ToString()).ToArray();
}
return new string[0];
}
}
}
| 29.891304 | 101 | 0.578909 | [
"MIT"
] | BrennanConroy/cli | src/Microsoft.DotNet.ProjectModel/Files/PackIncludeEntry.cs | 1,377 | C# |
#region Apache License Version 2.0
/*----------------------------------------------------------------
Copyright 2022 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd.
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.
Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md
----------------------------------------------------------------*/
#endregion Apache License Version 2.0
/*----------------------------------------------------------------
Copyright (C) 2022 Senparc
文件名:DeactivateBusifavorCouponsReturnJson.cs
文件功能描述:使商家券失效返回Json类
创建标识:Senparc - 20210913
----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Senparc.Weixin.TenPayV3.Apis.Entities;
namespace Senparc.Weixin.TenPayV3.Apis.Marketing
{
/// <summary>
/// 使商家券失效返回Json类
/// <para>详细请参考微信支付官方文档 https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter9_2_13.shtml </para>
/// </summary>
public class DeactivateBusifavorCouponReturnJson : ReturnJsonBase
{
/// <summary>
/// 含参构造函数
/// </summary>
/// <param name="wechatpay_deactivate_time">券成功失效的时间 <para>系统券成功失效的时间,遵循rfc3339标准格式,格式为YYYY-MM-DDTHH:mm:ss+TIMEZONE,YYYY-MM-DD表示年月日,T出现在字符串中,表示time元素的开头,HH:mm:ss表示时分秒,TIMEZONE表示时区(+08:00表示东八区时间,领先UTC8小时,即北京时间)。例如:2015-05-20T13:29:35+08:00表示,北京时间2015年5月20日13点29分35秒。</para><para>示例值:2020-05-20T13:29:35.08:00</para></param>
public DeactivateBusifavorCouponReturnJson(string wechatpay_deactivate_time)
{
this.wechatpay_deactivate_time = wechatpay_deactivate_time;
}
/// <summary>
/// 无参构造函数
/// </summary>
public DeactivateBusifavorCouponReturnJson()
{
}
/// <summary>
/// 券成功失效的时间
/// <para>系统券成功失效的时间,遵循rfc3339标准格式,格式为YYYY-MM-DDTHH:mm:ss+TIMEZONE,YYYY-MM-DD表示年月日,T出现在字符串中,表示time元素的开头,HH:mm:ss表示时分秒,TIMEZONE表示时区(+08:00表示东八区时间,领先UTC 8小时,即北京时间)。例如:2015-05-20T13:29:35+08:00表示,北京时间2015年5月20日 13点29分35秒。 </para>
/// <para>示例值:2020-05-20T13:29:35.08:00</para>
/// </summary>
public string wechatpay_deactivate_time { get; set; }
}
}
| 37.671233 | 330 | 0.644 | [
"Apache-2.0"
] | AaronWu666/WeiXinMPSDK | src/Senparc.Weixin.TenPay/Senparc.Weixin.TenPayV3/Apis/Marketing/Entities/ReturnJson/DeactivateBusifavorCouponReturnJson.cs | 3,286 | C# |
/********************************************************************************
* WrapperTests.cs *
* *
* Author: Denes Solti *
********************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using NUnit.Framework;
namespace Solti.Utils.SQL.Tests
{
using Internals;
using Interfaces;
using Interfaces.DataAnnotations;
using Properties;
[TestFixture]
public sealed class WrapperTests
{
[OneTimeSetUp]
public void SetupFixture() => Config.Use(new DiscoveredDataTables(typeof(WrapperTests).Assembly));
[Test]
public void UnwrappedView_ShouldUnwrapSimpleViews()
{
Type unwrapped = UnwrappedView<View2>.Type;
typeof(View2)
.GetProperties()
.ForEach(prop =>
{
ColumnSelectionAttribute originalAttr = prop.GetCustomAttribute<ColumnSelectionAttribute>();
PropertyInfo queried = unwrapped.GetProperty(prop.Name);
if (originalAttr == null)
Assert.That(queried, Is.Null);
else
{
Assert.That(queried, Is.Not.Null);
Assert.That(queried.PropertyType, Is.EqualTo(prop.PropertyType));
ColumnSelectionAttribute queriedAttr = queried.GetCustomAttribute<ColumnSelectionAttribute>();
Assert.That(originalAttr.GetType(), Is.EqualTo(queriedAttr.GetType()));
originalAttr
.GetType()
.GetProperties()
.ForEach(p => Assert.That(p.FastGetValue(originalAttr), Is.EqualTo(p.FastGetValue(queriedAttr))));
}
});
}
[Test]
public void UnwrappedView_ShouldUnwrapSimpleViewsDescendingFromDataTable()
{
Type unwrapped = UnwrappedView<Extension1>.Type;
typeof(Extension1)
.GetProperties()
.ForEach(prop =>
{
PropertyInfo queried = unwrapped.GetProperty(prop.Name);
if (prop.GetCustomAttribute<IgnoreAttribute>() != null)
Assert.That(queried, Is.Null);
else
{
Assert.That(queried, Is.Not.Null);
Assert.That(queried.PropertyType, Is.EqualTo(prop.PropertyType));
ColumnSelectionAttribute
originalAttr = prop.GetCustomAttribute<ColumnSelectionAttribute>(),
queriedAttr = queried.GetCustomAttribute<ColumnSelectionAttribute>();
if (originalAttr == null)
{
Assert.That(queriedAttr.GetType(), Is.EqualTo(typeof(BelongsToAttribute)));
Assert.That(queriedAttr.OrmType, Is.EqualTo(typeof(Extension1).GetBaseDataTable()));
}
else
{
Assert.That(originalAttr.GetType(), Is.EqualTo(queriedAttr.GetType()));
originalAttr
.GetType()
.GetProperties()
.ForEach(p => Assert.That(p.FastGetValue(originalAttr), Is.EqualTo(p.FastGetValue(queriedAttr))));
}
}
});
}
[Test]
public void UnwrappedView_ShouldCache() => Assert.AreSame(UnwrappedView<View2>.Type, UnwrappedView<View2>.Type);
[TestCase(typeof(WrappedView1), nameof(WrappedView1.ViewList))]
[TestCase(typeof(WrappedView3), nameof(WrappedView3.View))]
public void UnwrappedView_ShouldUnwrapComplexViews(Type view, string wrappedProp)
{
Type unwrapped = (Type) typeof(UnwrappedView<>)
.MakeGenericType(view)
.GetProperty(nameof(UnwrappedView<object>.Type), BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)
.GetValue(null);
view
.GetColumnSelectionsDeep()
.ForEach(sel =>
{
ColumnSelectionAttribute originalAttr = sel.Reason;
PropertyInfo queried = unwrapped.GetProperty(sel.ViewProperty.Name);
if (originalAttr == null)
Assert.That(queried, Is.Null);
else
{
Assert.That(queried, Is.Not.Null);
Assert.That(queried.PropertyType, Is.EqualTo(sel.ViewProperty.PropertyType));
ColumnSelectionAttribute queriedAttr = queried.GetCustomAttribute<ColumnSelectionAttribute>();
Assert.That(originalAttr.GetType(), Is.EqualTo(queriedAttr.GetType()));
originalAttr
.GetType()
.GetProperties()
.ForEach(p => Assert.That(p.FastGetValue(originalAttr), Is.EqualTo(p.FastGetValue(queriedAttr))));
}
});
}
[Test]
public void UnwrappedView_ShouldUnwrapMoreComplexViewHavingMultipleWrappedProperties()
{
Type unwrapped = UnwrappedView<WrappedView2>.Type;
typeof(WrappedView2)
.GetProperties()
.Where(prop => prop.GetCustomAttribute<WrappedAttribute>() == null)
.Concat(typeof(WrappedView2).GetProperty(nameof(WrappedView2.ViewList)).PropertyType.GetGenericArguments().Single().GetProperties())
.Concat(typeof(WrappedView2).GetProperty(nameof(WrappedView2.ViewList2)).PropertyType.GetGenericArguments().Single().GetProperties())
.ForEach(prop =>
{
ColumnSelectionAttribute originalAttr = prop.GetCustomAttribute<ColumnSelectionAttribute>();
PropertyInfo queried = unwrapped.GetProperty(prop.Name);
if (originalAttr == null)
Assert.That(queried, Is.Null);
else
{
Assert.That(queried, Is.Not.Null);
Assert.That(queried.PropertyType, Is.EqualTo(prop.PropertyType));
ColumnSelectionAttribute queriedAttr = queried.GetCustomAttribute<ColumnSelectionAttribute>();
Assert.That(originalAttr.GetType(), Is.EqualTo(queriedAttr.GetType()));
originalAttr
.GetType()
.GetProperties()
.ForEach(p => Assert.That(p.FastGetValue(originalAttr), Is.EqualTo(p.FastGetValue(queriedAttr))));
}
});
}
[Test]
public void UnwrappedView_ShouldUnwrapViewsHavingWrappedPropertyWithTypeOfDataTableDescendant()
{
Type unwrapped = UnwrappedView<WrappedView3_Extesnion>.Type;
typeof(Extension1)
.GetProperties()
.Concat(typeof(WrappedView3_Extesnion).GetProperty(nameof(WrappedView3_Extesnion.ViewList)).PropertyType.GetGenericArguments().Single().GetProperties())
.ForEach(prop =>
{
PropertyInfo queried = unwrapped.GetProperty(prop.Name);
if (prop.GetCustomAttribute<IgnoreAttribute>() != null)
Assert.That(queried, Is.Null);
else
{
Assert.That(queried, Is.Not.Null);
Assert.That(queried.PropertyType, Is.EqualTo(prop.PropertyType));
ColumnSelectionAttribute
originalAttr = prop.GetCustomAttribute<ColumnSelectionAttribute>(),
queriedAttr = queried.GetCustomAttribute<ColumnSelectionAttribute>();
if (originalAttr == null)
{
Assert.That(queriedAttr.GetType(), Is.EqualTo(typeof(BelongsToAttribute)));
Assert.That(queriedAttr.OrmType, Is.EqualTo(typeof(Extension1).GetBaseDataTable()));
}
else
{
Assert.That(originalAttr.GetType(), Is.EqualTo(queriedAttr.GetType()));
originalAttr
.GetType()
.GetProperties()
.ForEach(p => Assert.That(p.FastGetValue(originalAttr), Is.EqualTo(p.FastGetValue(queriedAttr))));
}
}
});
}
[Test]
public void UnwrappedView_ShouldBeRecursive()
{
Type unwrapped = UnwrappedView<WrappedView4_Complex>.Type;
typeof(WrappedView4_Complex)
.GetProperties()
.Where(prop => prop.GetCustomAttribute<WrappedAttribute>() == null)
.Concat(typeof(WrappedView1).GetProperties().Where(prop => prop.GetCustomAttribute<WrappedAttribute>() == null))
.Concat(typeof(View3).GetProperties())
.ForEach(prop =>
{
ColumnSelectionAttribute originalAttr = prop.GetCustomAttribute<ColumnSelectionAttribute>();
PropertyInfo queried = unwrapped.GetProperty(prop.Name);
Assert.That(queried, Is.Not.Null);
Assert.That(queried.PropertyType, Is.EqualTo(prop.PropertyType));
ColumnSelectionAttribute queriedAttr = queried.GetCustomAttribute<ColumnSelectionAttribute>();
Assert.That(originalAttr.GetType(), Is.EqualTo(queriedAttr.GetType()));
originalAttr
.GetType()
.GetProperties()
.ForEach(p => Assert.That(p.FastGetValue(originalAttr), Is.EqualTo(p.FastGetValue(queriedAttr))));
});
}
[Test]
public void UnwrappedView_ShouldHandlePropertyNameCollisions()
{
Type unwrapped = null;
Assert.DoesNotThrow(() => unwrapped = UnwrappedView<CollidingWrappedView>.Type);
Assert.That(unwrapped.GetProperty("Id_0"), Is.Not.Null);
Assert.That(unwrapped.GetProperty("Id_0").GetCustomAttribute<MapToAttribute>()?.Property, Is.EqualTo("Solti.Utils.SQL.Tests.CollidingWrappedView.Id"));
Assert.That(unwrapped.GetProperty("Id_1"), Is.Not.Null);
Assert.That(unwrapped.GetProperty("Id_1").GetCustomAttribute<MapToAttribute>()?.Property, Is.EqualTo("Solti.Utils.SQL.Tests.View3.Id"));
}
[Test]
public void Wrapper_ShouldWorkWithViewsWithoutListProperty()
{
Type unwrapped = UnwrappedView<View3 /*Nincs benn lista tulajdonsag*/>.Type;
var objs = (IList) typeof(List<>).MakeInstance(unwrapped);
objs.Add(unwrapped.MakeInstance()
.Set("Id", 1.ToString())
.Set("Count", 10));
List<View3> result = Wrapper<View3>.Wrap(objs);
Assert.That(result.Count, Is.EqualTo(objs.Count));
Assert.That(result[0].Id, Is.EqualTo("1"));
Assert.That(result[0].Count, Is.EqualTo(10));
}
[Test]
public void Wrapper_ShouldWorkWithComplexViews()
{
Type unwrapped = UnwrappedView<WrappedView1>.Type;
var objs = (IList) typeof(List<>).MakeInstance(unwrapped);
objs.Add(unwrapped.MakeInstance()
.Set("Azonosito", 1)
.Set("Id", 1.ToString())
.Set("Count", 10));
objs.Add(unwrapped.MakeInstance()
.Set("Azonosito", 1)
.Set("Id", 2.ToString())
.Set("Count", 15));
objs.Add(unwrapped.MakeInstance()
.Set("Azonosito", 2)
.Set("Id", 2.ToString()) // DIREKT 2 megint
.Set("Count", 20));
List<WrappedView1> result = Wrapper<WrappedView1>.Wrap(objs);
Assert.That(result.Count, Is.EqualTo(2));
Assert.That(result[0].Azonosito, Is.EqualTo(1));
Assert.That(result[0].ViewList, Is.Not.Null);
Assert.That(result[0].ViewList.Count, Is.EqualTo(2));
Assert.That(result[0].ViewList[0].Id, Is.EqualTo("1"));
Assert.That(result[0].ViewList[0].Count, Is.EqualTo(10));
Assert.That(result[0].ViewList[1].Id, Is.EqualTo("2"));
Assert.That(result[0].ViewList[1].Count, Is.EqualTo(15));
Assert.That(result[1].Azonosito, Is.EqualTo(2));
Assert.That(result[1].ViewList, Is.Not.Null);
Assert.That(result[1].ViewList.Count, Is.EqualTo(1));
Assert.That(result[1].ViewList[0].Id, Is.EqualTo("2"));
Assert.That(result[1].ViewList[0].Count, Is.EqualTo(20));
}
[Test]
public void Wrapper_ShouldTakeEmptyListMarkerAttributeIntoAccount()
{
Type unwrapped = UnwrappedView<WrappedView1>.Type;
var objs = (IList) typeof(List<>).MakeInstance(unwrapped);
objs.Add(unwrapped.MakeInstance()
.Set("Azonosito", 1));
List<WrappedView1> result = Wrapper<WrappedView1>.Wrap(objs);
Assert.That(result.Count, Is.EqualTo(1));
Assert.That(result[0].Azonosito, Is.EqualTo(1));
Assert.That(result[0].ViewList, Is.Not.Null);
Assert.That(result[0].ViewList, Is.Empty);
}
[Test]
public void Wrapper_ShouldWorkWithMoreComplexViews()
{
Type unwrapped = UnwrappedView<WrappedView2>.Type;
var objs = (IList) typeof(List<>).MakeInstance(unwrapped);
Guid id = Guid.NewGuid();
objs.Add(unwrapped.MakeInstance()
.Set("Azonosito", 1)
.Set("Id", id)
.Set("IdSelection", 1.ToString())
.Set("SimpleColumnSelection", "xyz")
.Set("Foo", 10)
.Set("Count", 15));
objs.Add(unwrapped.MakeInstance()
.Set("Azonosito", 1)
.Set("Id", id)
.Set("IdSelection", 2.ToString())
.Set("SimpleColumnSelection", "abc")
.Set("Foo", 10)
.Set("Count", 15));
id = Guid.NewGuid();
objs.Add(unwrapped.MakeInstance()
.Set("Azonosito", 2)
.Set("Id", id)
.Set("IdSelection", 2.ToString())
.Set("SimpleColumnSelection", "zyx")
.Set("Foo", 20)
.Set("Count", 25));
objs.Add(unwrapped.MakeInstance()
.Set("Azonosito", 2)
.Set("Id", id)
.Set("IdSelection", 2.ToString())
.Set("SimpleColumnSelection", "zyx")
.Set("Foo", 30)
.Set("Count", 35));
List<WrappedView2> result = Wrapper<WrappedView2>.Wrap(objs);
Assert.That(result.Count, Is.EqualTo(2));
Assert.That(result[0].Azonosito, Is.EqualTo(1));
Assert.That(result[0].ViewList.Count, Is.EqualTo(2));
Assert.That(result[0].ViewList[0].IdSelection, Is.EqualTo("1"));
Assert.That(result[0].ViewList[0].SimpleColumnSelection, Is.EqualTo("xyz"));
Assert.That(result[0].ViewList[1].IdSelection, Is.EqualTo("2"));
Assert.That(result[0].ViewList[1].SimpleColumnSelection, Is.EqualTo("abc"));
Assert.That(result[0].ViewList2.Count, Is.EqualTo(1));
Assert.That(result[0].ViewList2[0].Foo, Is.EqualTo(10));
Assert.That(result[0].ViewList2[0].Count, Is.EqualTo(15));
Assert.That(result[1].Azonosito, Is.EqualTo(2));
Assert.That(result[1].ViewList.Count, Is.EqualTo(1));
Assert.That(result[1].ViewList[0].IdSelection, Is.EqualTo("2"));
Assert.That(result[1].ViewList[0].SimpleColumnSelection, Is.EqualTo("zyx"));
Assert.That(result[1].ViewList2.Count, Is.EqualTo(2));
Assert.That(result[1].ViewList2[0].Foo, Is.EqualTo(20));
Assert.That(result[1].ViewList2[0].Count, Is.EqualTo(25));
Assert.That(result[1].ViewList2[1].Foo, Is.EqualTo(30));
Assert.That(result[1].ViewList2[1].Count, Is.EqualTo(35));
}
[Test]
public void Wrapper_ShouldWorkWithViewsDescendingFromOrmType()
{
Type unwrapped = UnwrappedView<WrappedView3_Extesnion>.Type;
Guid
id1 = Guid.NewGuid(),
id2 = Guid.NewGuid();
var objs = (IList) typeof(List<>).MakeInstance(unwrapped);
objs.Add(unwrapped.MakeInstance()
.Set("Azonosito", 1)
.Set("Id", id1)
.Set("IdSelection", "cica"));
objs.Add(unwrapped.MakeInstance()
.Set("Azonosito", 1)
.Set("Id", id2)
.Set("IdSelection", "kutya"));
List<WrappedView3_Extesnion> result = Wrapper<WrappedView3_Extesnion>.Wrap(objs);
Assert.That(result.Count, Is.EqualTo(1));
Assert.That(result[0].Azonosito, Is.EqualTo(1));
Assert.That(result[0].ViewList, Is.Not.Null);
Assert.That(result[0].ViewList.Count, Is.EqualTo(2));
Assert.That(result[0].ViewList[0].Id, Is.EqualTo(id1));
Assert.That(result[0].ViewList[0].IdSelection, Is.EqualTo("cica"));
Assert.That(result[0].ViewList[1].Id, Is.EqualTo(id2));
Assert.That(result[0].ViewList[1].IdSelection, Is.EqualTo("kutya"));
}
[Test]
public void Wrapper_ShouldBeRecursive()
{
Type unwrapped = UnwrappedView<WrappedView4_Complex>.Type;
var objs = (IList) typeof(List<>).MakeInstance(unwrapped);
objs.Add(unwrapped.MakeInstance()
.Set("NagyonId", 1)
.Set("Azonosito", 2)
.Set("Id", 1.ToString())
.Set("Count", 10));
objs.Add(unwrapped.MakeInstance()
.Set("NagyonId", 1)
.Set("Azonosito", 2)
.Set("Id", 2.ToString())
.Set("Count", 20));
objs.Add(unwrapped.MakeInstance()
.Set("NagyonId", 1)
.Set("Azonosito", 3)
.Set("Id", 1.ToString())
.Set("Count", 50));
objs.Add(unwrapped.MakeInstance()
.Set("NagyonId", 2)
.Set("Azonosito", 3)
.Set("Id", 4.ToString())
.Set("Count", 100));
objs.Add(unwrapped.MakeInstance()
.Set("NagyonId", 2)
.Set("Azonosito", 3)
.Set("Id", 5.ToString())
.Set("Count", 200));
List<WrappedView4_Complex> result = Wrapper<WrappedView4_Complex>.Wrap(objs);
Assert.That(result.Count, Is.EqualTo(2));
Assert.That(result[0].NagyonId, Is.EqualTo(1));
Assert.That(result[0].AnotherViewList.Count, Is.EqualTo(2));
Assert.That(result[0].AnotherViewList[0].Azonosito, Is.EqualTo(2));
Assert.That(result[0].AnotherViewList[0].ViewList.Count, Is.EqualTo(2));
Assert.That(result[0].AnotherViewList[0].ViewList[0].Id, Is.EqualTo(1.ToString()));
Assert.That(result[0].AnotherViewList[0].ViewList[0].Count, Is.EqualTo(10));
Assert.That(result[0].AnotherViewList[0].ViewList[1].Id, Is.EqualTo(2.ToString()));
Assert.That(result[0].AnotherViewList[0].ViewList[1].Count, Is.EqualTo(20));
Assert.That(result[0].AnotherViewList[1].Azonosito, Is.EqualTo(3));
Assert.That(result[0].AnotherViewList[1].ViewList.Count, Is.EqualTo(1));
Assert.That(result[0].AnotherViewList[1].ViewList[0].Id, Is.EqualTo(1.ToString()));
Assert.That(result[0].AnotherViewList[1].ViewList[0].Count, Is.EqualTo(50));
Assert.That(result[1].NagyonId, Is.EqualTo(2));
Assert.That(result[1].AnotherViewList.Count, Is.EqualTo(1));
Assert.That(result[1].AnotherViewList[0].Azonosito, Is.EqualTo(3));
Assert.That(result[1].AnotherViewList[0].ViewList.Count, Is.EqualTo(2));
Assert.That(result[1].AnotherViewList[0].ViewList[0].Id, Is.EqualTo(4.ToString()));
Assert.That(result[1].AnotherViewList[0].ViewList[0].Count, Is.EqualTo(100));
Assert.That(result[1].AnotherViewList[0].ViewList[1].Id, Is.EqualTo(5.ToString()));
Assert.That(result[1].AnotherViewList[0].ViewList[1].Count, Is.EqualTo(200));
}
[Test]
public void Wrapper_ShouldWorkWithViewsHavingNonListWrappedProperty()
{
Type unwrapped = UnwrappedView<WrappedView3>.Type;
var objs = (IList) typeof(List<>).MakeInstance(unwrapped);
objs.Add(unwrapped.MakeInstance()
.Set("Azonosito", 2)
.Set("Id", 1.ToString())
.Set("Count", 10));
objs.Add(unwrapped.MakeInstance()
.Set("Azonosito", 1)
.Set("Id", 2.ToString())
.Set("Count", 0));
List<WrappedView3> result = Wrapper<WrappedView3>.Wrap(objs);
Assert.That(result.Count, Is.EqualTo(2));
Assert.That(result[0].Azonosito, Is.EqualTo(2));
Assert.That(result[0].View.Id, Is.EqualTo("1"));
Assert.That(result[0].View.Count, Is.EqualTo(10));
Assert.That(result[1].Azonosito, Is.EqualTo(1));
Assert.That(result[1].View.Id, Is.EqualTo("2"));
Assert.That(result[1].View.Count, Is.EqualTo(0));
}
[Test]
public void Wrapper_ShouldWorkWithViewsHavingNonListWrappedOptionalProperty()
{
Type unwrapped = UnwrappedView<WrappedView3>.Type;
var objs = (IList)typeof(List<>).MakeInstance(unwrapped);
objs.Add(unwrapped.MakeInstance()
.Set("Azonosito", 1));
List<WrappedView3> result = Wrapper<WrappedView3>.Wrap(objs);
Assert.That(result.Count, Is.EqualTo(1));
Assert.That(result[0].Azonosito, Is.EqualTo(1));
Assert.That(result[0].View, Is.Null);
}
[Test]
public void Wrapper_ShouldValidateTheSourceList()
{
Type unwrapped = UnwrappedView<WrappedView1>.Type;
Assert.Throws<ArgumentException>(() => Wrapper<WrappedView1>.Wrap(Array.CreateInstance(unwrapped, 0)), Resources.NOT_A_LIST);
Assert.Throws<ArgumentException>(() => Wrapper<WrappedView1>.Wrap(new List<object>()), Resources.INCOMPATIBLE_LIST);
}
[Test]
public void Wrapper_ShouldThrowIfTheViewIsAmbiguous()
{
Type unwrapped = UnwrappedView<WrappedView3>.Type;
var objs = (IList) typeof(List<>).MakeInstance(unwrapped);
objs.Add(unwrapped.MakeInstance()
.Set("Azonosito", 2)
.Set("Id", 1.ToString())
.Set("Count", 10));
objs.Add(unwrapped.MakeInstance()
.Set("Azonosito", 2)
.Set("Id", 1.ToString())
.Set("Count", 0));
Assert.Throws<InvalidOperationException>(() => Wrapper<WrappedView3>.Wrap(objs), Resources.AMBIGUOUS_RESULT);
}
[Test]
public void Wrapper_ShouldWorkWithValueLists()
{
Type unwrapped = UnwrappedView<Start_Node_View_ValueList>.Type;
var objs = (IList) typeof(List<>).MakeInstance(unwrapped);
Guid id1 = Guid.NewGuid();
objs.Add(unwrapped.MakeInstance()
.Set("Id_1", id1)
.Set("Id_0", Guid.NewGuid())
.Set("Reference", 1.ToString()));
Guid id2 = Guid.NewGuid();
objs.Add(unwrapped.MakeInstance()
.Set("Id_1", id2)
.Set("Id_0", Guid.NewGuid())
.Set("Reference", 1.ToString()));
objs.Add(unwrapped.MakeInstance()
.Set("Id_1", id2)
.Set("Id_0", Guid.NewGuid())
.Set("Reference", 2.ToString()));
List<Start_Node_View_ValueList> result = Wrapper<Start_Node_View_ValueList>.Wrap(objs);
Assert.That(result.Count, Is.EqualTo(2));
Assert.That(result[0].References.Count, Is.EqualTo(1));
Assert.That(result[0].References[0], Is.EqualTo(1.ToString()));
Assert.That(result[1].References.Count, Is.EqualTo(2));
Assert.That(result[1].References[0], Is.EqualTo(1.ToString()));
Assert.That(result[1].References[1], Is.EqualTo(2.ToString()));
}
[Test]
public void Wrapper_ShouldHandleEmptyValueLists()
{
Type unwrapped = UnwrappedView<Start_Node_View_ValueList>.Type;
var objs = (IList) typeof(List<>).MakeInstance(unwrapped);
Guid id1 = Guid.NewGuid();
objs.Add(unwrapped.MakeInstance().Set("Id_1", id1));
Guid id2 = Guid.NewGuid();
objs.Add(unwrapped.MakeInstance()
.Set("Id_1", id2)
.Set("Id_0", Guid.NewGuid())
.Set("Reference", 1.ToString()));
objs.Add(unwrapped.MakeInstance()
.Set("Id_1", id2)
.Set("Id_0", Guid.NewGuid())
.Set("Reference", 2.ToString()));
List<Start_Node_View_ValueList> result = Wrapper<Start_Node_View_ValueList>.Wrap(objs);
Assert.That(result.Count, Is.EqualTo(2));
Assert.That(result[0].References, Is.Empty);
Assert.That(result[1].References.Count, Is.EqualTo(2));
Assert.That(result[1].References[0], Is.EqualTo(1.ToString()));
Assert.That(result[1].References[1], Is.EqualTo(2.ToString()));
}
[Test]
public void Wrapper_ShouldHandlePropertyNameCollision()
{
Type unwrapped = UnwrappedView<CollidingWrappedView>.Type;
var objs = (IList) typeof(List<>).MakeInstance(unwrapped);
objs.Add(unwrapped.MakeInstance()
.Set("Id_0", 1)
.Set("Id_1", "kutya")
.Set("Count", 10));
objs.Add(unwrapped.MakeInstance()
.Set("Id_0", 2)
.Set("Id_1", "cica")
.Set("Count", 20));
objs.Add(unwrapped.MakeInstance()
.Set("Id_0", 2)
.Set("Id_1", "meresi hiba")
.Set("Count", 30));
List<CollidingWrappedView> result = Wrapper<CollidingWrappedView>.Wrap(objs);
Assert.That(result.Count, Is.EqualTo(2));
Assert.That(result[0].Id, Is.EqualTo(1));
Assert.That(result[0].ViewList.Count, Is.EqualTo(1));
Assert.That(result[0].ViewList[0].Id, Is.EqualTo("kutya"));
Assert.That(result[0].ViewList[0].Count, Is.EqualTo(10));
Assert.That(result[1].Id, Is.EqualTo(2));
Assert.That(result[1].ViewList.Count, Is.EqualTo(2));
Assert.That(result[1].ViewList[0].Id, Is.EqualTo("cica"));
Assert.That(result[1].ViewList[0].Count, Is.EqualTo(20));
Assert.That(result[1].ViewList[1].Id, Is.EqualTo("meresi hiba"));
Assert.That(result[1].ViewList[1].Count, Is.EqualTo(30));
}
}
}
| 43.651235 | 168 | 0.538429 | [
"MIT"
] | Sholtee/sql | TEST/SqlUtils.Tests/Wrapper/WrapperTests.cs | 28,288 | C# |
using System.Threading;
using NUnit.Framework;
namespace Fibrous.Tests
{
[TestFixture]
public class EventBusTests
{
[Test]
public void EventBusInt()
{
using Fiber fiber = new Fiber();
using AutoResetEvent reset = new AutoResetEvent(false);
EventBus<int>.Subscribe(fiber, _ => reset.Set());
EventBus<int>.Publish(0);
Assert.IsTrue(reset.WaitOne(100));
}
[Test]
public void EventBusMixed()
{
using Fiber fiber = new Fiber();
using Fiber fiber2 = new Fiber();
using AutoResetEvent reset = new AutoResetEvent(false);
using AutoResetEvent reset2 = new AutoResetEvent(false);
EventBus<int>.Subscribe(fiber, _ => reset.Set());
EventBus<string>.Subscribe(fiber2, _ => reset2.Set());
EventBus<int>.Publish(0);
EventBus<string>.Publish("!");
Assert.IsTrue(WaitHandle.WaitAll(new[] {reset, reset2}, 100));
}
}
}
| 30.941176 | 74 | 0.565589 | [
"MIT"
] | chrisa23/Fibrous | Tests/Fibrous.Tests/EventBusTEsts.cs | 1,054 | 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 pinpoint-sms-voice-v2-2022-03-31.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.PinpointSMSVoiceV2.Model
{
/// <summary>
/// Container for the parameters to the RequestPhoneNumber operation.
/// Request an origination phone number for use in your account. For more information
/// on phone number request see <a href="https://docs.aws.amazon.com/pinpoint/latest/userguide/settings-sms-request-number.html">
/// Requesting a number </a> in the <i>Amazon Pinpoint User Guide</i>.
/// </summary>
public partial class RequestPhoneNumberRequest : AmazonPinpointSMSVoiceV2Request
{
private string _clientToken;
private bool? _deletionProtectionEnabled;
private string _isoCountryCode;
private MessageType _messageType;
private List<string> _numberCapabilities = new List<string>();
private RequestableNumberType _numberType;
private string _optOutListName;
private string _poolId;
private string _registrationId;
private List<Tag> _tags = new List<Tag>();
/// <summary>
/// Gets and sets the property ClientToken.
/// <para>
/// Unique, case-sensitive identifier that you provide to ensure the idempotency of the
/// request. If you don't specify a client token, a randomly generated token is used for
/// the request to ensure idempotency.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=64)]
public string ClientToken
{
get { return this._clientToken; }
set { this._clientToken = value; }
}
// Check to see if ClientToken property is set
internal bool IsSetClientToken()
{
return this._clientToken != null;
}
/// <summary>
/// Gets and sets the property DeletionProtectionEnabled.
/// <para>
/// By default this is set to false. When set to true the phone number can't be deleted.
/// </para>
/// </summary>
public bool DeletionProtectionEnabled
{
get { return this._deletionProtectionEnabled.GetValueOrDefault(); }
set { this._deletionProtectionEnabled = value; }
}
// Check to see if DeletionProtectionEnabled property is set
internal bool IsSetDeletionProtectionEnabled()
{
return this._deletionProtectionEnabled.HasValue;
}
/// <summary>
/// Gets and sets the property IsoCountryCode.
/// <para>
/// The two-character code, in ISO 3166-1 alpha-2 format, for the country or region.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=2, Max=2)]
public string IsoCountryCode
{
get { return this._isoCountryCode; }
set { this._isoCountryCode = value; }
}
// Check to see if IsoCountryCode property is set
internal bool IsSetIsoCountryCode()
{
return this._isoCountryCode != null;
}
/// <summary>
/// Gets and sets the property MessageType.
/// <para>
/// The type of message. Valid values are TRANSACTIONAL for messages that are critical
/// or time-sensitive and PROMOTIONAL for messages that aren't critical or time-sensitive.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public MessageType MessageType
{
get { return this._messageType; }
set { this._messageType = value; }
}
// Check to see if MessageType property is set
internal bool IsSetMessageType()
{
return this._messageType != null;
}
/// <summary>
/// Gets and sets the property NumberCapabilities.
/// <para>
/// Indicates if the phone number will be used for text messages, voice messages, or both.
///
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=2)]
public List<string> NumberCapabilities
{
get { return this._numberCapabilities; }
set { this._numberCapabilities = value; }
}
// Check to see if NumberCapabilities property is set
internal bool IsSetNumberCapabilities()
{
return this._numberCapabilities != null && this._numberCapabilities.Count > 0;
}
/// <summary>
/// Gets and sets the property NumberType.
/// <para>
/// The type of phone number to request.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public RequestableNumberType NumberType
{
get { return this._numberType; }
set { this._numberType = value; }
}
// Check to see if NumberType property is set
internal bool IsSetNumberType()
{
return this._numberType != null;
}
/// <summary>
/// Gets and sets the property OptOutListName.
/// <para>
/// The name of the OptOutList to associate with the phone number. You can use the OutOutListName
/// or OptPutListArn.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=256)]
public string OptOutListName
{
get { return this._optOutListName; }
set { this._optOutListName = value; }
}
// Check to see if OptOutListName property is set
internal bool IsSetOptOutListName()
{
return this._optOutListName != null;
}
/// <summary>
/// Gets and sets the property PoolId.
/// <para>
/// The pool to associated with the phone number. You can use the PoolId or PoolArn.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=256)]
public string PoolId
{
get { return this._poolId; }
set { this._poolId = value; }
}
// Check to see if PoolId property is set
internal bool IsSetPoolId()
{
return this._poolId != null;
}
/// <summary>
/// Gets and sets the property RegistrationId.
/// <para>
/// Use this field to attach your phone number for an external registration process.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=64)]
public string RegistrationId
{
get { return this._registrationId; }
set { this._registrationId = value; }
}
// Check to see if RegistrationId property is set
internal bool IsSetRegistrationId()
{
return this._registrationId != null;
}
/// <summary>
/// Gets and sets the property Tags.
/// <para>
/// An array of tags (key and value pairs) associate with the requested phone number.
///
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=200)]
public List<Tag> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
}
} | 33.308943 | 133 | 0.584208 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/PinpointSMSVoiceV2/Generated/Model/RequestPhoneNumberRequest.cs | 8,194 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*============================================================
**
**
**
** Purpose: The contract class allows for expressing preconditions,
** postconditions, and object invariants about methods in source
** code for runtime checking & static analysis.
**
** Two classes (Contract and ContractHelper) are split into partial classes
** in order to share the public front for multiple platforms (this file)
** while providing separate implementation details for each platform.
**
===========================================================*/
#define DEBUG // The behavior of this contract library should be consistent regardless of build type.
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace System.Diagnostics.Contracts
{
#region Attributes
/// <summary>
/// Methods and classes marked with this attribute can be used within calls to Contract methods. Such methods not make any visible state changes.
/// </summary>
[Conditional("CONTRACTS_FULL")]
[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Delegate | AttributeTargets.Class | AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
public sealed class PureAttribute : Attribute
{
}
/// <summary>
/// Types marked with this attribute specify that a separate type contains the contracts for this type.
/// </summary>
[Conditional("CONTRACTS_FULL")]
[Conditional("DEBUG")]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
public sealed class ContractClassAttribute : Attribute
{
private readonly Type _typeWithContracts;
public ContractClassAttribute(Type typeContainingContracts)
{
_typeWithContracts = typeContainingContracts;
}
public Type TypeContainingContracts => _typeWithContracts;
}
/// <summary>
/// Types marked with this attribute specify that they are a contract for the type that is the argument of the constructor.
/// </summary>
[Conditional("CONTRACTS_FULL")]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public sealed class ContractClassForAttribute : Attribute
{
private readonly Type _typeIAmAContractFor;
public ContractClassForAttribute(Type typeContractsAreFor)
{
_typeIAmAContractFor = typeContractsAreFor;
}
public Type TypeContractsAreFor => _typeIAmAContractFor;
}
/// <summary>
/// This attribute is used to mark a method as being the invariant
/// method for a class. The method can have any name, but it must
/// return "void" and take no parameters. The body of the method
/// must consist solely of one or more calls to the method
/// Contract.Invariant. A suggested name for the method is
/// "ObjectInvariant".
/// </summary>
[Conditional("CONTRACTS_FULL")]
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public sealed class ContractInvariantMethodAttribute : Attribute
{
}
/// <summary>
/// Attribute that specifies that an assembly is a reference assembly with contracts.
/// </summary>
[AttributeUsage(AttributeTargets.Assembly)]
public sealed class ContractReferenceAssemblyAttribute : Attribute
{
}
/// <summary>
/// Methods (and properties) marked with this attribute can be used within calls to Contract methods, but have no runtime behavior associated with them.
/// </summary>
[Conditional("CONTRACTS_FULL")]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class ContractRuntimeIgnoredAttribute : Attribute
{
}
/// <summary>
/// Instructs downstream tools whether to assume the correctness of this assembly, type or member without performing any verification or not.
/// Can use [ContractVerification(false)] to explicitly mark assembly, type or member as one to *not* have verification performed on it.
/// Most specific element found (member, type, then assembly) takes precedence.
/// (That is useful if downstream tools allow a user to decide which polarity is the default, unmarked case.)
/// </summary>
/// <remarks>
/// Apply this attribute to a type to apply to all members of the type, including nested types.
/// Apply this attribute to an assembly to apply to all types and members of the assembly.
/// Apply this attribute to a property to apply to both the getter and setter.
/// </remarks>
[Conditional("CONTRACTS_FULL")]
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property)]
public sealed class ContractVerificationAttribute : Attribute
{
private readonly bool _value;
public ContractVerificationAttribute(bool value) { _value = value; }
public bool Value => _value;
}
/// <summary>
/// Allows a field f to be used in the method contracts for a method m when f has less visibility than m.
/// For instance, if the method is public, but the field is private.
/// </summary>
[Conditional("CONTRACTS_FULL")]
[AttributeUsage(AttributeTargets.Field)]
public sealed class ContractPublicPropertyNameAttribute : Attribute
{
private readonly string _publicName;
public ContractPublicPropertyNameAttribute(string name)
{
_publicName = name;
}
public string Name => _publicName;
}
/// <summary>
/// Enables factoring legacy if-then-throw into separate methods for reuse and full control over
/// thrown exception and arguments
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
[Conditional("CONTRACTS_FULL")]
public sealed class ContractArgumentValidatorAttribute : Attribute
{
}
/// <summary>
/// Enables writing abbreviations for contracts that get copied to other methods
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
[Conditional("CONTRACTS_FULL")]
public sealed class ContractAbbreviatorAttribute : Attribute
{
}
/// <summary>
/// Allows setting contract and tool options at assembly, type, or method granularity.
/// </summary>
[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]
[Conditional("CONTRACTS_FULL")]
public sealed class ContractOptionAttribute : Attribute
{
private readonly string _category;
private readonly string _setting;
private readonly bool _enabled;
private readonly string? _value;
public ContractOptionAttribute(string category, string setting, bool enabled)
{
_category = category;
_setting = setting;
_enabled = enabled;
}
public ContractOptionAttribute(string category, string setting, string value)
{
_category = category;
_setting = setting;
_value = value;
}
public string Category => _category;
public string Setting => _setting;
public bool Enabled => _enabled;
public string? Value => _value;
}
#endregion Attributes
/// <summary>
/// Contains static methods for representing program contracts such as preconditions, postconditions, and invariants.
/// </summary>
/// <remarks>
/// WARNING: A binary rewriter must be used to insert runtime enforcement of these contracts.
/// Otherwise some contracts like Ensures can only be checked statically and will not throw exceptions during runtime when contracts are violated.
/// Please note this class uses conditional compilation to help avoid easy mistakes. Defining the preprocessor
/// symbol CONTRACTS_PRECONDITIONS will include all preconditions expressed using Contract.Requires in your
/// build. The symbol CONTRACTS_FULL will include postconditions and object invariants, and requires the binary rewriter.
/// </remarks>
public static partial class Contract
{
#region User Methods
#region Assume
/// <summary>
/// Instructs code analysis tools to assume the expression <paramref name="condition"/> is true even if it can not be statically proven to always be true.
/// </summary>
/// <param name="condition">Expression to assume will always be true.</param>
/// <remarks>
/// At runtime this is equivalent to an <seealso cref="System.Diagnostics.Contracts.Contract.Assert(bool)"/>.
/// </remarks>
[Pure]
[Conditional("DEBUG")]
[Conditional("CONTRACTS_FULL")]
public static void Assume([DoesNotReturnIf(false)] bool condition)
{
if (!condition)
{
ReportFailure(ContractFailureKind.Assume, null, null, null);
}
}
/// <summary>
/// Instructs code analysis tools to assume the expression <paramref name="condition"/> is true even if it can not be statically proven to always be true.
/// </summary>
/// <param name="condition">Expression to assume will always be true.</param>
/// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param>
/// <remarks>
/// At runtime this is equivalent to an <seealso cref="System.Diagnostics.Contracts.Contract.Assert(bool)"/>.
/// </remarks>
[Pure]
[Conditional("DEBUG")]
[Conditional("CONTRACTS_FULL")]
public static void Assume([DoesNotReturnIf(false)] bool condition, string? userMessage)
{
if (!condition)
{
ReportFailure(ContractFailureKind.Assume, userMessage, null, null);
}
}
#endregion Assume
#region Assert
/// <summary>
/// In debug builds, perform a runtime check that <paramref name="condition"/> is true.
/// </summary>
/// <param name="condition">Expression to check to always be true.</param>
[Pure]
[Conditional("DEBUG")]
[Conditional("CONTRACTS_FULL")]
public static void Assert([DoesNotReturnIf(false)] bool condition)
{
if (!condition)
ReportFailure(ContractFailureKind.Assert, null, null, null);
}
/// <summary>
/// In debug builds, perform a runtime check that <paramref name="condition"/> is true.
/// </summary>
/// <param name="condition">Expression to check to always be true.</param>
/// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param>
[Pure]
[Conditional("DEBUG")]
[Conditional("CONTRACTS_FULL")]
public static void Assert([DoesNotReturnIf(false)] bool condition, string? userMessage)
{
if (!condition)
ReportFailure(ContractFailureKind.Assert, userMessage, null, null);
}
#endregion Assert
#region Requires
/// <summary>
/// Specifies a contract such that the expression <paramref name="condition"/> must be true before the enclosing method or property is invoked.
/// </summary>
/// <param name="condition">Boolean expression representing the contract.</param>
/// <remarks>
/// This call must happen at the beginning of a method or property before any other code.
/// This contract is exposed to clients so must only reference members at least as visible as the enclosing method.
/// Use this form when backward compatibility does not force you to throw a particular exception.
/// </remarks>
[Pure]
[Conditional("CONTRACTS_FULL")]
public static void Requires(bool condition)
{
AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires");
}
/// <summary>
/// Specifies a contract such that the expression <paramref name="condition"/> must be true before the enclosing method or property is invoked.
/// </summary>
/// <param name="condition">Boolean expression representing the contract.</param>
/// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param>
/// <remarks>
/// This call must happen at the beginning of a method or property before any other code.
/// This contract is exposed to clients so must only reference members at least as visible as the enclosing method.
/// Use this form when backward compatibility does not force you to throw a particular exception.
/// </remarks>
[Pure]
[Conditional("CONTRACTS_FULL")]
public static void Requires(bool condition, string? userMessage)
{
AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires");
}
/// <summary>
/// Specifies a contract such that the expression <paramref name="condition"/> must be true before the enclosing method or property is invoked.
/// </summary>
/// <param name="condition">Boolean expression representing the contract.</param>
/// <remarks>
/// This call must happen at the beginning of a method or property before any other code.
/// This contract is exposed to clients so must only reference members at least as visible as the enclosing method.
/// Use this form when you want to throw a particular exception.
/// </remarks>
[Pure]
public static void Requires<TException>(bool condition) where TException : Exception
{
AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires<TException>");
}
/// <summary>
/// Specifies a contract such that the expression <paramref name="condition"/> must be true before the enclosing method or property is invoked.
/// </summary>
/// <param name="condition">Boolean expression representing the contract.</param>
/// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param>
/// <remarks>
/// This call must happen at the beginning of a method or property before any other code.
/// This contract is exposed to clients so must only reference members at least as visible as the enclosing method.
/// Use this form when you want to throw a particular exception.
/// </remarks>
[Pure]
public static void Requires<TException>(bool condition, string? userMessage) where TException : Exception
{
AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires<TException>");
}
#endregion Requires
#region Ensures
/// <summary>
/// Specifies a public contract such that the expression <paramref name="condition"/> will be true when the enclosing method or property returns normally.
/// </summary>
/// <param name="condition">Boolean expression representing the contract. May include <seealso cref="OldValue"/> and <seealso cref="Result"/>.</param>
/// <remarks>
/// This call must happen at the beginning of a method or property before any other code.
/// This contract is exposed to clients so must only reference members at least as visible as the enclosing method.
/// The contract rewriter must be used for runtime enforcement of this postcondition.
/// </remarks>
[Pure]
[Conditional("CONTRACTS_FULL")]
public static void Ensures(bool condition)
{
AssertMustUseRewriter(ContractFailureKind.Postcondition, "Ensures");
}
/// <summary>
/// Specifies a public contract such that the expression <paramref name="condition"/> will be true when the enclosing method or property returns normally.
/// </summary>
/// <param name="condition">Boolean expression representing the contract. May include <seealso cref="OldValue"/> and <seealso cref="Result"/>.</param>
/// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param>
/// <remarks>
/// This call must happen at the beginning of a method or property before any other code.
/// This contract is exposed to clients so must only reference members at least as visible as the enclosing method.
/// The contract rewriter must be used for runtime enforcement of this postcondition.
/// </remarks>
[Pure]
[Conditional("CONTRACTS_FULL")]
public static void Ensures(bool condition, string? userMessage)
{
AssertMustUseRewriter(ContractFailureKind.Postcondition, "Ensures");
}
/// <summary>
/// Specifies a contract such that if an exception of type <typeparamref name="TException"/> is thrown then the expression <paramref name="condition"/> will be true when the enclosing method or property terminates abnormally.
/// </summary>
/// <typeparam name="TException">Type of exception related to this postcondition.</typeparam>
/// <param name="condition">Boolean expression representing the contract. May include <seealso cref="OldValue"/> and <seealso cref="Result"/>.</param>
/// <remarks>
/// This call must happen at the beginning of a method or property before any other code.
/// This contract is exposed to clients so must only reference types and members at least as visible as the enclosing method.
/// The contract rewriter must be used for runtime enforcement of this postcondition.
/// </remarks>
[Pure]
[Conditional("CONTRACTS_FULL")]
public static void EnsuresOnThrow<TException>(bool condition) where TException : Exception
{
AssertMustUseRewriter(ContractFailureKind.PostconditionOnException, "EnsuresOnThrow");
}
/// <summary>
/// Specifies a contract such that if an exception of type <typeparamref name="TException"/> is thrown then the expression <paramref name="condition"/> will be true when the enclosing method or property terminates abnormally.
/// </summary>
/// <typeparam name="TException">Type of exception related to this postcondition.</typeparam>
/// <param name="condition">Boolean expression representing the contract. May include <seealso cref="OldValue"/> and <seealso cref="Result"/>.</param>
/// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param>
/// <remarks>
/// This call must happen at the beginning of a method or property before any other code.
/// This contract is exposed to clients so must only reference types and members at least as visible as the enclosing method.
/// The contract rewriter must be used for runtime enforcement of this postcondition.
/// </remarks>
[Pure]
[Conditional("CONTRACTS_FULL")]
public static void EnsuresOnThrow<TException>(bool condition, string? userMessage) where TException : Exception
{
AssertMustUseRewriter(ContractFailureKind.PostconditionOnException, "EnsuresOnThrow");
}
#region Old, Result, and Out Parameters
/// <summary>
/// Represents the result (a.k.a. return value) of a method or property.
/// </summary>
/// <typeparam name="T">Type of return value of the enclosing method or property.</typeparam>
/// <returns>Return value of the enclosing method or property.</returns>
/// <remarks>
/// This method can only be used within the argument to the <seealso cref="Ensures(bool)"/> contract.
/// </remarks>
[Pure]
public static T Result<T>() { return default!; }
/// <summary>
/// Represents the final (output) value of an out parameter when returning from a method.
/// </summary>
/// <typeparam name="T">Type of the out parameter.</typeparam>
/// <param name="value">The out parameter.</param>
/// <returns>The output value of the out parameter.</returns>
/// <remarks>
/// This method can only be used within the argument to the <seealso cref="Ensures(bool)"/> contract.
/// </remarks>
[Pure]
public static T ValueAtReturn<T>(out T value) { value = default!; return value; }
/// <summary>
/// Represents the value of <paramref name="value"/> as it was at the start of the method or property.
/// </summary>
/// <typeparam name="T">Type of <paramref name="value"/>. This can be inferred.</typeparam>
/// <param name="value">Value to represent. This must be a field or parameter.</param>
/// <returns>Value of <paramref name="value"/> at the start of the method or property.</returns>
/// <remarks>
/// This method can only be used within the argument to the <seealso cref="Ensures(bool)"/> contract.
/// </remarks>
[Pure]
public static T OldValue<T>(T value) { return default!; }
#endregion Old, Result, and Out Parameters
#endregion Ensures
#region Invariant
/// <summary>
/// Specifies a contract such that the expression <paramref name="condition"/> will be true after every method or property on the enclosing class.
/// </summary>
/// <param name="condition">Boolean expression representing the contract.</param>
/// <remarks>
/// This contact can only be specified in a dedicated invariant method declared on a class.
/// This contract is not exposed to clients so may reference members less visible as the enclosing method.
/// The contract rewriter must be used for runtime enforcement of this invariant.
/// </remarks>
[Pure]
[Conditional("CONTRACTS_FULL")]
public static void Invariant(bool condition)
{
AssertMustUseRewriter(ContractFailureKind.Invariant, "Invariant");
}
/// <summary>
/// Specifies a contract such that the expression <paramref name="condition"/> will be true after every method or property on the enclosing class.
/// </summary>
/// <param name="condition">Boolean expression representing the contract.</param>
/// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param>
/// <remarks>
/// This contact can only be specified in a dedicated invariant method declared on a class.
/// This contract is not exposed to clients so may reference members less visible as the enclosing method.
/// The contract rewriter must be used for runtime enforcement of this invariant.
/// </remarks>
[Pure]
[Conditional("CONTRACTS_FULL")]
public static void Invariant(bool condition, string? userMessage)
{
AssertMustUseRewriter(ContractFailureKind.Invariant, "Invariant");
}
#endregion Invariant
#region Quantifiers
#region ForAll
/// <summary>
/// Returns whether the <paramref name="predicate"/> returns <c>true</c>
/// for all integers starting from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.
/// </summary>
/// <param name="fromInclusive">First integer to pass to <paramref name="predicate"/>.</param>
/// <param name="toExclusive">One greater than the last integer to pass to <paramref name="predicate"/>.</param>
/// <param name="predicate">Function that is evaluated from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.</param>
/// <returns><c>true</c> if <paramref name="predicate"/> returns <c>true</c> for all integers
/// starting from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.</returns>
/// <seealso cref="System.Collections.Generic.List<T>.TrueForAll"/>
[Pure]
public static bool ForAll(int fromInclusive, int toExclusive, Predicate<int> predicate)
{
if (fromInclusive > toExclusive)
throw new ArgumentException(SR.Argument_ToExclusiveLessThanFromExclusive);
if (predicate == null)
throw new ArgumentNullException(nameof(predicate));
for (int i = fromInclusive; i < toExclusive; i++)
if (!predicate(i)) return false;
return true;
}
/// <summary>
/// Returns whether the <paramref name="predicate"/> returns <c>true</c>
/// for all elements in the <paramref name="collection"/>.
/// </summary>
/// <param name="collection">The collection from which elements will be drawn from to pass to <paramref name="predicate"/>.</param>
/// <param name="predicate">Function that is evaluated on elements from <paramref name="collection"/>.</param>
/// <returns><c>true</c> if and only if <paramref name="predicate"/> returns <c>true</c> for all elements in
/// <paramref name="collection"/>.</returns>
/// <seealso cref="System.Collections.Generic.List<T>.TrueForAll"/>
[Pure]
public static bool ForAll<T>(IEnumerable<T> collection, Predicate<T> predicate)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
if (predicate == null)
throw new ArgumentNullException(nameof(predicate));
foreach (T t in collection)
if (!predicate(t)) return false;
return true;
}
#endregion ForAll
#region Exists
/// <summary>
/// Returns whether the <paramref name="predicate"/> returns <c>true</c>
/// for any integer starting from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.
/// </summary>
/// <param name="fromInclusive">First integer to pass to <paramref name="predicate"/>.</param>
/// <param name="toExclusive">One greater than the last integer to pass to <paramref name="predicate"/>.</param>
/// <param name="predicate">Function that is evaluated from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.</param>
/// <returns><c>true</c> if <paramref name="predicate"/> returns <c>true</c> for any integer
/// starting from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.</returns>
/// <seealso cref="System.Collections.Generic.List<T>.Exists"/>
[Pure]
public static bool Exists(int fromInclusive, int toExclusive, Predicate<int> predicate)
{
if (fromInclusive > toExclusive)
throw new ArgumentException(SR.Argument_ToExclusiveLessThanFromExclusive);
if (predicate == null)
throw new ArgumentNullException(nameof(predicate));
for (int i = fromInclusive; i < toExclusive; i++)
if (predicate(i)) return true;
return false;
}
/// <summary>
/// Returns whether the <paramref name="predicate"/> returns <c>true</c>
/// for any element in the <paramref name="collection"/>.
/// </summary>
/// <param name="collection">The collection from which elements will be drawn from to pass to <paramref name="predicate"/>.</param>
/// <param name="predicate">Function that is evaluated on elements from <paramref name="collection"/>.</param>
/// <returns><c>true</c> if and only if <paramref name="predicate"/> returns <c>true</c> for an element in
/// <paramref name="collection"/>.</returns>
/// <seealso cref="System.Collections.Generic.List<T>.Exists"/>
[Pure]
public static bool Exists<T>(IEnumerable<T> collection, Predicate<T> predicate)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
if (predicate == null)
throw new ArgumentNullException(nameof(predicate));
foreach (T t in collection)
if (predicate(t)) return true;
return false;
}
#endregion Exists
#endregion Quantifiers
#region Misc.
/// <summary>
/// Marker to indicate the end of the contract section of a method.
/// </summary>
[Conditional("CONTRACTS_FULL")]
public static void EndContractBlock() { }
#endregion
#endregion User Methods
#region Private Methods
/// <summary>
/// This method is used internally to trigger a failure indicating to the "programmer" that they are using the interface incorrectly.
/// It is NEVER used to indicate failure of actual contracts at runtime.
/// </summary>
private static void AssertMustUseRewriter(ContractFailureKind kind, string contractKind)
{
// For better diagnostics, report which assembly is at fault. Walk up stack and
// find the first non-mscorlib assembly.
Assembly thisAssembly = typeof(Contract).Assembly; // In case we refactor mscorlib, use Contract class instead of Object.
StackTrace stack = new StackTrace();
Assembly? probablyNotRewritten = null;
for (int i = 0; i < stack.FrameCount; i++)
{
Assembly? caller = stack.GetFrame(i)!.GetMethod()?.DeclaringType?.Assembly;
if (caller != null && caller != thisAssembly)
{
probablyNotRewritten = caller;
break;
}
}
probablyNotRewritten ??= thisAssembly;
string? simpleName = probablyNotRewritten.GetName().Name;
ContractHelper.TriggerFailure(kind, SR.Format(SR.MustUseCCRewrite, contractKind, simpleName), null, null, null);
}
#endregion Private Methods
#region Failure Behavior
/// <summary>
/// Without contract rewriting, failing Assert/Assumes end up calling this method.
/// Code going through the contract rewriter never calls this method. Instead, the rewriter produced failures call
/// ContractHelper.RaiseContractFailedEvent, followed by ContractHelper.TriggerFailure.
/// </summary>
[System.Diagnostics.DebuggerNonUserCode]
private static void ReportFailure(ContractFailureKind failureKind, string? userMessage, string? conditionText, Exception? innerException)
{
if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume)
throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), nameof(failureKind));
// displayMessage == null means: yes we handled it. Otherwise it is the localized failure message
string? displayMessage = ContractHelper.RaiseContractFailedEvent(failureKind, userMessage, conditionText, innerException);
if (displayMessage == null)
return;
ContractHelper.TriggerFailure(failureKind, displayMessage, userMessage, conditionText, innerException);
}
/// <summary>
/// Allows a managed application environment such as an interactive interpreter (IronPython)
/// to be notified of contract failures and
/// potentially "handle" them, either by throwing a particular exception type, etc. If any of the
/// event handlers sets the Cancel flag in the ContractFailedEventArgs, then the Contract class will
/// not pop up an assert dialog box or trigger escalation policy. Hooking this event requires
/// full trust, because it will inform you of bugs in the appdomain and because the event handler
/// could allow you to continue execution.
/// </summary>
public static event EventHandler<ContractFailedEventArgs>? ContractFailed
{
add
{
ContractHelper.InternalContractFailed += value;
}
remove
{
ContractHelper.InternalContractFailed -= value;
}
}
#endregion Failure Behavior
}
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public enum ContractFailureKind
{
Precondition,
Postcondition,
PostconditionOnException,
Invariant,
Assert,
Assume,
}
} // namespace System.Runtime.CompilerServices
| 47.811966 | 252 | 0.651025 | [
"MIT"
] | 2m0nd/runtime | src/libraries/System.Private.CoreLib/src/System/Diagnostics/Contracts/Contracts.cs | 33,564 | C# |
using System;
using System.Windows;
using System.Windows.Controls;
namespace WpfHint2.UIBuilding
{
internal class ParamPanel : Panel
{
public static bool GetNameColumn(DependencyObject obj)
{
return (bool)obj.GetValue(NameColumnProperty);
}
public static void SetNameColumn(DependencyObject obj, bool value)
{
obj.SetValue(NameColumnProperty, value);
}
public static readonly DependencyProperty NameColumnProperty =
DependencyProperty.RegisterAttached(
"NameColumn", typeof(bool), typeof(ParamPanel),
new FrameworkPropertyMetadata(false));
public static readonly DependencyProperty WrapProperty =
HintDecorator.WrapProperty.AddOwner(
typeof(ParamPanel),
new FrameworkPropertyMetadata((d, e) => ((UIElement)d).InvalidateMeasure()));
#region Layout
private const double tabSpace = 20;
private double nameColumnWidth;
protected override Size MeasureOverride(Size availableSize)
{
var panelSize = new Size();
if (!HintDecorator.GetWrap(this))
{
foreach (UIElement child in base.InternalChildren)
{
child.Measure(availableSize);
var desiredSize = child.DesiredSize;
panelSize.Width += desiredSize.Width;
panelSize.Height = Math.Max(panelSize.Height, desiredSize.Height);
}
}
else
{
nameColumnWidth = 0.0;
var typeColumnWidth = 0.0;
var rowHeight = 0.0;
foreach (UIElement child in base.InternalChildren)
{
child.Measure(availableSize);
var ds = child.DesiredSize;
if (GetNameColumn(child))
{
panelSize.Height += rowHeight;
// tab sapce
ds.Width += tabSpace;
if (ds.Width > nameColumnWidth) nameColumnWidth = ds.Width;
rowHeight = ds.Height;
}
else
{
if (ds.Width > typeColumnWidth) typeColumnWidth = ds.Width;
rowHeight = Math.Max(rowHeight, ds.Height);
}
}
panelSize.Height += rowHeight;
panelSize.Width = nameColumnWidth + typeColumnWidth;
}
return panelSize;
}
protected override Size ArrangeOverride(Size finalSize)
{
if (!HintDecorator.GetWrap(this))
{
var pt = new Point();
foreach (UIElement child in base.InternalChildren)
{
var size = child.DesiredSize;
child.Arrange(new Rect(pt, size));
pt.X += size.Width;
}
}
else
{
var ht = 0.0;
var y = 0.0;
foreach (UIElement child in base.InternalChildren)
{
var size = child.DesiredSize;
if (GetNameColumn(child))
{
child.Arrange(new Rect(tabSpace, y, nameColumnWidth - tabSpace, size.Height));
ht = size.Height;
}
else
{
child.Arrange(new Rect(nameColumnWidth, y, size.Width, size.Height));
y += Math.Max(ht, size.Height);
}
}
}
return finalSize;
}
#endregion
}
} | 23.918033 | 85 | 0.637423 | [
"BSD-3-Clause"
] | CyberFlameGO/Nitra | Ide/WpfHint/UIBuilding/ParamPanel.cs | 2,918 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Lucene.Net.Tests.Grouping")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Lucene.Net.Tests.Grouping")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c2349f0d-fb66-4544-9c33-4d87f73c6004")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.459459 | 84 | 0.745608 | [
"Apache-2.0"
] | BlueCurve-Team/lucenenet | src/Lucene.Net.Tests.Grouping/Properties/AssemblyInfo.cs | 1,426 | C# |
#region Usings
using System;
using FluentAssertions;
using Xunit;
#endregion
namespace Extend.Testing
{
public partial class Int32ExTest
{
[Fact]
public void ToDaysTest()
{
var value = RandomValueEx.GetRandomInt32( 1, 100 );
var expected = TimeSpan.FromDays( value );
var actual = value.ToDays();
actual
.Should()
.Be( expected );
}
[Fact]
public void ToDaysTooLargeTest()
{
var value = TimeSpan.MaxValue.Days + 1;
// ReSharper disable once ReturnValueOfPureMethodIsNotUsed
Action test = () => value.ToDays();
Assert.Throws<OverflowException>( test );
}
[Fact]
public void ToDaysTooSmallTest()
{
var value = TimeSpan.MinValue.Days - 1;
// ReSharper disable once ReturnValueOfPureMethodIsNotUsed
Action test = () => value.ToDays();
Assert.Throws<OverflowException>( test );
}
}
} | 24.282609 | 71 | 0.523724 | [
"MIT"
] | DaveSenn/Extend | .Src/Extend.Testing/System.Int32/System.TimeSpan/Int32.ToDays.Test.cs | 1,074 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("App1.iOS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("App1.iOS")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("72bdc44f-c588-44f3-b6df-9aace7daafdd")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.513514 | 85 | 0.723509 | [
"Apache-2.0"
] | CHUNHUNGFAN/Nantou_iBus | CommandPage/App1/App1.iOS/Properties/AssemblyInfo.cs | 1,428 | C# |
using System.Collections.ObjectModel;
namespace CommandsCode
{
/// <summary>
/// Scouts collection class.
/// </summary>
public class Scouts : ObservableCollection<Scout> { }
}
| 19.5 | 57 | 0.671795 | [
"MIT"
] | glennpoorman/wpf-samples | 34-CommandsCode/Scouts.cs | 197 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace NuGet.Frameworks
{
/// <summary>
/// A portable implementation of the .NET FrameworkName type with added support for NuGet folder names.
/// </summary>
#if NUGET_FRAMEWORKS_INTERNAL
internal
#else
public
#endif
partial class NuGetFramework : IEquatable<NuGetFramework>
{
private readonly string _frameworkIdentifier;
private readonly Version _frameworkVersion;
private readonly string _frameworkProfile;
private const string Portable = "portable";
private int? _hashCode;
public NuGetFramework(NuGetFramework framework)
: this(framework.Framework, framework.Version, framework.Profile, framework.Platform, framework.PlatformVersion)
{
}
public NuGetFramework(string framework)
: this(framework, FrameworkConstants.EmptyVersion)
{
}
public NuGetFramework(string framework, Version version)
: this(framework, version, string.Empty, FrameworkConstants.EmptyVersion)
{
}
private const int Version5 = 5;
/// <summary>
/// Creates a new NuGetFramework instance, with an optional profile (only available for netframework)
/// </summary>
public NuGetFramework(string frameworkIdentifier, Version frameworkVersion, string frameworkProfile)
: this(frameworkIdentifier, frameworkVersion, profile: ProcessProfile(frameworkProfile), platform: string.Empty, platformVersion: FrameworkConstants.EmptyVersion)
{
}
private static string ProcessProfile(string profile)
{
return profile ?? string.Empty;
}
/// <summary>
/// Creates a new NuGetFramework instance, with an optional platform and platformVersion (only available for net5.0+)
/// </summary>
public NuGetFramework(string frameworkIdentifier, Version frameworkVersion, string platform, Version platformVersion)
: this(frameworkIdentifier, frameworkVersion, profile: string.Empty, platform: platform, platformVersion: platformVersion)
{
}
internal NuGetFramework(string frameworkIdentifier, Version frameworkVersion, string profile, string platform, Version platformVersion)
{
if (frameworkIdentifier == null)
{
throw new ArgumentNullException("frameworkIdentifier");
}
if (frameworkVersion == null)
{
throw new ArgumentNullException("frameworkVersion");
}
if (platform == null)
{
throw new ArgumentNullException("platform");
}
if (platformVersion == null)
{
throw new ArgumentNullException("platformVersion");
}
_frameworkIdentifier = frameworkIdentifier;
_frameworkVersion = NormalizeVersion(frameworkVersion);
_frameworkProfile = profile;
IsNet5Era = (_frameworkVersion.Major >= Version5 && StringComparer.OrdinalIgnoreCase.Equals(FrameworkConstants.FrameworkIdentifiers.NetCoreApp, _frameworkIdentifier));
Platform = IsNet5Era ? platform : string.Empty;
PlatformVersion = IsNet5Era ? NormalizeVersion(platformVersion) : FrameworkConstants.EmptyVersion;
}
/// <summary>
/// Target framework
/// </summary>
public string Framework
{
get { return _frameworkIdentifier; }
}
/// <summary>
/// Target framework version
/// </summary>
public Version Version
{
get { return _frameworkVersion; }
}
/// <summary>
/// Framework Platform (net5.0+)
/// </summary>
public string Platform
{
get;
private set;
}
/// <summary>
/// Framework Platform Version (net5.0+)
/// </summary>
public Version PlatformVersion
{
get;
private set;
}
/// <summary>
/// True if the platform is non-empty
/// </summary>
public bool HasPlatform
{
get { return !string.IsNullOrEmpty(Platform); }
}
/// <summary>
/// True if the profile is non-empty
/// </summary>
public bool HasProfile
{
get { return !string.IsNullOrEmpty(Profile); }
}
/// <summary>
/// Target framework profile
/// </summary>
public string Profile
{
get { return _frameworkProfile; }
}
/// <summary>
/// Formatted to a System.Versioning.FrameworkName
/// </summary>
public string DotNetFrameworkName
{
get
{
return GetDotNetFrameworkName(DefaultFrameworkNameProvider.Instance);
}
}
/// <summary>
/// Formatted to a System.Versioning.FrameworkName
/// </summary>
public string GetDotNetFrameworkName(IFrameworkNameProvider mappings)
{
// Check for rewrites
var framework = mappings.GetFullNameReplacement(this);
if (framework.IsNet5Era)
{
return GetShortFolderName();
}
else if (framework.IsSpecificFramework)
{
var parts = new List<string>(3) { Framework };
parts.Add(string.Format(CultureInfo.InvariantCulture, "Version=v{0}", GetDisplayVersion(framework.Version)));
if (!string.IsNullOrEmpty(framework.Profile))
{
parts.Add(string.Format(CultureInfo.InvariantCulture, "Profile={0}", framework.Profile));
}
return string.Join(",", parts);
}
else
{
return string.Format(CultureInfo.InvariantCulture, "{0},Version=v0.0", framework.Framework);
}
}
/// <summary>
/// Creates the shortened version of the framework using the default mappings.
/// Ex: net45
/// </summary>
public string GetShortFolderName()
{
return GetShortFolderName(DefaultFrameworkNameProvider.Instance);
}
/// <summary>
/// Helper that is .NET 5 Era aware to replace identifier when appropriate
/// </summary>
private string GetFrameworkIdentifier()
{
return IsNet5Era ? FrameworkConstants.FrameworkIdentifiers.Net : Framework;
}
/// <summary>
/// Creates the shortened version of the framework using the given mappings.
/// </summary>
public virtual string GetShortFolderName(IFrameworkNameProvider mappings)
{
// Check for rewrites
var framework = mappings.GetShortNameReplacement(this);
var sb = new StringBuilder();
if (IsSpecificFramework)
{
var shortFramework = string.Empty;
// get the framework
if (!mappings.TryGetShortIdentifier(
GetFrameworkIdentifier(),
out shortFramework))
{
shortFramework = GetLettersAndDigitsOnly(framework.Framework);
}
if (string.IsNullOrEmpty(shortFramework))
{
throw new FrameworkException(string.Format(
CultureInfo.CurrentCulture,
Strings.InvalidFrameworkIdentifier,
shortFramework));
}
// add framework
sb.Append(shortFramework);
// add the version if it is non-empty
if (!AllFrameworkVersions)
{
sb.Append(mappings.GetVersionString(framework.Framework, framework.Version));
}
if (IsPCL)
{
sb.Append("-");
IEnumerable<NuGetFramework> frameworks = null;
if (framework.HasProfile
&& mappings.TryGetPortableFrameworks(framework.Profile, false, out frameworks)
&& frameworks.Any())
{
var required = new HashSet<NuGetFramework>(frameworks, Comparer);
// Normalize by removing all optional frameworks
mappings.TryGetPortableFrameworks(framework.Profile, false, out frameworks);
// sort the PCL frameworks by alphabetical order
var sortedFrameworks = required.Select(e => e.GetShortFolderName(mappings)).OrderBy(e => e, StringComparer.OrdinalIgnoreCase).ToList();
sb.Append(string.Join("+", sortedFrameworks));
}
else
{
throw new FrameworkException(string.Format(
CultureInfo.CurrentCulture,
Strings.MissingPortableFrameworks,
framework.DotNetFrameworkName));
}
}
else if (IsNet5Era)
{
if (!string.IsNullOrEmpty(framework.Platform))
{
sb.Append("-");
sb.Append(framework.Platform.ToLowerInvariant());
if (framework.PlatformVersion != FrameworkConstants.EmptyVersion)
{
sb.Append(mappings.GetVersionString(framework.Framework, framework.PlatformVersion));
}
}
}
else
{
// add the profile
var shortProfile = string.Empty;
if (framework.HasProfile && !mappings.TryGetShortProfile(framework.Framework, framework.Profile, out shortProfile))
{
// if we have a profile, but can't get a mapping, just use the profile as is
shortProfile = framework.Profile;
}
if (!string.IsNullOrEmpty(shortProfile))
{
sb.Append("-");
sb.Append(shortProfile);
}
}
}
else
{
// unsupported, any, agnostic
sb.Append(Framework);
}
return sb.ToString().ToLowerInvariant();
}
private static string GetDisplayVersion(Version version)
{
var sb = new StringBuilder(string.Format(CultureInfo.InvariantCulture, "{0}.{1}", version.Major, version.Minor));
if (version.Build > 0
|| version.Revision > 0)
{
sb.AppendFormat(CultureInfo.InvariantCulture, ".{0}", version.Build);
if (version.Revision > 0)
{
sb.AppendFormat(CultureInfo.InvariantCulture, ".{0}", version.Revision);
}
}
return sb.ToString();
}
private static string GetLettersAndDigitsOnly(string s)
{
var sb = new StringBuilder();
foreach (var c in s.ToCharArray())
{
if (char.IsLetterOrDigit(c))
{
sb.Append(c);
}
}
return sb.ToString();
}
/// <summary>
/// Portable class library check
/// </summary>
public bool IsPCL
{
get { return StringComparer.OrdinalIgnoreCase.Equals(Framework, FrameworkConstants.FrameworkIdentifiers.Portable) && Version.Major < 5; }
}
/// <summary>
/// True if the framework is packages based.
/// Ex: dotnet, dnxcore, netcoreapp, netstandard, uap, netcore50
/// </summary>
public bool IsPackageBased
{
get
{
// For these frameworks all versions are packages based.
if (PackagesBased.Contains(Framework))
{
return true;
}
// NetCore 5.0 and up are packages based.
// Everything else is not packages based.
return NuGetFrameworkUtility.IsNetCore50AndUp(this);
}
}
/// <summary>
/// True if this framework matches for all versions.
/// Ex: net
/// </summary>
public bool AllFrameworkVersions
{
get { return Version.Major == 0 && Version.Minor == 0 && Version.Build == 0 && Version.Revision == 0; }
}
/// <summary>
/// True if this framework was invalid or unknown. This framework is only compatible with Any and Agnostic.
/// </summary>
public bool IsUnsupported
{
get { return UnsupportedFramework.Equals(this); }
}
/// <summary>
/// True if this framework is non-specific. Always compatible.
/// </summary>
public bool IsAgnostic
{
get { return AgnosticFramework.Equals(this); }
}
/// <summary>
/// True if this is the any framework. Always compatible.
/// </summary>
public bool IsAny
{
get { return AnyFramework.Equals(this); }
}
/// <summary>
/// True if this framework is real and not one of the special identifiers.
/// </summary>
public bool IsSpecificFramework
{
get { return !IsAgnostic && !IsAny && !IsUnsupported; }
}
/// <summary>
/// True if this framework is Net5 or later, until we invent something new.
/// </summary>
internal bool IsNet5Era { get; private set; }
/// <summary>
/// Full framework comparison of the identifier, version, profile, platform, and platform version
/// </summary>
public static readonly IEqualityComparer<NuGetFramework> Comparer = new NuGetFrameworkFullComparer();
/// <summary>
/// Framework name only comparison.
/// </summary>
public static readonly IEqualityComparer<NuGetFramework> FrameworkNameComparer = new NuGetFrameworkNameComparer();
public override string ToString()
{
return DotNetFrameworkName;
}
public bool Equals(NuGetFramework other)
{
return Comparer.Equals(this, other);
}
public static bool operator ==(NuGetFramework left, NuGetFramework right)
{
return Comparer.Equals(left, right);
}
public static bool operator !=(NuGetFramework left, NuGetFramework right)
{
return !(left == right);
}
public override int GetHashCode()
{
if (_hashCode == null)
{
_hashCode = Comparer.GetHashCode(this);
}
return _hashCode.Value;
}
public override bool Equals(object obj)
{
var other = obj as NuGetFramework;
if (other != null)
{
return Equals(other);
}
else
{
return base.Equals(obj);
}
}
private static Version NormalizeVersion(Version version)
{
var normalized = version;
if (version.Build < 0
|| version.Revision < 0)
{
normalized = new Version(
version.Major,
version.Minor,
Math.Max(version.Build, 0),
Math.Max(version.Revision, 0));
}
return normalized;
}
/// <summary>
/// Frameworks that are packages based across all versions.
/// </summary>
private static readonly SortedSet<string> PackagesBased = new SortedSet<string>(
new[]
{
FrameworkConstants.FrameworkIdentifiers.DnxCore,
FrameworkConstants.FrameworkIdentifiers.NetPlatform,
FrameworkConstants.FrameworkIdentifiers.NetStandard,
FrameworkConstants.FrameworkIdentifiers.NetStandardApp,
FrameworkConstants.FrameworkIdentifiers.NetCoreApp,
FrameworkConstants.FrameworkIdentifiers.UAP,
FrameworkConstants.FrameworkIdentifiers.Tizen,
},
StringComparer.OrdinalIgnoreCase);
}
}
| 33.406977 | 179 | 0.536025 | [
"Apache-2.0"
] | KirillOsenkov/NuGet.Client | src/NuGet.Core/NuGet.Frameworks/NuGetFramework.cs | 17,238 | C# |
using System;
using System.Collections.Generic;
using Framework;
using UnityEngine;
namespace SuperSport
{
[RequireComponent(typeof(Rigidbody))]
public class RaceNPC : RaceCharacter
{
Collider _collider;
Rigidbody _rigidbody;
Transform _transform;
Renderer _renderer;
Vector3 _defaultPosition;
[Serializable]
public class Boost
{
[SerializeField]
public float value;
[SerializeField]
public int timing;
}
[SerializeField]
float _addForce = 10f;
[SerializeField]
List<Boost> _boosts = new List<Boost>();
[SerializeField]
EasyAnimation _easyAnimation = null;
bool _isUpdate;
int _updateFrame;
float _time;
float _randomAccelerator;
void Awake()
{
_rigidbody = GetComponent<Rigidbody>();
_transform = GetComponent<Transform>();
_renderer = GetComponentInChildren<Renderer>();
_collider = GetComponent<Collider>();
_isUpdate = false;
_time = 0;
_randomAccelerator = UnityEngine.Random.Range(0, 1);
_defaultPosition = _transform.position;
_easyAnimation.Initialize();
}
void Update()
{
if (_isUpdate)
{
Boost boost = _boosts.Find(x => x.timing == _updateFrame);
if (boost != null)
{
Accelerator(boost.value);
}
else
{
Accelerator(1f);
}
_updateFrame++;
_time += Time.deltaTime;
_easyAnimation.SetSpeed(_rigidbody.velocity.magnitude * 0.3f);
}
}
void Accelerator(float boost)
{
_rigidbody.AddForce(new Vector3((_addForce + _randomAccelerator) * boost, 0f, 0f));
}
public void SetupStart(float force)
{
_rigidbody.velocity = Vector3.zero;
_rigidbody.angularVelocity = Vector3.zero;
_transform.position = _defaultPosition;
_isUpdate = false;
_updateFrame = 0;
Timer = 99.9f;
_addForce = force;
}
public void StartRun()
{
_isUpdate = true;
_updateFrame = 0;
_easyAnimation.CrossFade(1, 0, 0.5f);
}
public void StopRun()
{
_isUpdate = false;
DebugLog.Normal($"{gameObject.name}の更新回数:{_updateFrame}, 記録:{_time}");
_easyAnimation.CrossFade(0, 0, 2);
_easyAnimation.SetSpeed(1);
}
public void Disable()
{
_renderer.enabled = false;
_collider.enabled = false;
}
public void Enable()
{
_renderer.enabled = true;
_collider.enabled = true;
}
}
} | 26.188034 | 95 | 0.506201 | [
"MIT"
] | r-kajiya/SuperSoprt-Race | Assets/Script/Race/RaceNPC.cs | 3,078 | C# |
using eilang.Compiling;
using eilang.Interfaces;
using eilang.Tokens;
namespace eilang.Ast
{
public class AstAssignmentReference : AstExpression
{
public AstExpression Reference { get; }
public AstAssignmentReference(AstExpression reference, Position position) : base(position)
{
Reference = reference;
}
public override void Accept(IVisitor visitor, Function function, Module mod)
{
visitor.Visit(this, function, mod);
}
public override string ToCode()
{
return Reference.ToCode();
}
}
} | 24.8 | 98 | 0.624194 | [
"MIT"
] | Szune/eilang | eilang/Ast/AstAssignmentReference.cs | 622 | C# |
namespace HiddenLoaderWinForms.User
{
public struct UserPcSpecificationStruct
{
public string Os;
public string CpuName;
public string RamCount;
public string GpuName;
}
} | 21.5 | 43 | 0.660465 | [
"MIT"
] | Tentrun/Silent-Loader | User/UserPcSpecificationStruct.cs | 215 | C# |
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace Common.Message
{
/// <summary>
/// Class with static methods to convert message objects from/to XML string/message objects from given namespace
/// </summary>
public class XmlMessageConverter
{
///<summary>
/// XML Desirializer
/// </summary>
///<returns>
/// Object of desired type if XML is valid
/// otherwise NULL
/// </returns>
public static object ToObject(string xmlString, string ns = "Common.Schema.")
{
XmlDocument xd = new XmlDocument();
//TODO when XmlValidation.Validate(xmlString) is uncommented few unit tests fail
XmlValidation.Instance.Validate(xmlString);
xd.LoadXml(xmlString);
try
{
XmlSerializer xs = new XmlSerializer(Type.GetType(ns + xd.LastChild.Name));
using (var s = new StringReader(xmlString))
{
return xs.Deserialize(s);
}
}
catch(ArgumentNullException e)
{
throw new ArgumentException("The given message type does not exist.");
}
}
public static string ToXml(object msg)
{
XmlSerializer xs = new XmlSerializer(msg.GetType());
StringBuilder sb = new StringBuilder();
using (StringWriter s = new Utf8StringWriter(sb))
{
xs.Serialize(s, msg);
}
return sb.ToString();
}
}
} | 32.769231 | 117 | 0.532864 | [
"BSD-3-Clause"
] | jasinskib/Software_Engineering_2_ProjectGame | src/Common/Message/XmlMessageConverter.cs | 1,706 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
using SiteManager.V4.Infrastructure.Identity;
namespace SiteManager.V4.WebUI.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class RegisterModel : PageModel
{
private readonly SignInManager<AppUser> _signInManager;
private readonly UserManager<AppUser> _userManager;
private readonly ILogger<RegisterModel> _logger;
private readonly IEmailSender _emailSender;
public RegisterModel(
UserManager<AppUser> userManager,
SignInManager<AppUser> signInManager,
ILogger<RegisterModel> logger,
IEmailSender emailSender)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
_emailSender = emailSender;
}
[BindProperty]
public InputModel Input { get; set; }
public string ReturnUrl { get; set; }
public IList<AuthenticationScheme> ExternalLogins { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public async Task<ActionResult> OnGetAsync(string returnUrl = null)
{
//RMC: Leaving these in place for potential use in a federated environment requiring non-angular/3rd party authentication.
//for now...redirect/disable
return Redirect("/");
ReturnUrl = returnUrl;
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
//RMC: Leaving these in place for potential use in a federated environment requiring non-angular/3rd party authentication.
//for now...redirect/disable
return Redirect("/");
returnUrl = returnUrl ?? Url.Content("~/");
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
if (ModelState.IsValid)
{
var user = new AppUser { UserName = Input.Email, Email = Input.Email };
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
protocol: Request.Scheme);
await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
if (_userManager.Options.SignIn.RequireConfirmedAccount)
{
return RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl });
}
else
{
await _signInManager.SignInAsync(user, isPersistent: false);
return LocalRedirect(returnUrl);
}
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
// If we got this far, something failed, redisplay form
return Page();
}
}
}
| 40.096774 | 134 | 0.601167 | [
"MIT"
] | rmcfar1999/SiteManager | Code/src/WebUI/Areas/Identity/Pages/Account/Register.cshtml.cs | 4,974 | C# |
using AccountAPI.Models;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AccountAPI.Services
{
public interface IAccountService
{
Task<ServiceResponse<int>> Register(User user, string password);
Task<ServiceResponse<string>> Login(string email, string password);
Task<ServiceResponse<string>> Delete(string password);
Task<ServiceResponse<GetUserDTO>> Update(User user);
Task<ServiceResponse<string>> UploadImage(HttpRequest httpContext);
Task<ServiceResponse<GetUserDTO>> GetUser();
Task<ServiceResponse<List<GetUserDTO>>> GetUnvalidatedUsers();
ServiceResponse<Enums.UserType> GetUserType(int id);
Task<ServiceResponse<string>> Validate(string email, bool accepted);
Task<bool> UserExists(string email);
}
}
| 37.333333 | 76 | 0.732143 | [
"MIT"
] | nikoladragas/public-transport | AccountAPI/Services/IAccountService.cs | 898 | C# |
namespace RustGen
{
public class Opcode
{
public string Code { get; set; }
public short Num { get; set; }
public string AddressingMode { get; set; }
public string ToHex() => Num.ToString("X2");
public string ToNamedCode() => $"{Code.Substring(0, 1).ToUpperInvariant()}{Code.Substring(1, 2).ToLowerInvariant()}";
public string ClassName => $"{ToNamedCode()}{AddressingMode}";
public string AddressingModeNice
{
get
{
switch (AddressingMode)
{
case "Imm": return "immediate";
case "Abs": return "absolute";
case "AbsX": return "absolute, indexed by X";
case "AbsY": return "absolute, indexed by Y";
case "Zp": return "zeropage";
case "ZpX": return "absolute, indexed by X";
case "ZpY": return "absolute, indexed by X";
case "Rel": return "relative";
case "Ind": return "indirect";
case "IndX": return "indirect, indexed by X";
case "IndY": return "indirect, indexed by Y";
default: return "";
}
}
}
}
}
| 32.9 | 125 | 0.477964 | [
"BSD-3-Clause"
] | gdoct/rustvm | generator/RustGen/Opcode.cs | 1,318 | C# |
//------------------------------------------------------------------------------
// <auto-generated />
//
// This file was automatically generated by SWIG (http://www.swig.org).
// Version 3.0.12
//
// Do not make changes to this file unless you know what you are doing--modify
// the SWIG interface file instead.
//------------------------------------------------------------------------------
namespace OSGeo_v3.GDAL {
public enum ExtendedDataTypeClass {
GEDTC_NUMERIC,
GEDTC_STRING,
GEDTC_COMPOUND
}
}
| 25.7 | 80 | 0.496109 | [
"Apache-2.0"
] | jugstalt/gview5 | gView.DataSources.OSGeo/OSGeo/v3/gdal/ExtendedDataTypeClass.cs | 514 | C# |
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.SimpleSystemsManagement")]
#if BCL35
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Simple Systems Manager (SSM). Amazon EC2 Simple Systems Manager (SSM) enables you to manage a number of administrative and configuration tasks on your instances.")]
#elif BCL45
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Amazon Simple Systems Manager (SSM). Amazon EC2 Simple Systems Manager (SSM) enables you to manage a number of administrative and configuration tasks on your instances.")]
#elif NETSTANDARD20
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - Amazon Simple Systems Manager (SSM). Amazon EC2 Simple Systems Manager (SSM) enables you to manage a number of administrative and configuration tasks on your instances.")]
#elif NETCOREAPP3_1
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - Amazon Simple Systems Manager (SSM). Amazon EC2 Simple Systems Manager (SSM) enables you to manage a number of administrative and configuration tasks on your instances.")]
#else
#error Unknown platform constant - unable to set correct AssemblyDescription
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.7.11.6")]
[assembly: System.CLSCompliant(true)]
#if BCL
[assembly: System.Security.AllowPartiallyTrustedCallers]
#endif | 51.215686 | 260 | 0.771057 | [
"Apache-2.0"
] | aws/aws-sdk-net | sdk/src/Services/SimpleSystemsManagement/Properties/AssemblyInfo.cs | 2,612 | C# |
/****
* Created by: Akram Taghavi-Burris
* Date Created: March 16, 2022
*
* Last Edited by: NA
* Last Edited: March 16, 2022
*
* Description: Enemy controler
****/
/** Using Namespaces **/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[SelectionBase] //forces selection of parent object
public class Enemy : MonoBehaviour
{
/*** VARIABLES ***/
[Header("Enemy Settings")]
public float speed = 10f;
public float fireRate = 0.3f;
public float health = 10;
public int score = 100;
private BoundsCheck bndCheck; //reference to bounds check component
//method that acts as a field (property)
public Vector3 pos
{
get { return (this.transform.position); }
set { this.transform.position = value; }
}
/*** MEHTODS ***/
//Awake is called when the game loads (before Start). Awake only once during the lifetime of the script instance.
void Awake()
{
bndCheck = GetComponent<BoundsCheck>();
}//end Awake()
// Update is called once per frame
void Update()
{
Move();
//Check if bounds check exists and the object is off the bottom of the screne
if(bndCheck != null && bndCheck.offDown)
{
Destroy(gameObject); //destory the object
}//end if(bndCheck != null && !bndCheck.offDown)
}//end Update()
//Virtual methods can be overiden by child instances
public virtual void Move()
{
Vector3 temPos = pos;
temPos.y -= speed * Time.deltaTime;
pos = temPos;
}
void OnCollisionEnter(Collision coll)
{
GameObject otherGO = coll.gameObject;
if(otherGO.tag == "Projectile Hero")
{
Destroy(otherGO);
Hero.SHIP.AddScore(score);
Destroy(gameObject);
}
else
{
print("Enemy hit by non-ProjectileHero: " + otherGO.name);
}
}
}
| 22.94186 | 118 | 0.598074 | [
"MIT"
] | SagesGrotto/SpaceSHUMP | SpaceSHMUP-Unity/Assets/Scripts/Enemy.cs | 1,973 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.